feat(dnssec): query the authoritative servers directly

This commit is contained in:
2025-09-04 18:11:39 +01:00
parent 1f2703df19
commit 234b1dcc86
17 changed files with 2218 additions and 4 deletions

View File

@@ -0,0 +1,3 @@
package dnscrypt
// DNSCrypt resolver implementation

View 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
View 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
View 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
View 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
}