2026-11-20 # Nameserver Roulette

TL;DR Writing my own nameserver in the C programming language for fun, more fun, and absolutely no profit. Initially concieved when I saw dns.museum, this project began as an experiment in RNG-over-DNS, then later became a test of what happens when your chosen nameserver returns unrelated, but valid IP addresses. Source at the bottom of the page.

open What the heck is DNS?

In short, DNS is a mapping between hostname and IP address. In reality, this is only one type of key-value pair that the system supports. DNS maps any hostname (including the root hostname, if it had records) to some records. These records can be an IPv4 address (A), nameserver for a domain (NS), canonical domain name (CNAME), mail stuff (MX), raw text (TXT), or even arbitrary data (NULL). These are listed in section 3.2.2 of RFC 1035, but many nameservers support more than just this RFC, as we now have record types like AAAA, which denote an IPv6 address. When someone purchases a domain, it pretty much means that they have the authority to manage these records (through their registrar), mapping the domain name to a server that hosts their website, minecraft server, discord bot, or whatever else. (I use cloudflare, so they have the authoritative nameserver, other registrars might require you to host your own.)

NS-type records are quite interesting though, as they allow you to run your own nameserver for your own subdomains. If you own example.com and want to have webpages at foo.bar.baz.example.com, then you can add an NS record pointing to your own DNS server (which can run on the same server hosting your website - DNS normally operates over port 53). You can then recieve incoming packets routed to your subdomains and answer any queries with whatever you want. If you really want to, you could even write a nameserver that responds to TXT queries to some-question-here.yourdomain.com with a (- albeit truncated -) response of an LLM.

Heck, TXT and NULL type records allow you to do a ton of stuff, including TCP-over-DNS, the common tool of which is called iodine (- quoting: "The name iodine was chosen since it starts with IOD (IP Over DNS) and since iodine has atomic number 53, which happens to be the DNS port number." - I thought that was cool). It basically encodes and decodes IP packets into DNS queries and responses, then sends them as DNS requests to a server running iodine, which is the proxy to the open web. DNS requests are fundamental to quite a lot of infrastructure, so they aren't often blocked... including on captive Wi-Fi portals! If you are ever stuck behind a captive Wi-Fi portal, then with TCP-over-DNS, you can often still get internet connectivity even without signing into the network or agreeing with T&C.

sona Initial conception

Not too long ago, I downloaded every RFC document in .txt format. Most of the RFCs are about how computer networks work, including DNS. I was feeling burnt out by some other projects (- and prolific online AI doomerism), so I decided to roll my hand at a RAAS (RNG-As-A-Service) DNS server. A bit whimsical, but the thought of getting 32 bits from a CSPRNG over an unsecured channel - past many restrictive network firewalls - was alluring.

DNS uses both TCP and UDP, but UDP is a bit simpler. I decided to write this nameserver using UDP in C - normally I use Zig, but I wanted to refresh my knowledge so it wouldn't stagnate. My general pattern for this project was:

  1. Listen for UDP packets on port 53
  2. Whenever a packet arrives:
    1. Ensure it is a valid DNS packet
    2. Ensure the query asked for an A or TXT type record
    3. Decode the QNAME in the packet, or domain name
    4. Based on the QNAME, respond to the packet (If a user queried for an A type record with a QNAME of rng.[server], it would respond with an IPv4 address of 32 random bits. If it were X.rng.[server], the random number will be less than X. If it were X.Y.rng.[server], the number will be in range [X, Y).)
    5. If the packet is invalid, respond with a DNS error code

I hosted this on my server for a while, and it was quite fun - it worked through my school's captive Wi-Fi portal - a cheap "we have random.org at home." To query the server, I would use dig. Notably, my program was recording far more handled requests than I queried it for, though it wasn't logging what these requests were for. It seemed that servers online would routinely traverse the IPv4 space, scanning for active services.

kama Next Implementation

