-
-
Notifications
You must be signed in to change notification settings - Fork 979
/
cpanel.go
331 lines (267 loc) · 9.14 KB
/
cpanel.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
321
322
323
324
325
326
327
328
329
330
331
// Package cpanel implements a DNS provider for solving the DNS-01 challenge using CPanel.
package cpanel
import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"slices"
"strings"
"time"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/platform/config/env"
"github.com/go-acme/lego/v4/providers/dns/cpanel/internal/cpanel"
"github.com/go-acme/lego/v4/providers/dns/cpanel/internal/shared"
"github.com/go-acme/lego/v4/providers/dns/cpanel/internal/whm"
)
// Environment variables names.
const (
envNamespace = "CPANEL_"
EnvMode = envNamespace + "MODE"
EnvUsername = envNamespace + "USERNAME"
EnvToken = envNamespace + "TOKEN"
EnvBaseURL = envNamespace + "BASE_URL"
EnvTTL = envNamespace + "TTL"
EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT"
EnvPollingInterval = envNamespace + "POLLING_INTERVAL"
EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT"
)
type apiClient interface {
FetchZoneInformation(ctx context.Context, domain string) ([]shared.ZoneRecord, error)
AddRecord(ctx context.Context, serial uint32, domain string, record shared.Record) (*shared.ZoneSerial, error)
EditRecord(ctx context.Context, serial uint32, domain string, record shared.Record) (*shared.ZoneSerial, error)
DeleteRecord(ctx context.Context, serial uint32, domain string, lineIndex int) (*shared.ZoneSerial, error)
}
// Config is used to configure the creation of the DNSProvider.
type Config struct {
Mode string
Username string
Token string
BaseURL string
TTL int
PropagationTimeout time.Duration
PollingInterval time.Duration
HTTPClient *http.Client
}
// NewDefaultConfig returns a default configuration for the DNSProvider.
func NewDefaultConfig() *Config {
return &Config{
Mode: env.GetOrDefaultString(EnvMode, "cpanel"),
TTL: env.GetOrDefaultInt(EnvTTL, 300),
PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, 2*time.Minute),
PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval),
HTTPClient: &http.Client{
Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second),
},
}
}
// DNSProvider implements the challenge.Provider interface.
type DNSProvider struct {
config *Config
client apiClient
}
// NewDNSProvider returns a DNSProvider instance configured for CPanel.
// Credentials must be passed in the environment variables:
// CPANEL_USERNAME, CPANEL_TOKEN, CPANEL_BASE_URL, CPANEL_NAMESERVER.
func NewDNSProvider() (*DNSProvider, error) {
values, err := env.Get(EnvUsername, EnvToken, EnvBaseURL)
if err != nil {
return nil, fmt.Errorf("cpanel: %w", err)
}
config := NewDefaultConfig()
config.Username = values[EnvUsername]
config.Token = values[EnvToken]
config.BaseURL = values[EnvBaseURL]
return NewDNSProviderConfig(config)
}
// NewDNSProviderConfig return a DNSProvider instance configured for CPanel.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("cpanel: the configuration of the DNS provider is nil")
}
if config.Username == "" || config.Token == "" {
return nil, errors.New("cpanel: some credentials information are missing")
}
if config.BaseURL == "" {
return nil, errors.New("cpanel: server information are missing")
}
client, err := createClient(config)
if err != nil {
return nil, fmt.Errorf("cpanel: create client error: %w", err)
}
return &DNSProvider{
config: config,
client: client,
}, nil
}
// Timeout returns the timeout and interval to use when checking for DNS propagation.
// Adjusting here to cope with spikes in propagation times.
func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
return d.config.PropagationTimeout, d.config.PollingInterval
}
// Present creates a TXT record to fulfill the dns-01 challenge.
func (d *DNSProvider) Present(domain, _, keyAuth string) error {
ctx := context.Background()
info := dns01.GetChallengeInfo(domain, keyAuth)
authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("arvancloud: could not find zone for domain %q: %w", domain, err)
}
zone := dns01.UnFqdn(authZone)
zoneInfo, err := d.client.FetchZoneInformation(ctx, zone)
if err != nil {
return fmt.Errorf("cpanel[mode=%s]: fetch zone information: %w", d.config.Mode, err)
}
serial, err := getZoneSerial(authZone, zoneInfo)
if err != nil {
return fmt.Errorf("cpanel[mode=%s]: get zone serial: %w", d.config.Mode, err)
}
valueB64 := base64.StdEncoding.EncodeToString([]byte(info.Value))
var found bool
var existingRecord shared.ZoneRecord
for _, record := range zoneInfo {
if slices.Contains(record.DataB64, valueB64) {
existingRecord = record
found = true
break
}
}
record := shared.Record{
DName: info.EffectiveFQDN,
TTL: d.config.TTL,
RecordType: "TXT",
}
// New record.
if !found {
record.Data = []string{info.Value}
_, err = d.client.AddRecord(ctx, serial, zone, record)
if err != nil {
return fmt.Errorf("cpanel[mode=%s]: add record: %w", d.config.Mode, err)
}
return nil
}
// Update existing record.
record.LineIndex = existingRecord.LineIndex
for _, dataB64 := range existingRecord.DataB64 {
data, errD := base64.StdEncoding.DecodeString(dataB64)
if errD != nil {
return fmt.Errorf("cpanel[mode=%s]: decode base64 record value: %w", d.config.Mode, errD)
}
record.Data = append(record.Data, string(data))
}
record.Data = append(record.Data, info.Value)
_, err = d.client.EditRecord(ctx, serial, zone, record)
if err != nil {
return fmt.Errorf("cpanel[mode=%s]: edit record: %w", d.config.Mode, err)
}
return nil
}
// CleanUp removes the TXT record matching the specified parameters.
func (d *DNSProvider) CleanUp(domain, _, keyAuth string) error {
ctx := context.Background()
info := dns01.GetChallengeInfo(domain, keyAuth)
authZone, err := dns01.FindZoneByFqdn(info.EffectiveFQDN)
if err != nil {
return fmt.Errorf("arvancloud: could not find zone for domain %q: %w", domain, err)
}
zone := dns01.UnFqdn(authZone)
zoneInfo, err := d.client.FetchZoneInformation(ctx, zone)
if err != nil {
return fmt.Errorf("cpanel[mode=%s]: fetch zone information: %w", d.config.Mode, err)
}
serial, err := getZoneSerial(authZone, zoneInfo)
if err != nil {
return fmt.Errorf("cpanel[mode=%s]: get zone serial: %w", d.config.Mode, err)
}
valueB64 := base64.StdEncoding.EncodeToString([]byte(info.Value))
var found bool
var existingRecord shared.ZoneRecord
for _, record := range zoneInfo {
if slices.Contains(record.DataB64, valueB64) {
existingRecord = record
found = true
break
}
}
if !found {
return nil
}
var newData []string
for _, dataB64 := range existingRecord.DataB64 {
if dataB64 == valueB64 {
continue
}
data, errD := base64.StdEncoding.DecodeString(dataB64)
if errD != nil {
return fmt.Errorf("cpanel[mode=%s]: decode base64 record value: %w", d.config.Mode, errD)
}
newData = append(newData, string(data))
}
// Delete record.
if len(newData) == 0 {
_, err = d.client.DeleteRecord(ctx, serial, zone, existingRecord.LineIndex)
if err != nil {
return fmt.Errorf("cpanel[mode=%s]: delete record: %w", d.config.Mode, err)
}
return nil
}
// Remove one value.
record := shared.Record{
DName: info.EffectiveFQDN,
TTL: d.config.TTL,
RecordType: "TXT",
Data: newData,
LineIndex: existingRecord.LineIndex,
}
_, err = d.client.EditRecord(ctx, serial, zone, record)
if err != nil {
return fmt.Errorf("cpanel[mode=%s]: edit record: %w", d.config.Mode, err)
}
return nil
}
func getZoneSerial(zoneFqdn string, zoneInfo []shared.ZoneRecord) (uint32, error) {
nameB64 := base64.StdEncoding.EncodeToString([]byte(zoneFqdn))
for _, record := range zoneInfo {
if record.Type != "record" || record.RecordType != "SOA" || record.DNameB64 != nameB64 {
continue
}
// https://github.com/go-acme/lego/issues/1060#issuecomment-1925572386
// https://github.com/go-acme/lego/issues/1060#issuecomment-1925581832
data, err := base64.StdEncoding.DecodeString(record.DataB64[2])
if err != nil {
return 0, fmt.Errorf("decode serial DNameB64: %w", err)
}
var newSerial uint32
_, err = fmt.Sscan(string(data), &newSerial)
if err != nil {
return 0, fmt.Errorf("decode serial DNameB64, invalid serial value %q: %w", string(data), err)
}
return newSerial, nil
}
return 0, errors.New("zone serial not found")
}
func createClient(config *Config) (apiClient, error) {
switch strings.ToLower(config.Mode) {
case "cpanel":
client, err := cpanel.NewClient(config.BaseURL, config.Username, config.Token)
if err != nil {
return nil, fmt.Errorf("failed to create cPanel API client: %w", err)
}
if config.HTTPClient != nil {
client.HTTPClient = config.HTTPClient
}
return client, nil
case "whm":
client, err := whm.NewClient(config.BaseURL, config.Username, config.Token)
if err != nil {
return nil, fmt.Errorf("failed to create WHM API client: %w", err)
}
if config.HTTPClient != nil {
client.HTTPClient = config.HTTPClient
}
return client, nil
default:
return nil, fmt.Errorf("unsupported mode: %q", config.Mode)
}
}