Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Get the container image from [ghcr.io](https://github.com/0xFelix/hetzner-dnsapi
| API | Endpoint |
|--------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| lego HTTP request | POST `/httpreq/present`<br>POST `/httpreq/cleanup`<br>(see https://go-acme.github.io/lego/dns/httpreq/) |
| Generic records | POST `/records/present`<br>POST `/records/cleanup`<br>(JSON body `fqdn`, `type` (A, AAAA, TXT, CNAME or SRV) and `value`; SRV values are `priority weight port target` and are added to existing SRV records of the same name, all other types replace existing records; CNAME/SRV targets are made absolute; opt-in, see [Enabled endpoints](#enabled-endpoints)) |
| ACMEDNS | POST `/acmedns/update`<br>(see https://github.com/joohoi/acme-dns#update-endpoint) |
| DirectAdmin Legacy | GET `/directadmin/CMD_API_SHOW_DOMAINS`<br>GET `/directadmin/CMD_API_DNS_CONTROL` (only adding A/AAAA/TXT records, everything else always returns `200 OK`)<br>GET `/directadmin/CMD_API_DOMAIN_POINTER` (only a stub, always returns `200 OK`)<br>(see https://docs.directadmin.com/developer/api/legacy-api.html and https://www.directadmin.com/features.php?id=504) |
| plain HTTP | GET `/plain/update` (query params `hostname` and `ip` (can be ipv4 for A or ipv6 for AAAA records), if auth method is `users` then HTTP Basic auth is used) <br/> |
Expand Down Expand Up @@ -98,6 +99,8 @@ active by listing only the ones you want:
- `acmedns` - `/acmedns/update`
- `httpreq` - `/httpreq/present`, `/httpreq/cleanup`
- `directadmin` - `/directadmin/CMD_API_*`
- `records` - `/records/present`, `/records/cleanup` (supports CNAME and SRV,
**not** enabled by default, must be listed explicitly)

Via config file set the `endpoints` key; via environment variable set
`ENDPOINTS` to a comma-separated list (e.g. `ENDPOINTS=plain,nic`). Listing
Expand Down Expand Up @@ -166,5 +169,5 @@ debug: false
| `LOCKOUT_MAX_ATTEMPTS` | int | Failures before lockout | N | `10` |
| `LOCKOUT_DURATION_SECONDS` | int | Lockout duration in seconds | N | `3600` |
| `LOCKOUT_WINDOW_SECONDS` | int | Window in seconds during which consecutive failures accumulate | N | `900` |
| `ENDPOINTS` | string | Comma-separated list of endpoint groups to enable: `plain`, `nic`, `acmedns`, `httpreq`, `directadmin`. All enabled when unset. | N | All enabled |
| `ENDPOINTS` | string | Comma-separated list of endpoint groups to enable: `plain`, `nic`, `acmedns`, `httpreq`, `directadmin`, `records`. All but `records` enabled when unset. | N | All but `records` |
| `DEBUG` | bool | Output debug logs of received requests | N | `false` |
6 changes: 6 additions & 0 deletions pkg/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ func New(cfg *config.Config) http.Handler {
mux.Handle("POST /httpreq/cleanup",
handle(cfg, rl, middleware.ContentTypeJSON, middleware.BindHTTPReq, authorizer, cleaner, middleware.StatusOk))
}
if cfg.Endpoints.Records {
mux.Handle("POST /records/present",
handle(cfg, rl, middleware.ContentTypeJSON, middleware.BindRecords, authorizer, updater, middleware.StatusOk))
mux.Handle("POST /records/cleanup",
handle(cfg, rl, middleware.ContentTypeJSON, middleware.BindRecords, authorizer, cleaner, middleware.StatusOk))
}
if cfg.Endpoints.DirectAdmin {
mux.Handle("GET /directadmin/CMD_API_SHOW_DOMAINS",
handle(cfg, rl, middleware.NewShowDomainsDirectAdmin(cfg, lockout)))
Expand Down
7 changes: 7 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ type Endpoints struct {
AcmeDNS bool `yaml:"acmedns"`
HTTPReq bool `yaml:"httpreq"`
DirectAdmin bool `yaml:"directadmin"`
Records bool `yaml:"records"`
}

func (e *Endpoints) Enabled() []string {
Expand All @@ -96,6 +97,9 @@ func (e *Endpoints) Enabled() []string {
if e.DirectAdmin {
names = append(names, EndpointDirectAdmin)
}
if e.Records {
names = append(names, EndpointRecords)
}
return names
}

Expand All @@ -121,6 +125,7 @@ const (
EndpointAcmeDNS = "acmedns"
EndpointHTTPReq = "httpreq"
EndpointDirectAdmin = "directadmin"
EndpointRecords = "records"
)

const (
Expand Down Expand Up @@ -298,6 +303,8 @@ func envEndpoints(endpoints *Endpoints) error {
endpoints.HTTPReq = true
case EndpointDirectAdmin:
endpoints.DirectAdmin = true
case EndpointRecords:
endpoints.Records = true
default:
return fmt.Errorf("invalid endpoint %q in ENDPOINTS", name)
}
Expand Down
29 changes: 29 additions & 0 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ var _ = Describe("Config", func() {
envDebug = "DEBUG"
envRateLimitRPS = "RATE_LIMIT_RPS"
envLockoutMaxAtt = "LOCKOUT_MAX_ATTEMPTS"
envEndpoints = "ENDPOINTS"
)

BeforeEach(func() {
Expand All @@ -146,6 +147,7 @@ var _ = Describe("Config", func() {
Expect(os.Unsetenv(envDebug)).To(Succeed())
Expect(os.Unsetenv(envRateLimitRPS)).To(Succeed())
Expect(os.Unsetenv(envLockoutMaxAtt)).To(Succeed())
Expect(os.Unsetenv(envEndpoints)).To(Succeed())
})

It("should parse environment successfully", func() {
Expand Down Expand Up @@ -187,6 +189,28 @@ var _ = Describe("Config", func() {
}))
})

It("should enable all endpoints but records when ENDPOINTS is unset", func() {
Expect(os.Setenv(envAPIToken, apiToken)).To(Succeed())
Expect(os.Setenv(envAllowedDomains, allowedDomainsStr)).To(Succeed())

cfg, err := config.ParseEnv()
Expect(err).ToNot(HaveOccurred())
Expect(cfg.Endpoints).To(Equal(config.Endpoints{
Plain: true, Nic: true, AcmeDNS: true, HTTPReq: true, DirectAdmin: true,
}))
})

It("should enable only the endpoints listed in ENDPOINTS", func() {
Expect(os.Setenv(envAPIToken, apiToken)).To(Succeed())
Expect(os.Setenv(envAllowedDomains, allowedDomainsStr)).To(Succeed())
Expect(os.Setenv(envEndpoints, "plain, records")).To(Succeed())

cfg, err := config.ParseEnv()
Expect(err).ToNot(HaveOccurred())
Expect(cfg.Endpoints).To(Equal(config.Endpoints{Plain: true, Records: true}))
Expect(cfg.Endpoints.Enabled()).To(Equal([]string{config.EndpointPlain, config.EndpointRecords}))
})

It("should lowercase domains of ALLOWED_DOMAINS", func() {
Expect(os.Setenv(envAPIToken, apiToken)).To(Succeed())
Expect(os.Setenv(envAllowedDomains, "Example.COM,127.0.0.1/32")).To(Succeed())
Expand Down Expand Up @@ -243,6 +267,11 @@ var _ = Describe("Config", func() {
Expect(os.Setenv(envAllowedDomains, allowedDomainsStr)).To(Succeed())
Expect(os.Setenv(envLockoutMaxAtt, "0")).To(Succeed())
}, "lockout.maxAttempts must be > 0"),
Entry("ENDPOINTS contains an unknown endpoint", func() {
Expect(os.Setenv(envAPIToken, apiToken)).To(Succeed())
Expect(os.Setenv(envAllowedDomains, allowedDomainsStr)).To(Succeed())
Expect(os.Setenv(envEndpoints, "plain,unknown")).To(Succeed())
}, `invalid endpoint "unknown" in ENDPOINTS`),
)
})

Expand Down
4 changes: 2 additions & 2 deletions pkg/hetzner/hcloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,11 @@ func RRSetTypeFromString(rType string) (hcloud.ZoneRRSetType, error) {
switch rrType := hcloud.ZoneRRSetType(rType); rrType {
case hcloud.ZoneRRSetTypeA,
hcloud.ZoneRRSetTypeAAAA,
hcloud.ZoneRRSetTypeCNAME,
hcloud.ZoneRRSetTypeSRV,
hcloud.ZoneRRSetTypeTXT:
return rrType, nil
case hcloud.ZoneRRSetTypeCAA,
hcloud.ZoneRRSetTypeCNAME,
hcloud.ZoneRRSetTypeDS,
hcloud.ZoneRRSetTypeHINFO,
hcloud.ZoneRRSetTypeHTTPS,
Expand All @@ -63,7 +64,6 @@ func RRSetTypeFromString(rType string) (hcloud.ZoneRRSetType, error) {
hcloud.ZoneRRSetTypePTR,
hcloud.ZoneRRSetTypeRP,
hcloud.ZoneRRSetTypeSOA,
hcloud.ZoneRRSetTypeSRV,
hcloud.ZoneRRSetTypeSVCB,
hcloud.ZoneRRSetTypeTLSA:
return "", fmt.Errorf("unsupported resource record set type %s", rrType)
Expand Down
120 changes: 120 additions & 0 deletions pkg/middleware/bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"log"
"net/http"
"net/netip"
"regexp"
"strconv"
"strings"

"golang.org/x/net/publicsuffix"
Expand All @@ -18,10 +20,16 @@ const (
recordTypeA = "A"
recordTypeAAAA = "AAAA"
recordTypeTXT = "TXT"
recordTypeCNAME = "CNAME"
recordTypeSRV = "SRV"
failedParseRequestFmt = "failed to parse request: %v"
maxRequestBodySize = 1 << 10 // 1 KB
maxHostnameLength = 253
srvFieldCount = 4
)

var hostnameRegexp = regexp.MustCompile(`^([a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?\.)*[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?$`)

func BindPlain(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodySize)
Expand Down Expand Up @@ -180,6 +188,67 @@ func BindHTTPReq(next http.Handler) http.Handler {
})
}

// BindRecords binds requests of the generic records endpoint, which in
// addition to A, AAAA and TXT also supports CNAME and SRV records.
func BindRecords(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodySize)
d := &struct {
FQDN string `json:"fqdn"`
Type string `json:"type"`
Value string `json:"value"`
}{}
if err := json.UnmarshalRead(r.Body, d); err != nil {
log.Printf(failedParseRequestFmt, err)
w.WriteHeader(http.StatusBadRequest)
return
}

if d.FQDN == "" || d.Type == "" || d.Value == "" {
http.Error(w, "fqdn, type or value is missing", http.StatusBadRequest)
return
}

recordType := strings.ToUpper(d.Type)
fqdn := NormalizeFQDN(d.FQDN)
name, zone, err := SplitFQDN(fqdn)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

if recordType == recordTypeCNAME && name == "" {
http.Error(w, "a CNAME record is not allowed at the zone apex", http.StatusBadRequest)
return
}

value, err := normalizeRecordValue(d.Value, recordType)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

username, password, _ := r.BasicAuth()
next.ServeHTTP(
w, r.WithContext(
data.NewContextWithReqData(
r.Context(),
&data.ReqData{
FullName: fqdn,
Name: name,
Zone: zone,
Value: value,
Type: recordType,
Username: username,
Password: password,
BasicAuth: true,
},
),
),
)
})
}

func BindDirectAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodySize)
Expand Down Expand Up @@ -262,6 +331,57 @@ func validateValue(value, recordType string) error {
return nil
}

// normalizeRecordValue validates the value for the given record type and
// returns it in the form expected by the API. Hostnames in CNAME and SRV
// values are made absolute by appending a trailing dot.
func normalizeRecordValue(value, recordType string) (string, error) {
switch recordType {
case recordTypeA, recordTypeAAAA:
return value, validateValue(value, recordType)
case recordTypeTXT:
return value, nil
case recordTypeCNAME:
target, err := normalizeHostname(value)
if err != nil {
return "", err
}
return target + ".", nil
case recordTypeSRV:
// priority weight port target
fields := strings.Fields(value)
if len(fields) != srvFieldCount {
return "", errors.New("srv value must be 'priority weight port target'")
}
for i, f := range fields[:srvFieldCount-1] {
n, err := strconv.ParseUint(f, 10, 16)
if err != nil {
return "", errors.New("srv priority, weight and port must be numbers between 0 and 65535")
}
// Canonicalize, e.g. strip leading zeros, so values compare equal
fields[i] = strconv.FormatUint(n, 10)
}
// A target of '.' means that the service is not available.
if fields[srvFieldCount-1] != "." {
target, err := normalizeHostname(fields[srvFieldCount-1])
if err != nil {
return "", err
}
fields[srvFieldCount-1] = target + "."
}
return strings.Join(fields, " "), nil
default:
return "", errors.New("type can only be A, AAAA, TXT, CNAME or SRV")
}
}

func normalizeHostname(host string) (string, error) {
host = NormalizeFQDN(host)
if len(host) > maxHostnameLength || !hostnameRegexp.MatchString(host) {
return "", errors.New("invalid hostname")
}
return host, nil
}

// NormalizeFQDN strips trailing dots and lowercases the name, so that
// comparisons against configured domains are case-insensitive.
func NormalizeFQDN(fqdn string) string {
Expand Down
64 changes: 64 additions & 0 deletions pkg/middleware/bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,70 @@ var _ = Describe("Binding of names", func() {
Entry("trailing dot", "example.com.", "sub"),
Entry("upper case", "Example.COM", "SUB"),
)

DescribeTable(
"should bind records requests", func(fqdn, recordType, value, expectedName, expectedType, expectedValue string) {
reqData, code := bind(middleware.BindRecords, newJSONRequest(
`{"fqdn":"`+fqdn+`","type":"`+recordType+`","value":"`+value+`"}`,
))
Expect(code).To(Equal(http.StatusOK))
Expect(reqData.Name).To(Equal(expectedName))
Expect(reqData.Zone).To(Equal("example.com"))
Expect(reqData.Type).To(Equal(expectedType))
Expect(reqData.Value).To(Equal(expectedValue))
},
Entry("A", "sub.example.com", "A", "127.0.0.1", "sub", "A", "127.0.0.1"),
Entry("AAAA", "sub.example.com", "AAAA", "::1", "sub", "AAAA", "::1"),
Entry("TXT at the zone apex", "example.com", "TXT", "some text", "", "TXT", "some text"),
Entry("lower case type", "sub.example.com", "cname", "target.example.com", "sub", "CNAME", "target.example.com."),
Entry("CNAME", "sub.example.com", "CNAME", "target.example.com", "sub", "CNAME", "target.example.com."),
Entry(
"CNAME with absolute upper case target", "SUB.example.com.", "CNAME", "Target.Example.COM.",
"sub", "CNAME", "target.example.com.",
),
Entry("CNAME with underscore", "sub.example.com", "CNAME", "_dkim.example.com", "sub", "CNAME", "_dkim.example.com."),
Entry("SRV", "_sip._tcp.example.com", "SRV", "10 5 5060 sip.example.com", "_sip._tcp", "SRV", "10 5 5060 sip.example.com."),
Entry(
"SRV with extra whitespace", "_sip._tcp.example.com", "SRV", ` 10 5 5060\tSIP.example.com. `,
"_sip._tcp", "SRV", "10 5 5060 sip.example.com.",
),
Entry(
"SRV with maximum values", "_sip._tcp.example.com", "SRV", "65535 65535 65535 sip.example.com",
"_sip._tcp", "SRV", "65535 65535 65535 sip.example.com.",
),
Entry(
"SRV with leading zeros", "_sip._tcp.example.com", "SRV", "00 05 05060 sip.example.com",
"_sip._tcp", "SRV", "0 5 5060 sip.example.com.",
),
Entry("SRV with unavailable service", "_sip._tcp.example.com", "SRV", "0 0 0 .", "_sip._tcp", "SRV", "0 0 0 ."),
)

DescribeTable(
"should reject invalid records requests", func(body string) {
reqData, code := bind(middleware.BindRecords, newJSONRequest(body))
Expect(code).To(Equal(http.StatusBadRequest))
Expect(reqData).To(BeNil())
},
Entry("missing fqdn", `{"type":"A","value":"127.0.0.1"}`),
Entry("missing type", `{"fqdn":"sub.example.com","value":"127.0.0.1"}`),
Entry("missing value", `{"fqdn":"sub.example.com","type":"A"}`),
Entry("unsupported type", `{"fqdn":"sub.example.com","type":"MX","value":"10 mx.example.com"}`),
Entry("invalid fqdn", `{"fqdn":"com","type":"A","value":"127.0.0.1"}`),
Entry("A with ipv6 address", `{"fqdn":"sub.example.com","type":"A","value":"::1"}`),
Entry("AAAA with ipv4 address", `{"fqdn":"sub.example.com","type":"AAAA","value":"127.0.0.1"}`),
Entry("CNAME at the zone apex", `{"fqdn":"example.com","type":"CNAME","value":"target.example.com"}`),
Entry("CNAME with space in target", `{"fqdn":"sub.example.com","type":"CNAME","value":"a b.example.com"}`),
Entry("CNAME with empty label", `{"fqdn":"sub.example.com","type":"CNAME","value":"a..example.com"}`),
Entry("CNAME with leading hyphen", `{"fqdn":"sub.example.com","type":"CNAME","value":"-a.example.com"}`),
Entry("CNAME with too long label", `{"fqdn":"sub.example.com","type":"CNAME","value":"`+strings.Repeat("a", 64)+`.example.com"}`),
Entry("CNAME with too long target", `{"fqdn":"sub.example.com","type":"CNAME","value":"`+strings.Repeat("a.", 127)+`com"}`),
Entry("SRV with too few fields", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"10 5 sip.example.com"}`),
Entry("SRV with too many fields", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"10 5 5060 sip.example.com x"}`),
Entry("SRV with negative priority", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"-1 5 5060 sip.example.com"}`),
Entry("SRV with non-numeric weight", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"10 x 5060 sip.example.com"}`),
Entry("SRV with port out of range", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"10 5 65536 sip.example.com"}`),
Entry("SRV with invalid target", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"10 5 5060 sip..example.com"}`),
)
})

var _ = Describe("JSON binding", func() {
Expand Down
Loading
Loading