When I see lots of logs for failed SSH login attempts, I am a bit miffed. When I see a bunch of PHP fetch requests over HTTP (I don't use PHP), I am somewhat concerned, but confident. After all, there are plenty of people out to get low-hanging fruit. However when I see several hundred DNS requests to my server (- which at the time, had no NS type record pointing to it -) I am very concerned about the security of my machine. The code I wrote (not included) was written in a few afternoons based on RFC 1035, in the C programming language. I was not confident in the security of my code - and while I highly doubt my code would possibly lead someone to break into my machine, there could be a possibility they would exhaust system resources due to bad allocation patterns, or the presence of a DNS server (one that kept complaining about invalid packets) would lead people to target my unprotected server far more than other machines. At this point in time, all ports were open on my machine.

I decided to enable the firewall for my server - for all ports except 22, 53, 80, 443, and 25565. As a matter of ethics, I try to avoid generating code using LLMs (this website gets routinely scraped, and the perplexity of many open-weight LLMs is lower on the code I have on github than the code I have never published to github - very frustrating). However, I decided that I should use it to proof-read my code, finding parts that didn't agree with RFC 1035, and parts which might have a vulnerability. It found several bugs, which was nice. My server was now secured, and my code sure. (Most of my errors are caught with -Werror -Wall -Wextra -Wpedantic, but LLMs can help catch logic errors and out-of-band memory leaks.)

After I had refactored my code, I figured it wouldn't be too hard to turn it into a real nameserver - one that would work for all queries listed in RFC 1035. I thought it would be funny having it resolve one website to another (eg. xkcd.com -> winworldpc.com) to see what my system would do, so I ditched much of the QNAME parsing logic and write the current version, code here. It was quite illuminating, both to see the effects on my computer, and also to see what people would query on my server.

pini Results and Thoughts

DNS is simple, but some parts are frustrating. In particular, name compression is really weird. DNS encodes domain names differently to what you see - xkcd.com is actually encoded by a leading byte "4", then "xkcd", then a leading byte "3", then "com", then a delimiter byte "0". Technically, the full domain name is actually xkcd.com. - with the ending period, but all the web browsers, command line programs, and libraries that I know of just don't care about that implicit last period. Name compression is a way to compress links like a.com.foo.com by having the next two bytes after "foo" point backwards to the first instance of "com." Question to readers, is this actually useful? I don't see how it can be useful.

Something I might have heard before, but never knew until writing this nameserver - apparently hostnames don't have a particular casing, so resolvers are free to query xKcD.COm and expect it to return the same result as xkcd.com would. If your nameserver caching doesn't same-case queries, then you could be wasting memory. In my "randomized" nameserver, my cache of the 64 most recent resolved IPv4 addresses would fill up sooner if I didn't lowercase before hashing.

I configured my system to use the nameserver I wrote. It turns out the internet breaks down when you resolve a hostname to the wrong address. Most interestingly, cloudflare has multiple types of errors that pop up when you shuffle A-type query responses (shown below). I don't know what the difference between cloudflare and cloudfront is, but I assume they both operate under the same company given the name similarity.

Beyond the webpage errors, I also noticed that firefox was trying to send a bunch of telemetry from my device (DNS queries to incoming.telemetry.mozilla.org). I originally started using firefox because of the privacy, and I guess they must have turned telemetry back on when I wasn't looking, sad. My university domain (byui.edu) was also getting some unrelated DNS queries - like to example.org.c.byui.edu or xkcd.com.byui.edu, after which firefox thought I was behind a captive Wi-Fi page (I wasn't) and needed to sign into the network. How strange. I don't know how firefox detects captive Wi-Fi portals, but it definitely wasn't working well with shuffled DNS responses.

I tried Google Chrome, and got similar results to firefox... except after running for about 2 minutes on the roulette nameserver, google chrome just up and crashed. What a strange bug. Also, it turns out that ipv4only.arpa exists, I forwarded several of these queries to cloudflare with my nameserver. It's a pretty cool feature of DNS I'd never heard of before.

Many websites love to ping home, whether it be telemetry, spyware, or unnecessary ad-related junk. Claude, ChatGPT, and other AI stuff were the worst offenders, but the Google search results page was not far behind. I noticed google was sending requests to googleusercontent.com, gstatic.com, googlevideo.com, ytimg.com... How many domains does google need for caching!?! There were also a bunch of requests google made for ads, like adtrafficquality.google - huh, who knew that "google" was a TLD?

