| 1 |
package cookie |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding/hex" |
| 6 |
"hash/fnv" |
| 7 |
"io" |
| 8 |
|
| 9 |
"codeberg.org/miekg/dns" |
| 10 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/dnsctx" |
| 11 |
"codeberg.org/miekg/dns/dnsutil" |
| 12 |
) |
| 13 |
|
| 14 |
type Cookie struct { |
| 15 |
Secret string |
| 16 |
} |
| 17 |
|
| 18 |
func (c *Cookie) HandlerFunc(next dns.HandlerFunc) dns.HandlerFunc { |
| 19 |
return dns.HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) { |
| 20 |
for _, o := range r.Pseudo { |
| 21 |
if cc, ok := o.(*dns.COOKIE); ok { |
| 22 |
if len(cc.Cookie) < 16 || len(cc.Cookie) > 40 { |
| 23 |
m := r.Copy() |
| 24 |
dnsutil.SetReply(m, r) |
| 25 |
m.Rcode = dns.RcodeFormatError |
| 26 |
m.Pack() |
| 27 |
io.Copy(w, m) |
| 28 |
return |
| 29 |
} |
| 30 |
|
| 31 |
// TODO(miek): if a longer client cookie we can actually check if this is our server cookie |
| 32 |
|
| 33 |
f := fnv.New64() |
| 34 |
io.WriteString(f, dnsutil.RemoteIP(w)) |
| 35 |
io.WriteString(f, cc.Cookie[:16]) |
| 36 |
io.WriteString(f, c.Secret) |
| 37 |
|
| 38 |
ctx = dnsctx.WithFunc(ctx, c, |
| 39 |
func(m *dns.Msg) *dns.Msg { |
| 40 |
cookie := &dns.COOKIE{Cookie: cc.Cookie[:16] + hex.EncodeToString(f.Sum(nil))} |
| 41 |
m.Pseudo = append(m.Pseudo, cookie) |
| 42 |
return m |
| 43 |
}) |
| 44 |
|
| 45 |
ctx = dnsctx.WithValue(ctx, dnsctx.Key(c, dnsctx.KeyStatus), true) |
| 46 |
break |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
next.ServeDNS(ctx, w, r) |
| 51 |
}) |
| 52 |
} |