forked from rekby/lets-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
acme.go
430 lines (371 loc) · 13.3 KB
/
acme.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
package main
// from time to time see https://godoc.org/golang.org/x/crypto/acme/autocert
// it isn't ready for usage now, but can simple code in future.
import (
"crypto/rsa"
"context"
cryptorand "crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"github.com/Sirupsen/logrus"
"github.com/hlandau/acme/acmeapi"
"github.com/hlandau/acme/acmeapi/acmeutils"
"strings"
"sync"
"time"
)
const (
SNI01_EXPIRE_TOKEN time.Duration = time.Minute * 10
ACME_DOMAIN_SUFFIX = ".acme.invalid"
)
type acmeStruct struct {
serverAddress string
privateKey *rsa.PrivateKey
acmePool *acmeClientPool
timeToRenew time.Duration
mutex *sync.Mutex
authDomainsMutex *sync.Mutex
authDomains map[string]time.Time
backgroundCertsObtain map[string]*sync.Mutex // sync for obtain only once certificate for the domain same time
}
func (this *acmeStruct) authDomainCheck(domain string) bool {
this.authDomainsMutex.Lock()
defer this.authDomainsMutex.Unlock()
logrus.Debug("Check acme auth domain:", domain)
_, ok := this.authDomains[domain]
return ok
}
func (this *acmeStruct) authDomainDelete(domain string) {
this.authDomainsMutex.Lock()
defer this.authDomainsMutex.Unlock()
logrus.Debug("Delete acme auth domain:", domain)
delete(this.authDomains, domain)
}
func (this *acmeStruct) authDomainPut(domain string) {
this.authDomainsMutex.Lock()
defer this.authDomainsMutex.Unlock()
logrus.Debug("Put acme auth domain:", domain)
this.authDomains[domain] = time.Now().Add(SNI01_EXPIRE_TOKEN)
}
// return ok domains for create cert. Order or returned domains unspecified.
func (this *acmeStruct) checkDomains(ctx context.Context, domains []string)[]string{
logrus.Debugf("Check allowable of domains for: %v", domains)
wg := &sync.WaitGroup{}
wg.Add(len(domains))
allowed := make(chan string, len(domains))
for _, domain := range domains {
go func(check_domain string){
defer func() {
err := recover()
if err != nil {
logrus.Errorf("Have panic while check domain '%v': %v", check_domain, err)
}
wg.Done()
}()
if domainHasLocalIP(ctx, check_domain) {
allowed <- check_domain
}
}(domain)
}
go func(){
wg.Wait()
close(allowed)
}()
allowedDomains := make([]string, 0, len(domains))
for domain := range allowed {
allowedDomains = append(allowedDomains, domain)
}
return allowedDomains
}
func (this *acmeStruct) Cleanup() {
this.mutex.Lock()
defer this.mutex.Unlock()
now := time.Now()
for token, expire := range this.authDomains {
if expire.Before(now) {
delete(this.authDomains, token)
}
}
}
func (this *acmeStruct) CleanupTimer() {
this.Cleanup()
time.AfterFunc(SNI01_EXPIRE_TOKEN, this.CleanupTimer)
}
func (this *acmeStruct) authorizeDomain(ctx context.Context, domain string) error {
client, err := this.acmePool.Get(ctx)
if client != nil {
defer this.acmePool.Put(client)
}
if err != nil {
logrus.Errorf("Can't get acme client for authorize domain '%v': %v", domain, err)
return err
}
var auth *acmeapi.Authorization
for i := 0; i < TRY_COUNT; i++ {
logrus.Debugf("Create new authorization for domain '%v'", domain)
auth, err = client.NewAuthorization(domain, ctx)
if err == nil {
break
} else {
logrus.Infof("Can't create new authorization for domain '%v': %v", domain, err)
time.Sleep(RETRY_SLEEP)
}
}
if err == nil {
logrus.Infof("Create authorization for domain '%v'", domain)
} else {
logrus.Errorf("Can't create new authorization for domain '%v': %v", domain, err)
return errors.New("Can't create new authorization for domain")
}
if logrus.GetLevel() >= logrus.DebugLevel {
challengeTypes := make([]string, len(auth.Challenges))
for i := range auth.Challenges {
challengeTypes[i] = auth.Challenges[i].Type
}
logrus.Debugf("Challenge types for domain '%v': %v. Challenge combinations: %v", domain, challengeTypes, auth.Combinations)
}
canAuthorize := false
var challenge *acmeapi.Challenge
for _, cmb := range auth.Combinations {
if len(cmb) == 1 && auth.Challenges[cmb[0]].Type == "tls-sni-01" {
canAuthorize = true
challenge = auth.Challenges[cmb[0]]
break
}
}
if !canAuthorize {
logrus.Errorf("Can't find good challange combination for domain: '%v'", domain)
return errors.New("Can't find good challange combination")
}
acmeHostName, err := acmeutils.TLSSNIHostname(this.privateKey, challenge.Token)
if err == nil {
logrus.Debugf("Create acme-auth hostname for domain '%v': %v", domain, acmeHostName)
} else {
logrus.Errorf("Can't create acme domain for domain '%v' token '%v': %v", domain, challenge.Token, err)
return errors.New("Can't create acme domain")
}
this.authDomainPut(acmeHostName)
// defer this.authDomainDelete(acmeHostName) // no detete auth domain - it will be cleaned up be timeout.
// it need for check authDomain while create cert - out of the function
logrus.Debugf("Create challenge response for domain '%v'", domain)
challengeResponse, err := acmeutils.ChallengeResponseJSON(this.privateKey, challenge.Token, challenge.Type)
if err == nil {
//pass
} else {
logrus.Errorf("Can't create challenge response for domain '%v', token '%v', challenge type %v: %v",
domain, challenge.Token, challenge.Type, err)
return errors.New("Can't create challenge response")
}
for i := 0; i < TRY_COUNT; i++ {
logrus.Debugf("Respond to challenge for domain '%v'", domain)
err = client.RespondToChallenge(challenge, challengeResponse, this.privateKey, ctx)
if err == nil {
break
} else {
logrus.Info("Can't send response for challenge of domain '%v': %v", domain, err)
time.Sleep(RETRY_SLEEP)
}
}
if err == nil {
logrus.Debugf("Send challenge response for domain '%v'", domain)
} else {
logrus.Errorf("Can't send response for challenge of domain '%v': %v", domain, err)
return errors.New("Can't send response for challenge")
}
for i := 0; i < TRY_COUNT; i++ {
logrus.Debugf("Load challenge for domain '%v'", domain)
err = client.LoadChallenge(challenge, ctx)
if err == nil {
break
} else {
logrus.Infof("Can't load challenge for domain '%v': %v", domain, err)
time.Sleep(RETRY_SLEEP)
}
}
if err == nil {
// pass
} else {
logrus.Errorf("Can't load challenge for domain '%v': %v", domain, err)
return errors.New("Can't load challenge")
}
return nil
}
/*
Create a certificate for domains (all domains in one certificate).
If can't create certificate for some of domains - certificate will be created for subset of domains.
Caller have to check ok domains in cert.Leaf.DNSNames
if main_domain != "" - return cert only if it contains main_domain.
Doesn't try to obtain cert if check of main_domain is bad or can't authorized it.
*/
func (this *acmeStruct) CreateCertificate(ctx context.Context, domains []string, main_domain string) (cert *tls.Certificate, err error) {
// Check suffix for avoid mutex sync in DeleteAcmeAuthDomain
if len(domains) == 1 && strings.HasSuffix(domains[0], ACME_DOMAIN_SUFFIX) {
logrus.Debugf("Detect auth-domain mode for domain '%v'", domains[0])
if this.authDomainCheck(domains[0]) {
logrus.Debugf("Return self-signed certificate for domain '%v'", domains[0])
return this.createCertificateSelfSigned(domains[0])
} else {
logrus.Debugf("Detect auth-domain is not present in list '%v'", domains[0])
return nil, errors.New("Not allowed auth-domain")
}
}
domainsForCert := this.checkDomains(ctx, domains)
if len(domainsForCert) == 0 {
return nil, errors.New("Domains is bad by self-check")
}
if main_domain != "" && !containString(domainsForCert, main_domain) {
return nil, errors.New("Main domain '%v' doesn't allowed by domainsCheck")
}
return this.createCertificateAcme(ctx, domainsForCert, main_domain)
}
func (this *acmeStruct) createCertificateAcme(ctx context.Context, domains []string, main_domain string) (cert *tls.Certificate, err error) {
authorizedDomains := make([]string, 0, len(domains))
authorizedDomainsChan := make(chan string, len(domains))
wg := &sync.WaitGroup{}
wg.Add(len(domains))
for _, domain := range domains {
go func(auth_domain string){
defer func(){
err := recover()
if err != nil {
logrus.Errorf("Panic while authorize domain '%v': %v", auth_domain, err)
}
wg.Done()
}()
auth_err := this.authorizeDomain(ctx, auth_domain)
if auth_err == nil {
authorizedDomainsChan <- auth_domain
} else {
logrus.Infof("Can't authorize domain '%v': %v", auth_domain, auth_err)
}
}(domain)
}
go func(){
wg.Wait()
close(authorizedDomainsChan)
}()
for domain := range authorizedDomainsChan {
authorizedDomains = append(authorizedDomains, domain)
}
if main_domain != "" && !containString(authorizedDomains, main_domain){
logrus.Info("Authorized domains '%v' doesn't contain main domain '%v'", authorizedDomains, main_domain)
return nil, errors.New("Authorized domains doesn't contain main domain")
}
// sort domains
for i := 0; i < len(authorizedDomains)-1; i++{
l := strings.ToLower(authorizedDomains[i])
r := strings.ToLower(authorizedDomains[i+1])
// www. - to end, other - alphabet
if strings.HasPrefix(l, "www.") && !strings.HasPrefix(r, "www.") || l > r {
tmp := authorizedDomains[i]
authorizedDomains[i] = authorizedDomains[i+1]
authorizedDomains[i+1] = tmp
}
}
if len(authorizedDomains) == 0 {
logrus.Info("Can't authorize any domains from '%v'", domains)
return nil, errors.New("Can't authorize domains")
}
client, err := this.acmePool.Get(ctx)
if client != nil {
defer this.acmePool.Put(client)
}
if err != nil {
logrus.Errorf("Can't get acme client from pool for domains '%v': %v", authorizedDomains, err)
return nil, err
}
// Generate CSR
certKey, err := rsa.GenerateKey(cryptorand.Reader, PRIVATE_KEY_BITS)
if err == nil {
logrus.Debugf("Create private key for domains '%v'", authorizedDomains)
} else {
logrus.Errorf("Can't create rsa key for domain '%v': %v", err)
return nil, errors.New("Can't create rsa key")
}
certRequest := &x509.CertificateRequest{
SignatureAlgorithm: x509.SHA256WithRSA,
PublicKeyAlgorithm: x509.RSA,
PublicKey: &certKey.PublicKey,
Subject: pkix.Name{CommonName: authorizedDomains[0]},
DNSNames: authorizedDomains,
}
logrus.Debugf("Create CSR for domains '%v'", authorizedDomains)
csrDER, err := x509.CreateCertificateRequest(cryptorand.Reader, certRequest, certKey)
if err == nil {
logrus.Debugf("Created CSR for domains '%v'", authorizedDomains)
} else {
logrus.Errorf("Can't create csr for domains '%v': %v", authorizedDomains, err)
return nil, errors.New("Can't create csr")
}
var certResponse *acmeapi.Certificate
for i := 0; i < TRY_COUNT; i++ {
logrus.Debugf("Certificate request for domains '%v'", authorizedDomains)
certResponse, err = client.RequestCertificate(csrDER, ctx)
if err == nil {
break
} else {
logrus.Infof("Can't get certificate for domains '%v': %v (response: %#v)", authorizedDomains, err, certResponse)
time.Sleep(RETRY_SLEEP)
}
}
if err == nil {
logrus.Infof("Get certificate for domains '%v'", authorizedDomains)
} else {
logrus.Errorf("Can't get certificate for domains '%v': %v", authorizedDomains, err)
return nil, errors.New("Can't request certificate")
}
pemEncode := func(b []byte, t string) []byte {
return pem.EncodeToMemory(&pem.Block{Bytes: b, Type: t})
}
certPEM := pem.EncodeToMemory(&pem.Block{Bytes: certResponse.Certificate, Type: "CERTIFICATE"})
for _, extraCert := range certResponse.ExtraCertificates {
extraCertPEM := pem.EncodeToMemory(&pem.Block{Bytes: extraCert, Type: "CERTIFICATE"})
certPEM = append(certPEM, '\n')
certPEM = append(certPEM, extraCertPEM...)
}
logrus.Debugf("CERT PEM:\n%s", certPEM)
certKeyPEM := pemEncode(x509.MarshalPKCS1PrivateKey(certKey), "RSA PRIVATE KEY")
tmpCert, err := tls.X509KeyPair(certPEM, certKeyPEM)
logrus.Debugf("Parsed cert count for domains '%v': %v", authorizedDomains, len(tmpCert.Certificate))
if err == nil {
logrus.Infof("Cert parsed for domains '%v'", authorizedDomains)
cert = &tmpCert
} else {
logrus.Errorf("Can't parse cert for domains '%v': %v", authorizedDomains, err)
return nil, errors.New("Can't parse cert for domain")
}
if len(cert.Certificate) > 0 {
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err == nil {
logrus.Debugf("Leaf certificate parsed from domains '%v'", authorizedDomains)
} else {
logrus.Errorf("Can't parse leaf certificate for domains '%v': %v", authorizedDomains, err)
cert.Leaf = nil
}
} else {
logrus.Errorf("Certificate for domains doesn't contain certificates '%v'", authorizedDomains)
return nil, errors.New("Certificate for domain doesn't contain certificates")
}
return cert, nil
}
func (this *acmeStruct) createCertificateSelfSigned(domain string) (cert *tls.Certificate, err error) {
derCert, privateKey, err := acmeutils.CreateTLSSNICertificate(domain)
if err != nil {
logrus.Errorf("Can't create tls-sni-01 self-signed certificate for '%v': %v", domain, err)
return nil, err
}
cert = &tls.Certificate{}
cert.Certificate = [][]byte{derCert}
cert.PrivateKey = privateKey
return cert, nil
}
func (this *acmeStruct) Init() {
this.acmePool = NewAcmeClientPool(*parallelAcmeRequests, this.privateKey, this.serverAddress)
this.mutex = &sync.Mutex{}
this.authDomainsMutex = &sync.Mutex{}
this.authDomains = make(map[string]time.Time)
this.CleanupTimer()
}