Anyways, this was all locally what my computer was requesting through my DNS server. Some of the more interesting results are what IP scanners query. This log is from the last about 12 hours the server has been running. I can understand why a lot of people would query for version.bind - it's a query to get the version information of a nameserver, but why uu.nl, ferc.gov, or even ni? If anyone has any thoughts for some of these strange queries, I'd love to hear them.

REQUEST FOR dnsscan.shadowserver.org - FORWARDED
REQUEST FOR version.bind - FORMAT ERROR - SENT
REQUEST FOR hostname.bind - FORMAT ERROR - SENT
REQUEST FOR hostname.bind - BAD QUERY - SENT
REQUEST FOR dhitc.com - FORWARDED
REQUEST FOR version.bind - FORMAT ERROR - SENT
REQUEST FOR version.bind - BAD QUERY - SENT
REQUEST FOR uu.nl - FORWARDED
REQUEST FOR VERSION.BIND - FORMAT ERROR - SENT
REQUEST FOR version.bind - FORMAT ERROR - SENT
REQUEST FOR VERSION.BIND - FORMAT ERROR - SENT
REQUEST FOR ferc.gov - FORWARDED
REQUEST FOR version.bind - FORMAT ERROR - SENT
 - BAD QUERY - SENT
REQUEST FOR www.baidu.com - FORWARDED
REQUEST FOR 000660b043677e04.559b.REDACTED_IPv4.asertdnsresearch.com - FORWARDED
REQUEST FOR version.bind - FORMAT ERROR - SENT
REQUEST FOR ip.parrotdns.com - FORWARDED
REQUEST FOR version.bind - FORMAT ERROR - SENT
 - BAD QUERY - SENT
REQUEST FOR ni - FORWARDED
REQUEST FOR dhitc.com - FORWARDED
REQUEST FOR dhitc.com - FORWARDED
REQUEST FOR VERSION.BIND - FORMAT ERROR - SENT
REQUEST FOR ip.parrotdns.com - FORWARDED
REQUEST FOR ip.parrotdns.com - FORWARDED
REQUEST FOR version.bind - FORMAT ERROR - SENT
REQUEST FOR VERSION.BIND - FORMAT ERROR - SENT
REQUEST FOR d7cfr2s2fnxrm.r3-95-5f.dnscheck.internet-measurement.com - FORWARDED
REQUEST FOR version.bind - FORMAT ERROR - SENT
REQUEST FOR hostname.bind - FORMAT ERROR - SENT
REQUEST FOR example.com - FORWARDED
REQUEST FOR id.server - FORMAT ERROR - SENT
REQUEST FOR dhitc.com - FORWARDED
REQUEST FOR id.server - FORMAT ERROR - SENT
REQUEST FOR version.bind - FORMAT ERROR - SENT
REQUEST FOR m.baidu.com - FORWARDED
REQUEST FOR cloudflare.com - FORWARDED
REQUEST FOR cloudflare.com - FORWARDED
REQUEST FOR version.bind - FORMAT ERROR - SENT
REQUEST FOR hostname.bind - FORMAT ERROR - SENT
REQUEST FOR id.server - FORMAT ERROR - SENT
REQUEST FOR version.bind - FORMAT ERROR - SENT
REQUEST FOR version.bind - FORMAT ERROR - SENT
REQUEST FOR VERSION.BIND - FORMAT ERROR - SENT
REQUEST FOR wisc.edu - FORWARDED

toki ilo Project Code

// ----------------------------------------------------------------------------
// Custom nameserver - runs on port 53, uses UDP:
// - A-type requests have a chance of returning a random recent IP-address
// - all other requests are forwarded to cloudflare or some other DNS server
// ----------------------------------------------------------------------------

#include <arpa/inet.h>
#include <ctype.h>
#include <netinet/in.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/random.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>

// 253 bytes is the max size of a parsed QNAME - first and last marker removed
#define QNAME_SIZE 253
// 512 bytes is the max size of a UDP DNS message - RFC 1035 2.3.4
#define DNS_BUF_SIZE 512
// 4096 bytes for EDNS compatible buffer size - forwarding
#define REPLY_BUF_SIZE 4096
// CLASS value for the internet - RFC 1035 3.2.4
#define CLASS_IN 1

// TYPE values for resource records - RFC 1035 3.2.2
#define TYPE_A 1 // an IPv4 host address

