-
-
Notifications
You must be signed in to change notification settings - Fork 293
/
zerosslissuer.go
320 lines (273 loc) · 9.67 KB
/
zerosslissuer.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
// Copyright 2015 Matthew Holt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package certmagic
import (
"context"
"crypto/x509"
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/caddyserver/zerossl"
"github.com/mholt/acmez/v2"
"github.com/mholt/acmez/v2/acme"
"go.uber.org/zap"
)
// ZeroSSLIssuer can get certificates from ZeroSSL's API. (To use ZeroSSL's ACME
// endpoint, use the ACMEIssuer instead.) Note that use of the API is restricted
// by payment tier.
type ZeroSSLIssuer struct {
// The API key (or "access key") for using the ZeroSSL API.
// REQUIRED.
APIKey string
// Where to store verification material temporarily.
// All instances in a cluster should have the same
// Storage value to enable distributed verification.
// REQUIRED. (TODO: Make it optional for those not
// operating in a cluster. For now, it's simpler to
// put info in storage whether distributed or not.)
Storage Storage
// How many days the certificate should be valid for.
ValidityDays int
// The host to bind to when opening a listener for
// verifying domain names (or IPs).
ListenHost string
// If HTTP is forwarded from port 80, specify the
// forwarded port here.
AltHTTPPort int
// To use CNAME validation instead of HTTP
// validation, set this field.
CNAMEValidation *DNSManager
// Delay between poll attempts.
PollInterval time.Duration
// An optional (but highly recommended) logger.
Logger *zap.Logger
}
// Issue obtains a certificate for the given csr.
func (iss *ZeroSSLIssuer) Issue(ctx context.Context, csr *x509.CertificateRequest) (*IssuedCertificate, error) {
client := iss.getClient()
identifiers := namesFromCSR(csr)
if len(identifiers) == 0 {
return nil, fmt.Errorf("no identifiers on CSR")
}
logger := iss.Logger
if logger == nil {
logger = zap.NewNop()
}
logger = logger.With(zap.Strings("identifiers", identifiers))
logger.Info("creating certificate")
cert, err := client.CreateCertificate(ctx, csr, iss.ValidityDays)
if err != nil {
return nil, fmt.Errorf("creating certificate: %v", err)
}
logger = logger.With(zap.String("cert_id", cert.ID))
logger.Info("created certificate")
defer func(certID string) {
if err != nil {
err := client.CancelCertificate(context.WithoutCancel(ctx), certID)
if err == nil {
logger.Info("canceled certificate")
} else {
logger.Error("unable to cancel certificate", zap.Error(err))
}
}
}(cert.ID)
var verificationMethod zerossl.VerificationMethod
if iss.CNAMEValidation == nil {
verificationMethod = zerossl.HTTPVerification
logger = logger.With(zap.String("verification_method", string(verificationMethod)))
httpVerifier := &httpSolver{
address: net.JoinHostPort(iss.ListenHost, strconv.Itoa(iss.getHTTPPort())),
handler: iss.HTTPValidationHandler(http.NewServeMux()),
}
var solver acmez.Solver = httpVerifier
if iss.Storage != nil {
solver = distributedSolver{
storage: iss.Storage,
storageKeyIssuerPrefix: iss.IssuerKey(),
solver: httpVerifier,
}
}
// since the distributed solver was originally designed for ACME,
// the API is geared around ACME challenges. ZeroSSL's HTTP validation
// is very similar to the HTTP challenge, but not quite compatible,
// so we kind of shim the ZeroSSL validation data into a Challenge
// object... it is not a perfect use of this type but it's pretty close
valInfo := cert.Validation.OtherMethods[identifiers[0]]
fakeChallenge := acme.Challenge{
Identifier: acme.Identifier{
Value: identifiers[0], // used for storage key
},
URL: valInfo.FileValidationURLHTTP,
Token: strings.Join(cert.Validation.OtherMethods[identifiers[0]].FileValidationContent, "\n"),
}
if err = solver.Present(ctx, fakeChallenge); err != nil {
return nil, fmt.Errorf("presenting validation file for verification: %v", err)
}
defer solver.CleanUp(ctx, fakeChallenge)
} else {
verificationMethod = zerossl.CNAMEVerification
logger = logger.With(zap.String("verification_method", string(verificationMethod)))
// create the CNAME record(s)
records := make(map[string]zoneRecord, len(cert.Validation.OtherMethods))
for name, verifyInfo := range cert.Validation.OtherMethods {
zr, err := iss.CNAMEValidation.createRecord(ctx, verifyInfo.CnameValidationP1, "CNAME", verifyInfo.CnameValidationP2+".") // see issue #304
if err != nil {
return nil, fmt.Errorf("creating CNAME record: %v", err)
}
defer func(name string, zr zoneRecord) {
if err := iss.CNAMEValidation.cleanUpRecord(ctx, zr); err != nil {
logger.Warn("cleaning up temporary validation record failed",
zap.String("dns_name", name),
zap.Error(err))
}
}(name, zr)
records[name] = zr
}
// wait for them to propagate
for name, zr := range records {
if err := iss.CNAMEValidation.wait(ctx, zr); err != nil {
// allow it, since the CA will ultimately decide, but definitely log it
logger.Warn("failed CNAME record propagation check", zap.String("domain", name), zap.Error(err))
}
}
}
logger.Info("validating identifiers")
cert, err = client.VerifyIdentifiers(ctx, cert.ID, verificationMethod, nil)
if err != nil {
return nil, fmt.Errorf("verifying identifiers: %v", err)
}
switch cert.Status {
case "pending_validation":
logger.Info("validations succeeded; waiting for certificate to be issued")
cert, err = iss.waitForCertToBeIssued(ctx, client, cert)
if err != nil {
return nil, fmt.Errorf("waiting for certificate to be issued: %v", err)
}
case "issued":
logger.Info("validations succeeded; downloading certificate bundle")
default:
return nil, fmt.Errorf("unexpected certificate status: %s", cert.Status)
}
bundle, err := client.DownloadCertificate(ctx, cert.ID, false)
if err != nil {
return nil, fmt.Errorf("downloading certificate: %v", err)
}
logger.Info("successfully downloaded issued certificate")
return &IssuedCertificate{
Certificate: []byte(bundle.CertificateCrt + bundle.CABundleCrt),
Metadata: cert,
}, nil
}
func (iss *ZeroSSLIssuer) waitForCertToBeIssued(ctx context.Context, client zerossl.Client, cert zerossl.CertificateObject) (zerossl.CertificateObject, error) {
ticker := time.NewTicker(iss.pollInterval())
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return cert, ctx.Err()
case <-ticker.C:
var err error
cert, err = client.GetCertificate(ctx, cert.ID)
if err != nil {
return cert, err
}
if cert.Status == "issued" {
return cert, nil
}
if cert.Status != "pending_validation" {
return cert, fmt.Errorf("unexpected certificate status: %s", cert.Status)
}
}
}
}
func (iss *ZeroSSLIssuer) pollInterval() time.Duration {
if iss.PollInterval == 0 {
return defaultPollInterval
}
return iss.PollInterval
}
func (iss *ZeroSSLIssuer) getClient() zerossl.Client {
return zerossl.Client{AccessKey: iss.APIKey}
}
func (iss *ZeroSSLIssuer) getHTTPPort() int {
useHTTPPort := HTTPChallengePort
if HTTPPort > 0 && HTTPPort != HTTPChallengePort {
useHTTPPort = HTTPPort
}
if iss.AltHTTPPort > 0 {
useHTTPPort = iss.AltHTTPPort
}
return useHTTPPort
}
// IssuerKey returns the unique issuer key for ZeroSSL.
func (iss *ZeroSSLIssuer) IssuerKey() string { return zerosslIssuerKey }
// Revoke revokes the given certificate. Only do this if there is a security or trust
// concern with the certificate.
func (iss *ZeroSSLIssuer) Revoke(ctx context.Context, cert CertificateResource, reason int) error {
r := zerossl.UnspecifiedReason
switch reason {
case acme.ReasonKeyCompromise:
r = zerossl.KeyCompromise
case acme.ReasonAffiliationChanged:
r = zerossl.AffiliationChanged
case acme.ReasonSuperseded:
r = zerossl.Superseded
case acme.ReasonCessationOfOperation:
r = zerossl.CessationOfOperation
default:
return fmt.Errorf("unsupported reason: %d", reason)
}
var certObj zerossl.CertificateObject
if err := json.Unmarshal(cert.IssuerData, &certObj); err != nil {
return err
}
return iss.getClient().RevokeCertificate(ctx, certObj.ID, r)
}
func (iss *ZeroSSLIssuer) getDistributedValidationInfo(ctx context.Context, identifier string) (acme.Challenge, bool, error) {
if iss.Storage == nil {
return acme.Challenge{}, false, nil
}
ds := distributedSolver{
storage: iss.Storage,
storageKeyIssuerPrefix: StorageKeys.Safe(iss.IssuerKey()),
}
tokenKey := ds.challengeTokensKey(identifier)
valObjectBytes, err := iss.Storage.Load(ctx, tokenKey)
if err != nil {
return acme.Challenge{}, false, fmt.Errorf("opening distributed challenge token file %s: %v", tokenKey, err)
}
if len(valObjectBytes) == 0 {
return acme.Challenge{}, false, fmt.Errorf("no information found to solve challenge for identifier: %s", identifier)
}
// since the distributed solver's API is geared around ACME challenges,
// we crammed the validation info into a Challenge object
var chal acme.Challenge
if err = json.Unmarshal(valObjectBytes, &chal); err != nil {
return acme.Challenge{}, false, fmt.Errorf("decoding HTTP validation token file %s (corrupted?): %v", tokenKey, err)
}
return chal, true, nil
}
const (
zerosslIssuerKey = "zerossl"
defaultPollInterval = 5 * time.Second
)
// Interface guards
var (
_ Issuer = (*ZeroSSLIssuer)(nil)
_ Revoker = (*ZeroSSLIssuer)(nil)
)