// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import ( "cmp" "errors" "net/netip" "reflect" "slices" "strings" "time" "github.com/miekg/dns" ) const maxRecordSeconds = 2147483647 type recordTypeRule struct { dnsType uint16 dataType reflect.Type } var recordRules = map[string]recordTypeRule{ "A": {dns.TypeA, reflect.TypeFor[aData]()}, "AAAA": {dns.TypeAAAA, reflect.TypeFor[aaaaData]()}, "CNAME": {dns.TypeCNAME, reflect.TypeFor[cnameData]()}, "NS": {dns.TypeNS, reflect.TypeFor[nsData]()}, "MX": {dns.TypeMX, reflect.TypeFor[mxData]()}, "TXT": {dns.TypeTXT, reflect.TypeFor[txtData]()}, "SRV": {dns.TypeSRV, reflect.TypeFor[srvData]()}, "CAA": {dns.TypeCAA, reflect.TypeFor[caaData]()}, "SOA": {dns.TypeSOA, reflect.TypeFor[soaData]()}, } func validateRecordOwner(recordType, name string) error { switch recordType { case "CNAME": if name == "" { return errors.New("CNAME is not allowed at the apex") } case "NS": if name == "*" || strings.HasPrefix(name, "*.") { return errors.New("NS is not allowed at a wildcard owner") } case "SRV": parts := strings.SplitN(name, ".", 3) if len(parts) < 2 || len(parts[0]) < 2 || parts[0][0] != '_' || len(parts[1]) < 2 || parts[1][0] != '_' { return errors.New("SRV owner must start with _service._proto") } case "SOA": if name != "" { return errors.New("SOA is allowed only at the apex") } } return nil } func normalizeRecordData(zone string, data any) (any, map[string]string) { fields := make(map[string]string) host := func(key, value string, allowRoot bool) string { normalized, err := normalizeHost(zone, value, allowRoot) if err != nil { fields[key] = err.Error() } return normalized } text := func(key, value string, max int) { if len(value) == 0 || len(value) > max { fields[key] = "text length is outside the allowed range" return } for i := range len(value) { if value[i] < 0x20 || value[i] > 0x7e || value[i] == '\\' { fields[key] = "must contain only printable ASCII without backslash" return } } } switch v := data.(type) { case aData: address, err := netip.ParseAddr(v.IP) if err != nil || !address.Is4() { fields["ip"] = "must be an IPv4 dotted quad" } else { v.IP = address.String() } data = v case aaaaData: address, err := netip.ParseAddr(v.IP) if err != nil || !address.Is6() || address.Is4In6() || address.Zone() != "" { fields["ip"] = "must be an IPv6 address without an IPv4 mapping or zone identifier" } else { v.IP = address.String() } data = v case cnameData: v.Host = host("host", v.Host, false) data = v case nsData: v.Host = host("host", v.Host, false) data = v case mxData: v.Host = host("host", v.Host, true) data = v case txtData: text("text", v.Text, 4096) case srvData: v.Target = host("target", v.Target, true) data = v case caaData: if v.Flag != 0 && v.Flag != 128 { fields["flag"] = "must be 0 or 128" } if len(v.Tag) == 0 || len(v.Tag) > 15 || strings.ContainsFunc(v.Tag, func(c rune) bool { return !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9') }) { fields["tag"] = "must contain 1 to 15 lowercase ASCII letters or digits" } text("value", v.Value, 1024) case soaData: v.NS = host("ns", v.NS, false) mailbox, err := normalizeMailbox(v.MBox) if err != nil { fields["MBox"] = err.Error() } v.MBox = mailbox for key, value := range map[string]uint32{"refresh": v.Refresh, "retry": v.Retry, "expire": v.Expire, "minttl": v.MinTTL} { if value > maxRecordSeconds { fields[key] = "must be an integer from 0 to 2147483647" } } data = v } return data, fields } type zoneProblem struct { RecordID int64 `json:"record_id"` Name string `json:"name"` Type string `json:"type"` Severity string `json:"severity"` Code string `json:"code"` Message string `json:"message"` } func recordProblem(row recordRow, severity, code, message string) zoneProblem { return zoneProblem{row.ID, row.Name, row.RecordType, severity, code, message} } type zoneChanges struct { Creates []recordRow Updates []recordRow Deletes []int64 SOAUpdate *recordRow ManageSerial bool } func (changes zoneChanges) empty() bool { return len(changes.Creates)+len(changes.Updates)+len(changes.Deletes) == 0 && changes.SOAUpdate == nil && !changes.ManageSerial } func (changes zoneChanges) deletesOnly() bool { return len(changes.Deletes) > 0 && len(changes.Creates)+len(changes.Updates) == 0 && changes.SOAUpdate == nil && !changes.ManageSerial } func (changes zoneChanges) finalRows(rows []recordRow) []recordRow { updates := make(map[int64]recordRow) deletes := make(map[int64]bool) for _, row := range changes.Updates { updates[row.ID] = row } if changes.SOAUpdate != nil { updates[changes.SOAUpdate.ID] = *changes.SOAUpdate } for _, id := range changes.Deletes { deletes[id] = true } result := make([]recordRow, 0, len(rows)+len(changes.Creates)) for _, row := range rows { if deletes[row.ID] { continue } if updated, ok := updates[row.ID]; ok { row = updated } result = append(result, row) } return append(result, changes.Creates...) } func validateZoneChanges(zone string, current []recordRow, changes zoneChanges) (problems, warnings []zoneProblem) { result := changes.finalRows(current) before := summarizeZone(current) after := summarizeZone(result) problems, warnings = zoneRuleProblems(zone, result, after, true) soaRepair := len(after.soa) != 0 && soaDefects(after.soa) < soaDefects(before.soa) soaOnlyRepair := soaRepair && slices.Equal(nonSOARows(current), nonSOARows(result)) cnameRepair := soaDefects(after.soa) != 0 && changes.deletesOnly() if len(problems) != 0 && (soaOnlyRepair || cnameRepair) { beforeProblems, _ := zoneRuleProblems(zone, current, before, true) if soaOnlyRepair || (len(problems) < len(beforeProblems) && deletesOnlyConflictingCNAMEs(changes.Deletes, beforeProblems)) { existing := make(map[zoneProblem]bool, len(beforeProblems)) for _, p := range beforeProblems { existing[p] = true } problems = slices.DeleteFunc(problems, func(p zoneProblem) bool { return existing[p] }) } } if soaRepair { problems = slices.DeleteFunc(problems, func(p zoneProblem) bool { return p.Code == "soa_multiple" || p.Code == "soa_not_apex" }) } if len(before.soa) != 0 { afterSOAs := make(map[int64]bool) for _, row := range after.soa { afterSOAs[row.ID] = true } for _, row := range before.soa { if !afterSOAs[row.ID] && !soaRepair { problems = append(problems, recordProblem(row, "error", "soa_delete", "SOA may only be deleted with the zone")) } } for _, row := range changes.Creates { if row.RecordType == "SOA" && len(after.soa) == 1 { problems = append(problems, recordProblem(row, "error", "soa_multiple", "an SOA already exists")) } } } if before.apexNS > 0 && after.apexNS == 0 { problems = append(problems, recordProblem(recordRow{}, "error", "ns_apex_missing", "the last apex NS cannot be removed")) warnings = slices.DeleteFunc(warnings, func(p zoneProblem) bool { return p.Code == "ns_apex_missing" }) } return problems, warnings } func nonSOARows(rows []recordRow) []recordRow { var records []recordRow for _, row := range rows { if row.RecordType != "SOA" { records = append(records, row) } } return records } func deletesOnlyConflictingCNAMEs(ids []int64, problems []zoneProblem) bool { conflicting := make(map[int64]bool) for _, problem := range problems { if problem.Type == "CNAME" && (problem.Code == "cname_apex" || problem.Code == "cname_conflict") { conflicting[problem.RecordID] = true } } for _, id := range ids { if !conflicting[id] { return false } } return true } func soaDefects(soa []recordRow) int { defects := len(soa) - 1 for _, row := range soa { if row.Name != "" { defects++ } } return defects } type recordIdentity struct { name, recordType, content string } func canonicalIdentity(row recordRow) (recordIdentity, any, bool) { if !row.Content.Valid { return recordIdentity{}, nil, false } decoded, err := inspectRecordContent(row.RecordType, row.Content.String) if err != nil || len(decoded.fields) > 0 { return recordIdentity{}, nil, false } data, fields := normalizeRecordData(row.Zone, decoded.data) if len(fields) != 0 { return recordIdentity{}, nil, false } content, _ := encodeRecord(data) return recordIdentity{strings.ToLower(row.Name), row.RecordType, content}, data, true } type zoneRuleState struct { soa []recordRow apexNS int owners map[string]int cnames map[string]bool cuts map[string]bool address map[string]bool } func summarizeZone(rows []recordRow) zoneRuleState { summary := zoneRuleState{ owners: make(map[string]int), cnames: make(map[string]bool), cuts: make(map[string]bool), address: make(map[string]bool), } for _, row := range rows { name := strings.ToLower(row.Name) summary.owners[name]++ switch row.RecordType { case "SOA": summary.soa = append(summary.soa, row) case "NS": if name == "" { summary.apexNS++ } else if validateRecordOwner("NS", name) == nil { summary.cuts[name] = true } case "CNAME": summary.cnames[name] = true case "A", "AAAA": if _, _, ok := canonicalIdentity(row); ok && row.TTL.Valid && row.TTL.Int64 >= 0 && row.TTL.Int64 <= maxRecordSeconds { summary.address[name] = true } } } return summary } func zoneRuleProblems(zone string, rows []recordRow, summary zoneRuleState, strictDuplicates bool) (problems, warnings []zoneProblem) { if len(summary.soa) == 0 { problems = append(problems, recordProblem(recordRow{}, "error", "soa_missing", "zone has no SOA")) } if summary.apexNS == 0 { warnings = append(warnings, recordProblem(recordRow{}, "warning", "ns_apex_missing", "zone has no apex NS")) } type rrset struct{ name, recordType string } mixedTTL := make(map[rrset]bool) firstTTL := make(map[rrset]int64) for _, row := range rows { if !row.TTL.Valid || row.TTL.Int64 < 0 || row.TTL.Int64 > maxRecordSeconds { continue } key := rrset{strings.ToLower(row.Name), row.RecordType} if first, ok := firstTTL[key]; ok { mixedTTL[key] = mixedTTL[key] || first != row.TTL.Int64 } else { firstTTL[key] = row.TTL.Int64 } } identities := make(map[recordIdentity]int) data := make([]any, len(rows)) keys := make([]recordIdentity, len(rows)) for i, row := range rows { if key, value, ok := canonicalIdentity(row); ok { identities[key]++ data[i] = value keys[i] = key } } for i, row := range rows { addError := func(code, message string) { problems = append(problems, recordProblem(row, "error", code, message)) } warn := func(code, message string) { warnings = append(warnings, recordProblem(row, "warning", code, message)) } name := strings.ToLower(row.Name) if row.RecordType == "SOA" { if len(summary.soa) > 1 { addError("soa_multiple", "zone has more than one SOA") } if name != "" { addError("soa_not_apex", "SOA is allowed only at the apex") } } if name == "" && row.RecordType == "CNAME" { addError("cname_apex", "CNAME is not allowed at the apex") } if summary.cnames[name] && summary.owners[name] > 1 { addError("cname_conflict", "an owner with a CNAME cannot have another record") } if identities[keys[i]] > 1 { const message = "another record has the same name, type and content" if strictDuplicates { addError("duplicate", message) } else { warn("duplicate", message) } } if mixedTTL[rrset{name, row.RecordType}] && row.TTL.Valid && row.TTL.Int64 >= 0 && row.TTL.Int64 <= maxRecordSeconds { warn("rrset_ttl_mismatch", "records in the RRset have different TTLs") } if target := zoneRuleTarget(data[i]); target != "" && target != "." { if relative, _, err := normalizeOwner(zone, target); err == nil { if summary.cnames[relative] { warn("target_is_cname", "in-zone target is a CNAME owner") } if !summary.address[relative] { warn("target_no_address", "in-zone target has no A or AAAA record") } } } for _, parent, ok := strings.Cut(name, "."); ok; _, parent, ok = strings.Cut(parent, ".") { if summary.cuts[parent] { warn("below_zone_cut", "owner is below a non-apex NS") break } } if txt, ok := data[i].(txtData); ok && len(txt.Text) > 255 { warn("txt_split", "TXT is served in strings of at most 255 bytes") } } return problems, warnings } func zoneRuleTarget(data any) string { switch v := data.(type) { case nsData: return v.Host case mxData: return v.Host case srvData: return v.Target default: return "" } } func sortZoneRecords(rows []recordRow, now time.Time) { values := make(map[recordRow]string, len(rows)) for _, row := range rows { values[row] = recordValue(row, now) } typeOrder := func(recordType string) int { switch recordType { case "SOA": return 0 case "NS": return 1 default: return 2 } } slices.SortStableFunc(rows, func(a, b recordRow) int { return cmp.Or( compareDNSNames(a.Name, b.Name), cmp.Compare(typeOrder(a.RecordType), typeOrder(b.RecordType)), cmp.Compare(a.RecordType, b.RecordType), cmp.Compare(values[a], values[b]), cmp.Compare(a.ID, b.ID), ) }) }