// maximum number of stored IPv4 addresses
#define CACHE_SIZE 64
// upstream resolver used for lookups (cloudflare)
#define RESOLVE_ADDR "1.1.1.1"
// timeout in seconds for resolver
#define RESOLVE_TIMEOUT 5

// number of bytes in the DNS header - 6x 16-bit fields is 12 bytes
#define HEADER_SIZE 12
// number of non-variable-length bytes in DNS question section
#define QUESTION_SIZE 4
// number of non-variable-length bytes in DNS resource definition
#define RESOURCE_SIZE 10

// DNS header definition - RFC 1035 4.1.1
typedef struct __attribute__((packed)) {
    // 16 bit identifier that generates any kind of query
    uint16_t id;
    // QR, OPCODE, AA, TC, RD, RA, Z, and RCODE flags
    uint16_t flags;
    // u16 - number of entries in question section
    uint16_t qd_count;
    // u16 - number of records in answer section
    uint16_t an_count;
    // u16 - number of records in authority section
    uint16_t ns_count;
    // u16 - number of records in additional section
    uint16_t ar_count;
} Header;

// DNS resource definition - RFC 1035 4.1.3
typedef struct __attribute__((packed)) {
    /* NAME - NOT INCLUDED, VARIABLE LENGTH */

    // u16 - code specifying meaning of data in RDATA
    uint16_t type;
    // u16 - code specifying class of data in RDATA
    uint16_t class;
    // u32 - time in seconds the interval is valid for
    uint32_t ttl;
    // u16 - length in bytes of the RDATA field
    uint16_t rd_len;

    /* RDATA - NOT INCLUDED, VARIABLE LENGTH */
} Resource;

// an entry into recently resolved IPv4 addresses
typedef struct {
    // query hash to prevent duplicate cache entries
    uint32_t hash;
    // resolved IPv4 address
    uint32_t address;
} Entry;

// cache of recently resolved addresses
typedef struct {
    Entry entries[CACHE_SIZE];
    uint32_t len, next;
} Cache;

// ----------------------------------------------------------------------------
// Create and bind IPv4/IPv6 UDP socket on port 53, open to all interfaces.
// Returns 0 on success, -1 on failure.
// ----------------------------------------------------------------------------
int create_ns_socket(int *const sock) {
    // create an IPv6 UDP [SOCK_DGRAM + IPPROTO_UDP] socket
    *sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
    if (*sock < 0) goto error;

    // explicitly accept both IPv4 and IPv6 packets
    int ipv6_only = 0, level = IPPROTO_IPV6, name = IPV6_V6ONLY;
    if (setsockopt(*sock, level, name, &ipv6_only, sizeof(ipv6_only)))
        goto error;

    // describe local address to listen on
    struct sockaddr_in6 server_addr = {
        .sin6_family = AF_INET6, // IPv6 [and IPv4] addresses
        .sin6_port = htons(53), // listen on port 53 - DNS
        .sin6_addr = in6addr_any, // listen on all interfaces
    };

    // attach opened socket to that address and port
    if (bind(*sock, (struct sockaddr *)&server_addr, sizeof(server_addr)))
        goto error;

    return 0;

error:
    // display error message
    perror(NULL);
    // close any opened socket
    if (*sock >= 0) close(*sock);
    // signal error occurred
    return -1;
}

// ----------------------------------------------------------------------------
// Create a UDP socket connected to the upstream resolver.
// Returns 0 on success, -1 on failure.
// ----------------------------------------------------------------------------
int create_resolver_socket(int *const sock) {
    // create an IPv4 UDP [SOCK_DGRAM + IPPROTO_UDP] socket
    *sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (*sock < 0) goto error;

    // describe address to connect to
    struct sockaddr_in upstream_addr = {
        .sin_family = AF_INET, // IPv4 address
        .sin_port = htons(53), // port 53 - DNS
    };

    // write the network address of the resolver into the upstream_addr
    if (inet_pton(AF_INET, RESOLVE_ADDR, &upstream_addr.sin_addr) != 1)
        goto error;

    // connect to the resolver
    struct sockaddr *resolve_addr = (struct sockaddr *)&upstream_addr;
    if (connect(*sock, resolve_addr, sizeof(upstream_addr))) goto error;

    struct timeval timeout = {RESOLVE_TIMEOUT, 0};
    // set a timeout of RESOLVE_TIMEOUT seconds on reading from the socket
    if (setsockopt(*sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)))
        goto error;

    return 0;

