diff --git a/client/client.go b/client/client.go new file mode 100644 index 0000000..f1d4e2f --- /dev/null +++ b/client/client.go @@ -0,0 +1,241 @@ +package client + +import ( + "fmt" + "net" + "net/url" + "strings" + + "github.com/afonsofrancof/sdns-proxy/common/dnssec" + "github.com/afonsofrancof/sdns-proxy/common/protocols/do53" + "github.com/afonsofrancof/sdns-proxy/common/protocols/doh" + "github.com/afonsofrancof/sdns-proxy/common/protocols/doq" + "github.com/afonsofrancof/sdns-proxy/common/protocols/dot" + "github.com/miekg/dns" +) + +type DNSClient interface { + Query(msg *dns.Msg) (*dns.Msg, error) + Close() +} + +type ValidatingDNSClient struct { + client DNSClient + validator *dnssec.Validator + options Options +} + +type Options struct { + DNSSEC bool + ValidateOnly bool + StrictValidation bool +} + +// New creates a DNS client based on the upstream string +func New(upstream string, opts Options) (DNSClient, error) { + // Try to parse as URL first + parsedURL, err := url.Parse(upstream) + if err != nil { + return nil, fmt.Errorf("invalid upstream format: %w", err) + } + + var baseClient DNSClient + + // If it has a scheme, treat it as a full URL + if parsedURL.Scheme != "" { + baseClient, err = createClientFromURL(parsedURL, opts) + } else { + // No scheme - treat as plain DNS address + baseClient, err = createClientFromPlainAddress(upstream, opts) + } + + if err != nil { + return nil, err + } + + // If DNSSEC is not enabled, return the base client + if !opts.DNSSEC { + return baseClient, nil + } + + // Wrap with DNSSEC validation + // validator := dnssec.NewValidator(func(qname string, qtype uint16) (*dns.Msg, error) { + // msg := new(dns.Msg) + // msg.SetQuestion(dns.Fqdn(qname), qtype) + // msg.Id = dns.Id() + // msg.RecursionDesired = true + // msg.SetEdns0(4096, true) // Enable DNSSEC + // return baseClient.Query(msg) + // }) + validator := dnssec.NewValidatorWithAuthoritativeQueries() + + return &ValidatingDNSClient{ + client: baseClient, + validator: validator, + options: opts, + }, nil +} + +func (v *ValidatingDNSClient) Query(msg *dns.Msg) (*dns.Msg, error) { + // Always query the upstream first + response, err := v.client.Query(msg) + if err != nil { + return nil, err + } + + // If DNSSEC validation is disabled, return response as-is + if !v.options.DNSSEC { + return response, nil + } + + // Extract question details for validation + if len(msg.Question) == 0 { + return response, nil + } + + question := msg.Question[0] + qname := question.Name + qtype := question.Qtype + + // Validate the response + validationErr := v.validator.ValidateResponse(response, qname, qtype) + + // Handle validation results based on options + if validationErr != nil { + // Check if it's a "not signed" error + if validationErr == dnssec.ErrResourceNotSigned { + if v.options.ValidateOnly { + return nil, fmt.Errorf("domain %s is not DNSSEC signed", qname) + } + // Return unsigned response if not in validate-only mode + return response, nil + } + + // For other validation errors + if v.options.StrictValidation { + return nil, fmt.Errorf("DNSSEC validation failed for %s: %w", qname, validationErr) + } + + // In non-strict mode, log the error but return the response + // (You might want to add logging here) + return response, nil + } + + // Validation successful + return response, nil +} + +func (v *ValidatingDNSClient) Close() { + if v.client != nil { + v.client.Close() + } +} + +func createClientFromURL(parsedURL *url.URL, opts Options) (DNSClient, error) { + scheme := strings.ToLower(parsedURL.Scheme) + host := parsedURL.Hostname() + if host == "" { + return nil, fmt.Errorf("missing host in upstream URL") + } + + port := parsedURL.Port() + if port == "" { + port = getDefaultPort(scheme) + } + + path := parsedURL.Path + if path == "" { + path = getDefaultPath(scheme) + } + + return createClient(scheme, host, port, path, opts) +} + +func createClientFromPlainAddress(address string, opts Options) (DNSClient, error) { + var host, port string + var err error + + host, port, err = net.SplitHostPort(address) + if err != nil { + host = address + port = "53" + } + + if host == "" { + return nil, fmt.Errorf("empty host in address: %s", address) + } + + return createClient("", host, port, "", opts) +} + +func getDefaultPort(scheme string) string { + switch scheme { + case "https", "doh", "doh3": + return "443" + case "tls", "dot": + return "853" + case "quic", "doq": + return "853" + default: + return "53" + } +} + +func getDefaultPath(scheme string) string { + switch scheme { + case "https", "doh", "doh3": + return "/dns-query" + default: + return "" + } +} + +func createClient(scheme, host, port, path string, opts Options) (DNSClient, error) { + switch scheme { + case "udp", "tcp", "do53", "": + config := do53.Config{ + HostAndPort: net.JoinHostPort(host, port), + DNSSEC: opts.DNSSEC, + } + return do53.New(config) + + case "http", "doh": + config := doh.Config{ + Host: host, + Port: port, + Path: path, + DNSSEC: opts.DNSSEC, + HTTP3: false, + } + return doh.New(config) + + case "https", "doh3": + config := doh.Config{ + Host: host, + Port: port, + Path: path, + DNSSEC: opts.DNSSEC, + HTTP3: true, + } + return doh.New(config) + + case "tls", "dot": + config := dot.Config{ + Host: host, + Port: port, + DNSSEC: opts.DNSSEC, + } + return dot.New(config) + + case "doq": // DNS over QUIC + config := doq.Config{ + Host: host, + Port: port, + DNSSEC: opts.DNSSEC, + } + return doq.New(config) + + default: + return nil, fmt.Errorf("unsupported scheme: %s", scheme) + } +} diff --git a/common/dnssec/authchain.go b/common/dnssec/authchain.go new file mode 100644 index 0000000..a88b4c4 --- /dev/null +++ b/common/dnssec/authchain.go @@ -0,0 +1,226 @@ +package dnssec + +// CODE ADAPTED FROM THIS + +// ISC License +// +// Copyright (c) 2012-2016 Peter Banik +// +// 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 +} diff --git a/common/dnssec/authoritative.go b/common/dnssec/authoritative.go new file mode 100644 index 0000000..a9692e0 --- /dev/null +++ b/common/dnssec/authoritative.go @@ -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 +} diff --git a/common/dnssec/errors.go b/common/dnssec/errors.go new file mode 100644 index 0000000..00bbe42 --- /dev/null +++ b/common/dnssec/errors.go @@ -0,0 +1,35 @@ +package dnssec + +// CODE ADAPTED FROM THIS + +// ISC License +// +// Copyright (c) 2012-2016 Peter Banik +// +// 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") +) diff --git a/common/dnssec/rrset.go b/common/dnssec/rrset.go new file mode 100644 index 0000000..704424a --- /dev/null +++ b/common/dnssec/rrset.go @@ -0,0 +1,77 @@ +package dnssec + +// CODE ADAPTED FROM THIS + +// ISC License +// +// Copyright (c) 2012-2016 Peter Banik +// +// 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 +} diff --git a/common/dnssec/signedzone.go b/common/dnssec/signedzone.go new file mode 100644 index 0000000..749527a --- /dev/null +++ b/common/dnssec/signedzone.go @@ -0,0 +1,104 @@ +package dnssec + +// CODE ADAPTED FROM THIS + +// ISC License +// +// Copyright (c) 2012-2016 Peter Banik +// +// 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 +} diff --git a/common/dnssec/validator.go b/common/dnssec/validator.go new file mode 100644 index 0000000..6e85ddd --- /dev/null +++ b/common/dnssec/validator.go @@ -0,0 +1,90 @@ +package dnssec + +// CODE ADAPTED FROM THIS + +// ISC License +// +// Copyright (c) 2012-2016 Peter Banik +// +// 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) +} diff --git a/common/protocols/dnscrypt/dnscrypt.go b/common/protocols/dnscrypt/dnscrypt.go new file mode 100644 index 0000000..9939b27 --- /dev/null +++ b/common/protocols/dnscrypt/dnscrypt.go @@ -0,0 +1,3 @@ +package dnscrypt + +// DNSCrypt resolver implementation diff --git a/common/protocols/do53/do53.go b/common/protocols/do53/do53.go new file mode 100644 index 0000000..18c498a --- /dev/null +++ b/common/protocols/do53/do53.go @@ -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 +} diff --git a/common/protocols/doh/doh.go b/common/protocols/doh/doh.go new file mode 100644 index 0000000..93a0e91 --- /dev/null +++ b/common/protocols/doh/doh.go @@ -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 +} diff --git a/common/protocols/doq/doq.go b/common/protocols/doq/doq.go new file mode 100644 index 0000000..12a6511 --- /dev/null +++ b/common/protocols/doq/doq.go @@ -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 +} diff --git a/common/protocols/dot/dot.go b/common/protocols/dot/dot.go new file mode 100644 index 0000000..35b2fe9 --- /dev/null +++ b/common/protocols/dot/dot.go @@ -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 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..a0740e5 --- /dev/null +++ b/flake.nix @@ -0,0 +1,33 @@ +{ + description = "A Nix-flake-based Go 1.22 development environment"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + + outputs = inputs: + let + goVersion = 25; # Change this to update the whole stack + + supportedSystems = [ "aarch64-darwin" ]; + forEachSupportedSystem = f: inputs.nixpkgs.lib.genAttrs supportedSystems (system: f { + pkgs = import inputs.nixpkgs { + inherit system; + overlays = [ inputs.self.overlays.default ]; + }; + }); + in + { + overlays.default = final: prev: { + go = final."go_1_${toString goVersion}"; + }; + + devShells = forEachSupportedSystem ({ pkgs }: { + default = pkgs.mkShell { + packages = with pkgs; [ + go + gotools + golangci-lint + ]; + }; + }); + }; +} diff --git a/go.mod b/go.mod index 307936c..40e95d0 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/afonsofrancof/sdns-perf +module github.com/afonsofrancof/sdns-proxy go 1.24.0 @@ -12,12 +12,14 @@ require ( github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 // indirect github.com/onsi/ginkgo/v2 v2.9.5 // indirect + github.com/quic-go/qpack v0.5.1 // indirect go.uber.org/mock v0.5.0 // indirect golang.org/x/crypto v0.33.0 // indirect golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect golang.org/x/mod v0.18.0 // indirect golang.org/x/net v0.35.0 // indirect - golang.org/x/sync v0.8.0 // indirect + golang.org/x/sync v0.11.0 // indirect golang.org/x/sys v0.30.0 // indirect + golang.org/x/text v0.22.0 // indirect golang.org/x/tools v0.22.0 // indirect ) diff --git a/go.sum b/go.sum index 25e4870..224a424 100644 --- a/go.sum +++ b/go.sum @@ -31,6 +31,8 @@ github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE= github.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI= +github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg= github.com/quic-go/quic-go v0.50.0 h1:3H/ld1pa3CYhkcc20TPIyG1bNsdhn9qZBGN3b9/UyUo= github.com/quic-go/quic-go v0.50.0/go.mod h1:Vim6OmUvlYdwBhXP9ZVrtGmCMWa3wEqhq3NgYrI8b4E= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -47,8 +49,8 @@ golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0= golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= -golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= -golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= +golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/main.go b/main.go new file mode 100644 index 0000000..ba0a058 --- /dev/null +++ b/main.go @@ -0,0 +1,168 @@ +package main + +import ( + "fmt" + "log" + "os" + "strings" + "time" + + "github.com/afonsofrancof/sdns-proxy/client" + "github.com/afonsofrancof/sdns-proxy/server" + + "github.com/alecthomas/kong" + "github.com/miekg/dns" +) + +var cli struct { + Query QueryCmd `cmd:"" help:"Perform a DNS query (client mode)."` + Listen ListenCmd `cmd:"" help:"Run as a DNS listener/resolver (server mode)."` +} + +type QueryCmd struct { + DomainName string `help:"Domain name to resolve." arg:"" required:""` + Server string `help:"Upstream server address (e.g., https://1.1.1.1/dns-query, tls://1.1.1.1, 8.8.8.8)." short:"s" required:""` + QueryType string `help:"Query type (A, AAAA, MX, TXT, etc.)." short:"t" enum:"A,AAAA,MX,TXT,NS,CNAME,SOA,PTR,DNSKEY" default:"A"` + DNSSEC bool `help:"Enable DNSSEC (DO bit)." short:"d"` + ValidateOnly bool `help:"Only return DNSSEC validated responses." short:"V"` + StrictValidation bool `help:"Fail on any DNSSEC validation error." short:"S"` + Timeout time.Duration `help:"Timeout for the query operation." default:"10s"` + KeyLogFile string `help:"Path to TLS key log file (for DoT/DoH/DoQ)." env:"SSLKEYLOGFILE"` +} + +type ListenCmd struct { + Address string `help:"Address to listen on (e.g., :53, :8053)." default:":53"` + Upstream string `help:"Upstream DNS server (e.g., https://1.1.1.1/dns-query, tls://8.8.8.8)." short:"u" required:""` + Fallback string `help:"Fallback DNS server (e.g., https://1.1.1.1/dns-query, tls://8.8.8.8)." short:"f"` + Bootstrap string `help:"Bootstrap DNS server (must be an IP address, e.g., 8.8.8.8, 1.1.1.1)." short:"b"` + DNSSEC bool `help:"Enable DNSSEC for upstream queries." short:"d"` + Timeout time.Duration `help:"Timeout for upstream queries." default:"5s"` + Verbose bool `help:"Enable verbose logging." short:"v"` +} + +func (q *QueryCmd) Run() error { + log.Printf("Querying %s for %s type %s (DNSSEC: %v, ValidateOnly: %v, StrictValidation: %v, Timeout: %v)\n", + q.Server, q.DomainName, q.QueryType, q.DNSSEC, q.ValidateOnly, q.StrictValidation, q.Timeout) + + opts := client.Options{ + DNSSEC: q.DNSSEC, + ValidateOnly: q.ValidateOnly, + StrictValidation: q.StrictValidation, + } + + dnsClient, err := client.New(q.Server, opts) + if err != nil { + return err + } + defer dnsClient.Close() + + qTypeUint, ok := dns.StringToType[strings.ToUpper(q.QueryType)] + if !ok { + return fmt.Errorf("invalid query type: %s", q.QueryType) + } + + // Prepare DNS message + msg := new(dns.Msg) + msg.SetQuestion(dns.Fqdn(q.DomainName), qTypeUint) + msg.Id = dns.Id() + msg.RecursionDesired = true + + recvMsg, err := dnsClient.Query(msg) + if err != nil { + return err + } + + printResponse(recvMsg.Question[0].Name, q.QueryType, recvMsg) + return nil +} + +func (l *ListenCmd) Run() error { + config := server.Config{ + Address: l.Address, + Upstream: l.Upstream, + Fallback: l.Fallback, + Bootstrap: l.Bootstrap, + DNSSEC: l.DNSSEC, + Timeout: l.Timeout, + Verbose: l.Verbose, + } + + srv, err := server.New(config) + if err != nil { + return fmt.Errorf("failed to create server: %w", err) + } + + log.Printf("Starting DNS proxy server on %s", l.Address) + log.Printf("Upstream server: %v", l.Upstream) + log.Printf("Fallback server: %v", l.Fallback) + log.Printf("Bootstrap server: %v", l.Bootstrap) + + return srv.Start() +} + +func printResponse(domain, qtype string, msg *dns.Msg) { + fmt.Println(";; QUESTION SECTION:") + + fmt.Printf(";%s.\tIN\t%s\n", dns.Fqdn(domain), strings.ToUpper(qtype)) + + fmt.Println("\n;; ANSWER SECTION:") + if len(msg.Answer) > 0 { + for _, rr := range msg.Answer { + fmt.Println(rr.String()) + } + } else { + fmt.Println(";; No records found in answer section.") + } + + if len(msg.Ns) > 0 { + fmt.Println("\n;; AUTHORITY SECTION:") + for _, rr := range msg.Ns { + fmt.Println(rr.String()) + } + } + if len(msg.Extra) > 0 { + hasRealExtra := false + for _, rr := range msg.Extra { + if rr.Header().Rrtype != dns.TypeOPT { + hasRealExtra = true + break + } + } + if hasRealExtra { + fmt.Println("\n;; ADDITIONAL SECTION:") + for _, rr := range msg.Extra { + if rr.Header().Rrtype != dns.TypeOPT { + fmt.Println(rr.String()) + } + } + } + } + + fmt.Printf("\n;; RCODE: %s, ID: %d", dns.RcodeToString[msg.Rcode], msg.Id) + opt := msg.IsEdns0() + if opt != nil { + fmt.Printf(", EDNS: version: %d; flags:", opt.Version()) + if opt.Do() { + fmt.Printf(" do;") + } else { + fmt.Printf(";") + } + fmt.Printf(" udp: %d", opt.UDPSize()) + } + fmt.Println() +} + +func main() { + log.SetOutput(os.Stderr) + log.SetFlags(log.Ltime | log.Lshortfile) + + kongCtx := kong.Parse(&cli, + kong.Name("sdns-proxy"), + kong.Description("A DNS client/server tool supporting multiple protocols."), + kong.UsageOnError(), + kong.ConfigureHelp(kong.HelpOptions{Compact: true, Summary: true}), + ) + + err := kongCtx.Run() + kongCtx.FatalIfErrorf(err) +} diff --git a/server/server.go b/server/server.go new file mode 100644 index 0000000..79d25dc --- /dev/null +++ b/server/server.go @@ -0,0 +1,494 @@ +package server + +import ( + "context" + "fmt" + "log" + "net" + "net/url" + "os" + "os/signal" + "strings" + "sync" + "syscall" + "time" + + "github.com/afonsofrancof/sdns-proxy/client" + "github.com/miekg/dns" +) + +type Config struct { + Address string + Upstream string + Fallback string + Bootstrap string + DNSSEC bool + Timeout time.Duration + Verbose bool +} + +type cacheKey struct { + domain string + qtype uint16 +} + +type cacheEntry struct { + records []dns.RR + expiresAt time.Time +} + +type Server struct { + config Config + upstreamClient client.DNSClient + fallbackClient client.DNSClient + bootstrapClient client.DNSClient + resolvedHosts map[string]string + queryCache map[cacheKey]*cacheEntry + hostsMutex sync.RWMutex + cacheMutex sync.RWMutex + dnsServer *dns.Server +} + +func New(config Config) (*Server, error) { + if config.Upstream == "" { + return nil, fmt.Errorf("upstream server is required") + } + + // Check if we need bootstrap server + needsBootstrap := containsHostname(config.Upstream) + if config.Fallback != "" { + needsBootstrap = needsBootstrap || containsHostname(config.Fallback) + } + + if needsBootstrap && config.Bootstrap == "" { + return nil, fmt.Errorf("bootstrap server is required when upstream or fallback contains hostnames") + } + + if config.Bootstrap != "" && containsHostname(config.Bootstrap) { + return nil, fmt.Errorf("bootstrap server cannot contain hostnames: %s", config.Bootstrap) + } + + s := &Server{ + config: config, + resolvedHosts: make(map[string]string), + queryCache: make(map[cacheKey]*cacheEntry), + } + + // Create bootstrap client if needed + if config.Bootstrap != "" { + bootstrapClient, err := client.New(config.Bootstrap, client.Options{ + DNSSEC: false, // For now + }) + if err != nil { + return nil, fmt.Errorf("failed to create bootstrap client: %w", err) + } + s.bootstrapClient = bootstrapClient + } + + // Initialize upstream and fallback clients + if err := s.initClients(); err != nil { + return nil, fmt.Errorf("failed to initialize clients: %w", err) + } + + // Setup DNS server + mux := dns.NewServeMux() + mux.HandleFunc(".", s.handleDNSRequest) + + s.dnsServer = &dns.Server{ + Addr: config.Address, + Net: "udp", + Handler: mux, + } + + return s, nil +} + +func containsHostname(serverAddr string) bool { + // Use the same parsing logic as the client package + parsedURL, err := url.Parse(serverAddr) + if err != nil { + // If URL parsing fails, assume it's a plain address + host, _, err := net.SplitHostPort(serverAddr) + if err != nil { + // Assume it's just a host + return net.ParseIP(serverAddr) == nil + } + return net.ParseIP(host) == nil + } + + host := parsedURL.Hostname() + if host == "" { + return false + } + + return net.ParseIP(host) == nil +} + +func (s *Server) initClients() error { + // Initialize upstream client + resolvedUpstream, err := s.resolveServerAddress(s.config.Upstream) + if err != nil { + return fmt.Errorf("failed to resolve upstream %s: %w", s.config.Upstream, err) + } + + upstreamClient, err := client.New(resolvedUpstream, client.Options{ + DNSSEC: s.config.DNSSEC, + }) + if err != nil { + return fmt.Errorf("failed to create upstream client: %w", err) + } + s.upstreamClient = upstreamClient + + if s.config.Verbose { + log.Printf("Initialized upstream client: %s -> %s", s.config.Upstream, resolvedUpstream) + } + + // Initialize fallback client if specified + if s.config.Fallback != "" { + resolvedFallback, err := s.resolveServerAddress(s.config.Fallback) + if err != nil { + return fmt.Errorf("failed to resolve fallback %s: %w", s.config.Fallback, err) + } + + fallbackClient, err := client.New(resolvedFallback, client.Options{ + DNSSEC: s.config.DNSSEC, + }) + if err != nil { + return fmt.Errorf("failed to create fallback client: %w", err) + } + s.fallbackClient = fallbackClient + + if s.config.Verbose { + log.Printf("Initialized fallback client: %s -> %s", s.config.Fallback, resolvedFallback) + } + } + + return nil +} + +func (s *Server) resolveServerAddress(serverAddr string) (string, error) { + // If it doesn't contain hostnames, return as-is + if !containsHostname(serverAddr) { + return serverAddr, nil + } + + // If no bootstrap client, we can't resolve hostnames + if s.bootstrapClient == nil { + return "", fmt.Errorf("cannot resolve hostname in %s: no bootstrap server configured", serverAddr) + } + + // Use the same parsing logic as the client package + parsedURL, err := url.Parse(serverAddr) + if err != nil { + // Handle plain host:port format + host, port, err := net.SplitHostPort(serverAddr) + if err != nil { + // Assume it's just a hostname + resolvedIP, err := s.resolveHostname(serverAddr) + if err != nil { + return "", err + } + return resolvedIP, nil + } + + resolvedIP, err := s.resolveHostname(host) + if err != nil { + return "", err + } + return net.JoinHostPort(resolvedIP, port), nil + } + + // Handle URL format + hostname := parsedURL.Hostname() + if hostname == "" { + return "", fmt.Errorf("no hostname in URL: %s", serverAddr) + } + + resolvedIP, err := s.resolveHostname(hostname) + if err != nil { + return "", err + } + + // Replace hostname with IP in the URL + port := parsedURL.Port() + if port == "" { + parsedURL.Host = resolvedIP + } else { + parsedURL.Host = net.JoinHostPort(resolvedIP, port) + } + + return parsedURL.String(), nil +} + +func (s *Server) resolveHostname(hostname string) (string, error) { + // Check cache first + s.hostsMutex.RLock() + if ip, exists := s.resolvedHosts[hostname]; exists { + s.hostsMutex.RUnlock() + return ip, nil + } + s.hostsMutex.RUnlock() + + // Resolve using bootstrap + if s.config.Verbose { + log.Printf("Resolving hostname %s using bootstrap server", hostname) + } + + msg := new(dns.Msg) + msg.SetQuestion(dns.Fqdn(hostname), dns.TypeA) + msg.Id = dns.Id() + msg.RecursionDesired = true + + msg, err := s.bootstrapClient.Query(msg) + if err != nil { + return "", fmt.Errorf("failed to resolve %s via bootstrap: %w", hostname, err) + } + + if len(msg.Answer) == 0 { + return "", fmt.Errorf("no A records found for %s", hostname) + } + + // Find first A record + for _, rr := range msg.Answer { + if a, ok := rr.(*dns.A); ok { + ip := a.A.String() + + // Cache the result + s.hostsMutex.Lock() + s.resolvedHosts[hostname] = ip + s.hostsMutex.Unlock() + + if s.config.Verbose { + log.Printf("Resolved %s to %s", hostname, ip) + } + + return ip, nil + } + } + + return "", fmt.Errorf("no valid A record found for %s", hostname) +} + +func (s *Server) handleDNSRequest(w dns.ResponseWriter, r *dns.Msg) { + if len(r.Question) == 0 { + dns.HandleFailed(w, r) + return + } + + question := r.Question[0] + domain := strings.ToLower(question.Name) + qtype := question.Qtype + + if s.config.Verbose { + log.Printf("Query: %s %s from %s", + question.Name, + dns.TypeToString[qtype], + w.RemoteAddr()) + } + + // Check cache first + if cachedRecords := s.getCachedRecords(domain, qtype); cachedRecords != nil { + response := s.buildResponse(r, cachedRecords) + if s.config.Verbose { + log.Printf("Cache hit: %s %s -> %d records", + question.Name, + dns.TypeToString[qtype], + len(cachedRecords)) + } + w.WriteMsg(response) + return + } + + // Try upstream first + response, err := s.queryUpstream(s.upstreamClient, question.Name, qtype) + if err != nil { + if s.config.Verbose { + log.Printf("Upstream query failed: %v", err) + } + + // Try fallback if available + if s.fallbackClient != nil { + if s.config.Verbose { + log.Printf("Trying fallback server") + } + + response, err = s.queryUpstream(s.fallbackClient, question.Name, qtype) + if err != nil { + log.Printf("Both upstream and fallback failed for %s %s: %v", + question.Name, + dns.TypeToString[qtype], + err) + } + } + + // If still failed, return SERVFAIL + if err != nil { + log.Printf("All servers failed for %s %s: %v", + question.Name, + dns.TypeToString[qtype], + err) + + m := new(dns.Msg) + m.SetReply(r) + m.Rcode = dns.RcodeServerFailure + w.WriteMsg(m) + return + } + } + + // Cache successful response + s.cacheResponse(domain, qtype, response) + + // Copy request ID to response + response.Id = r.Id + + if s.config.Verbose { + log.Printf("Response: %s %s -> %d answers", + question.Name, + dns.TypeToString[qtype], + len(response.Answer)) + } + + w.WriteMsg(response) +} + +func (s *Server) getCachedRecords(domain string, qtype uint16) []dns.RR { + key := cacheKey{domain: domain, qtype: qtype} + + s.cacheMutex.RLock() + entry, exists := s.queryCache[key] + s.cacheMutex.RUnlock() + + if !exists { + return nil + } + + // Check if expired and clean up on the spot + if time.Now().After(entry.expiresAt) { + s.cacheMutex.Lock() + delete(s.queryCache, key) + s.cacheMutex.Unlock() + return nil + } + + // Return a copy of the cached records + records := make([]dns.RR, len(entry.records)) + for i, rr := range entry.records { + records[i] = dns.Copy(rr) + } + return records +} + +func (s *Server) buildResponse(request *dns.Msg, records []dns.RR) *dns.Msg { + response := new(dns.Msg) + response.SetReply(request) + + response.Answer = records + + return response +} + +func (s *Server) cacheResponse(domain string, qtype uint16, msg *dns.Msg) { + if msg == nil || len(msg.Answer) == 0 { + return + } + + var validRecords []dns.RR + minTTL := uint32(3600) + + // Find minimum TTL from answer records + for _, rr := range msg.Answer { + // Only cache records that match our query type or are CNAMEs + if rr.Header().Rrtype == qtype || rr.Header().Rrtype == dns.TypeCNAME { + validRecords = append(validRecords, dns.Copy(rr)) + if rr.Header().Ttl < minTTL { + minTTL = rr.Header().Ttl + } + } + } + + if len(validRecords) == 0 { + return + } + + // Don't cache responses with very low TTL + if minTTL < 10 { + return + } + + key := cacheKey{domain: domain, qtype: qtype} + entry := &cacheEntry{ + records: validRecords, + expiresAt: time.Now().Add(time.Duration(minTTL) * time.Second), + } + + s.cacheMutex.Lock() + s.queryCache[key] = entry + s.cacheMutex.Unlock() + + if s.config.Verbose { + log.Printf("Cached %d records for %s %s (TTL: %ds)", + len(validRecords), domain, dns.TypeToString[qtype], minTTL) + } +} + +func (s *Server) queryUpstream(upstreamClient client.DNSClient, domain string, qtype uint16) (*dns.Msg, error) { + // Create context with timeout + ctx, cancel := context.WithTimeout(context.Background(), s.config.Timeout) + defer cancel() + + // Channel to receive result + type result struct { + msg *dns.Msg + err error + } + resultChan := make(chan result, 1) + + // Query in goroutine to respect context timeout + go func() { + msg := new(dns.Msg) + msg.SetQuestion(dns.Fqdn(domain), qtype) + msg.Id = dns.Id() + msg.RecursionDesired = true + recvMsg, err := upstreamClient.Query(msg) + resultChan <- result{msg: recvMsg, err: err} + }() + + select { + case res := <-resultChan: + return res.msg, res.err + case <-ctx.Done(): + return nil, fmt.Errorf("upstream query timeout") + } +} + +func (s *Server) Start() error { + go func() { + sigChan := make(chan os.Signal, 1) + signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) + <-sigChan + log.Println("Shutting down DNS server...") + s.Shutdown() + }() + + log.Printf("DNS proxy server listening on %s", s.config.Address) + return s.dnsServer.ListenAndServe() +} + +func (s *Server) Shutdown() { + if s.dnsServer != nil { + s.dnsServer.Shutdown() + } + + if s.upstreamClient != nil { + s.upstreamClient.Close() + } + + if s.fallbackClient != nil { + s.fallbackClient.Close() + } + + if s.bootstrapClient != nil { + s.bootstrapClient.Close() + } +}