aboutsummaryrefslogtreecommitdiff
path: root/solve_tls.go
blob: 4390539c43c03a9ca0e37b7a07f64fd10ea0e1d8 (plain)
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
98
99
100
101
102
103
104
105
106
package acme

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/hex"
	"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(sniName(""))
	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 s.ListenAndServeTLS("", "")
	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)
	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,
		Subject: pkix.Name{
			Organization: []string{"Acme Co"},
		},
		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 sniName(keyAuth string) string {
	hash := sha256.Sum256([]byte(keyAuth))
	z := hex.EncodeToString(hash[:])
	return z[:32] + "." + z[32:] + ".acme.invalid"
}

func (s *tlsSolver) Solve(_, keyAuth string) error {
	log.Println("solve tls")
	name := sniName(keyAuth)
	crt, err := newCert(name)
	if err != nil {
		return err
	}
	s.sni[name] = &crt
	return nil
}

func (s *tlsSolver) Solved() error {
	return nil
}