| 1 |
package acl |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"net/netip" |
| 6 |
"slices" |
| 7 |
|
| 8 |
"codeberg.org/miekg/dns" |
| 9 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/dnsctx" |
| 10 |
"codeberg.org/miekg/dns/dnsutil" |
| 11 |
"github.com/phemmer/go-iptrie" |
| 12 |
) |
| 13 |
|
| 14 |
// rule defines ACL policies which will be enforced. |
| 15 |
type rule struct { |
| 16 |
policies []policy |
| 17 |
} |
| 18 |
|
| 19 |
// policy defines the ACL policy for DNS messages. |
| 20 |
// A policy performs the specified action (block/allow) on all DNS messages matched by source IP or QTYPE. |
| 21 |
type policy struct { |
| 22 |
action dns.MsgAcceptAction |
| 23 |
|
| 24 |
// One of these is non-nil and carries the policy |
| 25 |
net *policyNet |
| 26 |
ctx *policyCtx |
| 27 |
} |
| 28 |
|
| 29 |
type policyNet struct { |
| 30 |
qtypes []uint16 |
| 31 |
opcodes []uint8 |
| 32 |
filter *iptrie.Trie |
| 33 |
} |
| 34 |
|
| 35 |
type policyCtx struct { |
| 36 |
ctx string |
| 37 |
values []any |
| 38 |
} |
| 39 |
|
| 40 |
const MsgFilter = dns.MsgAcceptAction(10) |
| 41 |
|
| 42 |
// match matches the DNS message with a list of ACL polices and returns suitable action against the message. |
| 43 |
func match(ctx context.Context, policies []policy, w dns.ResponseWriter, r *dns.Msg) dns.MsgAcceptAction { |
| 44 |
for _, policy := range policies { |
| 45 |
switch { |
| 46 |
case policy.net != nil: |
| 47 |
ip := netip.MustParseAddr(dnsutil.RemoteIP(w)) |
| 48 |
if x := dnsctx.Addr(ctx, "etc/address"); x.IsValid() { |
| 49 |
ip = x |
| 50 |
} |
| 51 |
|
| 52 |
matchAll := len(policy.net.opcodes) == 0 |
| 53 |
match := slices.Contains(policy.net.opcodes, r.Opcode) |
| 54 |
if !matchAll && !match { |
| 55 |
continue |
| 56 |
} |
| 57 |
|
| 58 |
_, qtype := dnsutil.Question(r) |
| 59 |
matchAll = len(policy.net.qtypes) == 0 |
| 60 |
match = slices.Contains(policy.net.qtypes, qtype) |
| 61 |
if !matchAll && !match { |
| 62 |
continue |
| 63 |
} |
| 64 |
|
| 65 |
if !policy.net.filter.Contains(ip) { |
| 66 |
continue |
| 67 |
} |
| 68 |
return policy.action |
| 69 |
case policy.ctx != nil: |
| 70 |
if dnsctx.Match(ctx, policy.ctx.ctx, policy.ctx.values) { |
| 71 |
return policy.action |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
return dns.MsgAccept |
| 76 |
} |