error:
    // display error message
    perror(NULL);
    // close any opened socket
    if (*sock >= 0) close(*sock);
    // signal error occurred
    return -1;
}

// ----------------------------------------------------------------------------
// Forward a DNS query to the upstream resolver and receive one reply.
// Returns the response length on success, -1 on failure.
// ----------------------------------------------------------------------------
ssize_t forward_query(
    const int resolver_fd,
    const uint8_t *const restrict request,
    const size_t req_len,
    uint8_t *const restrict response,
    const size_t resp_len
) {
    // not a valid DNS request, can't fit the header
    if (req_len < HEADER_SIZE) return -1;

    // send the request to the resolver
    ssize_t sent = send(resolver_fd, request, req_len, 0);
    if (sent < 0) return -1;

    while (1) {
        // receive the response from the resolver
        ssize_t got = recv(resolver_fd, response, resp_len, 0);
        // not a valid DNS response, can't fit the header
        if (got < HEADER_SIZE) return -1;
        // 16 bit response ID does not match request
        if (memcmp(response, request, 2) != 0) continue;

        return got;
    }
}

// ----------------------------------------------------------------------------
// Parse a DNS question into a QNAME buffer, QTYPE integer, and QCLASS integer.
// Returns 0 on success, -1 on failure. Format defined in RFC 1035 4.1.2.
// ----------------------------------------------------------------------------
int parse_question(
    const uint8_t *const restrict packet,
    size_t *const restrict off,
    const size_t packet_len,
    char *const restrict q_name,
    uint16_t *const restrict q_type,
    uint16_t *const restrict q_class
) {
    // there is no room for a question within the packet
    if (*off >= packet_len) return -1;
    // the QNAME is empty, only the root label is present
    if (packet[*off] == 0) return -1;

    size_t write = 0;
    uint16_t target;
    int jumped = 0;
    size_t end = 0;

    while (1) {
        // QNAME is not finished yet we ran out of bounds
        if (*off >= packet_len) return -1;
        // read label length and advance past the byte
        uint8_t label = packet[(*off)++];
        // the root label has been found
        if (label == 0) break;

        // RFC 1035 4.1.4. Message compression
        switch (label & 0xC0) {
            // normal labels - top bits 00
            case 0x00:
                // the packet is too small to have that label
                if (label > packet_len - *off) return -1;
                // the QNAME is too large to be valid
                if (write + 1 + label > QNAME_SIZE) return -1;
                // write QNAME label separator
                if (write > 0) q_name[write++] = '.';
                // write QNAME label content
                memcpy(q_name + write, packet + *off, label);
                // advance read and write pointers
                write += label, *off += label;
                break;

            // compression pointers - top bits 11
            case 0xC0:
                // ensure there is enough space for the pointer
                if (*off >= packet_len) return -1;
                // continue reading labels from the target pointer
                target = ((label & 0x3F) << 8) | packet[(*off)++];
                // only allow backwards jumps to prevent infinitely looping
                if (target >= *off - 2) return -1;
                // the question continues after the current reading head
                if (!jumped) jumped = 1, end = *off;
                // continue reading labels from the target pointer
                *off = target;
                break;

            // reserved for future use - top bits 01 or 10
            default:
                return -1;
        }
    }

    // the QNAME must not be empty
    if (write == 0) return -1;
    // restore the reading head if we jumped
    if (jumped) *off = end;
    // both QTYPE and QCLASS must fit in the packet
    if (QUESTION_SIZE > packet_len - *off) return -1;

    // copy the QTYPE and convert to host endianness
    memcpy(q_type, packet + *off, 2);
    *q_type = ntohs(*q_type);
    *off += 2;

    // copy the QCLASS and convert to host endianness
    memcpy(q_class, packet + *off, 2);
    *q_class = ntohs(*q_class);
    *off += 2;

    // add a null-character delimiter to qname
    q_name[write] = 0;

    return 0;
}

