forked from OneOfOne/gserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocert.go
180 lines (144 loc) · 4.04 KB
/
autocert.go
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package gserv
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"os"
"strings"
"sync"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/net/idna"
)
// RunAutoCert enables automatic support for LetsEncrypt, using the optional passed domains list.
// certCacheDir is where the certificates will be cached, defaults to "./autocert".
// Note that it must always run on *BOTH* ":80" and ":443" so the addr param is omitted.
func (s *Server) RunAutoCert(ctx context.Context, certCacheDir string, domains ...string) error {
if certCacheDir == "" {
certCacheDir = "./autocert"
}
if err := os.MkdirAll(certCacheDir, 0o700); err != nil {
return fmt.Errorf("couldn't create cert cache dir: %v", err)
}
m := &autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: autocert.DirCache(certCacheDir),
}
if len(domains) > 0 {
m.HostPolicy = autocert.HostWhitelist(domains...)
}
srv := s.newHTTPServer(ctx, ":https", false)
tlsCfg := m.TLSConfig()
tlsCfg.MinVersion = tls.VersionTLS12
srv.TLSConfig = tlsCfg
s.serversMux.Lock()
s.servers = append(s.servers, srv)
s.serversMux.Unlock()
go func() {
if err := http.ListenAndServe(":80", m.HTTPHandler(nil)); err != nil {
s.Logf("gserv: autocert on :80 error: %v", err)
}
}()
return srv.ListenAndServeTLS("", "")
}
func NewAutoCertHosts(hosts ...string) *AutoCertHosts {
return &AutoCertHosts{
m: makeHosts(hosts...),
}
}
type AutoCertHosts struct {
mux sync.RWMutex
m map[string]struct{}
}
func (a *AutoCertHosts) Set(hosts ...string) {
m := makeHosts(hosts...)
a.mux.Lock()
a.m = m
a.mux.Unlock()
}
func makeHosts(hosts ...string) (m map[string]struct{}) {
var e struct{}
m = make(map[string]struct{}, len(hosts)+1)
for _, h := range hosts {
// copied from autocert.HostWhiteList
if h, err := idna.Lookup.ToASCII(h); err == nil {
m[h] = e
}
}
return
}
func (a *AutoCertHosts) Contains(host string) bool {
a.mux.RLock()
_, ok := a.m[strings.ToLower(host)]
a.mux.RUnlock()
return ok
}
func (a *AutoCertHosts) IsAllowed(_ context.Context, host string) error {
if a.Contains(host) {
return nil
}
return fmt.Errorf("gserv/autocert: host %q not configured in AutoCertHosts", host)
}
// RunTLSAndAuto allows using custom certificates and autocert together.
// It will always listen on both :80 and :443
func (s *Server) RunTLSAndAuto(ctx context.Context, certCacheDir string, certPairs []CertPair, hosts *AutoCertHosts) error {
if hosts == nil {
return fmt.Errorf("gserv/autocert: hosts can't be nil")
}
m := &autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: hosts.IsAllowed,
}
m.HostPolicy = hosts.IsAllowed
if certCacheDir == "" {
certCacheDir = "./autocert"
}
if err := os.MkdirAll(certCacheDir, 0o700); err != nil {
return fmt.Errorf("couldn't create cert cache dir (%s): %v", certCacheDir, err)
}
m.Cache = autocert.DirCache(certCacheDir)
srv := s.newHTTPServer(ctx, ":https", false)
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
PreferServerCipherSuites: true,
NextProtos: []string{
"h2", "http/1.1", // enable HTTP/2
acme.ALPNProto, // enable tls-alpn ACME challenges
},
GetCertificate: m.GetCertificate,
}
for _, cp := range certPairs {
cert, err := tls.LoadX509KeyPair(cp.CertFile, cp.KeyFile)
if err != nil {
return fmt.Errorf("%s: %v", cp.CertFile, err)
}
cfg.Certificates = append(cfg.Certificates, cert)
}
cfg.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
crt, err := m.GetCertificate(hello)
if err == nil {
return crt, err
}
// fallback to default impl tls impl
return nil, nil
}
srv.TLSConfig = cfg
s.serversMux.Lock()
s.servers = append(s.servers, srv)
s.serversMux.Unlock()
ch := make(chan error, 2)
go func() {
if err := http.ListenAndServe(":80", m.HTTPHandler(nil)); err != nil {
s.Logf("gserv: autocert on :80 error: %v", err)
ch <- err
}
}()
go func() {
if err := srv.ListenAndServeTLS("", ""); err != nil {
s.Logf("gserv: autocert on :443 error: %v", err)
ch <- err
}
}()
return <-ch
}