forked from riobard/go-acme
-
Notifications
You must be signed in to change notification settings - Fork 0
/
acme.go
318 lines (289 loc) · 7.32 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
package main
import (
"bytes"
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
// ACME Challenge object
type Challenge struct {
Type string
Status string
URI string
Token string
Error *struct {
Type string
Detail string
}
}
// ACME Authorization object
type Auth struct {
Challenges []Challenge
Expires time.Time
Status string
Identifier struct {
Type string // ACME spec only supports Type=DNS
Value string // so Value must be a domain name
}
Combinations [][]int // pointers to sets of challenges to solve
}
// ACME API
type ACME struct {
URL string // ACME directory URL
Dir struct {
NewReg string `json:"new-reg"`
NewCert string `json:"new-cert"`
NewAuthz string `json:"new-authz"`
RevokeCert string `json:"revoke-cert"`
}
key *rsa.PrivateKey
keyAuth map[string]string // token => key authorization
rwmutex sync.RWMutex
noncePool chan string
}
// Connect to the ACME server at the url using the given account key
func OpenACME(url string, key *rsa.PrivateKey) (*ACME, error) {
acme := &ACME{
URL: url,
key: key,
keyAuth: make(map[string]string),
noncePool: make(chan string, 100),
}
rsp, err := http.Get(url)
if err != nil {
return nil, err
}
if rsp.StatusCode != 200 {
return nil, fmt.Errorf("ACME server error: %s", rsp.Status)
}
acme.noncePool <- rsp.Header.Get("Replay-Nonce")
if err := json.NewDecoder(rsp.Body).Decode(&acme.Dir); err != nil {
return nil, err
}
return acme, nil
}
// Post a JWS signed payload to the given url
func (a *ACME) do(url string, payload []byte) (*http.Response, error) {
var nonce string
select {
case nonce = <-a.noncePool:
default: // nonce pool is empty
rsp, err := http.Head(a.URL)
if err != nil {
return nil, err
}
nonce = rsp.Header.Get("Replay-Nonce")
}
rsp, err := http.Post(url, "", bytes.NewBuffer(jsonWebSign(a.key, payload, nonce)))
if err != nil {
return nil, err
}
go func() { // put back a new nonce
a.noncePool <- rsp.Header.Get("Replay-Nonce")
}()
return rsp, nil
}
// Update the registration object at regURL with the agreement to Terms of
// Service at tosURL.
func (a *ACME) agreeTOS(regURL, tosURL string) error {
payload, err := json.Marshal(map[string]string{
"resource": "reg",
"agreement": tosURL,
})
if err != nil {
return err
}
rsp, err := a.do(regURL, payload)
if err != nil {
return err
}
if rsp.StatusCode != 202 {
return fmt.Errorf("failed to agree terms of service: HTTP %s", rsp.Status)
}
return nil
}
// Register the account key, even if the key is already registred.
func (a *ACME) NewReg() error {
payload, err := json.Marshal(map[string]string{
"resource": "new-reg",
})
if err != nil {
return err
}
rsp, err := a.do(a.Dir.NewReg, payload)
if err != nil {
return err
}
switch rsp.StatusCode {
case 201: // new registration ok
links := parseLinks(rsp.Header["Link"])
// agree to Terms of Service if present
if tos, ok := links["terms-of-service"]; ok {
a.agreeTOS(rsp.Header.Get("Location"), tos)
}
case 409: // key already registered
default: // error
return fmt.Errorf("key registration failed: HTTP %s", rsp.Status)
}
return nil
}
// Authorize a domain name. Currently only http-01 method is supported.
func (a *ACME) NewAuthz(domain string) error {
payload, err := json.Marshal(map[string]interface{}{
"resource": "new-authz",
"identifier": map[string]string{
"type": "dns",
"value": domain,
},
})
if err != nil {
return err
}
rsp, err := a.do(a.Dir.NewAuthz, payload)
if err != nil {
return err
}
if rsp.StatusCode != 201 {
return fmt.Errorf("failed to create authorization: HTTP %s", rsp.Status)
}
auth := new(Auth)
if err := json.NewDecoder(rsp.Body).Decode(auth); err != nil {
return err
}
for _, c := range auth.Challenges {
switch c.Type {
case "http-01":
if err := a.http01(domain, c.URI, c.Token); err != nil {
return err
}
}
}
return nil
}
// Solve http01 challenge at at uri fro domain using token
func (a *ACME) http01(domain, uri, token string) error {
keyAuth := token + "." + b64(rsa2jwk(a.key).Thumbprint(crypto.SHA256))
a.rwmutex.Lock()
a.keyAuth[token] = keyAuth
a.rwmutex.Unlock()
// ask the ACME server to start challenge validation
payload, err := json.Marshal(map[string]string{
"resource": "challenge",
"keyAuthorization": keyAuth,
})
if err != nil {
return err
}
rsp, err := a.do(uri, payload)
if err != nil {
return err
}
if rsp.StatusCode != 202 {
return fmt.Errorf("failed to post challenge")
}
c := new(Challenge)
if err := json.NewDecoder(rsp.Body).Decode(c); err != nil {
return err
}
// poll to get latest validation status
for {
time.Sleep(2 * time.Second)
rsp, err := http.Get(c.URI)
if err != nil {
return err
}
if rsp.StatusCode != 202 {
return fmt.Errorf("HTTP %s", rsp.Status)
}
c := new(Challenge)
if err := json.NewDecoder(rsp.Body).Decode(c); err != nil {
return err
}
switch c.Status {
case "", "pending", "processing":
// missing status defaults to pending. wait and poll again.
case "valid":
return nil
default:
if c.Error != nil {
return fmt.Errorf("%s [%s] %s", c.Status, c.Error.Type, c.Error.Detail)
}
return fmt.Errorf("%s", c.Status)
}
}
}
// HTTP handler to solve ACME HTTP challenge
func (a *ACME) ServeHTTP(w http.ResponseWriter, r *http.Request) {
tok := strings.TrimPrefix(r.URL.Path, ACMEChallengePathPrefix)
a.rwmutex.RLock()
keyAuth, ok := a.keyAuth[tok]
a.rwmutex.RUnlock()
if ok {
io.WriteString(w, keyAuth)
} else {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
}
// Create a new certificate using the given certificate signing request
func (a *ACME) NewCert(csr []byte) (domainCrt *x509.Certificate, issuerCrt *x509.Certificate, err error) {
payload, err := json.Marshal(map[string]string{
"resource": "new-cert",
"csr": b64(csr),
})
if err != nil {
return nil, nil, err
}
rsp, err := a.do(a.Dir.NewCert, payload)
if err != nil {
return nil, nil, err
}
if rsp.StatusCode != 201 {
return nil, nil, fmt.Errorf("failed to get domain certificate: HTTP %s", rsp.Status)
}
// The server might not return the certificate in the body, in which case
// we need to poll the Location header to get the actual certificate. If
// the certificate is unavailable, GET request to the Location header will
// return 202 Accepted with a Retry-After header.
for rsp.Header.Get("Content-Type") != "application/pkix-cert" {
delay, _ := strconv.Atoi(rsp.Header.Get("Retry-After"))
if delay == 0 {
delay = 2
}
time.Sleep(time.Duration(delay) * time.Second)
rsp, err = http.Get(rsp.Header.Get("Location"))
if err != nil {
return nil, nil, err
}
}
// now the certificate should be available
domainCrt, err = parseCert(rsp.Body)
if err != nil {
return nil, nil, err
}
// fetch issuer certificate
links := parseLinks(rsp.Header["Link"])
issuer, ok := links["up"]
if !ok {
return nil, nil, fmt.Errorf("issuer certificate not specified")
}
rsp, err = http.Get(issuer)
if err != nil {
return nil, nil, err
}
if rsp.StatusCode != 200 {
return nil, nil, fmt.Errorf("failed to fetch issuer certificate: HTTP %s", rsp.Status)
}
issuerCrt, err = parseCert(rsp.Body)
if err != nil {
return nil, nil, err
}
return domainCrt, issuerCrt, nil
}