// ----------------------------------------------------------------------------
// Skip one encoded DNS name, starting at *off. Handles compression pointers.
// Returns 0 on success, -1 on failure. Format defined in RFC 1035 4.1.2.
// ----------------------------------------------------------------------------
int skip_name_bytes(
    const uint8_t *const restrict packet,
    const size_t packet_len,
    size_t *const restrict off
) {
    while (1) {
        // offset is out of bounds - abort
        if (*off >= packet_len) return -1;
        const uint8_t label = packet[*off];

        switch (label & 0xC0) {
            case 0x00:
                // skip past label and text bytes
                *off += label + 1;
                // return if this is the root label
                if (!label) return 0;
                // continue to the next label
                break;

            case 0xC0:
                // pointer must be within the packet
                if (packet_len - *off < 2) return -1;
                // skip past compression pointer bytes
                *off += 2;
                // text ends immediately after pointer
                return 0;

            default:
                // reserved label not in use - invalid
                return -1;
        }
    }
}

// ----------------------------------------------------------------------------
// Parse the first A/IN answer from a DNS response, if present.
// Returns 0 on success, -1 on failure.
// ----------------------------------------------------------------------------
int parse_response_first_a(
    const uint8_t *const restrict packet,
    const size_t packet_len,
    uint32_t *const restrict address
) {
    // packet too small to be valid response
    if (packet_len < HEADER_SIZE) return -1;

    Header header; // copy header out
    memcpy(&header, packet, HEADER_SIZE);

    // convert to host byte order
    const uint16_t flags = ntohs(header.flags);
    const uint16_t qd_count = ntohs(header.qd_count);
    const uint16_t an_count = ntohs(header.an_count);

    // packet is a request, not a response
    if ((flags & 0x8000) == 0) return -1;
    // resolver signalled error with RCODE
    if ((flags & 0x000F) != 0) return -1;

    // offset into the packet
    size_t off = HEADER_SIZE;

    // skip the question entries: NAME + QTYPE + QCLASS
    for (uint16_t i = 0; i < qd_count; i++) {
        // name bytes are invalid, or the packet is truncated
        if (skip_name_bytes(packet, packet_len, &off)) return -1;
        // packet too small to hold QTYPE and QCLASS
        if (packet_len - off < QUESTION_SIZE) return -1;
        // advance past QTYPE and QCLASS
        off += QUESTION_SIZE;
    }

    // walk records - NAME + TYPE + CLASS + TTL + RDLENGTH + RDATA
    for (uint32_t i = 0; i < an_count; i++) {
        // name bytes are invalid, or the packet is truncated
        if (skip_name_bytes(packet, packet_len, &off)) return -1;
        // packet too small to hold TYPE and CLASS and TTL and RDLENGTH
        if (packet_len - off < RESOURCE_SIZE) return -1;

        Resource resource; // copy resource out
        memcpy(&resource, packet + off, RESOURCE_SIZE);
        const uint16_t type = ntohs(resource.type);
        const uint16_t class = ntohs(resource.class);
        const uint16_t rd_len = ntohs(resource.rd_len);
        // skip past non-variable-length resource bytes
        off += RESOURCE_SIZE;

        // RDATA bytes must fit within the packet
        if (rd_len > packet_len - off) return -1;

        // looking for an IPv4 address (type A) in internet (IN)
        if (type == TYPE_A && class == CLASS_IN && rd_len == 4) {
            uint32_t network_address; // copy out address
            memcpy(&network_address, packet + off, 4);
            *address = ntohl(network_address);
            return 0;
        }

        // skip past resource data
        off += rd_len;
    }

    // no A record in the answer section
    return -1;
}

// ----------------------------------------------------------------------------
// Write a response into output packet, with given name, type, TTL, and
// data. Returns 0 on success, -1 on failure. Format defined in RFC
// 1035 4.1.3.
// ----------------------------------------------------------------------------
int resource(
    uint8_t *const packet,
    size_t *const restrict off,
    const uint8_t *const name,
    const size_t name_len,
    const uint16_t type,
    const uint32_t time_to_live,
    const uint8_t *const restrict data,
    const uint16_t data_len
) {
    // there is no room for this response in the packet
    if (*off + name_len + data_len + RESOURCE_SIZE > DNS_BUF_SIZE) return -1;

    // write the name into the output packet
    memcpy(packet + *off, name, name_len);
    *off += name_len;

    // write the type into the output packet
    uint16_t type_network = htons(type);
    memcpy(packet + *off, &type_network, 2);
    *off += 2;

    // write the class into the output packet
    uint16_t class_network = htons(CLASS_IN);
    memcpy(packet + *off, &class_network, 2);
    *off += 2;

    // write the TTL into the output packet
    uint32_t ttl_network = htonl(time_to_live);
    memcpy(packet + *off, &ttl_network, 4);
    *off += 4;

    // write data length into output packet
    uint16_t len_network = htons(data_len);
    memcpy(packet + *off, &len_network, 2);
    *off += 2;

    // write the data into the output packet
    memcpy(packet + *off, data, data_len);
    *off += data_len;

    return 0;
}

