aboutsummaryrefslogtreecommitdiff
path: root/solve_tls.go
blob: 2017cd71876cfcdffd2fcfea1d04c8269ce9f0c1 (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
package acme

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/hex"
	"log"
	"math/big"
	"net/http"
	"time"
)

type tlsSolver struct {
	http.Server
}

func NewTLSSolver(addr string) Solver {
	s := new(tlsSolver)
	s.Server = http.Server{
		Addr:      addr,
		TLSConfig: &tls.Config{},
	}
	go s.ListenAndServe()
	return s
}

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")
	crt, err := newCert(sniName(keyAuth))
	if err != nil {
		return err
	}
	log.Println(crt)
	return errNotImplemented
}

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