A recursive DNS server

For this one we are going to make a recursive DNS server. Our goals:

TL;DR this is going to be a bit long. You can find the repo that holds everything here.

NOTES

  1. As you will see later, you don't want to use this if you play video games online, maybe. You'll see why. Caching helps but compared to your ISPs DNS, this won't do. Trade-offs.
  2. This is not a light service and probably a bit over-engineered. I ended up having a bit too much fun with it. It could be trimmed down.
  3. This has been my DNS resolver for a while now.
  4. I run 3 instances on VPSes since i use these on devices that go outside with me as well, but if you don't need that(why?), you could host them on your internal network.

The Design

Let's first address anonymity and privacy. We want the incoming traffic to our server to be encrypted coming in and going out(it's a recursive resolver). For incoming traffic we can choose between DoH, DoT and DoQ. There is no reason for us not to choose all three so we choose all three. DoH is nice. DoT is supported by systemd-resolved so you don't need anything else if you're running a systemd distro. We'll keep DoQ for future-proofing or something. We could benchmark DoQ vs DoT/DoH speeds and check whether there is a meaningful difference but since our upstream is going to go over tor, the significant chunk of the RTT will be tor so we'll leave that be for now. For the other end, so outgoing connections, we can do the same. We only send queries to servers which support some sort of encrypted DNS. That requires us to use a forwarder that allows us to do that.

As for our outgoing transport, we will be sending all queries over tor. This will mean that our queries will be much slower(way slower, seriously!) but we gain anonymity. Needless to say, since we are forwarding all queries over tor, we will be forcing TCP-only queries upstream so no upstream UDP for us. Downstream, as in, when receiving queries, we will accept encrypted UDP. We will also need some rate-limiting mechanism and security measures since this is going to be a server on the internet using components that are not exactly bind or knot levels of battle-tested. We will use docker as the runtime. Any OCI-compatible runtime will do, of course.

For our DoH endpoint, we will be using a web application firewall to filter malicious http queries. If you've ever hosted some http service on the internets and have bothered to actually look at the logs, you know what i mean. For DoT and DoQ we will use powerDNS's dnsdist. DoH and DoH3 will be sent here as well but after having gone through our WAF. We could have the modsecurity crs nginx instance(our web application firewall, waf) handle DoT but for DoQ we will not be able to do that since DoQ will be using UDP(its quic, remember?) and we will need something that understands the DoQ ALPN. Nginx cant do that so we use dnsdist. We will see in a bit that using dnsdist has some benefits as well.

We will use dnscrypt-proxy as our forwarder through tor. It can fulfill all our requirements: TCP-only queries, only encrypted upstreams, sends traffic through a socks5 proxy which makes sending over tor a cinch. Since all dnscrypt-proxy traffic will be going through tor, the initial startup time will be a little too long for comfort. So we will bindmount the cache directory for dnscrypt-proxy so after the first-time start, we can avoid a fresh resolver-list download on every container recreation.

Tor is tor. It's slow, circuits go down etc. so we will be running 3 tor containers behind a reverse proxy doing round robin to attempt to somewhat mitigate the fickleness of the tor network. You can also choose to use obfuscation for tor if that makes sense for you. VPN upstream transports are also possible. We will not explore them here but in some later posts in the future, we might get there. I2P doesn't have US gov backing so it has almost no exit nodes so we can't really pass through there.

That's pretty much it for the design part. The rest of the post will just be us talking about implementation details.

We will also use supercronic to update our filter lists that CoreDNS consumes. We will also leave the caching to Coredns. I experimented with both dnsdist and Coredns as the service in charge of caching. My best guess is that coredns's prefetching makes a big difference in terms of responsiveness and believe me we need responsiveness when we are forwarding everything on TCP through tor(dnsdist does not support prefetching). If you decide to go with dnsdist as your cache, keep in mind that queries with EDNS will have a different hash than the same query without EDNS so dnsdist caches those as different cache entries.

The filtering and blocking will be handled mostly by CoreDNS. Supercronic will handle updating and merging the lists. Keep in mind that very big lists will require a lot of initial processing time and also a lot of memory(multiple gigabytes). Some part of the blocking will be handled by dnsdist. Because of that, we will be using dnsdist to block certain domains. The reason for this is this incident. If you don't feel like reading that, the short version is that ad-blocking is no longer just a privacy concern. It's also a security concern.