// ----------------------------------------------------------------------------
// Change request header to a response header, set error code. RFC 1035 4.1.1.
// ----------------------------------------------------------------------------
void set_error_response(uint8_t *const buf, const uint8_t rcode) {
    // copy OPCODE and RD, mark response and authority
    buf[2] = 0x84 | (buf[2] & 0x79);
    // set desired rcode & recursion available
    buf[3] = 0x80 | rcode;
    // no AN, NS, or AR records
    memset(buf + 6, 0, 6);
}

// ----------------------------------------------------------------------------
// Change request header to a valid response header. RFC 1035 4.1.1.
// ----------------------------------------------------------------------------
void set_response(uint8_t *const buf, uint16_t an_count) {
    // buffer is now a response, and with no error
    set_error_response(buf, 0x00);

    // set the number of answers in the header
    an_count = htons(an_count);
    memcpy(buf + 6, &an_count, 2);
}

// ----------------------------------------------------------------------------
// Read a uint32_t from getrandom. Returns 0 on success, -1 on failure.
// ----------------------------------------------------------------------------
int random_u32(uint32_t *const number) {
    if (getrandom(number, 4, 0) != 4) {
        perror("getrandom");
        return -1;
    } else {
        return 0;
    }
}

// ----------------------------------------------------------------------------
// Hash an array of bytes into a uint32_t - Fowler–Noll–Vo, variant 1a
// ----------------------------------------------------------------------------
uint32_t hash_fnv1a_u32(const uint8_t *const bytes, const size_t len) {
    uint32_t value = 0x811c9dc5; // FNV offset basis
    for (size_t i = 0; i < len; i++) {
        value = (value ^ bytes[i]) * 0x01000193;
    }
    return value;
}

// ----------------------------------------------------------------------------
// Add an address to the cache. Infallible function.
// ----------------------------------------------------------------------------
void cache_add(Cache *const cache, const uint32_t hash, const uint32_t addr) {
    for (uint32_t i = 0; i < cache->len; i++) {
        // the cache must not contain duplicates
        if (cache->entries[i].hash == hash) return;
    }

    // entry consists of both the hash and the address
    const Entry entry = {.hash = hash, .address = addr};

    if (cache->len < CACHE_SIZE) {
        // cache is not full - append to the cache
        cache->entries[cache->len++] = entry;
    } else {
        // cache is full - replace at next scheduled slot
        cache->entries[cache->next++ % CACHE_SIZE] = entry;
    }
}

// ----------------------------------------------------------------------------
// Pick a random cached address. Returns 0 on success, -1 on failure / empty.
// ----------------------------------------------------------------------------
int cache_get(const Cache *const restrict cache, uint32_t *const address) {
    // cache is not completely filled - do not serve from cache
    if (cache->len < CACHE_SIZE) return -1;

    uint32_t index;
    // numbers below this threshold are discarded to avoid modulo bias
    const uint32_t threshold = (uint32_t)(0 - CACHE_SIZE) % CACHE_SIZE;

    for (uint_fast8_t try = 0; try < 16; try++) {
        // failed to get a random number, or avoiding modulo bias
        if (random_u32(&index) || index < threshold) continue;
        // return the cache entry address at the random index
        *address = cache->entries[index % CACHE_SIZE].address;
        // exit with success - an address has been returned
        return 0;
    }

    // CSPRNG could be broken
    return -1;
}

