-
Notifications
You must be signed in to change notification settings - Fork 56
/
certbot.go
295 lines (241 loc) · 8.01 KB
/
certbot.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
package libknary
import (
"crypto"
"errors"
"log"
"os"
"path/filepath"
"strconv"
"time"
"github.com/go-acme/lego/v4/certcrypto"
"github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/lego"
cmd "github.com/sudosammy/knary/v3/libknary/lego"
)
// Config is used to configure the creation of the DNSProvider.
type Config struct {
TTL int
PropagationTimeout time.Duration
PollingInterval time.Duration
}
// NewDefaultConfig returns a default configuration for the DNSProvider.
func NewDefaultConfig() *Config {
var confTTL int
var confTimeout time.Duration
var confPoll time.Duration
if value, ok := os.LookupEnv("CERTBOT_TTL"); ok {
confTTL, _ = strconv.Atoi(value)
} else {
confTTL = 120
}
if value, ok := os.LookupEnv("CERTBOT_PROPAGATION_TIMEOUT"); ok {
timeVal, _ := strconv.Atoi(value)
confTimeout = time.Duration(timeVal) * time.Second
} else {
confTimeout = 60 * time.Second
}
if value, ok := os.LookupEnv("CERTBOT_POLLING_INTERVAL"); ok {
timeVal, _ := strconv.Atoi(value)
confPoll = time.Duration(timeVal) * time.Second
} else {
confPoll = 2 * time.Second
}
return &Config{
TTL: confTTL,
PropagationTimeout: confTimeout,
PollingInterval: confPoll,
}
}
// DNSProvider implements the challenge.Provider interface.
type DNSProvider struct {
config *Config
}
func NewDNSProvider() (*DNSProvider, error) {
config := NewDefaultConfig()
return NewDNSProviderConfig(config)
}
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("There was an error getting the configuration for Lets Encrypt")
}
return &DNSProvider{
config: config,
}, nil
}
// Present creates a TXT record to fulfill the dns-01 challenge.
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
fqdn, value := dns01.GetRecord(domain, keyAuth)
err := addZone(fqdn, d.config.TTL, "TXT", value)
return err
}
// CleanUp removes the TXT record matching the specified parameters.
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
fqdn, _ := dns01.GetRecord(domain, keyAuth)
remZone(fqdn)
return nil
}
func StartLetsEncrypt() {
// check if folder structure is correct
cmd.CreateFolderStructure()
myUser := loadMyUser()
config := lego.NewConfig(myUser)
if os.Getenv("LE_ENV") == "staging" {
config.CADirURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
} else if os.Getenv("LE_ENV") == "dev" {
config.CADirURL = "http://127.0.0.1:4001/directory"
}
// A client facilitates communication with the CA server.
client, err := lego.NewClient(config)
if err != nil {
logger("ERROR", err.Error())
GiveHead(2)
log.Fatal(err)
}
knaryDNS, err := NewDNSProvider()
if err != nil {
logger("ERROR", err.Error())
GiveHead(2)
log.Fatal(err)
}
if os.Getenv("DNS_RESOLVER") != "" {
client.Challenge.SetDNS01Provider(knaryDNS, dns01.AddRecursiveNameservers([]string{os.Getenv("DNS_RESOLVER")}))
} else {
client.Challenge.SetDNS01Provider(knaryDNS)
}
// if we're an existing user, loadMyUser would have populated cmd.Account with our Registration details
currentReg, err := client.Registration.QueryRegistration()
if err == nil && currentReg.Body.Status != "valid" {
Printy("Found the Let's Encrypt user, but apparently the registration is not valid. We'll try re-registering...", 2)
myUser.Registration = registerAccount(client)
// save these registration details to disk
accountStorage := cmd.NewAccountsStorage()
if err := accountStorage.Save(myUser); err != nil {
logger("ERROR", err.Error())
GiveHead(2)
log.Fatal(err)
}
} else if err == nil && currentReg.Body.Status == "valid" {
myUser.Registration = currentReg
} else {
myUser.Registration = registerAccount(client)
// save these registration details to disk
accountStorage := cmd.NewAccountsStorage()
if err := accountStorage.Save(myUser); err != nil {
logger("ERROR", err.Error())
GiveHead(2)
log.Fatal(err)
}
}
certsStorage := cmd.NewCertificatesStorage()
firstDomain := GetFirstDomain()
// should only request certs if currently none exist
if fileExists(certsStorage.GetFileName("*."+firstDomain, ".key")) &&
fileExists(certsStorage.GetFileName("*."+firstDomain, ".crt")) {
if os.Getenv("DEBUG") == "true" {
Printy("TLS private key found: "+certsStorage.GetFileName("*."+firstDomain, ".key"), 3)
Printy("TLS certificate found: "+certsStorage.GetFileName("*."+firstDomain, ".crt"), 3)
}
// Set TLS_CRT and TLS_KEY to our LE generated certs
os.Setenv("TLS_CRT", filepath.Join(cmd.GetCertPath(), cmd.SanitizedDomain("*."+firstDomain)+".crt"))
os.Setenv("TLS_KEY", filepath.Join(cmd.GetCertPath(), cmd.SanitizedDomain("*."+firstDomain)+".key"))
return
}
if os.Getenv("DEBUG") == "true" {
Printy("No existing certificates found at:", 3)
Printy(certsStorage.GetFileName("*."+firstDomain, ".key"), 2)
Printy(certsStorage.GetFileName("*."+firstDomain, ".crt"), 2)
Printy("Let's Encrypt ourselves some new ones!", 3)
}
request := certificate.ObtainRequest{
Domains: getDomainsForCert(),
Bundle: true,
}
certificates, err := client.Certificate.Obtain(request)
if err != nil {
logger("ERROR", err.Error())
GiveHead(2)
log.Fatal(err)
}
certsStorage.SaveResource(certificates)
// Set TLS_CRT and TLS_KEY to our LE generated certs
os.Setenv("TLS_CRT", filepath.Join(cmd.GetCertPath(), cmd.SanitizedDomain("*."+firstDomain)+".crt"))
os.Setenv("TLS_KEY", filepath.Join(cmd.GetCertPath(), cmd.SanitizedDomain("*."+firstDomain)+".key"))
}
func renewError(msg string) {
go sendMsg(":warning: " + msg)
go sendMsg(":warning: knary is shutting down because of this error :(")
logger("ERROR", msg)
GiveHead(2)
log.Fatal(msg)
}
func renewLetsEncrypt() {
Printy("Attempting Let's Encrypt renewal", 1)
logger("INFO", "Attempting Let's Encrypt certificate renewal.")
go sendMsg(":lock: Attempting renewal of the Let's Encrypt certificate. I'll let you know how I go.")
myUser := loadMyUser()
config := lego.NewConfig(myUser)
if os.Getenv("LE_ENV") == "staging" {
config.CADirURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
} else if os.Getenv("LE_ENV") == "dev" {
config.CADirURL = "http://127.0.0.1:4001/directory"
}
client, err := lego.NewClient(config)
if err != nil {
renewError(err.Error())
}
knaryDNS, err := NewDNSProvider()
if err != nil {
renewError(err.Error())
}
client.Challenge.SetDNS01Provider(knaryDNS)
//certDomains := getDomainsForCert()
certsStorage := cmd.NewCertificatesStorage()
var privateKey crypto.PrivateKey
keyBytes, errR := certsStorage.ReadFile("*."+GetFirstDomain(), ".key")
if errR != nil {
renewError(errR.Error())
}
privateKey, errR = certcrypto.ParsePEMPrivateKey(keyBytes)
if errR != nil {
renewError(errR.Error())
}
pemBundle, errR := certsStorage.ReadFile("*."+GetFirstDomain(), ".pem")
if errR != nil {
renewError(errR.Error())
}
certificates, errR := certcrypto.ParsePEMBundle(pemBundle)
if errR != nil {
renewError(errR.Error())
}
x509Cert := certificates[0]
if x509Cert.IsCA {
renewError("Certificate bundle starts with a CA certificate")
}
query := certificate.ObtainRequest{
Domains: certcrypto.ExtractDomains(x509Cert),
Bundle: true,
PrivateKey: privateKey,
MustStaple: false,
}
certRes, errR := client.Certificate.Obtain(query)
if errR != nil {
renewError(errR.Error())
}
// move old certificates to archive folder
if os.Getenv("DEBUG") == "true" {
Printy("Archiving old certificates", 3)
}
err = certsStorage.MoveToArchive("*." + GetFirstDomain())
if err != nil {
msg := "There was an error moving the old certificates to the archive folder. Did you delete the folder? I'll overwrite the old certificates instead. See the log for more information."
go sendMsg(":warning: " + msg)
Printy(msg, 2)
logger("WARNING", "Could not move certificates to archive: "+err.Error())
}
certsStorage.SaveResource(certRes)
msg := "Certificate successfully renewed!"
go sendMsg(":lock: " + msg)
logger("INFO", msg)
Printy(msg, 3)
}