github.com/devops-filetransfer/sshego@v7.0.4+incompatible/_vendor/golang.org/x/crypto/acme/autocert/autocert.go (about)

     1  // Copyright 2016 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package autocert provides automatic access to certificates from Let's Encrypt
     6  // and any other ACME-based CA.
     7  //
     8  // This package is a work in progress and makes no API stability promises.
     9  package autocert
    10  
    11  import (
    12  	"bytes"
    13  	"context"
    14  	"crypto"
    15  	"crypto/ecdsa"
    16  	"crypto/elliptic"
    17  	"crypto/rand"
    18  	"crypto/rsa"
    19  	"crypto/tls"
    20  	"crypto/x509"
    21  	"crypto/x509/pkix"
    22  	"encoding/pem"
    23  	"errors"
    24  	"fmt"
    25  	"io"
    26  	mathrand "math/rand"
    27  	"net/http"
    28  	"strconv"
    29  	"strings"
    30  	"sync"
    31  	"time"
    32  
    33  	"golang.org/x/crypto/acme"
    34  )
    35  
    36  // pseudoRand is safe for concurrent use.
    37  var pseudoRand *lockedMathRand
    38  
    39  func init() {
    40  	src := mathrand.NewSource(timeNow().UnixNano())
    41  	pseudoRand = &lockedMathRand{rnd: mathrand.New(src)}
    42  }
    43  
    44  // AcceptTOS is a Manager.Prompt function that always returns true to
    45  // indicate acceptance of the CA's Terms of Service during account
    46  // registration.
    47  func AcceptTOS(tosURL string) bool { return true }
    48  
    49  // HostPolicy specifies which host names the Manager is allowed to respond to.
    50  // It returns a non-nil error if the host should be rejected.
    51  // The returned error is accessible via tls.Conn.Handshake and its callers.
    52  // See Manager's HostPolicy field and GetCertificate method docs for more details.
    53  type HostPolicy func(ctx context.Context, host string) error
    54  
    55  // HostWhitelist returns a policy where only the specified host names are allowed.
    56  // Only exact matches are currently supported. Subdomains, regexp or wildcard
    57  // will not match.
    58  func HostWhitelist(hosts ...string) HostPolicy {
    59  	whitelist := make(map[string]bool, len(hosts))
    60  	for _, h := range hosts {
    61  		whitelist[h] = true
    62  	}
    63  	return func(_ context.Context, host string) error {
    64  		if !whitelist[host] {
    65  			return errors.New("acme/autocert: host not configured")
    66  		}
    67  		return nil
    68  	}
    69  }
    70  
    71  // defaultHostPolicy is used when Manager.HostPolicy is not set.
    72  func defaultHostPolicy(context.Context, string) error {
    73  	return nil
    74  }
    75  
    76  // Manager is a stateful certificate manager built on top of acme.Client.
    77  // It obtains and refreshes certificates automatically,
    78  // as well as providing them to a TLS server via tls.Config.
    79  //
    80  // To preserve issued certificates and improve overall performance,
    81  // use a cache implementation of Cache. For instance, DirCache.
    82  type Manager struct {
    83  	// Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS).
    84  	// The registration may require the caller to agree to the CA's TOS.
    85  	// If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report
    86  	// whether the caller agrees to the terms.
    87  	//
    88  	// To always accept the terms, the callers can use AcceptTOS.
    89  	Prompt func(tosURL string) bool
    90  
    91  	// Cache optionally stores and retrieves previously-obtained certificates.
    92  	// If nil, certs will only be cached for the lifetime of the Manager.
    93  	//
    94  	// Manager passes the Cache certificates data encoded in PEM, with private/public
    95  	// parts combined in a single Cache.Put call, private key first.
    96  	Cache Cache
    97  
    98  	// HostPolicy controls which domains the Manager will attempt
    99  	// to retrieve new certificates for. It does not affect cached certs.
   100  	//
   101  	// If non-nil, HostPolicy is called before requesting a new cert.
   102  	// If nil, all hosts are currently allowed. This is not recommended,
   103  	// as it opens a potential attack where clients connect to a server
   104  	// by IP address and pretend to be asking for an incorrect host name.
   105  	// Manager will attempt to obtain a certificate for that host, incorrectly,
   106  	// eventually reaching the CA's rate limit for certificate requests
   107  	// and making it impossible to obtain actual certificates.
   108  	//
   109  	// See GetCertificate for more details.
   110  	HostPolicy HostPolicy
   111  
   112  	// RenewBefore optionally specifies how early certificates should
   113  	// be renewed before they expire.
   114  	//
   115  	// If zero, they're renewed 30 days before expiration.
   116  	RenewBefore time.Duration
   117  
   118  	// Client is used to perform low-level operations, such as account registration
   119  	// and requesting new certificates.
   120  	// If Client is nil, a zero-value acme.Client is used with acme.LetsEncryptURL
   121  	// directory endpoint and a newly-generated ECDSA P-256 key.
   122  	//
   123  	// Mutating the field after the first call of GetCertificate method will have no effect.
   124  	Client *acme.Client
   125  
   126  	// Email optionally specifies a contact email address.
   127  	// This is used by CAs, such as Let's Encrypt, to notify about problems
   128  	// with issued certificates.
   129  	//
   130  	// If the Client's account key is already registered, Email is not used.
   131  	Email string
   132  
   133  	// ForceRSA makes the Manager generate certificates with 2048-bit RSA keys.
   134  	//
   135  	// If false, a default is used. Currently the default
   136  	// is EC-based keys using the P-256 curve.
   137  	ForceRSA bool
   138  
   139  	clientMu sync.Mutex
   140  	client   *acme.Client // initialized by acmeClient method
   141  
   142  	stateMu sync.Mutex
   143  	state   map[string]*certState // keyed by domain name
   144  
   145  	// tokenCert is keyed by token domain name, which matches server name
   146  	// of ClientHello. Keys always have ".acme.invalid" suffix.
   147  	tokenCertMu sync.RWMutex
   148  	tokenCert   map[string]*tls.Certificate
   149  
   150  	// renewal tracks the set of domains currently running renewal timers.
   151  	// It is keyed by domain name.
   152  	renewalMu sync.Mutex
   153  	renewal   map[string]*domainRenewal
   154  }
   155  
   156  // GetCertificate implements the tls.Config.GetCertificate hook.
   157  // It provides a TLS certificate for hello.ServerName host, including answering
   158  // *.acme.invalid (TLS-SNI) challenges. All other fields of hello are ignored.
   159  //
   160  // If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting
   161  // a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation.
   162  // The error is propagated back to the caller of GetCertificate and is user-visible.
   163  // This does not affect cached certs. See HostPolicy field description for more details.
   164  func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
   165  	if m.Prompt == nil {
   166  		return nil, errors.New("acme/autocert: Manager.Prompt not set")
   167  	}
   168  
   169  	name := hello.ServerName
   170  	if name == "" {
   171  		return nil, errors.New("acme/autocert: missing server name")
   172  	}
   173  
   174  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
   175  	defer cancel()
   176  
   177  	// check whether this is a token cert requested for TLS-SNI challenge
   178  	if strings.HasSuffix(name, ".acme.invalid") {
   179  		m.tokenCertMu.RLock()
   180  		defer m.tokenCertMu.RUnlock()
   181  		if cert := m.tokenCert[name]; cert != nil {
   182  			return cert, nil
   183  		}
   184  		if cert, err := m.cacheGet(ctx, name); err == nil {
   185  			return cert, nil
   186  		}
   187  		// TODO: cache error results?
   188  		return nil, fmt.Errorf("acme/autocert: no token cert for %q", name)
   189  	}
   190  
   191  	// regular domain
   192  	name = strings.TrimSuffix(name, ".") // golang.org/issue/18114
   193  	cert, err := m.cert(ctx, name)
   194  	if err == nil {
   195  		return cert, nil
   196  	}
   197  	if err != ErrCacheMiss {
   198  		return nil, err
   199  	}
   200  
   201  	// first-time
   202  	if err := m.hostPolicy()(ctx, name); err != nil {
   203  		return nil, err
   204  	}
   205  	cert, err = m.createCert(ctx, name)
   206  	if err != nil {
   207  		return nil, err
   208  	}
   209  	m.cachePut(ctx, name, cert)
   210  	return cert, nil
   211  }
   212  
   213  // cert returns an existing certificate either from m.state or cache.
   214  // If a certificate is found in cache but not in m.state, the latter will be filled
   215  // with the cached value.
   216  func (m *Manager) cert(ctx context.Context, name string) (*tls.Certificate, error) {
   217  	m.stateMu.Lock()
   218  	if s, ok := m.state[name]; ok {
   219  		m.stateMu.Unlock()
   220  		s.RLock()
   221  		defer s.RUnlock()
   222  		return s.tlscert()
   223  	}
   224  	defer m.stateMu.Unlock()
   225  	cert, err := m.cacheGet(ctx, name)
   226  	if err != nil {
   227  		return nil, err
   228  	}
   229  	signer, ok := cert.PrivateKey.(crypto.Signer)
   230  	if !ok {
   231  		return nil, errors.New("acme/autocert: private key cannot sign")
   232  	}
   233  	if m.state == nil {
   234  		m.state = make(map[string]*certState)
   235  	}
   236  	s := &certState{
   237  		key:  signer,
   238  		cert: cert.Certificate,
   239  		leaf: cert.Leaf,
   240  	}
   241  	m.state[name] = s
   242  	go m.renew(name, s.key, s.leaf.NotAfter)
   243  	return cert, nil
   244  }
   245  
   246  // cacheGet always returns a valid certificate, or an error otherwise.
   247  // If a cached certficate exists but is not valid, ErrCacheMiss is returned.
   248  func (m *Manager) cacheGet(ctx context.Context, domain string) (*tls.Certificate, error) {
   249  	if m.Cache == nil {
   250  		return nil, ErrCacheMiss
   251  	}
   252  	data, err := m.Cache.Get(ctx, domain)
   253  	if err != nil {
   254  		return nil, err
   255  	}
   256  
   257  	// private
   258  	priv, pub := pem.Decode(data)
   259  	if priv == nil || !strings.Contains(priv.Type, "PRIVATE") {
   260  		return nil, ErrCacheMiss
   261  	}
   262  	privKey, err := parsePrivateKey(priv.Bytes)
   263  	if err != nil {
   264  		return nil, err
   265  	}
   266  
   267  	// public
   268  	var pubDER [][]byte
   269  	for len(pub) > 0 {
   270  		var b *pem.Block
   271  		b, pub = pem.Decode(pub)
   272  		if b == nil {
   273  			break
   274  		}
   275  		pubDER = append(pubDER, b.Bytes)
   276  	}
   277  	if len(pub) > 0 {
   278  		// Leftover content not consumed by pem.Decode. Corrupt. Ignore.
   279  		return nil, ErrCacheMiss
   280  	}
   281  
   282  	// verify and create TLS cert
   283  	leaf, err := validCert(domain, pubDER, privKey)
   284  	if err != nil {
   285  		return nil, ErrCacheMiss
   286  	}
   287  	tlscert := &tls.Certificate{
   288  		Certificate: pubDER,
   289  		PrivateKey:  privKey,
   290  		Leaf:        leaf,
   291  	}
   292  	return tlscert, nil
   293  }
   294  
   295  func (m *Manager) cachePut(ctx context.Context, domain string, tlscert *tls.Certificate) error {
   296  	if m.Cache == nil {
   297  		return nil
   298  	}
   299  
   300  	// contains PEM-encoded data
   301  	var buf bytes.Buffer
   302  
   303  	// private
   304  	switch key := tlscert.PrivateKey.(type) {
   305  	case *ecdsa.PrivateKey:
   306  		if err := encodeECDSAKey(&buf, key); err != nil {
   307  			return err
   308  		}
   309  	case *rsa.PrivateKey:
   310  		b := x509.MarshalPKCS1PrivateKey(key)
   311  		pb := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: b}
   312  		if err := pem.Encode(&buf, pb); err != nil {
   313  			return err
   314  		}
   315  	default:
   316  		return errors.New("acme/autocert: unknown private key type")
   317  	}
   318  
   319  	// public
   320  	for _, b := range tlscert.Certificate {
   321  		pb := &pem.Block{Type: "CERTIFICATE", Bytes: b}
   322  		if err := pem.Encode(&buf, pb); err != nil {
   323  			return err
   324  		}
   325  	}
   326  
   327  	return m.Cache.Put(ctx, domain, buf.Bytes())
   328  }
   329  
   330  func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error {
   331  	b, err := x509.MarshalECPrivateKey(key)
   332  	if err != nil {
   333  		return err
   334  	}
   335  	pb := &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
   336  	return pem.Encode(w, pb)
   337  }
   338  
   339  // createCert starts the domain ownership verification and returns a certificate
   340  // for that domain upon success.
   341  //
   342  // If the domain is already being verified, it waits for the existing verification to complete.
   343  // Either way, createCert blocks for the duration of the whole process.
   344  func (m *Manager) createCert(ctx context.Context, domain string) (*tls.Certificate, error) {
   345  	// TODO: maybe rewrite this whole piece using sync.Once
   346  	state, err := m.certState(domain)
   347  	if err != nil {
   348  		return nil, err
   349  	}
   350  	// state may exist if another goroutine is already working on it
   351  	// in which case just wait for it to finish
   352  	if !state.locked {
   353  		state.RLock()
   354  		defer state.RUnlock()
   355  		return state.tlscert()
   356  	}
   357  
   358  	// We are the first; state is locked.
   359  	// Unblock the readers when domain ownership is verified
   360  	// and the we got the cert or the process failed.
   361  	defer state.Unlock()
   362  	state.locked = false
   363  
   364  	der, leaf, err := m.authorizedCert(ctx, state.key, domain)
   365  	if err != nil {
   366  		return nil, err
   367  	}
   368  	state.cert = der
   369  	state.leaf = leaf
   370  	go m.renew(domain, state.key, state.leaf.NotAfter)
   371  	return state.tlscert()
   372  }
   373  
   374  // certState returns a new or existing certState.
   375  // If a new certState is returned, state.exist is false and the state is locked.
   376  // The returned error is non-nil only in the case where a new state could not be created.
   377  func (m *Manager) certState(domain string) (*certState, error) {
   378  	m.stateMu.Lock()
   379  	defer m.stateMu.Unlock()
   380  	if m.state == nil {
   381  		m.state = make(map[string]*certState)
   382  	}
   383  	// existing state
   384  	if state, ok := m.state[domain]; ok {
   385  		return state, nil
   386  	}
   387  
   388  	// new locked state
   389  	var (
   390  		err error
   391  		key crypto.Signer
   392  	)
   393  	if m.ForceRSA {
   394  		key, err = rsa.GenerateKey(rand.Reader, 2048)
   395  	} else {
   396  		key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   397  	}
   398  	if err != nil {
   399  		return nil, err
   400  	}
   401  
   402  	state := &certState{
   403  		key:    key,
   404  		locked: true,
   405  	}
   406  	state.Lock() // will be unlocked by m.certState caller
   407  	m.state[domain] = state
   408  	return state, nil
   409  }
   410  
   411  // authorizedCert starts domain ownership verification process and requests a new cert upon success.
   412  // The key argument is the certificate private key.
   413  func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, domain string) (der [][]byte, leaf *x509.Certificate, err error) {
   414  	// TODO: make m.verify retry or retry m.verify calls here
   415  	if err := m.verify(ctx, domain); err != nil {
   416  		return nil, nil, err
   417  	}
   418  	client, err := m.acmeClient(ctx)
   419  	if err != nil {
   420  		return nil, nil, err
   421  	}
   422  	csr, err := certRequest(key, domain)
   423  	if err != nil {
   424  		return nil, nil, err
   425  	}
   426  	der, _, err = client.CreateCert(ctx, csr, 0, true)
   427  	if err != nil {
   428  		return nil, nil, err
   429  	}
   430  	leaf, err = validCert(domain, der, key)
   431  	if err != nil {
   432  		return nil, nil, err
   433  	}
   434  	return der, leaf, nil
   435  }
   436  
   437  // verify starts a new identifier (domain) authorization flow.
   438  // It prepares a challenge response and then blocks until the authorization
   439  // is marked as "completed" by the CA (either succeeded or failed).
   440  //
   441  // verify returns nil iff the verification was successful.
   442  func (m *Manager) verify(ctx context.Context, domain string) error {
   443  	client, err := m.acmeClient(ctx)
   444  	if err != nil {
   445  		return err
   446  	}
   447  
   448  	// start domain authorization and get the challenge
   449  	authz, err := client.Authorize(ctx, domain)
   450  	if err != nil {
   451  		return err
   452  	}
   453  	// maybe don't need to at all
   454  	if authz.Status == acme.StatusValid {
   455  		return nil
   456  	}
   457  
   458  	// pick a challenge: prefer tls-sni-02 over tls-sni-01
   459  	// TODO: consider authz.Combinations
   460  	var chal *acme.Challenge
   461  	for _, c := range authz.Challenges {
   462  		if c.Type == "tls-sni-02" {
   463  			chal = c
   464  			break
   465  		}
   466  		if c.Type == "tls-sni-01" {
   467  			chal = c
   468  		}
   469  	}
   470  	if chal == nil {
   471  		return errors.New("acme/autocert: no supported challenge type found")
   472  	}
   473  
   474  	// create a token cert for the challenge response
   475  	var (
   476  		cert tls.Certificate
   477  		name string
   478  	)
   479  	switch chal.Type {
   480  	case "tls-sni-01":
   481  		cert, name, err = client.TLSSNI01ChallengeCert(chal.Token)
   482  	case "tls-sni-02":
   483  		cert, name, err = client.TLSSNI02ChallengeCert(chal.Token)
   484  	default:
   485  		err = fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type)
   486  	}
   487  	if err != nil {
   488  		return err
   489  	}
   490  	m.putTokenCert(ctx, name, &cert)
   491  	defer func() {
   492  		// verification has ended at this point
   493  		// don't need token cert anymore
   494  		go m.deleteTokenCert(name)
   495  	}()
   496  
   497  	// ready to fulfill the challenge
   498  	if _, err := client.Accept(ctx, chal); err != nil {
   499  		return err
   500  	}
   501  	// wait for the CA to validate
   502  	_, err = client.WaitAuthorization(ctx, authz.URI)
   503  	return err
   504  }
   505  
   506  // putTokenCert stores the cert under the named key in both m.tokenCert map
   507  // and m.Cache.
   508  func (m *Manager) putTokenCert(ctx context.Context, name string, cert *tls.Certificate) {
   509  	m.tokenCertMu.Lock()
   510  	defer m.tokenCertMu.Unlock()
   511  	if m.tokenCert == nil {
   512  		m.tokenCert = make(map[string]*tls.Certificate)
   513  	}
   514  	m.tokenCert[name] = cert
   515  	m.cachePut(ctx, name, cert)
   516  }
   517  
   518  // deleteTokenCert removes the token certificate for the specified domain name
   519  // from both m.tokenCert map and m.Cache.
   520  func (m *Manager) deleteTokenCert(name string) {
   521  	m.tokenCertMu.Lock()
   522  	defer m.tokenCertMu.Unlock()
   523  	delete(m.tokenCert, name)
   524  	if m.Cache != nil {
   525  		m.Cache.Delete(context.Background(), name)
   526  	}
   527  }
   528  
   529  // renew starts a cert renewal timer loop, one per domain.
   530  //
   531  // The loop is scheduled in two cases:
   532  // - a cert was fetched from cache for the first time (wasn't in m.state)
   533  // - a new cert was created by m.createCert
   534  //
   535  // The key argument is a certificate private key.
   536  // The exp argument is the cert expiration time (NotAfter).
   537  func (m *Manager) renew(domain string, key crypto.Signer, exp time.Time) {
   538  	m.renewalMu.Lock()
   539  	defer m.renewalMu.Unlock()
   540  	if m.renewal[domain] != nil {
   541  		// another goroutine is already on it
   542  		return
   543  	}
   544  	if m.renewal == nil {
   545  		m.renewal = make(map[string]*domainRenewal)
   546  	}
   547  	dr := &domainRenewal{m: m, domain: domain, key: key}
   548  	m.renewal[domain] = dr
   549  	dr.start(exp)
   550  }
   551  
   552  // stopRenew stops all currently running cert renewal timers.
   553  // The timers are not restarted during the lifetime of the Manager.
   554  func (m *Manager) stopRenew() {
   555  	m.renewalMu.Lock()
   556  	defer m.renewalMu.Unlock()
   557  	for name, dr := range m.renewal {
   558  		delete(m.renewal, name)
   559  		dr.stop()
   560  	}
   561  }
   562  
   563  func (m *Manager) accountKey(ctx context.Context) (crypto.Signer, error) {
   564  	const keyName = "acme_account.key"
   565  
   566  	genKey := func() (*ecdsa.PrivateKey, error) {
   567  		return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   568  	}
   569  
   570  	if m.Cache == nil {
   571  		return genKey()
   572  	}
   573  
   574  	data, err := m.Cache.Get(ctx, keyName)
   575  	if err == ErrCacheMiss {
   576  		key, err := genKey()
   577  		if err != nil {
   578  			return nil, err
   579  		}
   580  		var buf bytes.Buffer
   581  		if err := encodeECDSAKey(&buf, key); err != nil {
   582  			return nil, err
   583  		}
   584  		if err := m.Cache.Put(ctx, keyName, buf.Bytes()); err != nil {
   585  			return nil, err
   586  		}
   587  		return key, nil
   588  	}
   589  	if err != nil {
   590  		return nil, err
   591  	}
   592  
   593  	priv, _ := pem.Decode(data)
   594  	if priv == nil || !strings.Contains(priv.Type, "PRIVATE") {
   595  		return nil, errors.New("acme/autocert: invalid account key found in cache")
   596  	}
   597  	return parsePrivateKey(priv.Bytes)
   598  }
   599  
   600  func (m *Manager) acmeClient(ctx context.Context) (*acme.Client, error) {
   601  	m.clientMu.Lock()
   602  	defer m.clientMu.Unlock()
   603  	if m.client != nil {
   604  		return m.client, nil
   605  	}
   606  
   607  	client := m.Client
   608  	if client == nil {
   609  		client = &acme.Client{DirectoryURL: acme.LetsEncryptURL}
   610  	}
   611  	if client.Key == nil {
   612  		var err error
   613  		client.Key, err = m.accountKey(ctx)
   614  		if err != nil {
   615  			return nil, err
   616  		}
   617  	}
   618  	var contact []string
   619  	if m.Email != "" {
   620  		contact = []string{"mailto:" + m.Email}
   621  	}
   622  	a := &acme.Account{Contact: contact}
   623  	_, err := client.Register(ctx, a, m.Prompt)
   624  	if ae, ok := err.(*acme.Error); err == nil || ok && ae.StatusCode == http.StatusConflict {
   625  		// conflict indicates the key is already registered
   626  		m.client = client
   627  		err = nil
   628  	}
   629  	return m.client, err
   630  }
   631  
   632  func (m *Manager) hostPolicy() HostPolicy {
   633  	if m.HostPolicy != nil {
   634  		return m.HostPolicy
   635  	}
   636  	return defaultHostPolicy
   637  }
   638  
   639  func (m *Manager) renewBefore() time.Duration {
   640  	if m.RenewBefore > renewJitter {
   641  		return m.RenewBefore
   642  	}
   643  	return 720 * time.Hour // 30 days
   644  }
   645  
   646  // certState is ready when its mutex is unlocked for reading.
   647  type certState struct {
   648  	sync.RWMutex
   649  	locked bool              // locked for read/write
   650  	key    crypto.Signer     // private key for cert
   651  	cert   [][]byte          // DER encoding
   652  	leaf   *x509.Certificate // parsed cert[0]; always non-nil if cert != nil
   653  }
   654  
   655  // tlscert creates a tls.Certificate from s.key and s.cert.
   656  // Callers should wrap it in s.RLock() and s.RUnlock().
   657  func (s *certState) tlscert() (*tls.Certificate, error) {
   658  	if s.key == nil {
   659  		return nil, errors.New("acme/autocert: missing signer")
   660  	}
   661  	if len(s.cert) == 0 {
   662  		return nil, errors.New("acme/autocert: missing certificate")
   663  	}
   664  	return &tls.Certificate{
   665  		PrivateKey:  s.key,
   666  		Certificate: s.cert,
   667  		Leaf:        s.leaf,
   668  	}, nil
   669  }
   670  
   671  // certRequest creates a certificate request for the given common name cn
   672  // and optional SANs.
   673  func certRequest(key crypto.Signer, cn string, san ...string) ([]byte, error) {
   674  	req := &x509.CertificateRequest{
   675  		Subject:  pkix.Name{CommonName: cn},
   676  		DNSNames: san,
   677  	}
   678  	return x509.CreateCertificateRequest(rand.Reader, req, key)
   679  }
   680  
   681  // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
   682  // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
   683  // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
   684  //
   685  // Inspired by parsePrivateKey in crypto/tls/tls.go.
   686  func parsePrivateKey(der []byte) (crypto.Signer, error) {
   687  	if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
   688  		return key, nil
   689  	}
   690  	if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
   691  		switch key := key.(type) {
   692  		case *rsa.PrivateKey:
   693  			return key, nil
   694  		case *ecdsa.PrivateKey:
   695  			return key, nil
   696  		default:
   697  			return nil, errors.New("acme/autocert: unknown private key type in PKCS#8 wrapping")
   698  		}
   699  	}
   700  	if key, err := x509.ParseECPrivateKey(der); err == nil {
   701  		return key, nil
   702  	}
   703  
   704  	return nil, errors.New("acme/autocert: failed to parse private key")
   705  }
   706  
   707  // validCert parses a cert chain provided as der argument and verifies the leaf, der[0],
   708  // corresponds to the private key, as well as the domain match and expiration dates.
   709  // It doesn't do any revocation checking.
   710  //
   711  // The returned value is the verified leaf cert.
   712  func validCert(domain string, der [][]byte, key crypto.Signer) (leaf *x509.Certificate, err error) {
   713  	// parse public part(s)
   714  	var n int
   715  	for _, b := range der {
   716  		n += len(b)
   717  	}
   718  	pub := make([]byte, n)
   719  	n = 0
   720  	for _, b := range der {
   721  		n += copy(pub[n:], b)
   722  	}
   723  	x509Cert, err := x509.ParseCertificates(pub)
   724  	if len(x509Cert) == 0 {
   725  		return nil, errors.New("acme/autocert: no public key found")
   726  	}
   727  	// verify the leaf is not expired and matches the domain name
   728  	leaf = x509Cert[0]
   729  	now := timeNow()
   730  	if now.Before(leaf.NotBefore) {
   731  		return nil, errors.New("acme/autocert: certificate is not valid yet")
   732  	}
   733  	if now.After(leaf.NotAfter) {
   734  		return nil, errors.New("acme/autocert: expired certificate")
   735  	}
   736  	if err := leaf.VerifyHostname(domain); err != nil {
   737  		return nil, err
   738  	}
   739  	// ensure the leaf corresponds to the private key
   740  	switch pub := leaf.PublicKey.(type) {
   741  	case *rsa.PublicKey:
   742  		prv, ok := key.(*rsa.PrivateKey)
   743  		if !ok {
   744  			return nil, errors.New("acme/autocert: private key type does not match public key type")
   745  		}
   746  		if pub.N.Cmp(prv.N) != 0 {
   747  			return nil, errors.New("acme/autocert: private key does not match public key")
   748  		}
   749  	case *ecdsa.PublicKey:
   750  		prv, ok := key.(*ecdsa.PrivateKey)
   751  		if !ok {
   752  			return nil, errors.New("acme/autocert: private key type does not match public key type")
   753  		}
   754  		if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 {
   755  			return nil, errors.New("acme/autocert: private key does not match public key")
   756  		}
   757  	default:
   758  		return nil, errors.New("acme/autocert: unknown public key algorithm")
   759  	}
   760  	return leaf, nil
   761  }
   762  
   763  func retryAfter(v string) time.Duration {
   764  	if i, err := strconv.Atoi(v); err == nil {
   765  		return time.Duration(i) * time.Second
   766  	}
   767  	if t, err := http.ParseTime(v); err == nil {
   768  		return t.Sub(timeNow())
   769  	}
   770  	return time.Second
   771  }
   772  
   773  type lockedMathRand struct {
   774  	sync.Mutex
   775  	rnd *mathrand.Rand
   776  }
   777  
   778  func (r *lockedMathRand) int63n(max int64) int64 {
   779  	r.Lock()
   780  	n := r.rnd.Int63n(max)
   781  	r.Unlock()
   782  	return n
   783  }
   784  
   785  // for easier testing
   786  var timeNow = time.Now