> your AI agent picks dependencies from memory; give it dated facts — try starlog.dev ↗ vet your agent's deps ↗ vibe-coding is fine. vibe-importing isn’t. — try starlog.dev ↗ vibe-importing isn’t fine ↗ your agent has never seen your private packages — try starlog.dev ↗ facts for private packages ↗ a linter for the dependencies your AI agent picks — try starlog.dev ↗ a linter for agent deps ↗ whois is redacted, cdns mask the rest — get the real operator — try whoisgeni.us ↗ who really runs that domain ↗ domain attribution that shows its work — full evidence chain — try whoisgeni.us ↗ domain intel w/ evidence ↗

← Back to Articles

Building an LLM Server That Responds to DNS Queries: A Deep Dive into Protocol Abuse

[ View on GitHub ]

Building an LLM Server That Responds to DNS Queries: A Deep Dive into Protocol Abuse

Hook

You can query an AI chatbot using only dig — the same DNS tool that resolves domain names — bypassing corporate firewalls, captive portals, and any network that allows basic name resolution.

Context

DNS is the internet's phonebook, designed for one thing: translating human-readable domains into IP addresses. It's also ubiquitous, implemented in every network stack from Kubernetes clusters to embedded IoT thermostats, and almost never blocked by enterprise security policies. This universality makes DNS an attractive covert channel.

The duyet/llm-over-dns project exploits this by building a DNS server that treats every incoming query as an LLM prompt. Run dig @llm.duyet.net -p 5000 'explain quantum computing' TXT +short and you get back ChatGPT-style responses chunked into DNS TXT records. It's equal parts network engineering curiosity and practical demonstration of why DNS tunneling remains a persistent security concern. The tool exists at the intersection of protocol abuse, API proxying, and the realization that DNS packets traverse networks where HTTP requests would be blocked, logged, or throttled.

Technical Insight

The architecture leverages hickory-dns (the successor to trust-dns after its archival) to handle DNS protocol parsing, wrapped in a Tokio async runtime for concurrent request handling. When a DNS TXT query arrives, the server extracts the QNAME — normally something like example.com — and treats the entire string as a verbatim LLM prompt. This design choice eliminates the need for subdomain routing or zone delegation logic, making every query a direct LLM invocation.

Here's the core handler logic, simplified:

async fn handle_query(
    qname: &str,
    cache: Arc<Cache<String, Vec<String>>>,
    semaphore: Arc<Semaphore>,
) -> Result<Vec<TxtRecord>, ServerError> {
    // Check cache first
    if let Some(cached) = cache.get(qname) {
        return Ok(cached.clone());
    }

    // Acquire semaphore permit for backpressure
    let _permit = semaphore.acquire().await?;

    // Forward to LLM API with model fallback
    let response = call_llm_with_fallback(qname).await?;

    // Chunk response into 255-byte TXT records
    let records = chunk_into_txt_records(&response);
    
    cache.insert(qname.to_string(), records.clone());
    Ok(records)
}

The concurrency model uses a tokio::sync::Semaphore initialized to MAX_CONCURRENT_LLM_REQUESTS (typically 10-20), creating explicit backpressure. When the semaphore is exhausted, new queries wait asynchronously rather than spawning unbounded tasks that could DOS the upstream OpenRouter API. If a timeout occurs, the server returns DNS SERVFAIL, which causes most resolvers to try alternate nameservers or cache negative responses — a graceful degradation pattern.

Model fallback is implemented as a static list tried serially: google/gemini-flash-1.5 → anthropic/claude-3-haiku → meta-llama/llama-3.1-8b-instruct. When an HTTP request returns 5xx or times out, the code immediately tries the next model. This handles free-tier rate limits and model availability issues without manual intervention, though it incurs full timeout penalties before moving to the next option.

The TXT record chunking reveals a DNS protocol constraint most developers never encounter. TXT records support multiple strings, each capped at 255 bytes (not characters). The implementation splits the LLM response:

fn chunk_into_txt_records(text: &str) -> Vec<String> {
    text.as_bytes()
        .chunks(255)
        .map(|chunk| String::from_utf8_lossy(chunk).to_string())
        .collect()
}

This naive byte-boundary split has a critical flaw: multibyte UTF-8 sequences (emoji, Chinese characters, accented letters) can be sliced mid-character, producing � replacement characters in the output. A production implementation would need UTF-8 boundary awareness, walking back from byte 255 to the last complete character boundary.

Caching uses the moka crate's LRU implementation with raw QNAME bytes as keys. This means 'hello world' and 'HELLO WORLD' are separate cache entries, and whitespace variations also miss the cache. A normalized key (lowercase, trimmed, Unicode NFC normalized) would improve hit rates significantly, but the current approach is simpler and avoids ambiguity about what transformations are acceptable.

Gotcha

The security model is non-existent. There's no authentication, per-client rate limiting, or abuse protection beyond the global concurrency semaphore. Since DNS queries can have spoofed source IPs (UDP is connectionless), you can't even implement IP-based allowlists reliably. The first time this server gets linked in a Reddit thread, someone will script a loop to drain your OpenRouter API credits. The repository README acknowledges this is a demo, but it's worth emphasizing: running this on a public IP with real API keys is financially dangerous.

DNS UDP packets have a practical limit around 512 bytes before fragmentation issues arise, and many middleboxes drop large DNS responses entirely. While DNS supports TCP fallback for oversized answers, hickory-dns requires explicit TCP listener configuration that this project doesn't implement. Long LLM responses exceeding ~1500 bytes after chunking will be silently truncated by network infrastructure, cutting off answers mid-sentence with no indication to the client.

The serial model fallback strategy optimizes for simplicity over latency. If the first model (Gemini) has a 30-second timeout, you wait the full duration before trying Claude, even if Claude would have responded in 2 seconds. A production system would fan out requests to multiple models concurrently and return the first success, or at least implement exponential backoff with jitter rather than fixed timeouts.

Verdict

Use if: You're demonstrating DNS tunneling concepts for security training, building a proof-of-concept for data exfiltration research, need LLM access in a DNS-only embedded environment (industrial IoT, airplane wifi), or want a memorable conference talk hook. The code is also an excellent learning resource for Rust async DNS handling with hickory-dns, showing real-world semaphore-based backpressure and API integration patterns.

Skip if: You need any form of production reliability, security, or cost control. There are no authentication mechanisms, responses get corrupted on UTF-8 boundaries, and public deployment will result in immediate API abuse. For actual restricted-network LLM access, run LocalAI or Ollama locally. For legitimate DNS-over-HTTPS implementations, use Cloudflare or Google's infrastructure. This tool is educational theater — a clever hack that illuminates protocol constraints and attack surfaces, but not a foundation for real systems.