- feat: implement dns record model and zone checks - feat: implement zone file import and export
405 lines
10 KiB
Go
405 lines
10 KiB
Go
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Copyright (C) 2026 Bryan Joshua Pedini
|
|
|
|
package main
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"net"
|
|
"reflect"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/miekg/dns"
|
|
)
|
|
|
|
type recordRow struct {
|
|
ID int64
|
|
Zone string
|
|
Name string
|
|
TTL sql.NullInt64
|
|
Content sql.NullString
|
|
RecordType string
|
|
}
|
|
|
|
type aData struct {
|
|
IP string `json:"ip"`
|
|
}
|
|
|
|
type aaaaData struct {
|
|
IP string `json:"ip"`
|
|
}
|
|
|
|
type cnameData struct {
|
|
Host string `json:"host"`
|
|
}
|
|
|
|
type nsData struct {
|
|
Host string `json:"host"`
|
|
}
|
|
|
|
type mxData struct {
|
|
Host string `json:"host"`
|
|
Preference uint16 `json:"preference"`
|
|
}
|
|
|
|
type txtData struct {
|
|
Text string `json:"text"`
|
|
}
|
|
|
|
type srvData struct {
|
|
Priority uint16 `json:"priority"`
|
|
Weight uint16 `json:"weight"`
|
|
Port uint16 `json:"port"`
|
|
Target string `json:"target"`
|
|
}
|
|
|
|
type caaData struct {
|
|
Flag uint8 `json:"flag"`
|
|
Tag string `json:"tag"`
|
|
Value string `json:"value"`
|
|
}
|
|
|
|
type soaData struct {
|
|
NS string `json:"ns"`
|
|
MBox string `json:"MBox"`
|
|
Refresh uint32 `json:"refresh"`
|
|
Retry uint32 `json:"retry"`
|
|
Expire uint32 `json:"expire"`
|
|
MinTTL uint32 `json:"minttl"`
|
|
Serial uint32 `json:"serial"`
|
|
}
|
|
|
|
type decodedRecord struct {
|
|
data any
|
|
object map[string]json.RawMessage
|
|
fields map[string]string
|
|
decodeErr error
|
|
}
|
|
|
|
func decodeRecord(recordType string, content string) (any, error) {
|
|
decoded, err := inspectRecordContent(recordType, content)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if decoded.decodeErr != nil {
|
|
return nil, decoded.decodeErr
|
|
}
|
|
return decoded.data, nil
|
|
}
|
|
|
|
func inspectRecordContent(recordType, content string) (decodedRecord, error) {
|
|
rule, ok := recordRules[recordType]
|
|
if !ok {
|
|
return decodedRecord{}, errors.New("unknown record type")
|
|
}
|
|
var object map[string]json.RawMessage
|
|
if err := json.Unmarshal([]byte(content), &object); err != nil || object == nil {
|
|
return decodedRecord{}, errors.New("content must be a JSON object")
|
|
}
|
|
data := reflect.New(rule.dataType)
|
|
decodeErr := json.Unmarshal([]byte(content), data.Interface())
|
|
fields := make(map[string]string)
|
|
present := make(map[string]bool)
|
|
for _, key := range slices.Sorted(maps.Keys(object)) {
|
|
raw := object[key]
|
|
for field := range rule.dataType.Fields() {
|
|
name := field.Tag.Get("json")
|
|
if !strings.EqualFold(key, name) {
|
|
continue
|
|
}
|
|
present[name] = true
|
|
if string(raw) == "null" {
|
|
fields[name] = "must not be null"
|
|
} else if err := json.Unmarshal(raw, reflect.New(field.Type).Interface()); err != nil {
|
|
fields[name] = "must be a valid " + fieldDescription(field.Type.Kind())
|
|
}
|
|
break
|
|
}
|
|
}
|
|
for field := range rule.dataType.Fields() {
|
|
name := field.Tag.Get("json")
|
|
if name != "serial" && !present[name] {
|
|
fields[name] = "is required"
|
|
}
|
|
}
|
|
if decodeErr != nil && len(fields) == 0 {
|
|
fields["content"] = "contains an invalid field"
|
|
}
|
|
return decodedRecord{data.Elem().Interface(), object, fields, decodeErr}, nil
|
|
}
|
|
|
|
func fieldDescription(kind reflect.Kind) string {
|
|
switch kind {
|
|
case reflect.String:
|
|
return "string"
|
|
case reflect.Uint8:
|
|
return "integer from 0 to 255"
|
|
case reflect.Uint16:
|
|
return "integer from 0 to 65535"
|
|
default:
|
|
return "integer from 0 to 4294967295"
|
|
}
|
|
}
|
|
|
|
func encodeRecord(data any) (string, error) {
|
|
switch data.(type) {
|
|
case aData, aaaaData, cnameData, nsData, mxData, txtData, srvData, caaData, soaData:
|
|
encoded, err := json.Marshal(data)
|
|
return string(encoded), err
|
|
default:
|
|
return "", errors.New("unsupported record data")
|
|
}
|
|
}
|
|
|
|
func validateRecord(zone, name, recordType string, ttl int64, content json.RawMessage, now time.Time) (recordRow, map[string]string) {
|
|
fields := make(map[string]string)
|
|
normalizedZone, _ := normalizeZone(zone)
|
|
relative, _, nameErr := normalizeOwner(zone, name)
|
|
if nameErr != nil {
|
|
fields["name"] = nameErr.Error()
|
|
}
|
|
if ttl < 0 || ttl > maxRecordSeconds {
|
|
fields["ttl"] = "must be an integer from 0 to 2147483647"
|
|
}
|
|
decoded, err := inspectRecordContent(recordType, string(content))
|
|
if err != nil {
|
|
field := "content"
|
|
if _, ok := recordRules[recordType]; !ok {
|
|
field = "type"
|
|
}
|
|
fields[field] = err.Error()
|
|
return recordRow{}, fields
|
|
}
|
|
data, dataFields := normalizeRecordData(normalizedZone, decoded.data)
|
|
if nameErr == nil {
|
|
if err := validateRecordOwner(recordType, relative); err != nil {
|
|
fields["name"] = err.Error()
|
|
}
|
|
}
|
|
for key, message := range dataFields {
|
|
fields[key] = message
|
|
}
|
|
for key, message := range decoded.fields {
|
|
fields[key] = message
|
|
}
|
|
if len(fields) != 0 {
|
|
return recordRow{}, fields
|
|
}
|
|
|
|
row := recordRow{
|
|
Zone: normalizedZone,
|
|
Name: relative,
|
|
TTL: sql.NullInt64{Int64: ttl, Valid: true},
|
|
RecordType: recordType,
|
|
}
|
|
rr, err := buildRecordRR(row, data, now)
|
|
if err != nil || packRecordRR(rr) != nil {
|
|
fields["name"] = "record cannot be packed as DNS data"
|
|
return recordRow{}, fields
|
|
}
|
|
row.Content.String, _ = encodeRecord(data)
|
|
row.Content.Valid = true
|
|
return row, nil
|
|
}
|
|
|
|
func recordFQDN(row recordRow) string {
|
|
if row.Name == "" {
|
|
return dns.Fqdn(row.Zone)
|
|
}
|
|
return dns.Fqdn(row.Name + "." + row.Zone)
|
|
}
|
|
|
|
func effectiveRecordTTL(ttl uint32) uint32 {
|
|
if ttl == 0 {
|
|
return 360
|
|
}
|
|
return ttl
|
|
}
|
|
|
|
func recordRR(row recordRow, now time.Time) (dns.RR, error) {
|
|
if !row.TTL.Valid || row.TTL.Int64 < 0 || row.TTL.Int64 > int64(^uint32(0)) || !row.Content.Valid {
|
|
return nil, errors.New("invalid record columns")
|
|
}
|
|
data, err := decodeRecord(row.RecordType, row.Content.String)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return buildRecordRR(row, data, now)
|
|
}
|
|
|
|
func buildRecordRR(row recordRow, data any, now time.Time) (dns.RR, error) {
|
|
header := dns.RR_Header{
|
|
Name: recordFQDN(row),
|
|
Rrtype: recordRules[row.RecordType].dnsType,
|
|
Class: dns.ClassINET,
|
|
Ttl: effectiveRecordTTL(uint32(row.TTL.Int64)),
|
|
}
|
|
switch v := data.(type) {
|
|
case aData, aaaaData:
|
|
address, err := recordIP(data)
|
|
if address == nil || err != nil {
|
|
return nil, err
|
|
}
|
|
if row.RecordType == "A" {
|
|
return &dns.A{Hdr: header, A: address}, nil
|
|
}
|
|
return &dns.AAAA{Hdr: header, AAAA: address}, nil
|
|
case cnameData:
|
|
if v.Host != "" {
|
|
return &dns.CNAME{Hdr: header, Target: dns.Fqdn(v.Host)}, nil
|
|
}
|
|
case nsData:
|
|
if v.Host != "" {
|
|
return &dns.NS{Hdr: header, Ns: v.Host}, nil
|
|
}
|
|
case mxData:
|
|
if v.Host != "" {
|
|
return &dns.MX{Hdr: header, Mx: v.Host, Preference: v.Preference}, nil
|
|
}
|
|
case txtData:
|
|
if v.Text != "" {
|
|
return &dns.TXT{Hdr: header, Txt: splitRecordTXT(v.Text)}, nil
|
|
}
|
|
case srvData:
|
|
if v.Target != "" {
|
|
return &dns.SRV{Hdr: header, Target: v.Target, Priority: v.Priority, Weight: v.Weight, Port: v.Port}, nil
|
|
}
|
|
case caaData:
|
|
if v.Tag != "" && v.Value != "" {
|
|
return &dns.CAA{Hdr: header, Flag: v.Flag, Tag: v.Tag, Value: v.Value}, nil
|
|
}
|
|
case soaData:
|
|
if v.Serial == 0 {
|
|
v.Serial = uint32(now.Unix())
|
|
}
|
|
if v.NS == "" {
|
|
v.NS, v.MBox = "ns1."+row.Name, "hostmaster."+row.Name
|
|
v.Refresh, v.Retry, v.Expire, v.MinTTL = 86400, 7200, 3600, header.Ttl
|
|
} else {
|
|
header.Name = dns.Fqdn(row.Zone)
|
|
}
|
|
return &dns.SOA{Hdr: header, Ns: v.NS, Mbox: v.MBox, Refresh: v.Refresh, Retry: v.Retry, Expire: v.Expire, Minttl: v.MinTTL, Serial: v.Serial}, nil
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
func recordIP(data any) (net.IP, error) {
|
|
var text string
|
|
switch v := data.(type) {
|
|
case aData:
|
|
text = v.IP
|
|
case aaaaData:
|
|
text = v.IP
|
|
}
|
|
if text == "" {
|
|
return nil, nil
|
|
}
|
|
address := net.ParseIP(text)
|
|
if address == nil {
|
|
return nil, errors.New("invalid IP address")
|
|
}
|
|
return address, nil
|
|
}
|
|
|
|
func splitRecordTXT(text string) []string {
|
|
var parts []string
|
|
for len(text) >= 255 {
|
|
parts = append(parts, text[:255])
|
|
text = text[255:]
|
|
}
|
|
return append(parts, text)
|
|
}
|
|
|
|
func packRecordRR(rr dns.RR) error {
|
|
if rr == nil {
|
|
return errors.New("record has no DNS data")
|
|
}
|
|
msg := dns.Msg{Answer: []dns.RR{rr}, Compress: true}
|
|
_, err := msg.Pack()
|
|
return err
|
|
}
|
|
|
|
func recordValue(row recordRow, now time.Time) string {
|
|
if rr, err := recordRR(row, now); err == nil && rr != nil {
|
|
if txt, ok := rr.(*dns.TXT); ok {
|
|
return strings.Join(txt.Txt, "")
|
|
}
|
|
return strings.TrimPrefix(rr.String(), rr.Header().String())
|
|
}
|
|
return row.Content.String
|
|
}
|
|
|
|
func recordETag(row recordRow) string {
|
|
hash := sha256.New()
|
|
for _, value := range []string{strconv.FormatInt(row.ID, 10), row.Zone, row.Name} {
|
|
fmt.Fprintf(hash, "%d:%s", len(value), value)
|
|
}
|
|
if row.TTL.Valid {
|
|
fmt.Fprintf(hash, "V%d:", row.TTL.Int64)
|
|
} else {
|
|
fmt.Fprint(hash, "N")
|
|
}
|
|
fmt.Fprintf(hash, "%d:%s", len(row.RecordType), row.RecordType)
|
|
if row.Content.Valid {
|
|
fmt.Fprintf(hash, "V%d:%s", len(row.Content.String), row.Content.String)
|
|
} else {
|
|
fmt.Fprint(hash, "N")
|
|
}
|
|
return fmt.Sprintf("\"%x\"", hash.Sum(nil))
|
|
}
|
|
|
|
type newZoneSpec struct {
|
|
Zone string
|
|
PrimaryNS string
|
|
Mailbox string
|
|
ExtraNS []string
|
|
Refresh uint32
|
|
Retry uint32
|
|
Expire uint32
|
|
MinTTL uint32
|
|
TTL int64
|
|
}
|
|
|
|
func newZoneRows(spec newZoneSpec, now time.Time) ([]recordRow, map[string]string) {
|
|
zone, err := normalizeZone(spec.Zone)
|
|
if err != nil {
|
|
return nil, map[string]string{"zone": err.Error()}
|
|
}
|
|
soa := soaData{
|
|
NS: spec.PrimaryNS, MBox: spec.Mailbox, Refresh: spec.Refresh, Retry: spec.Retry,
|
|
Expire: spec.Expire, MinTTL: spec.MinTTL, Serial: newSOASerial(now),
|
|
}
|
|
content, _ := encodeRecord(soa)
|
|
apexSOA, fields := validateRecord(zone, "", "SOA", spec.TTL, json.RawMessage(content), now)
|
|
if len(fields) != 0 {
|
|
return nil, fields
|
|
}
|
|
rows := []recordRow{apexSOA}
|
|
hosts := make(map[string]bool)
|
|
for i, host := range append([]string{spec.PrimaryNS}, spec.ExtraNS...) {
|
|
content, _ := encodeRecord(nsData{Host: host})
|
|
row, fields := validateRecord(zone, "", "NS", spec.TTL, json.RawMessage(content), now)
|
|
key := "ns"
|
|
if i > 0 {
|
|
key = fmt.Sprintf("extra_ns.%d", i-1)
|
|
}
|
|
if len(fields) != 0 {
|
|
return nil, map[string]string{key: fields["host"]}
|
|
}
|
|
if hosts[row.Content.String] {
|
|
return nil, map[string]string{key: "duplicates another nameserver"}
|
|
}
|
|
hosts[row.Content.String] = true
|
|
rows = append(rows, row)
|
|
}
|
|
return rows, nil
|
|
}
|