Packet Policies¶
dnsdist works in essence like any other loadbalancer:
It receives packets on one or several addresses it listens on, and determines whether it will process this packet based on the Access Control. Should the packet be processed, dnsdist attempts to match any of the configured rules in order and when one matches, the associated action is performed.
These rule and action combinations are considered policies.
Packet Actions¶
Each packet can be:
- Dropped
- Turned into an answer directly
- Forwarded to a downstream server
- Modified and forwarded to a downstream and be modified back
- Be delayed
This decision can be taken at different times during the forwarding process.
Examples¶
Rules for traffic exceeding QPS limits¶
Traffic that exceeds a QPS limit, in total or per IP (subnet) can be matched by a rule.
For example:
addAction(MaxQPSIPRule(5, 32, 48), DelayAction(100))
This measures traffic per IPv4 address and per /48 of IPv6, and if traffic for such an address (range) exceeds 5 qps, it gets delayed by 100ms. (Please note: DelayAction()
can only delay UDP traffic).
As another example:
addAction(MaxQPSIPRule(5), NoRecurseAction())
This strips the Recursion Desired (RD) bit from any traffic per IPv4 or IPv6 /64 that exceeds 5 qps. This means any those traffic bins is allowed to make a recursor do ‘work’ for only 5 qps.
If this is not enough, try:
addAction(MaxQPSIPRule(5), DropAction())
or:
addAction(MaxQPSIPRule(5), TCAction())
This will respectively drop traffic exceeding that 5 QPS limit per IP or range, or return it with TC=1, forcing clients to fall back to TCP.
To turn this per IP or range limit into a global limit, use NotRule(MaxQPSRule(5000))
instead of MaxQPSIPRule()
.
Regular Expressions¶
RegexRule()
matches a regular expression on the query name, and it works like this:
addAction(RegexRule("[0-9]{5,}"), DelayAction(750)) -- milliseconds
addAction(RegexRule("[0-9]{4,}\\.example$"), DropAction())
This delays any query for a domain name with 5 or more consecutive digits in it. The second rule drops anything with more than 4 consecutive digits within a .example domain.
Note that the query name is presented without a trailing dot to the regex. The regex is applied case insensitively.
Alternatively, if compiled in, RE2Rule()
provides similar functionality, but against libre2.
Rule Generators¶
dnsdist contains several functions that make it easier to add actions and rules.
-
addAnyTCRule
()¶ Deprecated since version 1.2.0.
Set the TC-bit (truncate) on ANY queries received over UDP, forcing a retry over TCP. This function is deprecated as of 1.2.0 and will be removed in 1.3.0. This is equivalent to doing:
addAction(AndRule({QTypeRule(DNSQType.ANY), TCPRule(false)}), TCAction())
Changed in version 1.4.0: Before 1.4.0, the QTypes were in the
dnsdist
namespace. Usednsdist.ANY
in these versions.
-
addDelay
(DNSrule, delay)¶ Deprecated since version 1.2.0.
Delay the query for
delay
milliseconds before sending to a backend. This function is deprecated as of 1.2.0 and will be removed in 1.3.0, please use instead:addAction(DNSRule, DelayAction(delay))Parameters: - DNSRule – The DNSRule to match traffic
- delay (int) – The delay time in milliseconds.
-
addDisableValidationRule
(DNSrule)¶ Deprecated since version 1.2.0.
Set the CD (Checking Disabled) flag to 1 for all queries matching the DNSRule. This function is deprecated as of 1.2.0 and will be removed in 1.3.0. Please use the
DisableValidationAction()
action instead.
-
addDomainBlock
(domain)¶ Deprecated since version 1.2.0.
Drop all queries for
domain
and all names below it. Deprecated as of 1.2.0 and will be removed in 1.3.0, please use instead:addAction(domain, DropAction())Parameters: domain (string) – The domain name to block
-
addDomainSpoof
(domain, IPv4[, IPv6])¶ -
addDomainSpoof
(domain, {IP[,...]}) Deprecated since version 1.2.0.
Generate answers for A/AAAA/ANY queries. This function is deprecated as of 1.2.0 and will be removed in 1.3.0, please use:
addAction(domain, SpoofAction({IP[,…]}))or:
addAction(domain, SpoofAction(IPv4[, IPv6]))Parameters: - domain (string) – Domain name to spoof for
- IPv4 (string) – IPv4 address to spoof in the reply
- IPv6 (string) – IPv6 address to spoof in the reply
- IP (string) – IP address to spoof in the reply
-
addDomainCNAMESpoof
(domain, cname)¶ Deprecated since version 1.2.0.
Generate CNAME answers for queries. This function is deprecated as of 1.2.0 and will be removed in 1.3.0, in favor of using:
addAction(domain, SpoofCNAMEAction(cname))Parameters: - domain (string) – Domain name to spoof for
- cname (string) – Domain name to add CNAME to
-
addLuaAction
(DNSrule, function[, options])¶ Changed in version 1.3.0: Added the optional parameter
options
.Changed in version 1.3.0: The second argument returned by the
function
can be omitted. For earlier releases, simply return an empty string.Deprecated since version 1.4.0: Removed in 1.4.0, use
LuaAction()
withaddAction()
instead.Invoke a Lua function that accepts a
DNSQuestion
. This function works similar to usingLuaAction()
. Thefunction
should return both a DNSAction and its argument rule. The rule is used as an argument of the following DNSAction: DNSAction.Spoof, DNSAction.Pool and DNSAction.Delay. If the Lua code fails, ServFail is returned.Parameters: - DNSRule – match queries based on this rule
- function (string) – the name of a Lua function
- options (table) – A table with key: value pairs with options.
Options:
uuid
: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
function luarule(dq) if(dq.qtype==dnsdist.NAPTR) then return DNSAction.Pool, "abuse" -- send to abuse pool else return DNSAction.None, "" -- no action -- return DNSAction.None -- as of dnsdist version 1.3.0 end end addLuaAction(AllRule(), luarule)
-
addLuaResponseAction
(DNSrule, function[, options])¶ Changed in version 1.3.0: Added the optional parameter
options
.Changed in version 1.3.0: The second argument returned by the
function
can be omitted. For earlier releases, simply return an empty string.Deprecated since version 1.4.0: Removed in 1.4.0, use
LuaResponseAction()
withaddResponseAction()
instead.Invoke a Lua function that accepts a
DNSResponse
. This function works similar to usingLuaResponseAction()
. Thefunction
should return both a DNSResponseAction and its argument rule. The rule is used as an argument of the DNSResponseAction.Delay. If the Lua code fails, ServFail is returned.Parameters: - DNSRule – match queries based on this rule
- function (string) – the name of a Lua function
- options (table) – A table with key: value pairs with options.
Options:
uuid
: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
-
addNoRecurseRule
(DNSrule)¶ Deprecated since version 1.2.0.
Clear the RD flag for all queries matching the rule. This function is deprecated as of 1.2.0 and will be removed in 1.3.0, please use:
addAction(DNSRule, NoRecurseAction())Parameters: DNSRule – match queries based on this rule
-
addPoolRule
(DNSRule, pool)¶ Deprecated since version 1.2.0.
Send queries matching the first argument to the pool
pool
. e.g.:addPoolRule("example.com", "myPool")
This function is deprecated as of 1.2.0 and will be removed in 1.3.0, this is equivalent to:
addAction("example.com", PoolAction("myPool"))
Parameters: - DNSRule – match queries based on this rule
- pool (string) – The name of the pool to send the queries to
-
addQPSLimit
(DNSrule, limit)¶ Deprecated since version 1.2.0.
Limit queries matching the DNSRule to
limit
queries per second. All queries over the limit are dropped. This function is deprecated as of 1.2.0 and will be removed in 1.3.0, please use:addAction(DNSRule, QPSAction(limit))Parameters: - DNSRule – match queries based on this rule
- limit (int) – QPS limit for this rule
-
addQPSPoolRule
(DNSRule, limit, pool)¶ Deprecated since version 1.2.0.
Send at most
limit
queries/s for this pool, letting the subsequent rules apply otherwise. This function is deprecated as of 1.2.0 and will be removed in 1.3.0, as it is only a convience function for the following syntax:addAction("192.0.2.0/24", QPSPoolAction(15, "myPool")
Parameters: - DNSRule – match queries based on this rule
- limit (int) – QPS limit for this rule
- pool (string) – The name of the pool to send the queries to
Managing Rules¶
Active Rules can be shown with showRules()
and removed with rmRule()
:
> addAction("h4xorbooter.xyz.", QPSAction(10))
> addAction({"130.161.0.0/16", "145.14.0.0/16"} , QPSAction(20))
> addAction({"nl.", "be."}, QPSAction(1))
> showRules()
# Matches Rule Action
0 0 h4xorbooter.xyz. qps limit to 10
1 0 130.161.0.0/16, 145.14.0.0/16 qps limit to 20
2 0 nl., be. qps limit to 1
For Rules related to the incoming query:
-
addAction
(DNSrule, action[, options])¶ Changed in version 1.3.0: Added the optional parameter
options
.Add a Rule and Action to the existing rules.
Parameters: Options:
uuid
: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
-
clearRules
()¶ Remove all current rules.
-
getAction
(n) → Action¶ Returns the Action associated with rule
n
.Parameters: n (int) – The rule number
-
mvRule
(from, to)¶ Move rule
from
to a position where it is in front ofto
.to
can be one larger than the largest rule, in which case the rule will be moved to the last position.Parameters: - from (int) – Rule number to move
- to (int) – Location to more the Rule to
-
newRuleAction
(rule, action[, options])¶ Changed in version 1.3.0: Added the optional parameter
options
.Return a pair of DNS Rule and DNS Action, to be used with
setRules()
.Parameters: Options:
uuid
: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
-
setRules
(rules)¶ Replace the current rules with the supplied list of pairs of DNS Rules and DNS Actions (see
newRuleAction()
)Parameters: rules ([RuleAction]) – A list of RuleActions
-
showRules
([options])¶ Changed in version 1.3.0:
options
optional parameter addedShow all defined rules for queries, optionally displaying their UUIDs.
Parameters: options (table) – A table with key: value pairs with display options. Options:
showUUIDs=false
: bool - Whether to display the UUIDs, defaults to false.truncateRuleWidth=-1
: int - Truncate rules output totruncateRuleWidth
size. Defaults to-1
to display the full rule.
-
topRule
()¶ Move the last rule to the first position.
-
rmRule
(id)¶ Changed in version 1.3.0:
id
can now be an UUID.Remove rule
id
.Parameters: id (int) – The UUID of the rule to remove if id
is an UUID, its position otherwise
For Rules related to responses:
-
addResponseAction
(DNSRule, action[, options])¶ Changed in version 1.3.0: Added the optional parameter
options
.Add a Rule and Action for responses to the existing rules.
Parameters: Options:
uuid
: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
-
mvResponseRule
(from, to)¶ Move response rule
from
to a position where it is in front ofto
.to
can be one larger than the largest rule, in which case the rule will be moved to the last position.Parameters: - from (int) – Rule number to move
- to (int) – Location to more the Rule to
-
rmResponseRule
(id)¶ Changed in version 1.3.0:
id
can now be an UUID.Remove response rule
id
.Parameters: id (int) – The UUID of the rule to remove if id
is an UUID, its position otherwise
-
showResponseRules
([options])¶ Changed in version 1.3.0:
options
optional parameter addedShow all defined response rules, optionally displaying their UUIDs.
Parameters: options (table) – A table with key: value pairs with display options. Options:
showUUIDs=false
: bool - Whether to display the UUIDs, defaults to false.truncateRuleWidth=-1
: int - Truncate rules output totruncateRuleWidth
size. Defaults to-1
to display the full rule.
-
topResponseRule
()¶ Move the last response rule to the first position.
Functions for manipulating Cache Hit Respone Rules:
-
addCacheHitResponseAction
(DNSRule, action[, options])¶ New in version 1.2.0.
Changed in version 1.3.0: Added the optional parameter
options
.Add a Rule and ResponseAction for Cache Hits to the existing rules.
Parameters: Options:
uuid
: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
-
mvCacheHitResponseRule
(from, to)¶ New in version 1.2.0.
Move cache hit response rule
from
to a position where it is in front ofto
.to
can be one larger than the largest rule, in which case the rule will be moved to the last position.Parameters: - from (int) – Rule number to move
- to (int) – Location to more the Rule to
-
rmCacheHitResponseRule
(id)¶ New in version 1.2.0.
Changed in version 1.3.0:
id
can now be an UUID.Parameters: id (int) – The UUID of the rule to remove if id
is an UUID, its position otherwise
-
showCacheHitResponseRules
([options])¶ New in version 1.2.0.
Changed in version 1.3.0:
options
optional parameter addedShow all defined cache hit response rules, optionally displaying their UUIDs.
Parameters: options (table) – A table with key: value pairs with display options. Options:
showUUIDs=false
: bool - Whether to display the UUIDs, defaults to false.truncateRuleWidth=-1
: int - Truncate rules output totruncateRuleWidth
size. Defaults to-1
to display the full rule.
-
topCacheHitResponseRule
()¶ New in version 1.2.0.
Move the last cache hit response rule to the first position.
Functions for manipulating Self-Answered Response Rules:
-
addSelfAnsweredResponseAction
(DNSRule, action[, options])¶ New in version 1.3.0.
Add a Rule and Action for Self-Answered queries to the existing rules.
Parameters:
-
mvSelfAnsweredResponseRule
(from, to)¶ New in version 1.3.0.
Move self answered response rule
from
to a position where it is in front ofto
.to
can be one larger than the largest rule, in which case the rule will be moved to the last position.Parameters: - from (int) – Rule number to move
- to (int) – Location to more the Rule to
-
rmSelfAnsweredResponseRule
(id)¶ New in version 1.3.0.
Remove self answered response rule
id
.Parameters: id (int) – The UUID of the rule to remove if id
is an UUID, its position otherwise
-
showSelfAnsweredResponseRules
([options])¶ New in version 1.3.0.
Show all defined self answered response rules, optionally displaying their UUIDs.
Parameters: options (table) – A table with key: value pairs with display options. Options:
showUUIDs=false
: bool - Whether to display the UUIDs, defaults to false.truncateRuleWidth=-1
: int - Truncate rules output totruncateRuleWidth
size. Defaults to-1
to display the full rule.
-
topSelfAnsweredResponseRule
()¶ New in version 1.3.0.
Move the last self answered response rule to the first position.
Matching Packets (Selectors)¶
Packets can be matched by selectors, called a DNSRule
.
These DNSRule
s be one of the following items:
New in version 1.2.0: A DNSRule can also be a DNSName
or a list of these
-
AllRule
()¶ Matches all traffic
-
DNSSECRule
()¶ Matches queries with the DO flag set
-
DSTPortRule
(port)¶ Matches questions received to the destination port.
Parameters: port (int) – Match destination port.
-
EDNSOptionRule
(optcode)¶ New in version 1.4.0.
Matches queries or responses with the specified EDNS option present.
optcode
is specified as an integer, or a constant such as EDNSOptionCode.ECS.
-
EDNSVersionRule
(version)¶ New in version 1.4.0.
Matches queries or responses with an OPT record whose EDNS version is greater than the specified EDNS version.
Parameters: version (int) – The EDNS version to match on
-
ERCodeRule
(rcode)¶ Matches queries or responses with the specified
rcode
.rcode
can be specified as an integer or as one of the built-in RCode. The full 16bit RCode will be matched. If no EDNS OPT RR is present, the upper 12 bits are treated as 0.Parameters: rcode (int) – The RCODE to match on
-
HTTPHeaderRule
(name, regex)¶ New in version 1.4.0.
Matches DNS over HTTPS queries with a HTTP header
name
whose content matches the regular expressionregex
.Parameters: - name (str) – The case-insensitive name of the HTTP header to match on
- regex (str) – A regular expression to match the content of the specified header
-
HTTPPathRegexRule
(regex)¶ New in version 1.4.0.
Matches DNS over HTTPS queries with a HTTP path matching the regular expression supplied in
regex
. For example, if the query has been sent to the https://192.0.2.1:443/PowerDNS?dns=… URL, the path would be ‘/PowerDNS’. Only valid DNS over HTTPS queries are matched. If you want to match all HTTP queries, seeDOHFrontend.setResponsesMap()
instead.Parameters: regex (str) – The regex to match on
-
HTTPPathRule
(path)¶ New in version 1.4.0.
Matches DNS over HTTPS queries with a HTTP path of
path
. For example, if the query has been sent to the https://192.0.2.1:443/PowerDNS?dns=… URL, the path would be ‘/PowerDNS’. Only valid DNS over HTTPS queries are matched. If you want to match all HTTP queries, seeDOHFrontend.setResponsesMap()
instead.Parameters: path (str) – The exact HTTP path to match on
-
KeyValueStoreLookupRule
(kvs, lookupKey)¶ New in version 1.4.0.
As of 1.4.0, this code is considered experimental.
Return true if the key returned by ‘lookupKey’ exists in the key value store referenced by ‘kvs’. The store can be a CDB (
newCDBKVStore()
) or a LMDB database (newLMDBKVStore()
). The key can be based on the qname (KeyValueLookupKeyQName()
andKeyValueLookupKeySuffix()
), source IP (KeyValueLookupKeySourceIP()
) or the value of an existing tag (KeyValueLookupKeyTag()
).Parameters: - kvs (KeyValueStore) – The key value store to query
- lookupKey (KeyValueLookupKey) – The key to use for the lookup
-
MaxQPSIPRule
(qps[, v4Mask[, v6Mask[, burst[, expiration[, cleanupDelay[, scanFraction]]]]]])¶ -
.. versionchanged:: 1.3.1
-
Added the optional parameters ``expiration``, ``cleanupDelay`` and ``scanFraction``.
Matches traffic for a subnet specified by
v4Mask
orv6Mask
exceedingqps
queries per second up toburst
allowed. This rule keeps track of QPS by netmask or source IP. This state is cleaned up regularly ifcleanupDelay
is greater than zero, removing existing netmasks or IP addresses that have not been seen in the lastexpiration
seconds.Parameters: - qps (int) – The number of queries per second allowed, above this number traffic is matched
- v4Mask (int) – The IPv4 netmask to match on. Default is 32 (the whole address)
- v6Mask (int) – The IPv6 netmask to match on. Default is 64
- burst (int) – The number of burstable queries per second allowed. Default is same as qps
- expiration (int) – How long to keep netmask or IP addresses after they have last been seen, in seconds. Default is 300
- cleanupDelay (int) – The number of seconds between two cleanups. Default is 60
- scanFraction (int) – The maximum fraction of the store to scan for expired entries, for example 5 would scan at most 20% of it. Default is 10 so 10%
-
MaxQPSRule
(qps)¶ Matches traffic not exceeding this qps limit. If e.g. this is set to 50, starting at the 51st query of the current second traffic stops being matched. This can be used to enforce a global QPS limit.
Parameters: qps (int) – The number of queries per second allowed, above this number the traffic is not matched anymore
-
NetmaskGroupRule
(nmg[, src[, quiet]])¶ Changed in version 1.4.0:
quiet
parameter addedMatches traffic from/to the network range specified in
nmg
.Set the
src
parameter to false to matchnmg
against destination address instead of source address. This can be used to differentiate between clientsParameters: - nmg (NetMaskGroup) – The NetMaskGroup to match on
- src (bool) – Whether to match source or destination address of the packet. Defaults to true (matches source)
- quiet (bool) – Do not display the list of matched netmasks in Rules. Default is false.
-
OpcodeRule
(code)¶ Matches queries with opcode
code
.code
can be directly specified as an integer, or one of the built-in DNSOpcodes.Parameters: code (int) – The opcode to match
-
ProbaRule
(probability)¶ New in version 1.3.0.
Matches queries with a given probability. 1.0 means “always”
Parameters: probability (double) – Probability of a match
-
QClassRule
(qclass)¶ Matches queries with the specified
qclass
.class
can be specified as an integer or as one of the built-in DNSClass.Parameters: qclass (int) – The Query Class to match on
-
QNameRule
(qname)¶ New in version 1.2.0: Matches queries with the specified qname exactly.
param string qname: Qname to match
-
QNameSetRule
(set)¶ New in version 1.4.0: Matches if the set contains exact qname.
To match subdomain names, see
SuffixMatchNodeRule()
.param DNSNameSet set: Set with qnames.
-
QNameLabelsCountRule
(min, max)¶ Matches if the qname has less than
min
or more thanmax
labels.Parameters: - min (int) – Minimum number of labels
- max (int) – Maximum nimber of labels
-
QNameWireLengthRule
(min, max)¶ Matches if the qname’s length on the wire is less than
min
or more thanmax
bytes.Parameters: - min (int) – Minimum number of bytes
- max (int) – Maximum nimber of bytes
-
QTypeRule
(qtype)¶ Matches queries with the specified
qtype
qtype
may be specified as an integer or as one of the built-in QTypes. For instancednsdist.A
,dnsdist.TXT
anddnsdist.ANY
.Parameters: qtype (int) – The QType to match on
-
RCodeRule
(rcode)¶ Matches queries or responses with the specified
rcode
.rcode
can be specified as an integer or as one of the built-in RCode. Only the non-extended RCode is matched (lower 4bits).Parameters: rcode (int) – The RCODE to match on
-
RDRule
()¶ New in version 1.2.0.
Matches queries with the RD flag set.
-
RegexRule
(regex)¶ Matches the query name against the
regex
.addAction(RegexRule("[0-9]{5,}"), DelayAction(750)) -- milliseconds addAction(RegexRule("[0-9]{4,}\\.example$"), DropAction())
This delays any query for a domain name with 5 or more consecutive digits in it. The second rule drops anything with more than 4 consecutive digits within a .EXAMPLE domain.
Note that the query name is presented without a trailing dot to the regex. The regex is applied case insensitively.
Parameters: regex (string) – A regular expression to match the traffic on
-
RecordsCountRule
(section, minCount, maxCount)¶ Matches if there is at least
minCount
and at mostmaxCount
records in the sectionsection
.section
can be specified as an integer or as a DNS Packet Sections.Parameters: - section (int) – The section to match on
- minCount (int) – The minimum number of entries
- maxCount (int) – The maximum number of entries
-
RecordsTypeCountRule
(section, qtype, minCount, maxCount)¶ Matches if there is at least
minCount
and at mostmaxCount
records of typetype
in the sectionsection
.section
can be specified as an integer or as a DNS Packet Sections.qtype
may be specified as an integer or as one of the built-in QTypes, for instanceDNSQType.A
orDNSQType.TXT
.Parameters: - section (int) – The section to match on
- qtype (int) – The QTYPE to match on
- minCount (int) – The minimum number of entries
- maxCount (int) – The maximum number of entries
-
RE2Rule
(regex)¶ Matches the query name against the supplied regex using the RE2 engine.
For an example of usage, see
RegexRule()
.Note: Only available when dnsdist was built with libre2 support. Parameters: regex (str) – The regular expression to match the QNAME.
-
SNIRule
(name)¶ New in version 1.4.0.
Matches against the TLS Server Name Indication value sent by the client, if any. Only makes sense for DoT or DoH, and for that last one matching on the HTTP Host header using
HTTPHeaderRule()
might provide more consistent results. As of the version 2.3.0-beta of h2o, it is unfortunately not possible to extract the SNI value from DoH connections, and it is therefore necessary to use the HTTP Host header until version 2.3.0 is released.Parameters: name (str) – The exact SNI name to match.
-
SuffixMatchNodeRule
(smn[, quiet])¶ Matches based on a group of domain suffixes for rapid testing of membership. Pass true as second parameter to prevent listing of all domains matched.
To match domain names exactly, see
QNameSetRule()
.Parameters: - smb (SuffixMatchNode) – The SuffixMatchNode to match on
- quiet (bool) – Do not display the list of matched domains in Rules. Default is false.
-
TagRule
(name[, value])¶ New in version 1.3.0.
Matches question or answer with a tag named
name
set. Ifvalue
is specified, the existing tag value should match too.Parameters: - name (bool) – The name of the tag that has to be set
- value (bool) – If set, the value the tag has to be set to. Default is unset
-
TCPRule
([tcp])¶ Matches question received over TCP if
tcp
is true, over UDP otherwise.Parameters: tcp (bool) – Match TCP traffic. Default is true.
-
TrailingDataRule
()¶ Matches if the query has trailing data.
-
PoolAvailableRule
(poolname)¶ New in version 1.3.3.
Check whether a pool has any servers available to handle queries
--- Send queries to default pool when servers are available addAction(PoolAvailableRule(""), PoolAction("")) --- Send queries to fallback pool if not addAction(AllRule(), PoolAction("fallback"))
Parameters: poolname (string) – Pool to check
Combining Rules¶
-
AndRule
(selectors)¶ Matches traffic if all
selectors
match.Parameters: selectors ({Rule}) – A table of Rules
-
NotRule
(selector)¶ Matches the traffic if the
selector
rule does not match;Parameters: selector (Rule) – A Rule
-
OrRule
(selectors)¶ Matches the traffic if one or more of the the
selectors
Rules does match.Parameters: selector ({Rule}) – A table of Rules
Convenience Functions¶
-
makeRule
(rule)¶ Make a
NetmaskGroupRule()
or aSuffixMatchNodeRule()
, depending on it is called.makeRule("0.0.0.0/0")
will for example match all IPv4 traffic,makeRule({"be","nl","lu"})
will match all Benelux DNS traffic.Parameters: rule (string) – A string to convert to a rule.
Actions¶
Matching Packets (Selectors) need to be combined with an action for them to actually do something with the matched packets. Some actions allow further processing of rules, this is noted in their description. The following actions exist.
-
AllowAction
()¶ Let these packets go through.
-
AllowResponseAction
()¶ Let these packets go through.
-
ContinueAction
(action)¶ New in version 1.4.0.
Execute the specified action and override its return with None, making it possible to continue the processing. Subsequent rules are processed after this action.
Parameters: action (int) – Any other action
-
DelayAction
(milliseconds)¶ Delay the response by the specified amount of milliseconds (UDP-only). Subsequent rules are processed after this action.
Parameters: milliseconds (int) – The amount of milliseconds to delay the response
-
DelayResponseAction
(milliseconds)¶ Delay the response by the specified amount of milliseconds (UDP-only). Subsequent rules are processed after this action.
Parameters: milliseconds (int) – The amount of milliseconds to delay the response
-
DisableECSAction
()¶ Disable the sending of ECS to the backend. Subsequent rules are processed after this action.
-
DisableValidationAction
()¶ Set the CD bit in the query and let it go through.
-
DnstapLogAction
(identity, logger[, alterFunction])¶ New in version 1.3.0.
Send the the current query to a remote logger as a dnstap message.
alterFunction
is a callback, receiving aDNSQuestion
and aDnstapMessage
, that can be used to modify the message. Subsequent rules are processed after this action.Parameters: - identity (string) – Server identity to store in the dnstap message
- logger – The
FrameStreamLogger
orRemoteLogger
object to write to - alterFunction – A Lua function to alter the message before sending
-
DnstapLogResponseAction
(identity, logger[, alterFunction])¶ New in version 1.3.0.
Send the the current response to a remote logger as a dnstap message.
alterFunction
is a callback, receiving aDNSQuestion
and aDnstapMessage
, that can be used to modify the message. Subsequent rules are processed after this action.Parameters: - identity (string) – Server identity to store in the dnstap message
- logger – The
FrameStreamLogger
orRemoteLogger
object to write to - alterFunction – A Lua function to alter the message before sending
-
DropAction
()¶ Drop the packet.
-
DropResponseAction
()¶ Drop the packet.
-
ECSOverrideAction
(override)¶ Whether an existing EDNS Client Subnet value should be overridden (true) or not (false). Subsequent rules are processed after this action.
Parameters: override (bool) – Whether or not to override ECS value
-
ECSPrefixLengthAction
(v4, v6)¶ Set the ECS prefix length. Subsequent rules are processed after this action.
Parameters: - v4 (int) – The IPv4 netmask length
- v6 (int) – The IPv6 netmask length
-
ERCodeAction
(rcode)¶ New in version 1.4.0.
Reply immediately by turning the query into a response with the specified EDNS extended
rcode
.rcode
can be specified as an integer or as one of the built-in RCode.Parameters: rcode (int) – The extended RCODE to respond with.
-
HTTPStatusAction
(status, body, contentType="")¶ New in version 1.4.0.
Return an HTTP response with a status code of ‘’status’’. For HTTP redirects, ‘’body’’ should be the redirect URL.
Parameters: - status (int) – The HTTP status code to return.
- body (string) – The body of the HTTP response, or a URL if the status code is a redirect (3xx).
- contentType (string) – The HTTP Content-Type header to return for a 200 response, ignored otherwise. Default is ‘’application/dns-message’’.
-
KeyValueStoreLookupAction
(kvs, lookupKey, destinationTag)¶ New in version 1.4.0.
As of 1.4.0, this code is considered experimental.
Does a lookup into the key value store referenced by ‘kvs’ using the key returned by ‘lookupKey’, and storing the result if any into the tag named ‘destinationTag’. The store can be a CDB (
newCDBKVStore()
) or a LMDB database (newLMDBKVStore()
). The key can be based on the qname (KeyValueLookupKeyQName()
andKeyValueLookupKeySuffix()
), source IP (KeyValueLookupKeySourceIP()
) or the value of an existing tag (KeyValueLookupKeyTag()
).Parameters: - kvs (KeyValueStore) – The key value store to query
- lookupKey (KeyValueLookupKey) – The key to use for the lookup
- destinationTag (string) – The name of the tag to store the result into
-
LogAction
([filename[, binary[, append[, buffered[, verboseOnly[, includeTimestamp]]]]]])¶ Changed in version 1.4.0: Added the optional parameters
verboseOnly
andincludeTimestamp
, madefilename
optional.Log a line for each query, to the specified
file
if any, to the console (require verbose) if the empty string is given as filename.If an empty string is supplied in the file name, the logging is done to stdout, and only in verbose mode by default. This can be changed by setting
verboseOnly
to true.When logging to a file, the
binary
optional parameter specifies whether we log in binary form (default) or in textual form. Before 1.4.0 the binary log format only included the qname and qtype. Since 1.4.0 it includes an optional timestamp, the query ID, qname, qtype, remote address and port.The
append
optional parameter specifies whether we open the file for appending or truncate each time (default). Thebuffered
optional parameter specifies whether writes to the file are buffered (default) or not.Subsequent rules are processed after this action.
Parameters: - filename (string) – File to log to. Set to an empty string to log to the normal stdout log, this only works when
-v
is set on the command line. - binary (bool) – Do binary logging. Default true
- append (bool) – Append to the log. Default false
- buffered (bool) – Use buffered I/O. Default true
- verboseOnly (bool) – Whether to log only in verbose mode when logging to stdout. Default is true
- includeTimestamp (bool) – Whether to include a timestamp for every entry. Default is false
- filename (string) – File to log to. Set to an empty string to log to the normal stdout log, this only works when
-
LuaAction
(function)¶ Invoke a Lua function that accepts a
DNSQuestion
.The
function
should return a DNSAction. If the Lua code fails, ServFail is returned.Parameters: function (string) – the name of a Lua function
-
LuaResponseAction
(function)¶ Invoke a Lua function that accepts a
DNSResponse
.The
function
should return a DNSResponseAction. If the Lua code fails, ServFail is returned.Parameters: function (string) – the name of a Lua function
-
MacAddrAction
(option)¶ Add the source MAC address to the query as EDNS0 option
option
. This action is currently only supported on Linux. Subsequent rules are processed after this action.Parameters: option (int) – The EDNS0 option number
-
NoneAction
()¶ Does nothing. Subsequent rules are processed after this action.
-
NoRecurseAction
()¶ Strip RD bit from the question, let it go through. Subsequent rules are processed after this action.
-
PoolAction
(poolname)¶ Send the packet into the specified pool.
Parameters: poolname (string) – The name of the pool
-
QPSAction
(maxqps)¶ Drop a packet if it does exceed the
maxqps
queries per second limits. Letting the subsequent rules apply otherwise.Parameters: maxqps (int) – The QPS limit
-
QPSPoolAction
(maxqps, poolname)¶ Send the packet into the specified pool only if it does not exceed the
maxqps
queries per second limits. Letting the subsequent rules apply otherwise.Parameters: - maxqps (int) – The QPS limit for that pool
- poolname (string) – The name of the pool
-
RCodeAction
(rcode)¶ Reply immediately by turning the query into a response with the specified
rcode
.rcode
can be specified as an integer or as one of the built-in RCode.Parameters: rcode (int) – The RCODE to respond with.
-
RemoteLogAction
(remoteLogger[, alterFunction[, options]])¶ Changed in version 1.3.0:
options
optional parameter added.Changed in version 1.4.0:
ipEncryptKey
optional key added to the options table.Send the content of this query to a remote logger via Protocol Buffer.
alterFunction
is a callback, receiving aDNSQuestion
and aDNSDistProtoBufMessage
, that can be used to modify the Protocol Buffer content, for example for anonymization purposes. Subsequent rules are processed after this action.Parameters: - remoteLogger (string) – The
remoteLogger
object to write to - alterFunction (string) – Name of a function to modify the contents of the logs before sending
- options (table) – A table with key: value pairs.
Options:
serverID=""
: str - Set the Server Identity field.ipEncryptKey=""
: str - A key, that can be generated via themakeIPCipherKey()
function, to encrypt the IP address of the requestor for anonymization purposes. The encryption is done using ipcrypt for IPv4 and a 128-bit AES ECB operation for IPv6.
- remoteLogger (string) – The
-
RemoteLogResponseAction
(remoteLogger[, alterFunction[, includeCNAME[, options]]])¶ Changed in version 1.3.0:
options
optional parameter added.Changed in version 1.4.0:
ipEncryptKey
optional key added to the options table.Send the content of this response to a remote logger via Protocol Buffer.
alterFunction
is the same callback that receiving aDNSQuestion
and aDNSDistProtoBufMessage
, that can be used to modify the Protocol Buffer content, for example for anonymization purposes.includeCNAME
indicates whether CNAME records inside the response should be parsed and exported. The default is to only exports A and AAAA records. Subsequent rules are processed after this action.Parameters: - remoteLogger (string) – The
remoteLogger
object to write to - alterFunction (string) – Name of a function to modify the contents of the logs before sending
- includeCNAME (bool) – Whether or not to parse and export CNAMEs. Default false
- options (table) – A table with key: value pairs.
Options:
serverID=""
: str - Set the Server Identity field.ipEncryptKey=""
: str - A key, that can be generated via themakeIPCipherKey()
function, to encrypt the IP address of the requestor for anonymization purposes. The encryption is done using ipcrypt for IPv4 and a 128-bit AES ECB operation for IPv6.
- remoteLogger (string) – The
-
SetECSAction
(v4[, v6])¶ New in version 1.3.1.
Set the ECS prefix and prefix length sent to backends to an arbitrary value. If both IPv4 and IPv6 masks are supplied the IPv4 one will be used for IPv4 clients and the IPv6 one for IPv6 clients. Otherwise the first mask is used for both, and can actually be an IPv6 mask. Subsequent rules are processed after this action.
Parameters: - v4 (string) – The IPv4 netmask, for example “192.0.2.1/32”
- v6 (string) – The IPv6 netmask, if any
-
SkipCacheAction
()¶ Don’t lookup the cache for this query, don’t store the answer.
-
SNMPTrapAction
([message])¶ Send an SNMP trap, adding the optional
message
string as the query description. Subsequent rules are processed after this action.Parameters: message (string) – The message to include
-
SNMPTrapResponseAction
([message])¶ Send an SNMP trap, adding the optional
message
string as the query description. Subsequent rules are processed after this action.Parameters: message (string) – The message to include
-
SpoofAction
(ip[, ip[...]])¶ -
SpoofAction
(ips) Forge a response with the specified IPv4 (for an A query) or IPv6 (for an AAAA) addresses. If you specify multiple addresses, all that match the query type (A, AAAA or ANY) will get spoofed in.
Parameters: - ip (string) – An IPv4 and/or IPv6 address to spoof
- ips ({string}) – A table of IPv4 and/or IPv6 addresses to spoof
-
SpoofCNAMEAction
(cname)¶ Forge a response with the specified CNAME value.
Parameters: cname (string) – The name to respond with
-
TagAction
(name, value)¶ New in version 1.3.0.
Associate a tag named
name
with a value ofvalue
to this query, that will be passed on to the response. Subsequent rules are processed after this action.Parameters: - name (string) – The name of the tag to set
- value (string) – The value of the tag
-
TagResponseAction
(name, value)¶ New in version 1.3.0.
Associate a tag named
name
with a value ofvalue
to this response. Subsequent rules are processed after this action.Parameters: - name (string) – The name of the tag to set
- value (string) – The value of the tag
-
TCAction
()¶ Create answer to query with TC and RD bits set, to force the client to TCP.
-
TeeAction
(remote[, addECS])¶ Send copy of query to
remote
, keep stats on responses. IfaddECS
is set to true, EDNS Client Subnet information will be added to the query.Parameters: - remote (string) – An IP:PORT conbination to send the copied queries to
- addECS (bool) – Whether or not to add ECS information. Default false
-
TempFailureCacheTTLAction
(ttl)¶ Set the cache TTL to use for ServFail and Refused replies. TTL is not applied for successful replies.
Parameters: ttl (int) – Cache TTL for temporary failure replies