feat(dnssec): query the authoritative servers directly
This commit is contained in:
226
common/dnssec/authchain.go
Normal file
226
common/dnssec/authchain.go
Normal file
@@ -0,0 +1,226 @@
|
||||
package dnssec
|
||||
|
||||
// CODE ADAPTED FROM THIS
|
||||
|
||||
// ISC License
|
||||
//
|
||||
// Copyright (c) 2012-2016 Peter Banik <peter@froggle.org>
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type AuthenticationChain struct {
|
||||
DelegationChain []SignedZone
|
||||
}
|
||||
|
||||
func NewAuthenticationChain() *AuthenticationChain {
|
||||
return &AuthenticationChain{}
|
||||
}
|
||||
|
||||
func (ac *AuthenticationChain) Populate(domainName string, queryFunc func(string, uint16) (*dns.Msg, error)) error {
|
||||
// Clean domain name and split into components
|
||||
domainName = strings.TrimSuffix(domainName, ".")
|
||||
qnameComponents := strings.Split(domainName, ".")
|
||||
|
||||
// Remove empty components
|
||||
var cleanComponents []string
|
||||
for _, comp := range qnameComponents {
|
||||
if comp != "" {
|
||||
cleanComponents = append(cleanComponents, comp)
|
||||
}
|
||||
}
|
||||
|
||||
// Build zones from root down to target
|
||||
// For example.com: [".","com.","example.com."]
|
||||
zones := []string{"."} // Start with root
|
||||
|
||||
// Add each level from TLD down to target
|
||||
for i := len(cleanComponents) - 1; i >= 0; i-- {
|
||||
zone := dns.Fqdn(strings.Join(cleanComponents[i:], "."))
|
||||
zones = append(zones, zone)
|
||||
}
|
||||
|
||||
log.Printf("Building DNSSEC chain for zones: %v", zones)
|
||||
|
||||
ac.DelegationChain = make([]SignedZone, 0, len(zones))
|
||||
|
||||
// Query each zone from root down
|
||||
for i, zoneName := range zones {
|
||||
log.Printf("Querying zone: %s", zoneName)
|
||||
|
||||
delegation, err := ac.queryDelegation(zoneName, queryFunc)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to query zone %s: %w", zoneName, err)
|
||||
}
|
||||
|
||||
// Set parent relationship (previous zone in chain is parent)
|
||||
if i > 0 {
|
||||
delegation.ParentZone = &ac.DelegationChain[i-1]
|
||||
}
|
||||
|
||||
ac.DelegationChain = append(ac.DelegationChain, *delegation)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ac *AuthenticationChain) queryDelegation(domainName string, queryFunc func(string, uint16) (*dns.Msg, error)) (*SignedZone, error) {
|
||||
signedZone := NewSignedZone(domainName)
|
||||
|
||||
// Query DNSKEY records
|
||||
dnskeyRRset, err := ac.queryRRset(domainName, dns.TypeDNSKEY, queryFunc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
signedZone.DNSKey = dnskeyRRset
|
||||
|
||||
log.Printf("Found %d DNSKEY records for %s", len(dnskeyRRset.RRs), domainName)
|
||||
|
||||
// Populate public key lookup
|
||||
for _, rr := range signedZone.DNSKey.RRs {
|
||||
if dnskey, ok := rr.(*dns.DNSKEY); ok {
|
||||
signedZone.AddPubKey(dnskey)
|
||||
log.Printf("Added DNSKEY for %s: keytag=%d, flags=%d, algorithm=%d", domainName, dnskey.KeyTag(), dnskey.Flags, dnskey.Algorithm)
|
||||
}
|
||||
}
|
||||
|
||||
// Only query DS records for non-root zones
|
||||
if domainName != "." {
|
||||
dsRRset, _ := ac.queryRRset(domainName, dns.TypeDS, queryFunc)
|
||||
signedZone.DS = dsRRset
|
||||
if dsRRset != nil && len(dsRRset.RRs) > 0 {
|
||||
log.Printf("Found %d DS records for %s", len(dsRRset.RRs), domainName)
|
||||
for _, rr := range dsRRset.RRs {
|
||||
if ds, ok := rr.(*dns.DS); ok {
|
||||
log.Printf("DS record for %s: keytag=%d", domainName, ds.KeyTag)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Root zone has no DS records - trusted by default
|
||||
signedZone.DS = NewRRSet()
|
||||
log.Printf("Root zone - no DS records, trusted by default")
|
||||
}
|
||||
|
||||
return signedZone, nil
|
||||
}
|
||||
|
||||
func (ac *AuthenticationChain) queryRRset(qname string, qtype uint16, queryFunc func(string, uint16) (*dns.Msg, error)) (*RRSet, error) {
|
||||
r, err := queryFunc(qname, qtype)
|
||||
if err != nil {
|
||||
log.Printf("cannot lookup %v", err)
|
||||
return NewRRSet(), nil // Return empty RRSet instead of nil
|
||||
}
|
||||
|
||||
if r.Rcode == dns.RcodeNameError {
|
||||
log.Printf("no such domain %s", qname)
|
||||
return NewRRSet(), nil // Return empty RRSet instead of nil
|
||||
}
|
||||
|
||||
result := NewRRSet()
|
||||
if r.Answer == nil {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
result.RRs = make([]dns.RR, 0, len(r.Answer))
|
||||
|
||||
for _, rr := range r.Answer {
|
||||
switch t := rr.(type) {
|
||||
case *dns.RRSIG:
|
||||
if result.RRSig == nil || t.TypeCovered == qtype {
|
||||
result.RRSig = t
|
||||
}
|
||||
default:
|
||||
if rr != nil && rr.Header().Rrtype == qtype {
|
||||
result.RRs = append(result.RRs, rr)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (ac *AuthenticationChain) Verify(answerRRset *RRSet) error {
|
||||
if len(ac.DelegationChain) == 0 {
|
||||
return ErrDnskeyNotAvailable
|
||||
}
|
||||
|
||||
// Find the target zone (last in chain)
|
||||
targetZone := &ac.DelegationChain[len(ac.DelegationChain)-1]
|
||||
|
||||
// Verify the answer RRset against target zone's keys
|
||||
err := targetZone.VerifyRRSIG(answerRRset)
|
||||
if err != nil {
|
||||
log.Printf("Answer RRSIG verification failed: %v", err)
|
||||
return ErrInvalidRRsig
|
||||
}
|
||||
|
||||
// Validate the chain from root down
|
||||
for _, zone := range ac.DelegationChain {
|
||||
log.Printf("Validating zone: %s", zone.Zone)
|
||||
|
||||
// Verify DNSKEY RRset signature
|
||||
if !zone.HasDNSKeys() {
|
||||
log.Printf("No DNSKEYs for zone %s", zone.Zone)
|
||||
return ErrDnskeyNotAvailable
|
||||
}
|
||||
|
||||
err := zone.VerifyRRSIG(zone.DNSKey)
|
||||
if err != nil {
|
||||
log.Printf("DNSKEY validation failed for %s: %v", zone.Zone, err)
|
||||
return ErrRrsigValidationError
|
||||
}
|
||||
|
||||
// Skip ALL validation for root - just trust it
|
||||
if zone.Zone == "." {
|
||||
log.Printf("Root zone - trusted by default, no validation performed")
|
||||
continue
|
||||
}
|
||||
|
||||
// For non-root zones, validate DS records against parent zone
|
||||
if zone.ParentZone == nil {
|
||||
log.Printf("Non-root zone %s has no parent", zone.Zone)
|
||||
return fmt.Errorf("non-root zone %s has no parent", zone.Zone)
|
||||
}
|
||||
|
||||
if zone.DS == nil || zone.DS.IsEmpty() {
|
||||
log.Printf("No DS records for zone %s", zone.Zone)
|
||||
return ErrDsNotAvailable
|
||||
}
|
||||
|
||||
// Verify DS signature using parent's key
|
||||
err = zone.ParentZone.VerifyRRSIG(zone.DS)
|
||||
if err != nil {
|
||||
log.Printf("DS signature validation failed for %s: %v", zone.Zone, err)
|
||||
return ErrRrsigValidationError
|
||||
}
|
||||
|
||||
// Verify DS matches this zone's DNSKEY
|
||||
err = zone.VerifyDS(zone.DS.RRs)
|
||||
if err != nil {
|
||||
log.Printf("DS-DNSKEY validation failed for %s: %v", zone.Zone, err)
|
||||
return ErrDsInvalid
|
||||
}
|
||||
|
||||
log.Printf("Zone %s validated successfully", zone.Zone)
|
||||
}
|
||||
|
||||
log.Printf("DNSSEC validation successful for entire chain!")
|
||||
return nil
|
||||
}
|
||||
213
common/dnssec/authoritative.go
Normal file
213
common/dnssec/authoritative.go
Normal file
@@ -0,0 +1,213 @@
|
||||
package dnssec
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type AuthoritativeQuerier struct {
|
||||
client *dns.Client
|
||||
// Cache of NS records to avoid repeated lookups
|
||||
nsCache map[string][]string
|
||||
ipCache map[string]string
|
||||
}
|
||||
|
||||
func NewAuthoritativeQuerier() *AuthoritativeQuerier {
|
||||
return &AuthoritativeQuerier{
|
||||
client: &dns.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
},
|
||||
nsCache: make(map[string][]string),
|
||||
ipCache: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
func (aq *AuthoritativeQuerier) QueryAuthoritative(qname string, qtype uint16) (*dns.Msg, error) {
|
||||
log.Printf("Querying authoritative servers for %s type %d", qname, qtype)
|
||||
|
||||
var zone string
|
||||
if qtype == dns.TypeDS {
|
||||
zone = aq.getParentZone(qname)
|
||||
if zone == "" {
|
||||
log.Printf("No parent zone for %s - returning NXDOMAIN for DS query", qname)
|
||||
msg := &dns.Msg{}
|
||||
msg.SetRcode(&dns.Msg{}, dns.RcodeNameError)
|
||||
return msg, nil
|
||||
}
|
||||
} else {
|
||||
zone = aq.findZone(qname)
|
||||
}
|
||||
|
||||
log.Printf("Determined zone: %s for query %s type %d", zone, qname, qtype)
|
||||
|
||||
// Get NS names (not IPs yet)
|
||||
nsNames, err := aq.findAuthoritativeNSNames(zone)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to find authoritative servers: %w", err)
|
||||
}
|
||||
|
||||
// Try servers one by one, resolving IPs lazily
|
||||
var lastErr error
|
||||
for _, nsName := range nsNames {
|
||||
server := aq.resolveNSToIP(nsName)
|
||||
if server == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("Trying server: %s (%s)", server, nsName)
|
||||
msg, err := aq.queryServer(server, qname, qtype)
|
||||
if err != nil {
|
||||
log.Printf("Server %s failed: %v", server, err)
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("Server %s responded, authoritative: %v, rcode: %d, answers: %d", server, msg.Authoritative, msg.Rcode, len(msg.Answer))
|
||||
if (msg.Rcode == dns.RcodeSuccess && len(msg.Answer) > 0) || msg.Rcode == dns.RcodeNameError {
|
||||
return msg, nil
|
||||
}
|
||||
}
|
||||
|
||||
if lastErr != nil {
|
||||
return nil, fmt.Errorf("all servers failed, last error: %w", lastErr)
|
||||
}
|
||||
return nil, fmt.Errorf("no authoritative response received")
|
||||
}
|
||||
|
||||
func (aq *AuthoritativeQuerier) findAuthoritativeNSNames(zone string) ([]string, error) {
|
||||
|
||||
if nsNames, exists := aq.nsCache[zone]; exists {
|
||||
log.Printf("Using cached NS names for %s: %v", zone, nsNames)
|
||||
return nsNames, nil
|
||||
}
|
||||
|
||||
log.Printf("Looking for NS records for zone: %s", zone)
|
||||
|
||||
// Use a public resolver to find the NS records
|
||||
resolver := &dns.Client{Timeout: 5 * time.Second}
|
||||
|
||||
msg, _, err := resolver.Exchange(&dns.Msg{
|
||||
MsgHdr: dns.MsgHdr{
|
||||
Id: dns.Id(),
|
||||
RecursionDesired: true,
|
||||
},
|
||||
Question: []dns.Question{{Name: dns.Fqdn(zone), Qtype: dns.TypeNS, Qclass: dns.ClassINET}},
|
||||
}, "8.8.8.8:53")
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to query NS records: %w", err)
|
||||
}
|
||||
|
||||
var nsNames []string
|
||||
|
||||
// Collect NS records from answer section
|
||||
for _, rr := range msg.Answer {
|
||||
if ns, ok := rr.(*dns.NS); ok {
|
||||
nsNames = append(nsNames, ns.Ns)
|
||||
}
|
||||
}
|
||||
|
||||
// Also check authority section if answer is empty
|
||||
if len(nsNames) == 0 {
|
||||
for _, rr := range msg.Ns {
|
||||
if ns, ok := rr.(*dns.NS); ok {
|
||||
nsNames = append(nsNames, ns.Ns)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(nsNames) == 0 {
|
||||
return nil, fmt.Errorf("no NS servers found for %s", zone)
|
||||
}
|
||||
|
||||
log.Printf("Found NS names for %s: %v", zone, nsNames)
|
||||
aq.nsCache[zone] = nsNames
|
||||
log.Printf("Cached NS names for %s: %v", zone, nsNames)
|
||||
return nsNames, nil
|
||||
}
|
||||
|
||||
func (aq *AuthoritativeQuerier) getParentZone(qname string) string {
|
||||
log.Printf("Getting parent zone for: %s", qname)
|
||||
|
||||
// Clean the qname
|
||||
qname = strings.TrimSuffix(qname, ".")
|
||||
|
||||
// Root zone has no parent
|
||||
if qname == "" || qname == "." {
|
||||
log.Printf("Root zone has no parent")
|
||||
return ""
|
||||
}
|
||||
|
||||
labels := dns.SplitDomainName(qname)
|
||||
log.Printf("Labels for %s: %v", qname, labels)
|
||||
|
||||
if len(labels) <= 1 {
|
||||
log.Printf("Parent of TLD %s is root", qname)
|
||||
return "." // Parent of TLD is root
|
||||
}
|
||||
|
||||
parentLabels := labels[1:]
|
||||
parent := dns.Fqdn(strings.Join(parentLabels, "."))
|
||||
log.Printf("Parent zone of %s is %s", qname, parent)
|
||||
return parent
|
||||
}
|
||||
|
||||
func (aq *AuthoritativeQuerier) findZone(qname string) string {
|
||||
// For now, assume the zone is the domain itself
|
||||
// In a more sophisticated implementation, you'd walk up the hierarchy
|
||||
labels := dns.SplitDomainName(qname)
|
||||
if len(labels) >= 2 {
|
||||
return labels[len(labels)-2] + "." + labels[len(labels)-1] + "."
|
||||
}
|
||||
return qname
|
||||
}
|
||||
|
||||
|
||||
func (aq *AuthoritativeQuerier) resolveNSToIP(nsName string) string {
|
||||
if ip, exists := aq.ipCache[nsName]; exists {
|
||||
log.Printf("Using cached IP for %s: %s", nsName, ip)
|
||||
return ip
|
||||
}
|
||||
|
||||
nsName = strings.TrimSuffix(nsName, ".")
|
||||
log.Printf("Resolving NS %s to IP", nsName)
|
||||
|
||||
ips, err := net.LookupIP(nsName)
|
||||
if err != nil {
|
||||
log.Printf("Failed to resolve %s: %v", nsName, err)
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, ip := range ips {
|
||||
if ip.To4() != nil { // Prefer IPv4
|
||||
result := ip.String() + ":53"
|
||||
log.Printf("Resolved %s to %s", nsName, result)
|
||||
|
||||
// Cache the result before returning
|
||||
aq.ipCache[nsName] = result
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func (aq *AuthoritativeQuerier) queryServer(server, qname string, qtype uint16) (*dns.Msg, error) {
|
||||
m := new(dns.Msg)
|
||||
m.SetQuestion(dns.Fqdn(qname), qtype)
|
||||
m.SetEdns0(4096, true) // Enable DNSSEC
|
||||
|
||||
log.Printf("Querying %s for %s type %d", server, qname, qtype)
|
||||
msg, _, err := aq.client.Exchange(m, server)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Printf("Response from %s: rcode=%d, answers=%d", server, msg.Rcode, len(msg.Answer))
|
||||
return msg, err
|
||||
}
|
||||
35
common/dnssec/errors.go
Normal file
35
common/dnssec/errors.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package dnssec
|
||||
|
||||
// CODE ADAPTED FROM THIS
|
||||
|
||||
// ISC License
|
||||
//
|
||||
// Copyright (c) 2012-2016 Peter Banik <peter@froggle.org>
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrResourceNotSigned = errors.New("resource is not signed with RRSIG")
|
||||
ErrNoResult = errors.New("requested RR not found")
|
||||
ErrDnskeyNotAvailable = errors.New("DNSKEY RR does not exist")
|
||||
ErrDsNotAvailable = errors.New("DS RR does not exist")
|
||||
ErrInvalidRRsig = errors.New("invalid RRSIG")
|
||||
ErrForgedRRsig = errors.New("forged RRSIG header")
|
||||
ErrRrsigValidationError = errors.New("RR doesn't validate against RRSIG")
|
||||
ErrRrsigValidityPeriod = errors.New("invalid RRSIG validity period")
|
||||
ErrUnknownDsDigestType = errors.New("unknown DS digest type")
|
||||
ErrDsInvalid = errors.New("DS RR does not match DNSKEY")
|
||||
ErrInvalidQuery = errors.New("invalid query input")
|
||||
)
|
||||
77
common/dnssec/rrset.go
Normal file
77
common/dnssec/rrset.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package dnssec
|
||||
|
||||
// CODE ADAPTED FROM THIS
|
||||
|
||||
// ISC License
|
||||
//
|
||||
// Copyright (c) 2012-2016 Peter Banik <peter@froggle.org>
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type RRSet struct {
|
||||
RRs []dns.RR
|
||||
RRSig *dns.RRSIG
|
||||
}
|
||||
|
||||
func NewRRSet() *RRSet {
|
||||
return &RRSet{
|
||||
RRs: make([]dns.RR, 0),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RRSet) IsSigned() bool {
|
||||
return r.RRSig != nil
|
||||
}
|
||||
|
||||
func (r *RRSet) IsEmpty() bool {
|
||||
return len(r.RRs) < 1
|
||||
}
|
||||
|
||||
func (r *RRSet) SignerName() string {
|
||||
if r.RRSig == nil {
|
||||
return ""
|
||||
}
|
||||
return r.RRSig.SignerName
|
||||
}
|
||||
|
||||
func (r *RRSet) CheckHeaderIntegrity(qname string) error {
|
||||
if r.RRSig != nil && r.RRSig.Header().Name != qname {
|
||||
return ErrForgedRRsig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RRSet) ValidateSignature(key *dns.DNSKEY) error {
|
||||
if !r.IsSigned() {
|
||||
return ErrInvalidRRsig
|
||||
}
|
||||
|
||||
err := r.RRSig.Verify(key, r.RRs)
|
||||
if err != nil {
|
||||
log.Printf("RRSIG verification failed: %v", err)
|
||||
return ErrRrsigValidationError
|
||||
}
|
||||
|
||||
if !r.RRSig.ValidityPeriod(time.Now()) {
|
||||
return ErrRrsigValidityPeriod
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
104
common/dnssec/signedzone.go
Normal file
104
common/dnssec/signedzone.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package dnssec
|
||||
|
||||
// CODE ADAPTED FROM THIS
|
||||
|
||||
// ISC License
|
||||
//
|
||||
// Copyright (c) 2012-2016 Peter Banik <peter@froggle.org>
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type SignedZone struct {
|
||||
Zone string
|
||||
DNSKey *RRSet
|
||||
DS *RRSet
|
||||
ParentZone *SignedZone
|
||||
PubKeyLookup map[uint16]*dns.DNSKEY
|
||||
}
|
||||
|
||||
func NewSignedZone(domainName string) *SignedZone {
|
||||
return &SignedZone{
|
||||
Zone: domainName,
|
||||
DS: NewRRSet(),
|
||||
DNSKey: NewRRSet(),
|
||||
PubKeyLookup: make(map[uint16]*dns.DNSKEY),
|
||||
}
|
||||
}
|
||||
|
||||
func (z *SignedZone) LookupPubKey(keyTag uint16) *dns.DNSKEY {
|
||||
return z.PubKeyLookup[keyTag]
|
||||
}
|
||||
|
||||
func (z *SignedZone) AddPubKey(k *dns.DNSKEY) {
|
||||
z.PubKeyLookup[k.KeyTag()] = k
|
||||
}
|
||||
|
||||
func (z *SignedZone) HasDNSKeys() bool {
|
||||
return len(z.DNSKey.RRs) > 0
|
||||
}
|
||||
|
||||
func (z *SignedZone) VerifyRRSIG(signedRRset *RRSet) error {
|
||||
if !signedRRset.IsSigned() {
|
||||
return ErrInvalidRRsig
|
||||
}
|
||||
|
||||
key := z.LookupPubKey(signedRRset.RRSig.KeyTag)
|
||||
if key == nil {
|
||||
log.Printf("DNSKEY keytag %d not found in zone %s", signedRRset.RRSig.KeyTag, z.Zone)
|
||||
return ErrDnskeyNotAvailable
|
||||
}
|
||||
|
||||
return signedRRset.ValidateSignature(key)
|
||||
}
|
||||
|
||||
func (z *SignedZone) VerifyDS(dsRRset []dns.RR) error {
|
||||
log.Printf("Verifying DS for zone %s with %d DS records", z.Zone, len(dsRRset))
|
||||
for _, rr := range dsRRset {
|
||||
ds, ok := rr.(*dns.DS)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("Checking DS keytag %d, digestType %d", ds.KeyTag, ds.DigestType)
|
||||
|
||||
if ds.DigestType != dns.SHA256 {
|
||||
log.Printf("Unknown digest type (%d) on DS RR", ds.DigestType)
|
||||
continue
|
||||
}
|
||||
|
||||
parentDsDigest := strings.ToUpper(ds.Digest)
|
||||
key := z.LookupPubKey(ds.KeyTag)
|
||||
if key == nil {
|
||||
log.Printf("DNSKEY keytag %d not found in zone %s", ds.KeyTag, z.Zone)
|
||||
return ErrDnskeyNotAvailable
|
||||
}
|
||||
|
||||
dsDigest := strings.ToUpper(key.ToDS(ds.DigestType).Digest)
|
||||
log.Printf("Parent DS digest: %s, Computed digest: %s", parentDsDigest, dsDigest)
|
||||
if parentDsDigest == dsDigest {
|
||||
log.Printf("DS validation successful for keytag %d", ds.KeyTag)
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Printf("DS does not match DNSKEY for keytag %d", ds.KeyTag)
|
||||
}
|
||||
log.Printf("No matching DS found")
|
||||
return ErrDsInvalid
|
||||
}
|
||||
90
common/dnssec/validator.go
Normal file
90
common/dnssec/validator.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package dnssec
|
||||
|
||||
// CODE ADAPTED FROM THIS
|
||||
|
||||
// ISC License
|
||||
//
|
||||
// Copyright (c) 2012-2016 Peter Banik <peter@froggle.org>
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type Validator struct {
|
||||
queryFunc func(string, uint16) (*dns.Msg, error)
|
||||
}
|
||||
|
||||
func NewValidator(queryFunc func(string, uint16) (*dns.Msg, error)) *Validator {
|
||||
return &Validator{
|
||||
queryFunc: queryFunc,
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Validator) ValidateResponse(msg *dns.Msg, qname string, qtype uint16) error {
|
||||
if msg == nil || len(msg.Answer) == 0 {
|
||||
return ErrNoResult
|
||||
}
|
||||
|
||||
// Extract RRSet from response
|
||||
rrset := NewRRSet()
|
||||
for _, rr := range msg.Answer {
|
||||
switch t := rr.(type) {
|
||||
case *dns.RRSIG:
|
||||
if t.TypeCovered == qtype {
|
||||
rrset.RRSig = t
|
||||
}
|
||||
default:
|
||||
if rr.Header().Rrtype == qtype {
|
||||
rrset.RRs = append(rrset.RRs, rr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if rrset.IsEmpty() {
|
||||
return ErrNoResult
|
||||
}
|
||||
|
||||
if !rrset.IsSigned() {
|
||||
return ErrResourceNotSigned
|
||||
}
|
||||
|
||||
// Check header integrity
|
||||
if err := rrset.CheckHeaderIntegrity(qname); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Build and verify authentication chain
|
||||
signerName := rrset.SignerName()
|
||||
authChain := NewAuthenticationChain()
|
||||
|
||||
if err := authChain.Populate(signerName, v.queryFunc); err != nil {
|
||||
log.Printf("Cannot populate authentication chain: %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := authChain.Verify(rrset); err != nil {
|
||||
log.Printf("DNSSEC validation failed: %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewValidatorWithAuthoritativeQueries() *Validator {
|
||||
querier := NewAuthoritativeQuerier()
|
||||
return NewValidator(querier.QueryAuthoritative)
|
||||
}
|
||||
3
common/protocols/dnscrypt/dnscrypt.go
Normal file
3
common/protocols/dnscrypt/dnscrypt.go
Normal file
@@ -0,0 +1,3 @@
|
||||
package dnscrypt
|
||||
|
||||
// DNSCrypt resolver implementation
|
||||
97
common/protocols/do53/do53.go
Normal file
97
common/protocols/do53/do53.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package do53
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
HostAndPort string
|
||||
DNSSEC bool
|
||||
WriteTimeout time.Duration
|
||||
ReadTimeout time.Duration
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
hostAndPort string
|
||||
config Config
|
||||
}
|
||||
|
||||
func New(config Config) (*Client, error) {
|
||||
if config.HostAndPort == "" {
|
||||
return nil, fmt.Errorf("do53: HostAndPort cannot be empty")
|
||||
}
|
||||
if config.WriteTimeout <= 0 {
|
||||
config.WriteTimeout = 2 * time.Second
|
||||
}
|
||||
if config.ReadTimeout <= 0 {
|
||||
config.ReadTimeout = 5 * time.Second
|
||||
}
|
||||
|
||||
return &Client{
|
||||
hostAndPort: config.HostAndPort,
|
||||
config: config,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Close() {
|
||||
}
|
||||
|
||||
func (c *Client) createConnection() (*net.UDPConn, error) {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", c.hostAndPort)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to resolve UDP address: %w", err)
|
||||
}
|
||||
|
||||
return net.DialUDP("udp", nil, udpAddr)
|
||||
}
|
||||
|
||||
func (c *Client) Query(msg *dns.Msg) (*dns.Msg, error) {
|
||||
// Create connection for this query
|
||||
conn, err := c.createConnection()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("do53: failed to create connection: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
if c.config.DNSSEC {
|
||||
msg.SetEdns0(4096, true)
|
||||
}
|
||||
|
||||
packedMsg, err := msg.Pack()
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("do53: failed to pack DNS message: %w", err)
|
||||
}
|
||||
|
||||
// Send query
|
||||
if err := conn.SetWriteDeadline(time.Now().Add(c.config.WriteTimeout)); err != nil {
|
||||
return nil, fmt.Errorf("do53: failed to set write deadline: %w", err)
|
||||
}
|
||||
|
||||
if _, err := conn.Write(packedMsg); err != nil {
|
||||
return nil, fmt.Errorf("do53: failed to send DNS query: %w", err)
|
||||
}
|
||||
|
||||
// Read response
|
||||
if err := conn.SetReadDeadline(time.Now().Add(c.config.ReadTimeout)); err != nil {
|
||||
return nil, fmt.Errorf("do53: failed to set read deadline: %w", err)
|
||||
}
|
||||
|
||||
buffer := make([]byte, dns.MaxMsgSize)
|
||||
n, err := conn.Read(buffer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("do53: failed to read DNS response: %w", err)
|
||||
}
|
||||
|
||||
// Parse response
|
||||
response := new(dns.Msg)
|
||||
if err := response.Unpack(buffer[:n]); err != nil {
|
||||
return nil, fmt.Errorf("do53: failed to unpack DNS response: %w", err)
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
145
common/protocols/doh/doh.go
Normal file
145
common/protocols/doh/doh.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package doh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
"github.com/quic-go/quic-go"
|
||||
"github.com/quic-go/quic-go/http3"
|
||||
"golang.org/x/net/http2"
|
||||
)
|
||||
|
||||
const dnsMessageContentType = "application/dns-message"
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
Path string
|
||||
DNSSEC bool
|
||||
HTTP3 bool
|
||||
HTTP2 bool
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
httpClient *http.Client
|
||||
upstreamURL *url.URL
|
||||
config Config
|
||||
}
|
||||
|
||||
func New(config Config) (*Client, error) {
|
||||
if config.Host == "" || config.Port == "" || config.Path == "" {
|
||||
fmt.Printf("%v,%v,%v", config.Host, config.Port, config.Path)
|
||||
return nil, errors.New("doh: host, port, and path must not be empty")
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(config.Path, "/") {
|
||||
config.Path = "/" + config.Path
|
||||
}
|
||||
rawURL := "https://" + net.JoinHostPort(config.Host, config.Port) + config.Path
|
||||
|
||||
parsedURL, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("doh: failed to parse constructed URL %q: %w", rawURL, err)
|
||||
}
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: config.Host,
|
||||
ClientSessionCache: tls.NewLRUClientSessionCache(100),
|
||||
}
|
||||
|
||||
quicConfig := &quic.Config{
|
||||
MaxIdleTimeout: 30 * time.Second,
|
||||
DisablePathMTUDiscovery: true,
|
||||
}
|
||||
|
||||
transport := http.DefaultTransport.(*http.Transport)
|
||||
transport.TLSClientConfig = tlsConfig
|
||||
httpClient := &http.Client{
|
||||
Transport: transport,
|
||||
}
|
||||
|
||||
if config.HTTP2 {
|
||||
httpClient.Transport = &http2.Transport{
|
||||
TLSClientConfig: tlsConfig,
|
||||
AllowHTTP: true,
|
||||
}
|
||||
}
|
||||
|
||||
if config.HTTP3 {
|
||||
quicTlsConfig := http3.ConfigureTLSConfig(tlsConfig)
|
||||
httpClient.Transport = &http3.Transport{
|
||||
TLSClientConfig: quicTlsConfig,
|
||||
QUICConfig: quicConfig,
|
||||
}
|
||||
}
|
||||
|
||||
return &Client{
|
||||
httpClient: httpClient,
|
||||
upstreamURL: parsedURL,
|
||||
config: config,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Close() {
|
||||
if t, ok := c.httpClient.Transport.(*http.Transport); ok {
|
||||
t.CloseIdleConnections()
|
||||
} else if t3, ok := c.httpClient.Transport.(*http3.Transport); ok {
|
||||
t3.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Query(msg *dns.Msg) (*dns.Msg, error) {
|
||||
if c.config.DNSSEC {
|
||||
msg.SetEdns0(4096, true)
|
||||
}
|
||||
packedMsg, err := msg.Pack()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("doh: failed to pack DNS message: %w", err)
|
||||
}
|
||||
|
||||
httpReq, err := http.NewRequest(http.MethodPost, c.upstreamURL.String(), bytes.NewReader(packedMsg))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("doh: failed to create HTTP request object: %w", err)
|
||||
}
|
||||
|
||||
httpReq.Header.Set("User-Agent", "sdns-proxy")
|
||||
httpReq.Header.Set("Content-Type", dnsMessageContentType)
|
||||
httpReq.Header.Set("Accept", dnsMessageContentType)
|
||||
|
||||
httpResp, err := c.httpClient.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("doh: failed executing HTTP request to %s: %w", c.upstreamURL.Host, err)
|
||||
}
|
||||
defer httpResp.Body.Close()
|
||||
|
||||
if httpResp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("doh: received non-200 HTTP status from %s: %s", c.upstreamURL.Host, httpResp.Status)
|
||||
}
|
||||
|
||||
if ct := httpResp.Header.Get("Content-Type"); ct != dnsMessageContentType {
|
||||
return nil, fmt.Errorf("doh: unexpected Content-Type from %s: got %q, want %q", c.upstreamURL.Host, ct, dnsMessageContentType)
|
||||
}
|
||||
|
||||
responseBody, err := io.ReadAll(httpResp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("doh: failed reading response body from %s: %w", c.upstreamURL.Host, err)
|
||||
}
|
||||
|
||||
// Unpack the DNS message
|
||||
recvMsg := new(dns.Msg)
|
||||
err = recvMsg.Unpack(responseBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("doh: failed to unpack DNS response from %s: %w", c.upstreamURL.Host, err)
|
||||
}
|
||||
|
||||
return recvMsg, nil
|
||||
}
|
||||
160
common/protocols/doq/doq.go
Normal file
160
common/protocols/doq/doq.go
Normal file
@@ -0,0 +1,160 @@
|
||||
package doq
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
"github.com/quic-go/quic-go"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
Debug bool
|
||||
DNSSEC bool
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
targetAddr *net.UDPAddr
|
||||
tlsConfig *tls.Config
|
||||
udpConn *net.UDPConn
|
||||
quicConn quic.Connection
|
||||
quicTransport *quic.Transport
|
||||
quicConfig *quic.Config
|
||||
config Config
|
||||
}
|
||||
|
||||
func New(config Config) (*Client, error) {
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: config.Host,
|
||||
MinVersion: tls.VersionTLS13,
|
||||
ClientSessionCache: tls.NewLRUClientSessionCache(100),
|
||||
NextProtos: []string{"doq"},
|
||||
}
|
||||
|
||||
targetAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(config.Host, config.Port))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
udpConn, err := net.ListenUDP("udp", nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to target address: %w", err)
|
||||
}
|
||||
|
||||
quicTransport := quic.Transport{
|
||||
Conn: udpConn,
|
||||
}
|
||||
|
||||
quicConfig := quic.Config{
|
||||
MaxIdleTimeout: 30 * time.Second,
|
||||
}
|
||||
|
||||
return &Client{
|
||||
targetAddr: targetAddr,
|
||||
tlsConfig: tlsConfig,
|
||||
udpConn: udpConn,
|
||||
quicConn: nil,
|
||||
quicTransport: &quicTransport,
|
||||
quicConfig: &quicConfig,
|
||||
config: config,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Close() {
|
||||
if c.udpConn != nil {
|
||||
c.udpConn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) OpenConnection() error {
|
||||
quicConn, err := c.quicTransport.DialEarly(context.Background(), c.targetAddr, c.tlsConfig, c.quicConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.quicConn = quicConn
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) Query(msg *dns.Msg) (*dns.Msg, error) {
|
||||
|
||||
if c.quicConn == nil {
|
||||
err := c.OpenConnection()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare DNS message
|
||||
msg.Id = 0
|
||||
if c.config.DNSSEC {
|
||||
msg.SetEdns0(4096, true)
|
||||
}
|
||||
packed, err := msg.Pack()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("doq: failed to pack message: %w", err)
|
||||
}
|
||||
|
||||
var quicStream quic.Stream
|
||||
quicStream, err = c.quicConn.OpenStream()
|
||||
if err != nil {
|
||||
err = c.OpenConnection()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
quicStream, err = c.quicConn.OpenStream()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var lengthPrefixedMessage bytes.Buffer
|
||||
err = binary.Write(&lengthPrefixedMessage, binary.BigEndian, uint16(len(packed)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to write message length: %w", err)
|
||||
}
|
||||
_, err = lengthPrefixedMessage.Write(packed)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to write DNS message: %w", err)
|
||||
}
|
||||
|
||||
_, err = quicStream.Write(lengthPrefixedMessage.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed writing to QUIC stream: %w", err)
|
||||
}
|
||||
// Indicate that no further data will be written from this side
|
||||
quicStream.Close()
|
||||
|
||||
lengthBuf := make([]byte, 2)
|
||||
_, err = io.ReadFull(quicStream, lengthBuf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed reading response length: %w", err)
|
||||
}
|
||||
|
||||
messageLength := binary.BigEndian.Uint16(lengthBuf)
|
||||
if messageLength == 0 {
|
||||
return nil, fmt.Errorf("received zero-length message")
|
||||
}
|
||||
|
||||
responseBuf := make([]byte, messageLength)
|
||||
_, err = io.ReadFull(quicStream, responseBuf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed reading response data: %w", err)
|
||||
}
|
||||
|
||||
recvMsg := new(dns.Msg)
|
||||
err = recvMsg.Unpack(responseBuf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse DNS response: %w", err)
|
||||
}
|
||||
|
||||
return recvMsg, nil
|
||||
}
|
||||
124
common/protocols/dot/dot.go
Normal file
124
common/protocols/dot/dot.go
Normal file
@@ -0,0 +1,124 @@
|
||||
package dot
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
DNSSEC bool
|
||||
WriteTimeout time.Duration
|
||||
ReadTimeout time.Duration
|
||||
Debug bool
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
hostAndPort string
|
||||
tlsConfig *tls.Config
|
||||
config Config
|
||||
}
|
||||
|
||||
func New(config Config) (*Client, error) {
|
||||
if config.Host == "" {
|
||||
return nil, fmt.Errorf("dot: Host cannot be empty")
|
||||
}
|
||||
if config.WriteTimeout <= 0 {
|
||||
config.WriteTimeout = 2 * time.Second
|
||||
}
|
||||
if config.ReadTimeout <= 0 {
|
||||
config.ReadTimeout = 5 * time.Second
|
||||
}
|
||||
|
||||
hostAndPort := net.JoinHostPort(config.Host, config.Port)
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: config.Host,
|
||||
}
|
||||
|
||||
return &Client{
|
||||
hostAndPort: hostAndPort,
|
||||
tlsConfig: tlsConfig,
|
||||
config: config,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Close() {
|
||||
}
|
||||
|
||||
func (c *Client) createConnection() (*tls.Conn, error) {
|
||||
dialer := &net.Dialer{
|
||||
Timeout: c.config.WriteTimeout,
|
||||
}
|
||||
|
||||
return tls.DialWithDialer(dialer, "tcp", c.hostAndPort, c.tlsConfig)
|
||||
}
|
||||
|
||||
func (c *Client) Query(msg *dns.Msg) (*dns.Msg, error) {
|
||||
// Create connection for this query
|
||||
conn, err := c.createConnection()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dot: failed to create connection: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// Prepare DNS message
|
||||
if c.config.DNSSEC {
|
||||
msg.SetEdns0(4096, true)
|
||||
}
|
||||
packed, err := msg.Pack()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dot: failed to pack message: %w", err)
|
||||
}
|
||||
|
||||
// Prepend message length (DNS over TCP format)
|
||||
length := make([]byte, 2)
|
||||
binary.BigEndian.PutUint16(length, uint16(len(packed)))
|
||||
data := append(length, packed...)
|
||||
|
||||
// Write query
|
||||
if err := conn.SetWriteDeadline(time.Now().Add(c.config.WriteTimeout)); err != nil {
|
||||
return nil, fmt.Errorf("dot: failed to set write deadline: %w", err)
|
||||
}
|
||||
|
||||
if _, err := conn.Write(data); err != nil {
|
||||
return nil, fmt.Errorf("dot: failed to write message: %w", err)
|
||||
}
|
||||
|
||||
// Read response
|
||||
if err := conn.SetReadDeadline(time.Now().Add(c.config.ReadTimeout)); err != nil {
|
||||
return nil, fmt.Errorf("dot: failed to set read deadline: %w", err)
|
||||
}
|
||||
|
||||
// Read message length
|
||||
lengthBuf := make([]byte, 2)
|
||||
if _, err := io.ReadFull(conn, lengthBuf); err != nil {
|
||||
return nil, fmt.Errorf("dot: failed to read response length: %w", err)
|
||||
}
|
||||
|
||||
msgLen := binary.BigEndian.Uint16(lengthBuf)
|
||||
if msgLen > dns.MaxMsgSize {
|
||||
return nil, fmt.Errorf("dot: response message too large: %d", msgLen)
|
||||
}
|
||||
|
||||
// Read message body
|
||||
buffer := make([]byte, msgLen)
|
||||
if _, err := io.ReadFull(conn, buffer); err != nil {
|
||||
return nil, fmt.Errorf("dot: failed to read response: %w", err)
|
||||
}
|
||||
|
||||
// Parse response
|
||||
response := new(dns.Msg)
|
||||
if err := response.Unpack(buffer); err != nil {
|
||||
return nil, fmt.Errorf("dot: failed to unpack response: %w", err)
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
Reference in New Issue
Block a user