Let's talk about the networks a bit as well. Among our containers, the CoreDNS and DNSCrypt-proxy networks will have docker networks marked internal,e.g. internal: true, because first, in case of CoreDNS it does not need to talk to anything outside this compose file and for DNSCrypt-proxy, it will only communicate through tor. This way, it's safer. They won't leak because they can't, not because i think i set them up correctly. This is a safer design.

All the endpoints are at standard locations, i.e. :443 and /dns-query for DoH, and :853 for DoT and DoQ. We do not serve non-encrypted DNS publicly.

One important note regarding DNSSEC for this design. DNSSEC validation will be happening client-side and not server-side(on this stack). Keep that in mind.

Diagram

That's the path our queries take through the system:

----------      -----      ---------       ---------      ----------------      ---------      -----
|DoH/DoH3| ---> |WAF| ---> |dnsdist|  ---> |CoreDNS| ---> |DNSCrypt-Proxy| ---> |HaProxy| ---> |Tor|
----------      -----      ---------       ---------      ----------------      ---------      -----

-----      ---------      ---------      ----------------      ---------      -----
|DoT| ---> |dnsdist| ---> |CoreDNS| ---> |DNSCrypt-Proxy| ---> |HaProxy| ---> |Tor|
-----      ---------      ---------      ----------------      ---------      -----

-----      ---------      ---------      ----------------      ---------      -----
|DoQ| ---> |dnsdist| ---> |CoreDNS| ---> |DNSCrypt-Proxy| ---> |HaProxy| ---> |Tor|
-----      ---------      ---------      ----------------      ---------      -----

The intakes are our waf and dnsdist. The default port for DoH is 443(duh!!!) and 853 for DoT and DoQ. We will serve over those but feel free to change them on your end.

Intake

The waf config is pretty straightforward. Its a normal reverse-proxy setting for nginx, with the added addition of us having to exempt our DoH URI since a valid DoH request looks all kinds of bad to our WAF given its current config.

server {
  listen 443 ssl;
  listen [::]:443 ssl;
  listen 443 quic reuseport;
  listen [::]:443 quic reuseport;
  http2 on;
  http3 on;
  if ($server_protocol !~* "^HTTP/(2|3)[.]0$") {
    return 444;
  }

  add_header Alt-Svc 'h3=":443"; ma=86400' always;

  keepalive_timeout 60;
  charset utf-8;

  ssl_certificate /certs/fullchain.pem;
  ssl_certificate_key /certs/privkey.pem;
  ssl_protocols TLSv1.3;
  ssl_session_cache shared:SSL:50m;
  ssl_session_timeout 1d;
  ssl_session_tickets on;

  tcp_nopush on;

  add_header X-Content-Type-Options "nosniff" always;
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
  add_header X-Frame-Options SAMEORIGIN always;
  add_header X-XSS-Protection "1; mode=block" always;
  add_header Referrer-Policy "no-referrer";

  fastcgi_hide_header X-Powered-By;

  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
      root   /usr/share/nginx/html;
  }

  location = /dns-query {
    grpc_pass grpc://172.31.33.9:8053;

    modsecurity_rules '
      SecRuleEngine On
      SecRuleRemoveById 920280 920420
    ';

    grpc_set_header Host              $host;
    grpc_set_header X-Real-IP         $remote_addr;
    grpc_set_header X-Forwarded-For   $remote_addr;
    grpc_set_header X-Forwarded-Proto $scheme;
  }
}

For DoH to work we need to exempt two rules: 920280 and 920420. We use grpc_pass here to forward DoH requests to dnsdist over HTTP/2; despite the directive’s name, the requests remain DoH and are not converted into gRPC. For further reading look here please. We will only answer to HTTP/2 and HTTP/3 for DoH and DoH3.

