plugin/rewrite: Limit rewrite cname recursion (#8570)

This PR limit rewrite cname recursion with the existing DNS server loop counter.
The issu was that rewrite cname can recurse indefinitely through internal lookups, causing crash at the end

Signed-off-by: Yong Tang <yong.tang.github@outlook.com>
This commit is contained in:
Yong Tang
2026-09-22 06:23:20 -07:00
committed by GitHub
parent 5aa4dc2941
commit d5c1188843
2 changed files with 82 additions and 1 deletions

View File

@@ -7,6 +7,7 @@ import (
"strconv"
"strings"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/pkg/log"
"github.com/coredns/coredns/plugin/pkg/upstream"
@@ -15,6 +16,8 @@ import (
"github.com/miekg/dns"
)
const maxCNAMERewriteDepth = 8
// UpstreamInt wraps the Upstream API for dependency injection during testing
type UpstreamInt interface {
Lookup(ctx context.Context, state request.Request, name string, typ uint16) (*dns.Msg, error)
@@ -82,12 +85,20 @@ func (r *cnameTargetRuleWithReqState) RewriteResponse(res *dns.Msg, rr dns.RR) {
if cname.Target != fromTarget {
return
}
// Limit internal lookups that re-enter the server.
loop, _ := r.ctx.Value(dnsserver.LoopKey{}).(int)
if loop > maxCNAMERewriteDepth {
return
}
ctx := context.WithValue(r.ctx, dnsserver.LoopKey{}, loop+1)
// create upstream request with the new target with the same qtype
r.state.Req.Question[0].Name = toTarget
// upRes can be nil if the internal query path didn't write a response
// (e.g. a plugin returned a success rcode without writing, dropped the query,
// or the context was canceled). Guard upRes before dereferencing.
upRes, err := r.rule.Upstream.Lookup(r.ctx, r.state, toTarget, r.state.Req.Question[0].Qtype)
upRes, err := r.rule.Upstream.Lookup(ctx, r.state, toTarget, r.state.Req.Question[0].Qtype)
if err != nil {
log.Errorf("upstream lookup failed: %v", err)
return