473 lines
15 KiB
Go
473 lines
15 KiB
Go
package dnsprovider
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const maxResponseBytes = 64 << 10
|
|
|
|
type Provider interface {
|
|
Present(context.Context, string, string) (string, error)
|
|
CreateRecord(context.Context, string, string, string) (string, error)
|
|
Cleanup(context.Context, string) error
|
|
}
|
|
|
|
type Credential struct {
|
|
Endpoint string `json:"endpoint,omitempty"`
|
|
UserID string `json:"userId,omitempty"`
|
|
APIKey string `json:"apiKey,omitempty"`
|
|
Username string `json:"username,omitempty"`
|
|
DomainKey string `json:"domainKey,omitempty"`
|
|
|
|
APIToken string `json:"apiToken,omitempty"`
|
|
ZoneID string `json:"zoneId,omitempty"`
|
|
AccessKeyID string `json:"accessKeyId,omitempty"`
|
|
AccessKeySecret string `json:"accessKeySecret,omitempty"`
|
|
SecretID string `json:"secretId,omitempty"`
|
|
SecretKey string `json:"secretKey,omitempty"`
|
|
}
|
|
|
|
func Validate(provider string, credential Credential) error {
|
|
provider = strings.ToLower(strings.TrimSpace(provider))
|
|
switch provider {
|
|
case "cloudflare":
|
|
if !validSecret(credential.APIToken, 20, 512) || !validIdentifier(credential.ZoneID, 8, 128) {
|
|
return errors.New("Cloudflare API Token 或 Zone ID 格式无效")
|
|
}
|
|
case "aliyun":
|
|
if !validIdentifier(credential.AccessKeyID, 8, 128) || !validSecret(credential.AccessKeySecret, 16, 512) {
|
|
return errors.New("阿里云 AccessKey ID 或 Secret 格式无效")
|
|
}
|
|
case "tencent":
|
|
if !validIdentifier(credential.SecretID, 8, 128) || !validSecret(credential.SecretKey, 16, 512) {
|
|
return errors.New("腾讯云 SecretId 或 SecretKey 格式无效")
|
|
}
|
|
case "west":
|
|
if credential.DomainKey != "" {
|
|
if !validSecret(credential.DomainKey, 8, 512) {
|
|
return errors.New("西部数码单域名密钥格式无效")
|
|
}
|
|
} else if !validSecret(credential.Username, 1, 128) || !validSecret(credential.APIKey, 8, 512) {
|
|
return errors.New("西部数码 API 用户名或 API 密码无效")
|
|
}
|
|
case "dnsmgr":
|
|
if !positiveID(credential.UserID) || !validSecret(credential.APIKey, 8, 512) {
|
|
return errors.New("彩虹 DNS 用户 ID 或密钥无效")
|
|
}
|
|
if _, err := publicEndpoint(credential.Endpoint); err != nil {
|
|
return err
|
|
}
|
|
default:
|
|
return errors.New("不支持的 DNS 服务商")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func New(provider, zone string, credential Credential) (Provider, error) {
|
|
if err := Validate(provider, credential); err != nil {
|
|
return nil, err
|
|
}
|
|
client := &http.Client{
|
|
Timeout: 20 * time.Second,
|
|
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
|
}
|
|
switch strings.ToLower(strings.TrimSpace(provider)) {
|
|
case "cloudflare":
|
|
return &cloudflare{client: client, token: credential.APIToken, zoneID: credential.ZoneID}, nil
|
|
case "aliyun":
|
|
return &aliyun{client: client, accessKeyID: credential.AccessKeyID, accessKeySecret: credential.AccessKeySecret, zone: zone, now: time.Now}, nil
|
|
case "tencent":
|
|
return &tencent{client: client, secretID: credential.SecretID, secretKey: credential.SecretKey, zone: zone, now: time.Now}, nil
|
|
case "west":
|
|
return &west{client: client, zone: zone, credential: credential, now: time.Now}, nil
|
|
case "dnsmgr":
|
|
return &dnsmgr{client: publicClient(), zone: zone, credential: credential, now: time.Now}, nil
|
|
default:
|
|
return nil, errors.New("不支持的 DNS 服务商")
|
|
}
|
|
}
|
|
|
|
func validSecret(value string, min, max int) bool {
|
|
if value != strings.TrimSpace(value) || strings.ContainsAny(value, "\r\n\x00") {
|
|
return false
|
|
}
|
|
return len(value) >= min && len(value) <= max && !strings.ContainsAny(value, "\r\n\x00")
|
|
}
|
|
|
|
func validIdentifier(value string, min, max int) bool {
|
|
if value != strings.TrimSpace(value) {
|
|
return false
|
|
}
|
|
if len(value) < min || len(value) > max {
|
|
return false
|
|
}
|
|
for _, char := range value {
|
|
if !(char >= 'a' && char <= 'z') && !(char >= 'A' && char <= 'Z') && !(char >= '0' && char <= '9') && char != '-' && char != '_' {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func relativeRecordName(fqdn, zone string) (string, error) {
|
|
fqdn = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(fqdn), "."))
|
|
zone = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(zone), "."))
|
|
if fqdn == zone {
|
|
return "@", nil
|
|
}
|
|
suffix := "." + zone
|
|
if !strings.HasSuffix(fqdn, suffix) {
|
|
return "", errors.New("DNS 记录不属于凭据区域")
|
|
}
|
|
return strings.TrimSuffix(fqdn, suffix), nil
|
|
}
|
|
|
|
type cloudflare struct {
|
|
client *http.Client
|
|
token string
|
|
zoneID string
|
|
baseURL string
|
|
}
|
|
|
|
func (p *cloudflare) endpoint(path string) string {
|
|
base := p.baseURL
|
|
if base == "" {
|
|
base = "https://api.cloudflare.com/client/v4"
|
|
}
|
|
return strings.TrimSuffix(base, "/") + "/zones/" + url.PathEscape(p.zoneID) + "/dns_records" + path
|
|
}
|
|
|
|
func (p *cloudflare) Present(ctx context.Context, fqdn, value string) (string, error) {
|
|
return p.CreateRecord(ctx, fqdn, "TXT", value)
|
|
}
|
|
|
|
func (p *cloudflare) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) {
|
|
if err := validateRecord(recordType, value); err != nil {
|
|
return "", err
|
|
}
|
|
payload, _ := json.Marshal(map[string]any{"type": recordType, "name": fqdn, "content": value, "ttl": 120, "proxied": false})
|
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint(""), bytes.NewReader(payload))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
request.Header.Set("Authorization", "Bearer "+p.token)
|
|
request.Header.Set("Content-Type", "application/json")
|
|
var response struct {
|
|
Success bool `json:"success"`
|
|
Result struct {
|
|
ID string `json:"id"`
|
|
} `json:"result"`
|
|
}
|
|
if err = doJSON(p.client, request, &response); err != nil || !response.Success || response.Result.ID == "" {
|
|
if err == nil {
|
|
err = errors.New("Cloudflare 未返回记录编号")
|
|
}
|
|
return "", err
|
|
}
|
|
return response.Result.ID, nil
|
|
}
|
|
|
|
func (p *cloudflare) Cleanup(ctx context.Context, recordID string) error {
|
|
if !validIdentifier(recordID, 1, 128) {
|
|
return errors.New("Cloudflare 记录编号无效")
|
|
}
|
|
request, err := http.NewRequestWithContext(ctx, http.MethodDelete, p.endpoint("/"+url.PathEscape(recordID)), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
request.Header.Set("Authorization", "Bearer "+p.token)
|
|
request.Header.Set("Content-Type", "application/json")
|
|
var response struct {
|
|
Success bool `json:"success"`
|
|
}
|
|
if err = doJSON(p.client, request, &response); err != nil {
|
|
return err
|
|
}
|
|
if !response.Success {
|
|
return errors.New("Cloudflare 删除 DNS 记录失败")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type aliyun struct {
|
|
client *http.Client
|
|
accessKeyID, accessKeySecret string
|
|
zone, baseURL string
|
|
now func() time.Time
|
|
}
|
|
|
|
func (p *aliyun) Present(ctx context.Context, fqdn, value string) (string, error) {
|
|
return p.CreateRecord(ctx, fqdn, "TXT", value)
|
|
}
|
|
|
|
func (p *aliyun) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) {
|
|
if err := validateRecord(recordType, value); err != nil {
|
|
return "", err
|
|
}
|
|
rr, err := relativeRecordName(fqdn, p.zone)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var response struct {
|
|
RecordID string `json:"RecordId"`
|
|
}
|
|
err = p.call(ctx, "AddDomainRecord", url.Values{"DomainName": {p.zone}, "RR": {rr}, "Type": {recordType}, "Value": {value}, "TTL": {"600"}}, &response)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if response.RecordID == "" {
|
|
return "", errors.New("阿里云未返回记录编号")
|
|
}
|
|
return response.RecordID, nil
|
|
}
|
|
|
|
func (p *aliyun) Cleanup(ctx context.Context, recordID string) error {
|
|
if !validIdentifier(recordID, 1, 128) {
|
|
return errors.New("阿里云记录编号无效")
|
|
}
|
|
var response struct {
|
|
Code string `json:"Code"`
|
|
Message string `json:"Message"`
|
|
}
|
|
if err := p.call(ctx, "DeleteDomainRecord", url.Values{"RecordId": {recordID}}, &response); err != nil {
|
|
return err
|
|
}
|
|
if response.Code != "" {
|
|
return &providerError{Code: response.Code, Message: response.Message}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *aliyun) call(ctx context.Context, action string, query url.Values, output any) error {
|
|
host := "dns.aliyuncs.com"
|
|
base := p.baseURL
|
|
if base == "" {
|
|
base = "https://" + host
|
|
}
|
|
parsed, err := url.Parse(base)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if parsed.Host != "" {
|
|
host = parsed.Host
|
|
}
|
|
now := p.now().UTC()
|
|
nonceBytes := make([]byte, 16)
|
|
if _, err = rand.Read(nonceBytes); err != nil {
|
|
return err
|
|
}
|
|
payloadHash := sha256Hex(nil)
|
|
headers := map[string]string{
|
|
"host": host,
|
|
"x-acs-action": action,
|
|
"x-acs-content-sha256": payloadHash,
|
|
"x-acs-date": now.Format("2006-01-02T15:04:05Z"),
|
|
"x-acs-signature-nonce": hex.EncodeToString(nonceBytes),
|
|
"x-acs-version": "2015-01-09",
|
|
}
|
|
signed := "host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version"
|
|
canonicalHeaders := "host:" + headers["host"] + "\n" + "x-acs-action:" + headers["x-acs-action"] + "\n" + "x-acs-content-sha256:" + headers["x-acs-content-sha256"] + "\n" + "x-acs-date:" + headers["x-acs-date"] + "\n" + "x-acs-signature-nonce:" + headers["x-acs-signature-nonce"] + "\n" + "x-acs-version:" + headers["x-acs-version"] + "\n"
|
|
canonical := "POST\n/\n" + query.Encode() + "\n" + canonicalHeaders + "\n" + signed + "\n" + payloadHash
|
|
stringToSign := "ACS3-HMAC-SHA256\n" + sha256Hex([]byte(canonical))
|
|
signature := hmacHex([]byte(p.accessKeySecret), stringToSign)
|
|
parsed.RawQuery = query.Encode()
|
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, parsed.String(), http.NoBody)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for name, value := range headers {
|
|
request.Header.Set(name, value)
|
|
}
|
|
request.Header.Set("Authorization", "ACS3-HMAC-SHA256 Credential="+p.accessKeyID+",SignedHeaders="+signed+",Signature="+signature)
|
|
return doJSON(p.client, request, output)
|
|
}
|
|
|
|
type tencent struct {
|
|
client *http.Client
|
|
secretID, secretKey string
|
|
zone, baseURL string
|
|
now func() time.Time
|
|
}
|
|
|
|
func (p *tencent) Present(ctx context.Context, fqdn, value string) (string, error) {
|
|
return p.CreateRecord(ctx, fqdn, "TXT", value)
|
|
}
|
|
|
|
func (p *tencent) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) {
|
|
if err := validateRecord(recordType, value); err != nil {
|
|
return "", err
|
|
}
|
|
rr, err := relativeRecordName(fqdn, p.zone)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var response struct {
|
|
Response struct {
|
|
RecordID uint64 `json:"RecordId"`
|
|
Error *providerError `json:"Error"`
|
|
} `json:"Response"`
|
|
}
|
|
err = p.call(ctx, "CreateRecord", map[string]any{"Domain": p.zone, "SubDomain": rr, "RecordType": recordType, "RecordLine": "默认", "Value": value, "TTL": 600}, &response)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if response.Response.Error != nil {
|
|
return "", response.Response.Error
|
|
}
|
|
if response.Response.RecordID == 0 {
|
|
return "", errors.New("腾讯云未返回记录编号")
|
|
}
|
|
return strconv.FormatUint(response.Response.RecordID, 10), nil
|
|
}
|
|
|
|
func (p *tencent) Cleanup(ctx context.Context, recordID string) error {
|
|
id, err := strconv.ParseUint(recordID, 10, 64)
|
|
if err != nil || id == 0 {
|
|
return errors.New("腾讯云记录编号无效")
|
|
}
|
|
var response struct {
|
|
Response struct {
|
|
Error *providerError `json:"Error"`
|
|
} `json:"Response"`
|
|
}
|
|
if err = p.call(ctx, "DeleteRecord", map[string]any{"Domain": p.zone, "RecordId": id}, &response); err != nil {
|
|
return err
|
|
}
|
|
if response.Response.Error != nil {
|
|
return response.Response.Error
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *tencent) call(ctx context.Context, action string, input any, output any) error {
|
|
payload, err := json.Marshal(input)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
host := "dnspod.tencentcloudapi.com"
|
|
endpoint := p.baseURL
|
|
if endpoint == "" {
|
|
endpoint = "https://" + host
|
|
}
|
|
parsed, err := url.Parse(endpoint)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if parsed.Host != "" {
|
|
host = parsed.Host
|
|
}
|
|
now := p.now().UTC()
|
|
timestamp := strconv.FormatInt(now.Unix(), 10)
|
|
contentType := "application/json; charset=utf-8"
|
|
canonicalHeaders := "content-type:" + contentType + "\n" + "host:" + host + "\n" + "x-tc-action:" + strings.ToLower(action) + "\n"
|
|
signedHeaders := "content-type;host;x-tc-action"
|
|
canonical := "POST\n/\n\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + sha256Hex(payload)
|
|
date := now.Format("2006-01-02")
|
|
scope := date + "/dnspod/tc3_request"
|
|
stringToSign := "TC3-HMAC-SHA256\n" + timestamp + "\n" + scope + "\n" + sha256Hex([]byte(canonical))
|
|
secretDate := hmacBytes([]byte("TC3"+p.secretKey), date)
|
|
secretService := hmacBytes(secretDate, "dnspod")
|
|
secretSigning := hmacBytes(secretService, "tc3_request")
|
|
signature := hmacHex(secretSigning, stringToSign)
|
|
authorization := "TC3-HMAC-SHA256 Credential=" + p.secretID + "/" + scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + signature
|
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, parsed.String(), bytes.NewReader(payload))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
request.Header.Set("Authorization", authorization)
|
|
request.Header.Set("Content-Type", contentType)
|
|
request.Header.Set("X-TC-Action", action)
|
|
request.Header.Set("X-TC-Timestamp", timestamp)
|
|
request.Header.Set("X-TC-Version", "2021-03-23")
|
|
return doJSON(p.client, request, output)
|
|
}
|
|
|
|
type providerError struct{ Code, Message string }
|
|
|
|
func (e *providerError) Error() string {
|
|
if e == nil {
|
|
return ""
|
|
}
|
|
if e.Code == "" {
|
|
return "DNS 服务商拒绝请求"
|
|
}
|
|
return "DNS 服务商返回错误 " + e.Code
|
|
}
|
|
|
|
func doJSON(client *http.Client, request *http.Request, output any) error {
|
|
response, err := client.Do(request)
|
|
if err != nil {
|
|
return errors.New("无法连接 DNS 服务商")
|
|
}
|
|
defer response.Body.Close()
|
|
body, err := io.ReadAll(io.LimitReader(response.Body, maxResponseBytes+1))
|
|
if err != nil {
|
|
return errors.New("读取 DNS 服务商响应失败")
|
|
}
|
|
if len(body) > maxResponseBytes {
|
|
return errors.New("DNS 服务商响应过大")
|
|
}
|
|
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
|
return fmt.Errorf("DNS 服务商返回 HTTP %d", response.StatusCode)
|
|
}
|
|
if err = json.Unmarshal(body, output); err != nil {
|
|
return errors.New("DNS 服务商响应格式无效")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func sha256Hex(data []byte) string { sum := sha256.Sum256(data); return hex.EncodeToString(sum[:]) }
|
|
func hmacBytes(key []byte, value string) []byte {
|
|
mac := hmac.New(sha256.New, key)
|
|
_, _ = mac.Write([]byte(value))
|
|
return mac.Sum(nil)
|
|
}
|
|
func hmacHex(key []byte, value string) string { return hex.EncodeToString(hmacBytes(key, value)) }
|
|
|
|
func validateRecord(recordType, value string) error {
|
|
recordType = strings.ToUpper(strings.TrimSpace(recordType))
|
|
value = strings.TrimSpace(value)
|
|
if recordType != "TXT" && recordType != "A" && recordType != "AAAA" && recordType != "CNAME" {
|
|
return errors.New("DNS record type is not supported")
|
|
}
|
|
if value == "" || len(value) > 1024 || strings.ContainsAny(value, "\r\n\x00") {
|
|
return errors.New("DNS record value is invalid")
|
|
}
|
|
if recordType == "A" && net.ParseIP(value).To4() == nil {
|
|
return errors.New("DNS A record requires IPv4")
|
|
}
|
|
if recordType == "AAAA" {
|
|
ip := net.ParseIP(value)
|
|
if ip == nil || ip.To4() != nil {
|
|
return errors.New("DNS AAAA record requires IPv6")
|
|
}
|
|
}
|
|
if recordType == "CNAME" && !brokerCompatibleDomainValue(value) {
|
|
return errors.New("DNS CNAME value is invalid")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func brokerCompatibleDomainValue(value string) bool {
|
|
value = strings.ToLower(strings.TrimSuffix(value, "."))
|
|
if len(value) < 3 || len(value) > 253 || strings.ContainsAny(value, " /\\:\t") {
|
|
return false
|
|
}
|
|
return strings.Contains(value, ".")
|
|
}
|