Http/1.1 has fundamental design flaws. There is no real reason or benefit for us to use it so we will be using HTTP/2 and HTTP/3 for our incoming DoH requests.

  waf:
    image: waf
    build:
      dockerfile: ./Dockerfile_waf
      context: .
    deploy:
      resources:
        limits:
          memory: 256M
    logging:
      driver: "json-file"
      options:
        max-size: "50m"
        max-file: "5"
    ports:
      - "443:443/tcp"
      - "443:443/udp"
    networks:
      frontend:
      dns:
        ipv4_address: 172.31.33.10
    restart: unless-stopped
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/waf.conf:ro
    depends_on:
      - dnsdist
    environment:
      - MODSECURITY_RULE_ENGINE=On
      - BLOCKING_PARANOIA=1
      - DETECTION_PARANOIA=1
      - ALLOWED_REQUEST_CONTENT_TYPE_CHARSET=|utf-8|
      - VALIDATE_UTF8_ENCODING=1
      - ALLOWED_METHODS=GET POST
      - ALLOWED_HTTP_VERSIONS=HTTP/2.0 HTTP/3.0
    runtime: runsc
    security_opt:
      - no-new-privileges
    cap_drop:
      - ALL
    cap_add:
      - CHOWN
      - DAC_OVERRIDE
      - SETUID
      - SETGID
      - NET_BIND_SERVICE

We will be using gvisor's runsc as our OCI runtime. We will do that for all containers. Just a few things to keep in mind when we are using runsc:

  1. runsc will block access to the docker resolver so we won't be able to use the container names as hostnames.
  2. because runsc blocks access to the docker resolver, we won't have any DNS in the containers either

For number 2, the supercronic container will be downloading and updating our block lists so it's going to need a DNS resolver along with the tor nodes. The rest of the containers dont need a DNS resolver. For inter-container connectivity, we will set static addresses and use those to reference a container.

For our other ingestion point, dnsdist, we have:

-- vim: ft=lua
infolog("CLIENT-IP-CHECK configuration loaded")
setLocal("127.0.0.1:5300")

setACL({"0.0.0.0/0", "::/0"})
addAction(AllRule(), LuaAction(function(dq)
    infolog(
        "CLIENT-IP-CHECK client=" .. dq.remoteaddr:toString() .. " qname=" ..
            dq.qname:toString())
    return DNSAction.None
end))

-- pc = newPacketCache(10000, {
--     maxTTL = 86400,
--     minTTL = 0,
--     temporaryFailureTTL = 60,
--     staleTTL = 60,
--     dontAge = false,
--     shuffle = false
-- })
-- getPool(""):setCache(pc)

local certificate = "/certs/fullchain.pem"
local privateKey = "/certs/privkey.pem"

addTLSLocal("0.0.0.0:8853", certificate, privateKey, {
    provider = "openssl",
    minTLSVersion = "tls1.3",
    maxConcurrentTCPConnections = 1000,
    numberOfStoredSessions = 0
})

addDOQLocal("0.0.0.0:8853", certificate, privateKey,
            {idleTimeout = 30, congestionControlAlgo = "cubic"})

addDOHLocal("0.0.0.0:8053", nil, nil, {"/dns-query"},
            {trustForwardedForHeader = true})

newServer({
    address = "172.31.33.20:8054",
    name = "coredns",
    tcpOnly = true,
    checkTCP = false,
    healthCheckMode = "up"
})

setRingBuffersSize(100000, 10)

local abuse = dynBlockRulesGroup()

abuse:setQueryRate(100, 10, "Exceeded query rate", 60, DNSAction.Drop, 50)

abuse:setQTypeRate(DNSQType.ANY, 5, 10, "Exceeded ANY query rate", 60,
                   DNSAction.Drop)

function maintenance() abuse:apply() end

webserver("0.0.0.0:8083")
setWebserverConfig({
    password = "",
    apiKey = "",
    acl = "172.16.0.0/12"
})

controlSocket("0.0.0.0:5199")
setKey("")
setConsoleACL({"172.16.0.0/12"})

local blockedDomains = newSuffixMatchNode()
for line in io.lines("/etc/dnsdist/blocked-domains.txt") do
    local domain = line:gsub("#.*$", ""):match("^%s*(%S+)%s*$")
    if domain then blockedDomains:add(newDNSName(domain)) end
end

