Created
November 29, 2018 10:14
-
-
Save riccardomc/9a1589b3f9ddd6ab70fb33d6ecd8b178 to your computer and use it in GitHub Desktop.
Minimal DNS proxy in golang. Reply NXDOMAIN for AAAA queries.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"net" | |
"os" | |
"strconv" | |
"github.com/miekg/dns" | |
) | |
func getDNSRequestHandler(client *dns.Client, config *dns.ClientConfig) func(dns.ResponseWriter, *dns.Msg) { | |
return func(w dns.ResponseWriter, r *dns.Msg) { | |
// Reply NXDOMAIN for AAAA queries | |
questionWithoutAAAA := []dns.Question{} | |
for _, q := range r.Question { | |
if q.Qtype == 28 { | |
emptyRR, _ := dns.NewRR(q.Name + "\tIN\tAAAA") | |
r.Answer = append(r.Answer, emptyRR) | |
r.Rcode = dns.RcodeNameError | |
w.WriteMsg(r) | |
continue | |
} | |
questionWithoutAAAA = append(questionWithoutAAAA, q) | |
} | |
r.Question = questionWithoutAAAA | |
r, _, err := client.Exchange(r, net.JoinHostPort(config.Servers[0], config.Port)) | |
if err != nil { | |
log.Printf("ERROR: %s\n", err.Error()) | |
return | |
} | |
w.WriteMsg(r) | |
} | |
} | |
func main() { | |
resolv := "/etc/resolv.conf" | |
if resolvEnv := os.Getenv("RESOLV"); resolvEnv != "" { | |
resolv = resolvEnv | |
} | |
port := 53 | |
if portEnv := os.Getenv("PORT"); portEnv != "" { | |
var err error | |
port, err = strconv.Atoi(portEnv) | |
if err != nil { | |
log.Fatalf("Invalid port: %s", portEnv) | |
} | |
} | |
config, _ := dns.ClientConfigFromFile(resolv) | |
client := new(dns.Client) | |
dns.HandleFunc(".", getDNSRequestHandler(client, config)) | |
server := &dns.Server{Addr: ":" + strconv.Itoa(port), Net: "udp"} | |
log.Printf("Starting at %d\n", port) | |
err := server.ListenAndServe() | |
defer server.Shutdown() | |
if err != nil { | |
log.Fatalf("Failed to start server: %s\n ", err.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment