Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
552 lines (452 loc) · 12.4 KB
/
Copy pathclient.go
File metadata and controls
552 lines (452 loc) · 12.4 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
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
package acme
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/hashicorp/go-retryablehttp"
)
const (
// Live and staging URLs
DirectoryLive = "https://acme-v02.api.letsencrypt.org/directory"
DirectoryStaging = "https://acme-staging-v02.api.letsencrypt.org/directory"
// Modes
ModeLive = "live"
ModeStaging = "staging"
// Directory endpoints
DirectoryNewAccount = "newAccount"
DirectoryNewNonce = "newNonce"
DirectoryNewOrder = "newOrder"
// Validation types - DNS only
ValidationDNS = "dns-01"
)
// ClientConfig holds configuration for the ACME client
type ClientConfig struct {
Username string
Mode string
KeyLength int
BasePath string
SourceIP string
}
// Client represents the ACME client
type Client struct {
config *ClientConfig
httpClient *retryablehttp.Client
directories map[string]string
nonce string
account *Account
privateKey *rsa.PrivateKey
privateKeyPEM string
digest string
accountURL string
maxAttempts int
}
// DirectoryResponse represents the ACME directory structure
type DirectoryResponse struct {
NewAccount string `json:"newAccount"`
NewNonce string `json:"newNonce"`
NewOrder string `json:"newOrder"`
RevokeCert string `json:"revokeCert"`
KeyChange string `json:"keyChange"`
}
// JWKHeader represents the JSON Web Key header
type JWKHeader struct {
Alg string `json:"alg"`
JWK *JWK `json:"jwk,omitempty"`
KID string `json:"kid,omitempty"`
Nonce string `json:"nonce"`
URL string `json:"url"`
}
// JWK represents a JSON Web Key
type JWK struct {
E string `json:"e"`
Kty string `json:"kty"`
N string `json:"n"`
}
// JWS represents a JSON Web Signature
type JWS struct {
Protected string `json:"protected"`
Payload string `json:"payload"`
Signature string `json:"signature"`
}
// NewClient creates a new ACME client
func NewClient(config *ClientConfig) (*Client, error) {
if config.Username == "" {
return nil, fmt.Errorf("username is required")
}
if config.Mode == "" {
config.Mode = ModeLive
}
if config.KeyLength == 0 {
config.KeyLength = 4096
}
if config.BasePath == "" {
config.BasePath = "le"
}
// Create retryable HTTP client
retryClient := retryablehttp.NewClient()
retryClient.RetryMax = 3
retryClient.RetryWaitMin = 1 * time.Second
retryClient.RetryWaitMax = 5 * time.Second
retryClient.HTTPClient.Timeout = 30 * time.Second
// Disable logging by default (can be enabled if needed)
retryClient.Logger = nil
client := &Client{
config: config,
httpClient: retryClient,
maxAttempts: 30,
}
if err := client.init(); err != nil {
return nil, fmt.Errorf("failed to initialize client: %w", err)
}
return client, nil
}
// Close cleans up the client
func (c *Client) Close() error {
return nil
}
// SetMaxAttempts sets the maximum number of attempts for a request
func (c *Client) SetMaxAttempts(attempts int) {
c.maxAttempts = attempts
}
// init initializes the client by loading directories, keys, and account
func (c *Client) init() error {
// Load directories from Let's Encrypt API
if err := c.loadDirectories(); err != nil {
return fmt.Errorf("failed to load directories: %w", err)
}
// Load or create private key
if err := c.loadKeys(); err != nil {
return fmt.Errorf("failed to load keys: %w", err)
}
// Agree to terms of service and get account
if err := c.tosAgree(); err != nil {
return fmt.Errorf("failed to agree to TOS: %w", err)
}
// Get account information
account, err := c.getAccount()
if err != nil {
return fmt.Errorf("failed to get account: %w", err)
}
c.account = account
return nil
}
// loadDirectories loads the ACME directory from Let's Encrypt
func (c *Client) loadDirectories() error {
var directoryURL string
if c.config.Mode == ModeLive {
directoryURL = DirectoryLive
} else {
directoryURL = DirectoryStaging
}
fmt.Printf("Loading ACME directory from: %s\n", directoryURL)
req, err := retryablehttp.NewRequest("GET", directoryURL, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to connect to ACME server: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("HTTP %d from ACME server: %s", resp.StatusCode, string(body))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
// Validate JSON before unmarshaling
if !json.Valid(body) {
return fmt.Errorf("invalid JSON response from ACME server")
}
var dir DirectoryResponse
if err := json.Unmarshal(body, &dir); err != nil {
return fmt.Errorf("failed to parse directory response: %w", err)
}
// Validate required fields
if dir.NewAccount == "" || dir.NewNonce == "" || dir.NewOrder == "" {
return fmt.Errorf("missing required fields in directory response")
}
c.directories = map[string]string{
DirectoryNewAccount: dir.NewAccount,
DirectoryNewNonce: dir.NewNonce,
DirectoryNewOrder: dir.NewOrder,
}
fmt.Printf("Successfully loaded ACME directories\n")
return nil
}
// loadKeys loads or creates the account private key
func (c *Client) loadKeys() error {
keyPath := c.getPath("account.pem")
// Check if key file exists
if _, err := os.Stat(keyPath); os.IsNotExist(err) {
// Create new key
privateKey, err := rsa.GenerateKey(rand.Reader, c.config.KeyLength)
if err != nil {
return fmt.Errorf("failed to generate private key: %w", err)
}
// Save key to file
keyPEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
if err := os.MkdirAll(filepath.Dir(keyPath), 0755); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
keyFile, err := os.Create(keyPath)
if err != nil {
return fmt.Errorf("failed to create key file: %w", err)
}
defer keyFile.Close()
if err := pem.Encode(keyFile, keyPEM); err != nil {
return fmt.Errorf("failed to encode key: %w", err)
}
c.privateKey = privateKey
} else {
// Load existing key
keyData, err := os.ReadFile(keyPath)
if err != nil {
return fmt.Errorf("failed to read key file: %w", err)
}
block, _ := pem.Decode(keyData)
if block == nil {
return fmt.Errorf("failed to decode PEM block")
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return fmt.Errorf("failed to parse private key: %w", err)
}
c.privateKey = privateKey
}
// Store PEM format for later use
keyPEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(c.privateKey),
}
c.privateKeyPEM = string(pem.EncodeToMemory(keyPEM))
return nil
}
// getPath returns a formatted path for the given filename
func (c *Client) getPath(filename string) string {
// Create a safe directory name from username
userDir := regexp.MustCompile(`[^a-z0-9]+`).ReplaceAllString(strings.ToLower(c.config.Username), "-")
return filepath.Join(c.config.BasePath, userDir, filename)
}
// tosAgree agrees to the terms of service
func (c *Client) tosAgree() error {
payload := map[string]interface{}{
"contact": []string{"mailto:" + c.config.Username},
"termsOfServiceAgreed": true,
}
url := c.directories[DirectoryNewAccount]
jws, err := c.signPayloadJWK(payload, url)
if err != nil {
return err
}
resp, err := c.request("POST", url, jws)
if err != nil {
return err
}
defer resp.Body.Close()
// Store account URL from Location header
c.accountURL = resp.Header.Get("Location")
return nil
}
// request sends an HTTP request to the ACME server using retryable HTTP
func (c *Client) request(method, url string, body interface{}) (*http.Response, error) {
var reqBody io.Reader
if body != nil {
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, err
}
reqBody = bytes.NewReader(jsonBody)
}
req, err := retryablehttp.NewRequest(method, url, reqBody)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/jose+json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
// Update nonce from response
if nonce := resp.Header.Get("Replay-Nonce"); nonce != "" {
c.nonce = nonce
}
if resp.StatusCode >= 400 {
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
}
return resp, nil
}
// getNonce gets a fresh nonce from the ACME server
func (c *Client) getNonce() error {
if c.nonce != "" {
return nil
}
req, err := retryablehttp.NewRequest("HEAD", c.directories[DirectoryNewNonce], nil)
if err != nil {
return err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
c.nonce = resp.Header.Get("Replay-Nonce")
if c.nonce == "" {
return fmt.Errorf("no nonce received")
}
return nil
}
// getJWK returns the JSON Web Key for the account
func (c *Client) getJWK() (*JWK, error) {
publicKey := &c.privateKey.PublicKey
nBytes := publicKey.N.Bytes()
eBytes := make([]byte, 4)
eBytes[0] = byte(publicKey.E >> 24)
eBytes[1] = byte(publicKey.E >> 16)
eBytes[2] = byte(publicKey.E >> 8)
eBytes[3] = byte(publicKey.E)
// Remove leading zeros from E
for len(eBytes) > 1 && eBytes[0] == 0 {
eBytes = eBytes[1:]
}
return &JWK{
Kty: "RSA",
N: base64.RawURLEncoding.EncodeToString(nBytes),
E: base64.RawURLEncoding.EncodeToString(eBytes),
}, nil
}
// getDigest returns the thumbprint of the account key
func (c *Client) getDigest() (string, error) {
if c.digest != "" {
return c.digest, nil
}
jwk, err := c.getJWK()
if err != nil {
return "", err
}
jwkJSON, err := json.Marshal(jwk)
if err != nil {
return "", err
}
hash := sha256.Sum256(jwkJSON)
c.digest = base64.RawURLEncoding.EncodeToString(hash[:])
return c.digest, nil
}
// signPayloadJWK signs a payload using JWK format
func (c *Client) signPayloadJWK(payload any, url string) (*JWS, error) {
if err := c.getNonce(); err != nil {
return nil, err
}
jwk, err := c.getJWK()
if err != nil {
return nil, err
}
header := &JWKHeader{
Alg: "RS256",
JWK: jwk,
Nonce: c.nonce,
URL: url,
}
return c.signPayload(header, payload)
}
// signPayloadKID signs a payload using KID format
func (c *Client) signPayloadKID(payload any, url string) (*JWS, error) {
if err := c.getNonce(); err != nil {
return nil, err
}
header := &JWKHeader{
Alg: "RS256",
KID: c.accountURL,
Nonce: c.nonce,
URL: url,
}
return c.signPayload(header, payload)
}
// signPayload signs a payload with the given header
func (c *Client) signPayload(header *JWKHeader, payload interface{}) (*JWS, error) {
headerJSON, err := json.Marshal(header)
if err != nil {
return nil, err
}
var payloadJSON []byte
if payload != nil {
payloadJSON, err = json.Marshal(payload)
if err != nil {
return nil, err
}
}
protectedEncoded := base64.RawURLEncoding.EncodeToString(headerJSON)
payloadEncoded := base64.RawURLEncoding.EncodeToString(payloadJSON)
signingInput := protectedEncoded + "." + payloadEncoded
hash := sha256.Sum256([]byte(signingInput))
signature, err := rsa.SignPKCS1v15(rand.Reader, c.privateKey, crypto.SHA256, hash[:])
if err != nil {
return nil, err
}
signatureEncoded := base64.RawURLEncoding.EncodeToString(signature)
return &JWS{
Protected: protectedEncoded,
Payload: payloadEncoded,
Signature: signatureEncoded,
}, nil
}
// getAccount retrieves account information (internal method)
func (c *Client) getAccount() (*Account, error) {
payload := map[string]any{
"onlyReturnExisting": true,
}
url := c.directories[DirectoryNewAccount]
jws, err := c.signPayloadJWK(payload, url)
if err != nil {
return nil, err
}
resp, err := c.request("POST", url, jws)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var accountResp struct {
Contact []string `json:"contact"`
CreatedAt string `json:"createdAt"`
Status string `json:"status"`
}
if err := json.Unmarshal(body, &accountResp); err != nil {
return nil, err
}
accountURL := resp.Header.Get("Location")
createdAt, err := time.Parse(time.RFC3339, accountResp.CreatedAt)
if err != nil {
return nil, err
}
return NewAccount(
accountResp.Contact,
createdAt,
accountResp.Status == "valid",
accountURL,
), nil
}