int main(void) {
    int sock, res_fd;
    // create and bind IPv4/IPv6 UDP socket on port 53
    if (create_ns_socket(&sock)) return 1;
    // create socket to external resolver we proxy
    if (create_resolver_socket(&res_fd)) return 1;
    // recently resolved A query addresses
    Cache cache = {0};

    uint8_t query[DNS_BUF_SIZE];
    uint8_t reply[REPLY_BUF_SIZE];

    while (1) {
        // store address of an IPv4 or IPv6 client
        struct sockaddr_in6 client_addr;
        socklen_t ca_len = sizeof(client_addr);
        struct sockaddr *ca_ptr = (struct sockaddr *)&client_addr;

        // receive a DNS query and store client's address
        ssize_t len = recvfrom(sock, query, DNS_BUF_SIZE, 0, ca_ptr, &ca_len);
        // ignore all incomplete packets (smaller than DNS header)
        if (len < HEADER_SIZE) continue;

        Header header; // copy into header
        memcpy(&header, query, HEADER_SIZE);

        // QR flag - ignore packets identifying as a response
        if (ntohs(header.flags) & 0x8000) continue;
        // QDCOUNT - respond to packets not asking one question
        if (ntohs(header.qd_count) != 1) goto bad_query;

        size_t off = HEADER_SIZE; // length/offset of the DNS packet
        char q_name[QNAME_SIZE + 1]; // +1 for null terminated string
        uint16_t q_type, q_class; // type and class of asked question

        int err = parse_question(query, &off, len, q_name, &q_type, &q_class);
        const uint16_t rq_len = off - HEADER_SIZE - QUESTION_SIZE;
        const uint8_t *const raw_q = query + HEADER_SIZE;

        printf("REQUEST FOR %s", q_name);

        // there was a problem parsing the question
        if (err) goto bad_query;
        // the request isn't asking for ordinary DNS data
        if (q_class != CLASS_IN) goto format_error;
        // A type queries are supported
        if (q_type != TYPE_A) goto forward;

        uint32_t address;
        // forward query if we cannot answer with cached address
        if (cache_get(&cache, &address)) goto forward;
        // change packet so it can be used to respond to request
        set_response(query, 1);

        // encode A type resource into r_data and rd_len
        uint8_t r_data[4];
        uint32_t network_address = htonl(address);
        memcpy(r_data, &network_address, 4);
        const uint16_t rd_len = 4;

        // sending resource with 0 TTL to help prevent caching
        err = resource(query, &off, raw_q, rq_len, q_type, 0, r_data, rd_len);
        if (err) goto server_failure;

        printf(" - RANDOM ADDRESS");

        // succeeded writing resource
        goto send_response;

    forward: {
        // relay the untouched query to the resolver server
        ssize_t got = forward_query(res_fd, query, len, reply, REPLY_BUF_SIZE);
        // the resolver did not answer, or answer with nonsense
        if (got < 0) goto server_failure;

        // record the address that was resolved for the query
        if (q_type == TYPE_A && !parse_response_first_a(reply, got, &address)) {
            size_t q_len; // count length of q_name
            for (q_len = 0; q_name[q_len]; q_len++)
                // lowercase QNAME for consistency before hashing
                q_name[q_len] = tolower((unsigned char)q_name[q_len]);
            // hash lowercased QNAME for the key within the cache
            const uint8_t *const qn_bytes = (const uint8_t *)q_name;
            cache_add(&cache, hash_fnv1a_u32(qn_bytes, q_len), address);
        }

        printf(" - FORWARDED\n");

        // relay the resolver's reply to the client
        sendto(sock, reply, got, 0, ca_ptr, ca_len);
        continue;
    }

    bad_query:
        off = HEADER_SIZE;
        set_error_response(query, 0x01); // format-error
        query[4] = 0x00, query[5] = 0x00;
        printf(" - BAD QUERY");
        goto send_response;

    format_error:
        off = len;
        set_error_response(query, 0x01); // format-error
        printf(" - FORMAT ERROR");
        goto send_response;

    server_failure:
        off = len;
        set_error_response(query, 0x02); // server-failure
        printf(" - SERVER FAILURE");
        goto send_response;

    send_response:
        sendto(sock, query, off, 0, ca_ptr, ca_len);
        printf(" - SENT\n");
    }

    close(res_fd);
    close(sock);
    return 0;
}

© Eric Petersen. All rights reserved.