addAction(QNameSuffixRule(blockedDomains, true), RCodeAction(DNSRCode.NXDOMAIN))
  dnsdist:
    image: powerdns/dnsdist-21:2.1.2
    deploy:
      resources:
        limits:
          memory: 384M
    logging:
      driver: "json-file"
      options:
        max-size: "50m"
        max-file: "5"
    volumes:
      - ./dnsdist.conf:/etc/dnsdist/conf.d/10-encrypted-dns.conf:ro
      - ./privkey1.pem:/certs/privkey.pem:ro
      - ./fullchain1.pem:/certs/fullchain.pem:ro
      - ./blocked-domains.txt:/etc/dnsdist/blocked-domains.txt:ro
    ports:
      - "853:8853/tcp"
      - "853:8853/udp"
      - "127.0.0.1:8083:8083/tcp"
      - "127.0.0.1:5199:5199/tcp"
    networks:
      frontend:
      dns:
        ipv4_address: 172.31.33.9
    restart: unless-stopped
    read_only: true
    security_opt:
      - no-new-privileges
    cap_drop:
      - ALL
    runtime: runsc

Our waf and dnsdist images both run as non-root so make sure they can both read your x.509 private key.

Forwarder Chain

https://.:8053 dns://.:8054 {
  errors
  log
  bufsize 4096
  loadbalance

  hosts /etc/coredns/hosts/hosts {
    fallthrough
  }

  forward . 172.31.33.15:53 {
    max_concurrent 1000
  }

  cache 3600 {
    success 10000
    denial 10000
    prefetch 20 10m 10%
    serve_stale 1h
    servfail 5s
  }

  loop
}
  coredns:
    image: coredns
    build:
      dockerfile: ./Dockerfile_coredns
      context: .
    deploy:
      resources:
        limits:
          memory: 1G
    logging:
      driver: "json-file"
      options:
        max-size: "50m"
        max-file: "3"
    networks:
      dns:
        ipv4_address: 172.31.33.20
    volumes:
      - ./Corefile:/etc/coredns/Corefile:ro
      - ./hosts/:/etc/coredns/hosts/:ro
    depends_on:
      - dnscryptproxy
      - supercronic
    command: ["-conf", "/etc/coredns/Corefile"]
    restart: unless-stopped
    security_opt:
      - no-new-privileges
    runtime: runsc
    read_only: true
    cap_drop:
      - ALL

Coredns is our main forwarder. This is where we cache the queries as well as where we enforce the block lists(e.g. The hosts file that we are bind mounting).

After Coredns, we have to hand off the requests to dnscrypt-proxy.

Below are the options that we need. The rest of the options are really up to you. Also, we turn caching off here since we really dont need dnscrypt-proxy to cache because coredns is already caching the queries for us. We don't want to have to deal with double-caching weirdness. For bootstrap resolvers, we will use tor's DNSPort so those will also pass through tor. Both networks that dnscrypt has, dns and tor will be marked internal, so this container cannot contact the outside world, i.e. We will not be leaking anything from dnscryptproxy.

cache = false
dnscrypt_servers = false
doh_servers = true
odoh_servers = false
require_dnssec = true
require_nolog = true
require_nofilter = true
proxy = 'socks5://172.31.66.66:9050'
force_tcp = true
listen_addresses = ['0.0.0.0:53']
bootstrap_resolvers = ['172.31.66.10:9053', '172.31.66.11:9053', '172.31.66.12:9053']
[sources.public-resolvers]
cache_file = '/var/cache/dnscrypt-proxy/public-resolvers.md'

The dnscrypt-proxy conf file is an excerpt. The full config would be too long to put here. You can look at it in the repo or just configure it the way you want. The excerpt includes the important bits.

  dnscryptproxy:
    image: dnscrypt-proxy
    build:
      dockerfile: ./Dockerfile_dnscrypt-proxy
      context: .
    deploy:
      resources:
        limits:
          memory: 128M
    logging:
      driver: "json-file"
      options:
        max-size: "50m"
        max-file: "3"
    networks:
      dns:
        ipv4_address: 172.31.33.15
      tor:
        ipv4_address: 172.31.66.15
    volumes:
      - ./dnscrypt-proxy-config.toml:/etc/dnscrypt-proxy/dnscrypt-proxy.toml:ro
      - ./resolv.conf:/etc/resolv.conf:ro
      - ./dnscrypt-cache:/var/cache/dnscrypt-proxy
    depends_on:
      - haproxy
    command: ["--config", "/etc/dnscrypt-proxy/dnscrypt-proxy.toml"]
    restart: unless-stopped
    security_opt:
      - no-new-privileges
    runtime: runsc
    cap_drop:
      - ALL

