-
Notifications
You must be signed in to change notification settings - Fork 479
Expand file tree
/
Copy pathacme_certbot.go
More file actions
165 lines (148 loc) · 5.02 KB
/
Copy pathacme_certbot.go
File metadata and controls
165 lines (148 loc) · 5.02 KB
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
package acme
import (
"context"
"crypto/tls"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/caddyserver/certmagic"
"github.com/pkg/errors"
"github.com/projectdiscovery/gologger"
"go.uber.org/zap"
)
// DefaultResolvers trusted
var DefaultResolvers = []string{
"1.1.1.1:53",
"1.0.0.1:53",
"8.8.8.8:53",
"8.8.4.4:53",
}
// CleanupStorage perform cleanup routines tasks
func CleanupStorage() {
cleanupOptions := certmagic.CleanStorageOptions{OCSPStaples: true}
_ = certmagic.CleanStorage(context.Background(), certmagic.Default.Storage, cleanupOptions)
}
type CertificateFiles struct {
CertPath string
PrivKeyPath string
}
// NewCertmagicConfig creates and configures a *certmagic.Config for ACME DNS-01 challenge.
// The returned config can be reused across multiple HandleWildcardCertificates calls.
func NewCertmagicConfig(email string, store *Provider, debug bool, customResolvers []string) (*certmagic.Config, error) {
logger, err := zap.NewProduction()
if err != nil {
return nil, err
}
certmagic.DefaultACME.Agreed = true
certmagic.DefaultACME.Email = email
certmagic.DefaultACME.DNS01Solver = &certmagic.DNS01Solver{
DNSManager: certmagic.DNSManager{
DNSProvider: store,
Resolvers: func() []string {
if len(customResolvers) == 0 {
return DefaultResolvers
}
return customResolvers
}(),
},
}
certmagic.DefaultACME.CA = certmagic.LetsEncryptProductionCA
if debug {
certmagic.DefaultACME.Logger = logger
}
certmagic.DefaultACME.DisableHTTPChallenge = true
certmagic.DefaultACME.DisableTLSALPNChallenge = true
cfg := certmagic.NewDefault()
if debug {
cfg.Logger = logger
}
return cfg, nil
}
// HandleWildcardCertificates handles ACME wildcard cert generation with DNS
// challenge using certmagic library from caddyserver.
func HandleWildcardCertificates(cfg *certmagic.Config, domain string) ([]tls.Certificate, []CertificateFiles, error) {
originalDomain := strings.TrimPrefix(domain, "*.")
var creating bool
if !certAlreadyExists(cfg, &certmagic.DefaultACME, domain) {
creating = true
gologger.Info().Msgf("Requesting SSL Certificate for: [%s, %s]", domain, originalDomain)
} else {
gologger.Info().Msgf("Loading existing SSL Certificate for: [%s, %s]", domain, originalDomain)
}
// this obtains certificates or renews them if necessary
if syncErr := cfg.ObtainCertSync(context.Background(), domain); syncErr != nil {
return nil, nil, syncErr
}
domains := []string{domain, originalDomain}
if syncErr := cfg.ManageSync(context.Background(), domains); syncErr != nil {
gologger.Error().Msgf("Could not manage certmagic certs: %s", syncErr)
}
if creating {
home, _ := os.UserHomeDir()
gologger.Info().Msgf("Successfully Created SSL Certificate at: %s", filepath.Join(home, ".local", "share", "certmagic"))
}
// attempts to extract certificates from caddy
var (
certs []tls.Certificate
certFiles []CertificateFiles
)
for _, domain := range domains {
var retried, retriedWildcard bool
retry_cert:
certPath, privKeyPath, err := ExtractCaddyPaths(cfg, &certmagic.DefaultACME, domain)
if err != nil {
return nil, nil, err
}
certFiles = append(certFiles, CertificateFiles{CertPath: certPath, PrivKeyPath: privKeyPath})
cert, err := tls.LoadX509KeyPair(certPath, privKeyPath)
if err != nil {
if !retried {
retried = true
// wait I/O to sync
time.Sleep(5 * time.Second)
goto retry_cert
}
if !retriedWildcard {
retriedWildcard = true
// wait I/O to sync
time.Sleep(5 * time.Second)
// attempt to load the domain as wildcard
domain = fmt.Sprintf("wildcard_.%s", domain)
goto retry_cert
}
}
if err != nil {
return nil, nil, err
}
certs = append(certs, cert)
}
return certs, certFiles, nil
}
// certAlreadyExists returns true if a cert already exists
func certAlreadyExists(cfg *certmagic.Config, issuer certmagic.Issuer, domain string) bool {
issuerKey := issuer.IssuerKey()
certKey := certmagic.StorageKeys.SiteCert(issuerKey, domain)
keyKey := certmagic.StorageKeys.SitePrivateKey(issuerKey, domain)
metaKey := certmagic.StorageKeys.SiteMeta(issuerKey, domain)
return cfg.Storage.Exists(context.Background(), certKey) &&
cfg.Storage.Exists(context.Background(), keyKey) &&
cfg.Storage.Exists(context.Background(), metaKey)
}
// ExtractCaddyPaths attempts to extract cert and private key through the layers of abstractions from the domain name
func ExtractCaddyPaths(cfg *certmagic.Config, issuer certmagic.Issuer, domain string) (certPath, privKeyPath string, err error) {
issuerKey := issuer.IssuerKey()
certId := certmagic.StorageKeys.SiteCert(issuerKey, domain)
keyId := certmagic.StorageKeys.SitePrivateKey(issuerKey, domain)
// we need to coerce the storage to file system one to be able to obtain access to the typed methods
if cfgStorage, ok := cfg.Storage.(*certmagic.FileStorage); ok {
certPath = cfgStorage.Filename(certId)
privKeyPath = cfgStorage.Filename(keyId)
}
if certPath != "" && privKeyPath != "" {
return
}
err = errors.New("couldn't extract cert and private key paths")
return
}