1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
package acme
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"errors"
"log"
"math/big"
"net/http"
"time"
)
var errNoCert = errors.New("no cert")
type tlsSolver struct {
http.Server
sni map[string]*tls.Certificate
}
func (s *tlsSolver) getCert(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
if crt, ok := s.sni[h.ServerName]; ok {
return crt, nil
}
return nil, errNoCert
}
func NewTLSSolver(addr string) (Solver, error) {
// we need at least one cert
dummy, err := newCert("dummy" + AcmeInvalid)
if err != nil {
return nil, err
}
s := &tlsSolver{
Server: http.Server{Addr: addr},
sni: make(map[string]*tls.Certificate),
}
config := &tls.Config{
Certificates: []tls.Certificate{dummy},
GetCertificate: s.getCert,
}
s.Server.TLSConfig = config
go func() {
if err := s.ListenAndServeTLS("", ""); err != nil {
log.Fatal(err)
}
}()
return s, nil
}
func newCert(domain string) (tls.Certificate, error) {
fail := func(err error) (tls.Certificate, error) {
return tls.Certificate{}, err
}
key, err := rsa.GenerateKey(rand.Reader, 2048) // NewKey(2048)
if err != nil {
return fail(err)
}
serialLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serial, err := rand.Int(rand.Reader, serialLimit)
if err != nil {
return fail(err)
}
tmpl := x509.Certificate{
SerialNumber: serial,
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
SignatureAlgorithm: x509.SHA256WithRSA,
DNSNames: []string{domain},
}
crt, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, key.Public(), key)
if err != nil {
return fail(err)
}
return tls.Certificate{
Certificate: [][]byte{crt},
PrivateKey: key,
}, nil
}
func (s *tlsSolver) Solve(ch Challenge) error {
name := ch.SNIName()
log.Println("solve tls", name)
crt, err := newCert(name)
if err != nil {
return err
}
s.sni[name] = &crt
return nil
}
func (tlsSolver) Solved() error { return nil }
func (tlsSolver) Type() ChalType { return ChallengeTLS }
|