Upstream Transport

First up is our reverse-proxy, haproxy.

The only thing worth noting here is we try connecting to 1.1.1.1:443 through our tor circuits to make sure they are working. A backend is removed after 3 consecutive failures and restored after 2 consecutive successes.

global
    maxconn 4096
    log stdout format raw local0

defaults
    log global
    mode tcp
    option tcplog
    option dontlognull

    timeout connect 5s
    timeout client 60s
    timeout server 60s
    timeout check 30s

listen socks5_rr_docker
    bind :9050
    mode tcp
    balance roundrobin

    option tcp-check
    option log-health-checks

    # Connect to the Tor SOCKS listener.
    tcp-check connect

    # SOCKS5 greeting: offer authentication method "no authentication".
    tcp-check send-binary 050100
    tcp-check expect min-recv 2 rbinary ^0500

    # Ask Tor to connect to 1.1.1.1:443 through a circuit.
    tcp-check send-binary 050100010101010101bb

    # SOCKS5 reply: version 5, success, reserved byte 0.
    tcp-check expect min-recv 3 rbinary ^050000

    default-server inter 60s fall 3 rise 2

    server server0 172.31.66.10:9050 check
    server server1 172.31.66.11:9050 check
    server server2 172.31.66.12:9050 check
  haproxy:
    image: haproxy:lts-alpine3.24
    deploy:
      resources:
        limits:
          memory: 128M
    logging:
      driver: "json-file"
      options:
        max-size: "50m"
        max-file: "3"
    volumes:
      - ./haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
    restart: unless-stopped
    security_opt:
      - no-new-privileges
    read_only: true
    runtime: runsc
    cap_drop:
      - ALL
    networks:
      tor:
        ipv4_address: 172.31.66.66
    depends_on:
      - tor1
      - tor2
      - tor3

And our Tor instances:

  tor1:
    image: tor
    build:
      dockerfile: ./Dockerfile_tor
      context: .
    deploy:
      resources:
        limits:
          memory: 512M
    logging:
      driver: "json-file"
      options:
        max-size: "50m"
        max-file: "3"
    networks:
      tor:
        ipv4_address: 172.31.66.10
      tor_egress:
    volumes:
      - ./torrc:/etc/tor/torrc:ro
      - ./resolv.conf:/etc/resolv.conf:ro
    command: ["-f", "/etc/tor/torrc"]
    security_opt:
      - no-new-privileges
    restart: unless-stopped
    runtime: runsc
    cap_drop:
      - ALL

The other tor instances, tor2 and tor3 will have the exact same config, only a different IP address, so 172.31.66.11 and 172.31.66.12.

We don't have any special requirements for tor besides the DNSPort that dnscryptproxy will use for its bootstrap resolver addresses. Just make sure that the port is being served on 0.0.0.0 and not localhost. Besides that, i guess use bridges. Maybe. The resolv.conf file is a static one, containing a DNS server of your choosing. I'm using cloudflare's 1.1.1.1 because the chances of them blocking tor is lower, for very obvious reasons, might i add.

Block Lists

