synthetic/synthetic.go
2024-02-10 23:02:52 -08:00

233 lines
6.7 KiB
Go

package synthetic
import (
"context"
"encoding/hex"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/pkg/dnstest"
clog "github.com/coredns/coredns/plugin/pkg/log"
"github.com/coredns/coredns/plugin/test"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
"net"
"strings"
)
// Define log to be a logger with the plugin name in it. This way we can just use log.Info and
// friends to log.
var log = clog.NewWithPlugin("synthetic")
// Name implements the Handler interface.
func (s synthetic) Name() string { return "synthetic" }
// synthetic is an synthetic plugin to show how to write a plugin.
type synthetic struct {
Next plugin.Handler
Config syntheticConfig
}
// ServeDNS implements the plugin.Handler interface.
//
// This method gets called when synthetic is used in a Server
func (s synthetic) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
// Create a new state for this request. This is used to store state and allows us to pass this
state := request.Request{W: w, Req: r}
log.Debug("Received request for ", state.QName(), " of type ", state.QType())
// Continue to the next plugin in the chain, and record the response.
rec := dnstest.NewRecorder(&test.ResponseWriter{})
rc, err := plugin.NextOrFailure(s.Name(), s.Next, ctx, rec, r)
// If the next plugin in the chain's recorded response is success, we go with that.
if rc == dns.RcodeNameError {
log.Debug("Next plugin in chain responded with acceptable response ", rc, " for ", state.QName())
w.WriteMsg(rec.Msg)
return rc, err
}
switch state.QType() {
//
// Handle AAAA and A requests (Forward Lookup)
// Note: on the forward lookup, we're guaranteed to have a match on the domain name
//
case dns.TypeA, dns.TypeAAAA:
// only continue if the first label starts with "ip-" (fall back to recorded response)
if !strings.HasPrefix(state.Name(), "ip-") {
w.WriteMsg(rec.Msg)
return rc, err
}
// parse first dns label (now we have: "ip-<ip>")
firstLabel := strings.Split(state.Name(), ".")[0]
// trim "ip-" prefix (now we have: "<ip>")
ipStr := strings.TrimPrefix(firstLabel, "ip-")
// attempt to parse as IPv4 or IPv6
ip := net.ParseIP(strings.ReplaceAll(ipStr, "-", "."))
if ip == nil {
ip = net.ParseIP(strings.ReplaceAll(ipStr, "-", ":"))
}
log.Debug(state.Name(), " parsed to ", ip)
// don't continue if we couldn't parse the IP (fall back to recorded respones)
if ip == nil {
log.Debug("Failed to parse IP from: ", state.QName())
w.WriteMsg(rec.Msg)
return rc, err
}
// check if ip is within the synthetic network
var found bool
for _, n := range s.Config.net {
if n.Contains(ip) {
found = true
break
}
}
// don't continue if the IP is not in the synthetic network (fall back to recorded response)
if !found {
log.Debug("IP ", ip, " not found in synthetic network")
w.WriteMsg(rec.Msg)
return rc, err
}
// handle AAAA requests with IPv6 address
if ip.To4() == nil && state.QType() == dns.TypeAAAA {
log.Debug("Responding to AAAA request for ", state.QName())
m := new(dns.Msg)
m.SetReply(r)
hdr := dns.RR_Header{Name: state.QName(), Rrtype: state.QType(), Class: state.QClass()}
m.Answer = append(m.Answer, &dns.AAAA{Hdr: hdr, AAAA: ip.To16()})
w.WriteMsg(m)
return dns.RcodeSuccess, nil
}
// handle A requests with IPv4 address
if ip.To4() != nil && state.QType() == dns.TypeA {
log.Debug("Responding to A request for ", state.QName())
m := new(dns.Msg)
m.SetReply(r)
hdr := dns.RR_Header{Name: state.QName(), Rrtype: state.QType(), Class: state.QClass()}
m.Answer = append(m.Answer, &dns.A{Hdr: hdr, A: ip.To4()})
w.WriteMsg(m)
return dns.RcodeSuccess, nil
}
// handle A requests with IPv6 address (respond with empty answer and NOERROR)
if ip.To4() == nil && state.QType() == dns.TypeA {
log.Debug("Responding to A request for ", state.QName(), " with empty answer")
m := new(dns.Msg)
m.SetReply(r)
w.WriteMsg(m)
return dns.RcodeSuccess, nil
}
// handle AAAA requests with IPv4 address (respond with empty answer and NOERROR)
if ip.To4() != nil && state.QType() == dns.TypeAAAA {
log.Debug("Responding to AAAA request for ", state.QName(), " with empty answer")
m := new(dns.Msg)
m.SetReply(r)
w.WriteMsg(m)
return dns.RcodeSuccess, nil
}
// if we got here, we couldn't handle the request (fall back to recorded response)
log.Debug("Failed to handle request for ", state.QName())
w.WriteMsg(rec.Msg)
return rc, err
//
// Handle PTR requests (Reverse Lookup)
// Note: on the forward lookup, we're guaranteed to have a match on the network
//
case dns.TypePTR:
ip := inArpaToIp(state.QName())
log.Debug("Received PTR request. Parsed ", state.QName(), " to ", ip)
// don't continue if we couldn't parse the IP (fall back to recorded response)
if ip == nil {
w.WriteMsg(rec.Msg)
return rc, err
}
// successful reverse lookup
forward := ipToDomainName(ip, s.Config.forward)
log.Debug("Responding to PTR request for ", state.QName(), " with ", forward)
m := new(dns.Msg)
m.SetReply(r)
hdr := dns.RR_Header{Name: state.QName(), Rrtype: state.QType(), Class: state.QClass()}
m.Answer = append(m.Answer, &dns.PTR{Hdr: hdr, Ptr: forward})
w.WriteMsg(m)
return dns.RcodeSuccess, nil
}
// if we got here, we couldn't handle the request (fall back to recorded response)
log.Debug("synthetic plugin not needed for ", state.QName(), " of type ", state.QType())
w.WriteMsg(rec.Msg)
return rc, err
}
func inArpaToIp(name string) net.IP {
ipv4Suffix := ".in-addr.arpa."
ipv6Suffix := ".ip6.arpa."
if idx := strings.Index(name, ipv4Suffix); idx > 6 {
name = name[:idx]
parts := strings.Split(name, ".")
if len(parts) != 4 {
return nil
}
name = parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0]
return net.ParseIP(name)
}
if len(name) == 73 && name[63:] == ipv6Suffix {
// we can rely on the fact that v6 reverse hostnames have a fixed length
// read the characters from the hostname into a buffer in reverse
v6chars := make([]byte, 32)
for i, j := 62, 0; i >= 0; i -= 2 {
v6chars[j] = name[i]
j++
}
// decode the characters in the buffer into 16 bytes and return it
v6bytes := make([]byte, 16)
if _, err := hex.Decode(v6bytes, v6chars); err != nil {
return nil
}
return v6bytes
}
return nil
}
func ipToDomainName(ip net.IP, zone string) string {
if ip == nil {
return ""
}
if !strings.HasPrefix(zone, ".") {
zone = "." + zone
}
if !strings.HasSuffix(zone, ".") {
zone = zone + "."
}
sep := ":"
if ip.To4() != nil {
sep = "."
}
response := strings.Join(strings.Split(ip.String(), sep), "-")
return "ip-" + response + zone
}