plugin/rewrite: add handling of TTL field rewrites (#2048)

Resolves: #1981

Signed-off-by: Paul Greenberg <greenpau@outlook.com>
This commit is contained in:
Paul G
2018-08-29 10:41:03 -04:00
committed by GitHub
parent 52147cd657
commit 38051b9089
6 changed files with 453 additions and 25 deletions

View File

@@ -1,18 +1,19 @@
package rewrite
import (
"github.com/miekg/dns"
"regexp"
"strconv"
"strings"
"github.com/miekg/dns"
)
// ResponseRule contains a rule to rewrite a response with.
type ResponseRule struct {
Active bool
Type string
Pattern *regexp.Regexp
Replacement string
Ttl uint32
}
// ResponseReverter reverses the operations done on the question section of a packet.
@@ -38,22 +39,40 @@ func (r *ResponseReverter) WriteMsg(res *dns.Msg) error {
res.Question[0] = r.originalQuestion
if r.ResponseRewrite {
for _, rr := range res.Answer {
name := rr.Header().Name
var isNameRewritten bool = false
var isTtlRewritten bool = false
var name string = rr.Header().Name
var ttl uint32 = rr.Header().Ttl
for _, rule := range r.ResponseRules {
regexGroups := rule.Pattern.FindStringSubmatch(name)
if len(regexGroups) == 0 {
continue
if rule.Type == "" {
rule.Type = "name"
}
s := rule.Replacement
for groupIndex, groupValue := range regexGroups {
groupIndexStr := "{" + strconv.Itoa(groupIndex) + "}"
if strings.Contains(s, groupIndexStr) {
s = strings.Replace(s, groupIndexStr, groupValue, -1)
switch rule.Type {
case "name":
regexGroups := rule.Pattern.FindStringSubmatch(name)
if len(regexGroups) == 0 {
continue
}
s := rule.Replacement
for groupIndex, groupValue := range regexGroups {
groupIndexStr := "{" + strconv.Itoa(groupIndex) + "}"
if strings.Contains(s, groupIndexStr) {
s = strings.Replace(s, groupIndexStr, groupValue, -1)
}
}
name = s
isNameRewritten = true
case "ttl":
ttl = rule.Ttl
isTtlRewritten = true
}
name = s
}
rr.Header().Name = name
if isNameRewritten == true {
rr.Header().Name = name
}
if isTtlRewritten == true {
rr.Header().Ttl = ttl
}
}
}
return r.ResponseWriter.WriteMsg(res)