And the final piece. Our supercronic service just downloads a block list. You can choose whichever one you want. There are a ton of block lists all over the internet. Feel free to add more lists or just a different list. One thing to note here is that we are bind-mounting a directory and that directory is being shared by both supercronic and CoreDNS. This is because for a bind-mount, what the bind-mount is actually watching is the inode. When we update a file, depending on how we do it, the inode might change, and so CoreDNS might not pick up the update since it's watching a totally different inode. By bind-mounting a directory, we can stop worrying about all of that so even if the inode changes, we will still see the change. Also, because of the way we are handling hosts file updates, we will get a new inode every time we update. So in our case, we have to bind-mount the directory containing the file for CoreDNS. The CoreDNS hosts plugin detects the change within its default reload time which is 5 seconds so we don't need to reload coredns on every hosts file update.

  supercronic:
    image: supercronic
    build:
      dockerfile: ./Dockerfile_supercronic
      context: .
    deploy:
      resources:
        limits:
          memory: 256M
    logging:
      driver: "json-file"
      options:
        max-size: "5m"
        max-file: "3"
    networks:
      - nil
    read_only: true
    security_opt:
      - no-new-privileges
    volumes:
      - ./crontab:/etc/crontab:ro
      - ./hosts:/hosts/:rw
      - ./resolv.conf:/etc/resolv.conf:ro
    tmpfs:
      - /tmp:nosuid,noexec,rw,size=32m
    restart: unless-stopped
    command: ["/etc/crontab"]
    runtime: runsc
    cap_drop:
      - ALL
#!/bin/sh
set -eu

update_hosts() (
    mkdir -p /hosts
    workdir=$(mktemp -d /hosts/.hosts-update.XXXXXX)
    trap 'rm -rf "$workdir"' 0
    trap 'exit 1' HUP INT TERM

    cat > "$workdir/sources" <<'EOF'
https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-gambling/hosts
https://raw.githubusercontent.com/hagezi/dns-blocklists-legacy/main/hosts/pro.txt
EOF
# https://raw.githubusercontent.com/hagezi/dns-blocklists-legacy/main/hosts/tif.txt

    : > "$workdir/combined"

    while IFS= read -r url; do
        printf 'Downloading %s\n' "$url"
        curl --fail --show-error --silent --location \
            --retry 10 \
            --retry-all-errors \
            --connect-timeout 30 \
            --max-time 300 \
            "$url" \
            -o "$workdir/download"
        awk '
            {
                sub(/\r$/, "")
                sub(/#.*/, "")
            }
            $1 == "0.0.0.0" && NF == 2 {
                print "0.0.0.0 " $2
            }
        ' "$workdir/download" > "$workdir/parsed"
        if [ ! -s "$workdir/parsed" ]; then
            printf 'ERROR: No usable hosts entries from %s\n' "$url" >&2
            exit 1
        fi
        cat "$workdir/parsed" >> "$workdir/combined"
    done < "$workdir/sources"
    rm -f "$workdir/download" "$workdir/parsed"
    TMPDIR="$workdir" LC_ALL=C sort -u \
        "$workdir/combined" > "$workdir/hosts"
    test -s "$workdir/hosts"
    count=$(wc -l < "$workdir/hosts")
    mv -f "$workdir/hosts" /hosts/hosts
    printf 'Updated /hosts/hosts: %s unique entries\n' "$count"
)

if [ "${1:-}" = "--update" ]; then
    update_hosts
    exit 0
fi
if ! /bin/sh "$0" --update; then
    printf 'Initial update failed; keeping existing hosts file.\n' >&2
fi

exec /usr/local/bin/supercronic "$@"

I have not included the tif list since its gigantic and my VPSes can't handle it. If you have more resources , then definitely go for it.

You can look here and here and here for more lists to choose from.

Finally, you can find the entire recursive resolver here.

Network definitions

networks:
  frontend:
    driver: bridge
    enable_ipv6: true
  dns:
    internal: true
    enable_ipv6: true
    driver: bridge
    ipam:
      config:
        - subnet: 172.31.33.0/24
  tor:
    internal: true
    enable_ipv6: true
    driver: bridge
    ipam:
      config:
        - subnet: 172.31.66.0/24
  tor_egress:
    driver: bridge
  nil:

Resource Usage

I've been running my instance on a VPS with 2GB of RAM and 2 CPU cores. You could probably get away with lower resources but you might be cutting it too close. I recommend the same loadout that I have. Ideally pick something with both IPv4 and IPv6 connectivity.

Future Improvements

written by terminaldweller, proofread by an LLM

timestamp:1793456076

version:1.6.0

https://raw.githubusercontent.com/terminaldweller/blog/main/mds/arecursivednsserver.md





Keywords:




Archive About     RSS