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. All packets not handled by an explicit action are forwarded to a downstream server in the default pool.

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), SetNoRecurseAction())

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(AndRule{MaxQPSIPRule(5), TCPRule(false)}, 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.

In that last one, note the use of TCPRule(). Without it, clients would get TC=1 even if they correctly fell 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.

Note that to check if a name is in a list of domains, SuffixMatchNodeRule() is preferred over complex regular expressions or multiple instances of RegexRule(). The makeRule() convenience function can be used to create a SuffixMatchNodeRule().

Rule Generators

dnsdist contains several functions that make it easier to add actions and rules.

addLuaAction(DNSrule, function[, options])

Deprecated since version 1.4.0: Removed in 1.4.0, use LuaAction() with addAction() instead.

Invoke a Lua function that accepts a DNSQuestion. This function works similar to using LuaAction(). The function 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 luaaction(dq)
  if(dq.qtype==DNSQType.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(), luaaction)
addLuaResponseAction(DNSrule, function[, options])

Deprecated since version 1.4.0: Removed in 1.4.0, use LuaResponseAction() with addResponseAction() instead.

Invoke a Lua function that accepts a DNSResponse. This function works similar to using LuaResponseAction(). The function 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.

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.6.0: Added name to the options.

Add a Rule and Action to the existing rules.

Parameters:
  • rule (DNSrule) – A DNSRule, e.g. an AllRule() or a compounded bunch of rules using e.g. AndRule()
  • action – The action to take
  • 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.
  • name: string - Name to assign to the new 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 of to. 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
mvRuleToTop()

New in version 1.6.0.

This function moves the last rule to the first position. Before 1.6.0 this was handled by topRule().

newRuleAction(rule, action[, options])

Changed in version 1.6.0: Added name to the options.

Return a pair of DNS Rule and DNS Action, to be used with setRules().

Parameters:
  • rule (Rule) – A Rule (see Matching Packets (Selectors))
  • action (Action) – The Action (see Actions) to apply to the matched traffic
  • 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.
  • name: string - Name to assign to the new 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])

Show 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 to truncateRuleWidth size. Defaults to -1 to display the full rule.
topRule()

Changed in version 1.6.0: Replaced by mvRuleToTop()

Before 1.6.0 this function used to move the last rule to the first position, which is now handled by mvRuleToTop().

rmRule(id)

Changed in version 1.6.0: id can now be a string representing the name of the rule.

Remove rule id.

Parameters:id (int) – The position of the rule to remove if id is numerical, its UUID or name otherwise

For Rules related to responses:

addResponseAction(DNSRule, action[, options])

Changed in version 1.6.0: Added name to the options.

Add a Rule and Action for responses to the existing rules.

Parameters:
  • DNSRule – A DNSRule, e.g. an AllRule() or a compounded bunch of rules using e.g. AndRule()
  • action – The action to take
  • 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.
  • name: string - Name to assign to the new rule.
mvResponseRule(from, to)

Move response rule from to a position where it is in front of to. 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
mvResponseRuleToTop()

New in version 1.6.0.

This function moves the last response rule to the first position. Before 1.6.0 this was handled by topResponseRule().

rmResponseRule(id)

Changed in version 1.6.0: id can now be a string representing the name of the rule.

Remove response rule id.

Parameters:id (int) – The position of the rule to remove if id is numerical, its UUID or name otherwise
showResponseRules([options])

Show 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 to truncateRuleWidth size. Defaults to -1 to display the full rule.
topResponseRule()

Changed in version 1.6.0: Replaced by mvResponseRuleToTop()

Before 1.6.0 this function used to move the last response rule to the first position, which is now handled by mvResponseRuleToTop().

Functions for manipulating Cache Hit Response Rules:

addCacheHitResponseAction(DNSRule, action[, options])

Changed in version 1.6.0: Added name to the options.

Add a Rule and ResponseAction for Cache Hits to the existing rules.

Parameters:
  • DNSRule – A DNSRule, e.g. an AllRule() or a compounded bunch of rules using e.g. AndRule()
  • action – The action to take
  • 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.
  • name: string - Name to assign to the new rule.
mvCacheHitResponseRule(from, to)

Move cache hit response rule from to a position where it is in front of to. 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
mvCacheHitResponseRuleToTop()

New in version 1.6.0.

This function moves the last cache hit response rule to the first position. Before 1.6.0 this was handled by topCacheHitResponseRule().

rmCacheHitResponseRule(id)

Changed in version 1.6.0: id can now be a string representing the name of the rule.

Parameters:id (int) – The position of the rule to remove if id is numerical, its UUID or name otherwise
showCacheHitResponseRules([options])

Show 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 to truncateRuleWidth size. Defaults to -1 to display the full rule.
topCacheHitResponseRule()

Changed in version 1.6.0: Replaced by mvCacheHitResponseRuleToTop()

Before 1.6.0 this function used to move the last cache hit response rule to the first position, which is now handled by mvCacheHitResponseRuleToTop().

Functions for manipulating Cache Inserted Response Rules:

addCacheInsertedResponseAction(DNSRule, action[, options])

New in version 1.8.0.

Add a Rule and ResponseAction that is executed after a cache entry has been inserted to the existing rules.

Parameters:
  • DNSRule – A DNSRule, e.g. an AllRule() or a compounded bunch of rules using e.g. AndRule()
  • action – The action to take
  • 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.
  • name: string - Name to assign to the new rule.
mvCacheInsertedResponseRule(from, to)

New in version 1.8.0.

Move cache inserted response rule from to a position where it is in front of to. 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
mvCacheInsertedResponseRuleToTop()

New in version 1.8.0.

This function moves the last cache inserted response rule to the first position.

rmCacheInsertedResponseRule(id)

New in version 1.8.0.

Parameters:id (int) – The position of the rule to remove if id is numerical, its UUID or name otherwise
showCacheInsertedResponseRules([options])

New in version 1.8.0.

Show all defined cache inserted 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 to truncateRuleWidth size. Defaults to -1 to display the full rule.

Functions for manipulating Self-Answered Response Rules:

addSelfAnsweredResponseAction(DNSRule, action[, options])

Changed in version 1.6.0: Added name to the options.

Add a Rule and Action for Self-Answered queries to the existing rules.

Parameters:
  • DNSRule – A DNSRule, e.g. an AllRule() or a compounded bunch of rules using e.g. AndRule()
  • action – The action to take
  • 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.
  • name: string - Name to assign to the new rule.
mvSelfAnsweredResponseRule(from, to)

Move self answered response rule from to a position where it is in front of to. 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
mvSelfAnsweredResponseRuleToTop()

New in version 1.6.0.

This function moves the last self-answered response rule to the first position. Before 1.6.0 this was handled by topSelfAnsweredResponseRule().

rmSelfAnsweredResponseRule(id)

Changed in version 1.6.0: id can now be a string representing the name of the rule.

Remove self answered response rule id.

Parameters:id (int) – The position of the rule to remove if id is numerical, its UUID or name otherwise
showSelfAnsweredResponseRules([options])

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 to truncateRuleWidth size. Defaults to -1 to display the full rule.
topSelfAnsweredResponseRule()

Changed in version 1.6.0: Replaced by mvSelfAnsweredResponseRuleToTop()

Before 1.6.0 this function used to move the last cache hit response rule to the first position, which is now handled by mvSelfAnsweredResponseRuleToTop().

Move the last self answered response rule to the first position.

Matching Packets (Selectors)

Packets can be matched by selectors, called a DNSRule. These DNSRules be one of the following items:

  • A string that is either a domain name or netmask
  • A list of strings that are either domain names or netmasks
  • A DNSName
  • A list of DNSNames
  • A (compounded) Rule
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.

Changed in version 1.8.0: see keepIncomingHeaders on addDOHLocal()

Matches DNS over HTTPS queries with a HTTP header name whose content matches the regular expression regex. Since 1.8.0 it is necessary to set the keepIncomingHeaders option to true on addDOHLocal() to be able to use this rule.

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, see DOHFrontend: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, see DOHFrontend:setResponsesMap() instead.

Parameters:path (str) – The exact HTTP path to match on
KeyValueStoreLookupRule(kvs, lookupKey)

New in version 1.4.0.

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() and KeyValueLookupKeySuffix()), 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
KeyValueStoreRangeLookupRule(kvs, lookupKey)

New in version 1.7.0.

Does a range-based lookup into the key value store referenced by ‘kvs’ using the key returned by ‘lookupKey’ and returns true if there is a range covering that key.

This assumes that there is a key, in network byte order, for the last element of the range (for example 2001:0db8:ffff:ffff:ffff:ffff:ffff:ffff for 2001:db8::/32) which contains the first element of the range (2001:0db8:0000:0000:0000:0000:0000:0000) (optionally followed by any data) as value, still in network byte order, and that there is no overlapping ranges in the database. This requires that the underlying store supports ordered keys, which is true for LMDB but not for CDB.

Parameters:
  • kvs (KeyValueStore) – The key value store to query
  • lookupKey (KeyValueLookupKey) – The key to use for the lookup
LuaFFIPerThreadRule(function)

New in version 1.7.0.

Invoke a Lua FFI function that accepts a pointer to a dnsdist_ffi_dnsquestion_t object, whose bindings are defined in dnsdist-lua-ffi.hh.

The function should return true if the query matches, or false otherwise. If the Lua code fails, false is returned.

The function will be invoked in a per-thread Lua state, without access to the global Lua state. All constants (DNSQType, RCode, …) are available in that per-thread context, as well as all FFI functions. Objects and their bindings that are not usable in a FFI context (DNSQuestion, DNSDistProtoBufMessage, PacketCache, …) are not available.

Parameters:function (string) – a Lua string returning a Lua function
LuaFFIRule(function)

New in version 1.5.0.

Invoke a Lua FFI function that accepts a pointer to a dnsdist_ffi_dnsquestion_t object, whose bindings are defined in dnsdist-lua-ffi.hh.

The function should return true if the query matches, or false otherwise. If the Lua code fails, false is returned.

Parameters:function (string) – the name of a Lua function
LuaRule(function)

New in version 1.5.0.

Invoke a Lua function that accepts a DNSQuestion object.

The function should return true if the query matches, or false otherwise. If the Lua code fails, false is returned.

Parameters:function (string) – the name of a Lua function
MaxQPSIPRule(qps[, v4Mask[, v6Mask[, burst[, expiration[, cleanupDelay[, scanFraction[, shards]]]]]]])

Changed in version 1.8.0: shards parameter added

Matches traffic for a subnet specified by v4Mask or v6Mask exceeding qps queries per second up to burst allowed. This rule keeps track of QPS by netmask or source IP. This state is cleaned up regularly if cleanupDelay is greater than zero, removing existing netmasks or IP addresses that have not been seen in the last expiration 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%
  • shards (int) – How many shards to use, to decrease lock contention between threads. Default is 10 and is a safe default unless a very high number of threads are used to process incoming queries
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 added

Matches traffic from/to the network range specified in nmg.

Set the src parameter to false to match nmg against destination address instead of source address. This can be used to differentiate between clients

Parameters:
  • 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)

Matches queries with a given probability. 1.0 means “always”

Parameters:probability (double) – Probability of a match
ProxyProtocolValueRule(type[, value])

New in version 1.6.0.

Matches queries that have a proxy protocol TLV value of the specified type. If value is set, the content of the value should also match the content of value.

Parameters:
  • type (int) – The type of the value, ranging from 0 to 255 (both included)
  • value (str) – The optional binary-safe value to 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)

Matches queries with the specified qname exactly.

Parameters:qname (string) – 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 than max 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 than max 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 instance DNSQType.A, DNSQType.TXT and DNSQType.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()

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 most maxCount records in the section section. 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 most maxCount records of type type in the section section. 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 instance DNSQType.A or DNSQType.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:
  • smn (SuffixMatchNode) – The SuffixMatchNode to match on
  • quiet (bool) – Do not display the list of matched domains in Rules. Default is false.
TagRule(name[, value])

Matches question or answer with a tag named name set. If value is specified, the existing tag value should match too.

Parameters:
  • name (string) – The name of the tag that has to be set
  • value (string) – 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 if true, UDP traffic if false.
TrailingDataRule()

Matches if the query has trailing data.

PoolAvailableRule(poolname)

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
PoolOutstandingRule(poolname, limit)

New in version 1.7.0.

Check whether a pool has total outstanding queries above limit

--- Send queries to spill over pool if default pool is under pressure
addAction(PoolOutstandingRule("", 5000), PoolAction("spillover"))
Parameters:
  • poolname (string) – Pool to check
  • limit (int) – Total outstanding limit

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 selectors Rules does match.

Parameters:selector ({Rule}) – A table of Rules

Convenience Functions

makeRule(rule)

Make a NetmaskGroupRule() or a SuffixMatchNodeRule(), 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. Most of these start with ‘Set’ with a few exceptions, mostly for logging actions. These exceptions are:

The following actions exist.

AllowAction()

Let these packets go through.

AllowResponseAction()

Let these packets go through.

ClearRecordTypesResponseAction(types)

New in version 1.8.0.

Removes given type(s) records from the response. Beware you can accidentally turn the answer into a NODATA response without a SOA record in the additional section in which case you may want to use NegativeAndSOAAction() to generate an answer, see example bellow. Subsequent rules are processed after this action.

-- removes any HTTPS record in the response
addResponseAction(
        QNameRule('www.example.com.'),
        ClearRecordTypesResponseAction(DNSQType.HTTPS)
)
-- reply directly with NODATA and a SOA record as we know the answer will be empty
addAction(
        AndRule{QNameRule('www.example.com.'), QTypeRule(DNSQType.HTTPS)},
        NegativeAndSOAAction(false, 'example.com.', 3600, 'ns.example.com.', 'postmaster.example.com.', 1, 1800, 900, 604800, 86400)
)
Parameters:types (int) – a single type or a list of types to remove
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). Note that the sending of the query to the backend, if needed, is not delayed. Only the sending of the response to the client will be delayed. 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). The only difference between this action and DelayAction() is that they can only be applied on, respectively, responses and queries. Subsequent rules are processed after this action.

Parameters:milliseconds (int) – The amount of milliseconds to delay the response
DisableECSAction()

Deprecated since version 1.6.0.

This function has been deprecated in 1.6.0 and removed in 1.7.0, please use SetDisableECSAction() instead.

Disable the sending of ECS to the backend. Subsequent rules are processed after this action.

DisableValidationAction()

Deprecated since version 1.6.0.

This function has been deprecated in 1.6.0 and removed in 1.7.0, please use SetDisableValidationAction() instead.

Set the CD bit in the query and let it go through. Subsequent rules are processed after this action.

DnstapLogAction(identity, logger[, alterFunction])

Send the current query to a remote logger as a dnstap message. alterFunction is a callback, receiving a DNSQuestion and a DnstapMessage, 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 or RemoteLogger object to write to
  • alterFunction – A Lua function to alter the message before sending
DnstapLogResponseAction(identity, logger[, alterFunction])

Send the current response to a remote logger as a dnstap message. alterFunction is a callback, receiving a DNSQuestion and a DnstapMessage, 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 or RemoteLogger object to write to
  • alterFunction – A Lua function to alter the message before sending
DropAction()

Drop the packet.

DropResponseAction()

Drop the packet.

ECSOverrideAction(override)

Deprecated since version 1.6.0.

This function has been deprecated in 1.6.0 and removed in 1.7.0, please use SetECSOverrideAction() instead.

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)

Deprecated since version 1.6.0.

This function has been deprecated in 1.6.0 and removed in 1.7.0, please use SetECSPrefixLengthAction() instead.

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[, options])

New in version 1.4.0.

Changed in version 1.5.0: Added the optional parameter options.

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.
  • options (table) – A table with key: value pairs with options.

Options:

  • aa: bool - Set the AA bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ad: bool - Set the AD bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ra: bool - Set the RA bit to this value (true means the bit is set, false means it’s cleared). Default is to copy the value of the RD bit from the incoming query.
HTTPStatusAction(status, body, contentType=""[, options])

New in version 1.4.0.

Changed in version 1.5.0: Added the optional parameter options.

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’’.
  • options (table) – A table with key: value pairs with options.

Options:

  • aa: bool - Set the AA bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ad: bool - Set the AD bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ra: bool - Set the RA bit to this value (true means the bit is set, false means it’s cleared). Default is to copy the value of the RD bit from the incoming query.
KeyValueStoreLookupAction(kvs, lookupKey, destinationTag)

New in version 1.4.0.

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() and KeyValueLookupKeySuffix()), source IP (KeyValueLookupKeySourceIP()) or the value of an existing tag (KeyValueLookupKeyTag()). Subsequent rules are processed after this action. Note that the tag is always created, even if there was no match, but in that case the content is empty.

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
KeyValueStoreRangeLookupAction(kvs, lookupKey, destinationTag)

New in version 1.7.0.

Does a range-based 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’. This assumes that there is a key in network byte order for the last element of the range (for example 2001:0db8:ffff:ffff:ffff:ffff:ffff:ffff for 2001:db8::/32) which contains the first element of the range (2001:0db8:0000:0000:0000:0000:0000:0000) (optionally followed by any data) as value, also in network byte order, and that there is no overlapping ranges in the database. This requires that the underlying store supports ordered keys, which is true for LMDB but not for CDB.

Subsequent rules are processed after this action.

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
LimitTTLResponseAction(min[, max[, types]])

New in version 1.8.0.

Cap the TTLs of the response to the given boundaries.

Parameters:
  • min (int) – The minimum allowed value
  • max (int) – The maximum allowed value
  • of int (list) – The record types to cap the TTL for. Default is empty which means all records will be capped.
LogAction([filename[, binary[, append[, buffered[, verboseOnly[, includeTimestamp]]]]]])

Changed in version 1.4.0: Added the optional parameters verboseOnly and includeTimestamp, made filename optional.

Changed in version 1.7.0: Added the reload method.

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 false.

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). The buffered optional parameter specifies whether writes to the file are buffered (default) or not.

Since 1.7.0 calling the reload() method on the object will cause it to close and re-open the log file, for rotation purposes.

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
LogResponseAction([filename[, append[, buffered[, verboseOnly[, includeTimestamp]]]]]])

New in version 1.5.0.

Changed in version 1.7.0: Added the reload method.

Log a line for each response, 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 false.

The append optional parameter specifies whether we open the file for appending or truncate each time (default). The buffered optional parameter specifies whether writes to the file are buffered (default) or not.

Since 1.7.0 calling the reload() method on the object will cause it to close and re-open the log file, for rotation purposes.

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.
  • 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
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
LuaFFIAction(function)

New in version 1.5.0.

Invoke a Lua FFI function that accepts a pointer to a dnsdist_ffi_dnsquestion_t object, whose bindings are defined in dnsdist-lua-ffi.hh.

The function should return a DNSAction. If the Lua code fails, ServFail is returned.

Parameters:function (string) – the name of a Lua function
LuaFFIPerThreadAction(function)

New in version 1.7.0.

Invoke a Lua FFI function that accepts a pointer to a dnsdist_ffi_dnsquestion_t object, whose bindings are defined in dnsdist-lua-ffi.hh.

The function should return a DNSAction. If the Lua code fails, ServFail is returned.

The function will be invoked in a per-thread Lua state, without access to the global Lua state. All constants (DNSQType, RCode, …) are available in that per-thread context, as well as all FFI functions. Objects and their bindings that are not usable in a FFI context (DNSQuestion, DNSDistProtoBufMessage, PacketCache, …) are not available.

Parameters:function (string) – a Lua string returning a Lua function
LuaFFIPerThreadResponseAction(function)

New in version 1.7.0.

Invoke a Lua FFI function that accepts a pointer to a dnsdist_ffi_dnsquestion_t object, whose bindings are defined in dnsdist-lua-ffi.hh.

The function should return a DNSResponseAction. If the Lua code fails, ServFail is returned.

The function will be invoked in a per-thread Lua state, without access to the global Lua state. All constants (DNSQType, RCode, …) are available in that per-thread context, as well as all FFI functions. Objects and their bindings that are not usable in a FFI context (DNSQuestion, DNSDistProtoBufMessage, PacketCache, …) are not available.

Parameters:function (string) – a Lua string returning a Lua function
LuaFFIResponseAction(function)

New in version 1.5.0.

Invoke a Lua FFI function that accepts a pointer to a dnsdist_ffi_dnsquestion_t object, whose bindings are defined in dnsdist-lua-ffi.hh.

The function should return a DNSResponseAction. 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)

Deprecated since version 1.6.0.

This function has been deprecated in 1.6.0 and removed in 1.7.0, please use SetMacAddrAction() instead.

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
NegativeAndSOAAction(nxd, zone, ttl, mname, rname, serial, refresh, retry, expire, minimum[, options])

New in version 1.6.0.

Changed in version 1.8.0: Added the soaInAuthoritySection option.

Turn a question into a response, either a NXDOMAIN or a NODATA one based on ‘’nxd’’, setting the QR bit to 1 and adding a SOA record in the additional section. Note that this function was called SetNegativeAndSOAAction() before 1.6.0.

Parameters:
  • nxd (bool) – Whether the answer is a NXDOMAIN (true) or a NODATA (false)
  • zone (string) – The owner name for the SOA record
  • ttl (int) – The TTL of the SOA record
  • mname (string) – The mname of the SOA record
  • rname (string) – The rname of the SOA record
  • serial (int) – The value of the serial field in the SOA record
  • refresh (int) – The value of the refresh field in the SOA record
  • retry (int) – The value of the retry field in the SOA record
  • expire (int) – The value of the expire field in the SOA record
  • minimum (int) – The value of the minimum field in the SOA record
  • options (table) – A table with key: value pairs with options

Options:

  • aa: bool - Set the AA bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ad: bool - Set the AD bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ra: bool - Set the RA bit to this value (true means the bit is set, false means it’s cleared). Default is to copy the value of the RD bit from the incoming query.
  • soaInAuthoritySection: bool - Place the SOA record in the authority section for a complete NXDOMAIN/NODATA response that works as a cacheable negative response, rather than the RPZ-style response with a purely informational SOA in the additional section. Default is false (SOA in additional section).
NoneAction()

Does nothing. Subsequent rules are processed after this action.

NoRecurseAction()

Deprecated since version 1.6.0.

This function has been deprecated in 1.6.0 and removed in 1.7.0, please use SetNoRecurseAction() instead.

Strip RD bit from the question, let it go through. Subsequent rules are processed after this action.

PoolAction(poolname[, stop])

Changed in version 1.8.0: Added the stop optional parameter.

Send the packet into the specified pool. If stop is set to false, subsequent rules will be processed after this action.

Parameters:
  • poolname (string) – The name of the pool
  • stop (bool) – Whether to stop processing rules after this action. Default is true, meaning the remaining rules will not be processed.
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)

Changed in version 1.8.0: Added the stop optional parameter.

Send the packet into the specified pool only if it does not exceed the maxqps queries per second limits. If stop is set to false, subsequent rules will be processed after this action. Letting the subsequent rules apply otherwise.

Parameters:
  • maxqps (int) – The QPS limit for that pool
  • poolname (string) – The name of the pool
  • stop (bool) – Whether to stop processing rules after this action. Default is true, meaning the remaining rules will not be processed.
RCodeAction(rcode[, options])

Changed in version 1.5.0: Added the optional parameter options.

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.
  • options (table) – A table with key: value pairs with options.

Options:

  • aa: bool - Set the AA bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ad: bool - Set the AD bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ra: bool - Set the RA bit to this value (true means the bit is set, false means it’s cleared). Default is to copy the value of the RD bit from the incoming query.
RemoteLogAction(remoteLogger[, alterFunction[, options[, metas]]])

Changed in version 1.4.0: ipEncryptKey optional key added to the options table.

Changed in version 1.8.0: metas optional parameter added. exportTags 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 a DNSQuestion and a DNSDistProtoBufMessage, that can be used to modify the Protocol Buffer content, for example for anonymization purposes. Since 1.8.0 it is possible to add configurable meta-data fields to the Protocol Buffer message via the metas parameter, which takes a list of name``=``key pairs. For each entry in the list, a new value named name will be added to the message with the value corresponding to the key. Available keys are:

  • doh-header:<HEADER>: the content of the corresponding <HEADER> HTTP header for DoH queries, empty otherwise
  • doh-host: the Host header for DoH queries, empty otherwise
  • doh-path: the HTTP path for DoH queries, empty otherwise
  • doh-query-string: the HTTP query string for DoH queries, empty otherwise
  • doh-scheme: the HTTP scheme for DoH queries, empty otherwise
  • pool: the currently selected pool of servers
  • proxy-protocol-value:<TYPE>: the content of the proxy protocol value of type <TYPE>, if any
  • proxy-protocol-values: the content of all proxy protocol values as a “<type1>:<value1>”, …, “<typeN>:<valueN>” strings
  • b64-content: the base64-encoded DNS payload of the current query
  • sni: the Server Name Indication value for queries received over DoT or DoH. Empty otherwise.
  • tag:<TAG>: the content of the corresponding <TAG> if any
  • tags: the list of all tags, and their values, as a “<key1>:<value1>”, …, “<keyN>:<valueN>” strings. Note that a tag with an empty value will be exported as “<key>”, not “<key>:”.

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.
  • metas (table) – A list of name``=``key pairs, for meta-data to be added to Protocol Buffer message.

Options:

  • serverID="": str - Set the Server Identity field.
  • ipEncryptKey="": str - A key, that can be generated via the makeIPCipherKey() 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.
  • exportTags="": str - The comma-separated list of keys of internal tags to export into the tags Protocol Buffer field, as “key:value” strings. Note that a tag with an empty value will be exported as “<key>”, not “<key>:”. An empty string means that no internal tag will be exported. The special value * means that all tags will be exported.
RemoteLogResponseAction(remoteLogger[, alterFunction[, includeCNAME[, options[, metas]]]])

Changed in version 1.4.0: ipEncryptKey optional key added to the options table.

Changed in version 1.8.0: metas optional parameter added. exportTags 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 a DNSQuestion and a DNSDistProtoBufMessage, 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. Since 1.8.0 it is possible to add configurable meta-data fields to the Protocol Buffer message via the metas parameter, which takes a list of name``=``key pairs. See RemoteLogAction() for the list of available keys. 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.
  • metas (table) – A list of name``=``key pairs, for meta-data to be added to Protocol Buffer message.

Options:

  • serverID="": str - Set the Server Identity field.
  • ipEncryptKey="": str - A key, that can be generated via the makeIPCipherKey() 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.
  • exportTags="": str - The comma-separated list of keys of internal tags to export into the tags Protocol Buffer field, as “key:value” strings. Note that a tag with an empty value will be exported as “<key>”, not “<key>:”. An empty string means that no internal tag will be exported. The special value * means that all tags will be exported.
SetAdditionalProxyProtocolValueAction(type, value)

New in version 1.6.0.

Add a Proxy-Protocol Type-Length value to be sent to the server along with this query. It does not replace any existing value with the same type but adds a new value. Be careful that Proxy Protocol values are sent once at the beginning of the TCP connection for TCP and DoT queries. That means that values received on an incoming TCP connection will be inherited by subsequent queries received over the same incoming TCP connection, if any, but values set to a query will not be inherited by subsequent queries. Subsequent rules are processed after this action.

Parameters:
  • type (int) – The type of the value to send, ranging from 0 to 255 (both included)
  • value (str) – The binary-safe value
SetDisableECSAction()

New in version 1.6.0.

Disable the sending of ECS to the backend. Subsequent rules are processed after this action. Note that this function was called DisableECSAction() before 1.6.0.

SetDisableValidationAction()

New in version 1.6.0.

Set the CD bit in the query and let it go through. Subsequent rules are processed after this action. Note that this function was called DisableValidationAction() before 1.6.0.

SetECSAction(v4[, v6])

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
SetECSOverrideAction(override)

New in version 1.6.0.

Whether an existing EDNS Client Subnet value should be overridden (true) or not (false). Subsequent rules are processed after this action. Note that this function was called ECSOverrideAction() before 1.6.0.

Parameters:override (bool) – Whether or not to override ECS value
SetECSPrefixLengthAction(v4, v6)

New in version 1.6.0.

Set the ECS prefix length. Subsequent rules are processed after this action. Note that this function was called ECSPrefixLengthAction() before 1.6.0.

Parameters:
  • v4 (int) – The IPv4 netmask length
  • v6 (int) – The IPv6 netmask length
SetEDNSOptionAction(option)

New in version 1.7.0.

Add arbitrary EDNS option and data to the query. Any existing EDNS content with the same option code will be overwritten. Subsequent rules are processed after this action.

Parameters:
  • option (int) – The EDNS option number
  • data (string) – The EDNS0 option raw content
SetMacAddrAction(option)

New in version 1.6.0.

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. Note that this function was called MacAddrAction() before 1.6.0.

Parameters:option (int) – The EDNS0 option number
SetMaxReturnedTTLAction(max)

New in version 1.8.0.

Cap the TTLs of the response to the given maximum, but only after inserting the response into the packet cache with the initial TTL values.

Parameters:max (int) – The maximum allowed value
SetMaxReturnedTTLResponseAction(max)

New in version 1.8.0.

Cap the TTLs of the response to the given maximum, but only after inserting the response into the packet cache with the initial TTL values.

Parameters:max (int) – The maximum allowed value
SetMaxTTLResponseAction(max)

New in version 1.8.0.

Cap the TTLs of the response to the given maximum.

Parameters:max (int) – The maximum allowed value
SetMinTTLResponseAction(min)

New in version 1.8.0.

Cap the TTLs of the response to the given minimum.

Parameters:min (int) – The minimum allowed value
SetNoRecurseAction()

New in version 1.6.0.

Strip RD bit from the question, let it go through. Subsequent rules are processed after this action. Note that this function was called NoRecurseAction() before 1.6.0.

SetNegativeAndSOAAction(nxd, zone, ttl, mname, rname, serial, refresh, retry, expire, minimum[, options])

New in version 1.5.0.

Deprecated since version 1.6.0.

This function has been deprecated in 1.6.0 and removed in 1.7.0, please use NegativeAndSOAAction() instead.

Turn a question into a response, either a NXDOMAIN or a NODATA one based on ‘’nxd’’, setting the QR bit to 1 and adding a SOA record in the additional section.

Parameters:
  • nxd (bool) – Whether the answer is a NXDOMAIN (true) or a NODATA (false)
  • zone (string) – The owner name for the SOA record
  • ttl (int) – The TTL of the SOA record
  • mname (string) – The mname of the SOA record
  • rname (string) – The rname of the SOA record
  • serial (int) – The value of the serial field in the SOA record
  • refresh (int) – The value of the refresh field in the SOA record
  • retry (int) – The value of the retry field in the SOA record
  • expire (int) – The value of the expire field in the SOA record
  • minimum (int) – The value of the minimum field in the SOA record
  • options (table) – A table with key: value pairs with options

Options:

  • aa: bool - Set the AA bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ad: bool - Set the AD bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ra: bool - Set the RA bit to this value (true means the bit is set, false means it’s cleared). Default is to copy the value of the RD bit from the incoming query.
SetProxyProtocolValuesAction(values)

New in version 1.5.0.

Set the Proxy-Protocol Type-Length values to be sent to the server along with this query to values. Subsequent rules are processed after this action.

Parameters:values (table) – A table of types and values to send, for example: { [0] = foo", [42] = "bar" }
SetReducedTTLResponseAction(percentage)

New in version 1.8.0.

Reduce the TTL of records in a response to a percentage of the original TTL. For example, passing 50 means that the original TTL will be cut in half. Subsequent rules are processed after this action.

Parameters:percentage (int) – The percentage to use
SetSkipCacheAction()

New in version 1.6.0.

Don’t lookup the cache for this query, don’t store the answer. Subsequent rules are processed after this action. Note that this function was called SkipCacheAction() before 1.6.0.

SetSkipCacheResponseAction()

New in version 1.6.0.

Don’t store this answer into the cache. Subsequent rules are processed after this action.

SetTagAction(name, value)

New in version 1.6.0.

Changed in version 1.7.0: Prior to 1.7.0 SetTagAction() would not overwrite an existing tag value if already set.

Associate a tag named name with a value of value to this query, that will be passed on to the response. This function will overwrite any existing tag value. Subsequent rules are processed after this action. Note that this function was called TagAction() before 1.6.0.

Parameters:
  • name (string) – The name of the tag to set
  • value (string) – The value of the tag
SetTagResponseAction(name, value)

New in version 1.6.0.

Changed in version 1.7.0: Prior to 1.7.0 SetTagResponseAction() would not overwrite an existing tag value if already set.

Associate a tag named name with a value of value to this response. This function will overwrite any existing tag value. Subsequent rules are processed after this action. Note that this function was called TagResponseAction() before 1.6.0.

Parameters:
  • name (string) – The name of the tag to set
  • value (string) – The value of the tag
SetTempFailureCacheTTLAction(ttl)

New in version 1.6.0.

Set the cache TTL to use for ServFail and Refused replies. TTL is not applied for successful replies. Subsequent rules are processed after this action. Note that this function was called TempFailureCacheTTLAction() before 1.6.0.

Parameters:ttl (int) – Cache TTL for temporary failure replies
SkipCacheAction()

Deprecated since version 1.6.0.

This function has been deprecated in 1.6.0 and removed in 1.7.0, please use SetSkipAction() instead.

Don’t lookup the cache for this query, don’t store the answer. Subsequent rules are processed after this action.

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[, options])
SpoofAction(ips[, options])

Changed in version 1.5.0: Added the optional parameter options.

Changed in version 1.6.0: Up to 1.6.0, the syntax for this function was SpoofAction(ips[, ip[, options]]).

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
  • options (table) – A table with key: value pairs with options.

Options:

  • aa: bool - Set the AA bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ad: bool - Set the AD bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ra: bool - Set the RA bit to this value (true means the bit is set, false means it’s cleared). Default is to copy the value of the RD bit from the incoming query.
  • ttl: int - The TTL of the record.
SpoofCNAMEAction(cname[, options])

Changed in version 1.5.0: Added the optional parameter options.

Forge a response with the specified CNAME value.

Parameters:
  • cname (string) – The name to respond with
  • options (table) – A table with key: value pairs with options.

Options:

  • aa: bool - Set the AA bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ad: bool - Set the AD bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ra: bool - Set the RA bit to this value (true means the bit is set, false means it’s cleared). Default is to copy the value of the RD bit from the incoming query.
  • ttl: int - The TTL of the record.
SpoofRawAction(rawAnswer[, options])
SpoofRawAction(rawAnswers[, options])

New in version 1.5.0.

Changed in version 1.6.0: Up to 1.6.0, it was only possible to spoof one answer.

Forge a response with the specified raw bytes as record data.

-- select queries for the 'raw.powerdns.com.' name and TXT type, and answer with both a "aaa" "bbbb" and "ccc" TXT record:
addAction(AndRule({QNameRule('raw.powerdns.com.'), QTypeRule(DNSQType.TXT)}), SpoofRawAction({"\003aaa\004bbbb", "\003ccc"}))
-- select queries for the 'raw-srv.powerdns.com.' name and SRV type, and answer with a '0 0 65535 srv.powerdns.com.' SRV record, setting the AA bit to 1 and the TTL to 3600s
addAction(AndRule({QNameRule('raw-srv.powerdns.com.'), QTypeRule(DNSQType.SRV)}), SpoofRawAction("\000\000\000\000\255\255\003srv\008powerdns\003com\000", { aa=true, ttl=3600 }))
-- select reverse queries for '127.0.0.1' and answer with 'localhost'
addAction(AndRule({QNameRule('1.0.0.127.in-addr.arpa.'), QTypeRule(DNSQType.PTR)}), SpoofRawAction("\009localhost\000"))

DNSName:toDNSString() is convenient for converting names to wire format for passing to SpoofRawAction.

sdig dumpluaraw and pdnsutil raw-lua-from-content from PowerDNS can generate raw answers for you:

$ pdnsutil raw-lua-from-content SRV '0 0 65535 srv.powerdns.com.'
"\000\000\000\000\255\255\003srv\008powerdns\003com\000"
$ sdig 127.0.0.1 53 open-xchange.com MX recurse dumpluaraw
Reply to question for qname='open-xchange.com.', qtype=MX
Rcode: 0 (No Error), RD: 1, QR: 1, TC: 0, AA: 0, opcode: 0
0 open-xchange.com. IN  MX  "\000c\004mx\049\049\012open\045xchange\003com\000"
0 open-xchange.com. IN  MX  "\000\010\003mx\049\012open\045xchange\003com\000"
0 open-xchange.com. IN  MX  "\000\020\003mx\050\012open\045xchange\003com\000"
Parameters:
  • rawAnswer (string) – The raw record data
  • rawAnswers ({string}) – A table of raw record data to spoof
  • options (table) – A table with key: value pairs with options.

Options:

  • aa: bool - Set the AA bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ad: bool - Set the AD bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ra: bool - Set the RA bit to this value (true means the bit is set, false means it’s cleared). Default is to copy the value of the RD bit from the incoming query.
  • ttl: int - The TTL of the record.
SpoofSVCAction(svcParams[, options])

New in version 1.7.0.

Forge a response with the specified SVC record data. If the list contains more than one class:SVCRecordParameters (generated via newSVCRecordParameters()) object, they are all returned, and should have different priorities. The hints provided in the SVC parameters, if any, will also be added as A/AAAA records in the additional section, using the target name present in the parameters as owner name if it’s not empty (root) and the qname instead.

:param list of class:SVCRecordParameters svcParams: The record data to return :param table options: A table with key: value pairs with options.

Options:

  • aa: bool - Set the AA bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ad: bool - Set the AD bit to this value (true means the bit is set, false means it’s cleared). Default is to clear it.
  • ra: bool - Set the RA bit to this value (true means the bit is set, false means it’s cleared). Default is to copy the value of the RD bit from the incoming query.
  • ttl: int - The TTL of the record.
SpoofPacketAction(rawPacket, len)

New in version 1.8.0.

Spoof a raw self-generated answer

Parameters:
  • rawPacket (string) – The raw wire-ready DNS answer
  • len (int) – The length of the packet
TagAction(name, value)

Deprecated since version 1.6.0: This function has been deprecated in 1.6.0 and removed in 1.7.0, please use SetTagAction() instead.

Associate a tag named name with a value of value 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)

Deprecated since version 1.6.0: This function has been deprecated in 1.6.0 and removed in 1.7.0, please use SetTagResponseAction() instead.

Associate a tag named name with a value of value 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()

Changed in version 1.7.0: This action is now only performed over UDP transports.

Create answer to query with the TC bit set, and the RA bit set to the value of RD in the query, to force the client to TCP. Before 1.7.0 this action was performed even when the query had been received over TCP, which required the use of TCPRule() to prevent the TC bit from being set over TCP transports.

TeeAction(remote[, addECS[, local]])

Changed in version 1.8.0: Added the optional parameter local.

Send copy of query to remote, keep stats on responses. If addECS is set to true, EDNS Client Subnet information will be added to the query. If local has provided a value like “192.0.2.53”, dnsdist will try binding that address as local address when sending the queries. Subsequent rules are processed after this action.

Parameters:
  • remote (string) – An IP:PORT combination to send the copied queries to
  • addECS (bool) – Whether or not to add ECS information. Default false
TempFailureCacheTTLAction(ttl)

Deprecated since version 1.6.0.

This function has been deprecated in 1.6.0 and removed in 1.7.0, please use SetTempFailureCacheTTLAction() instead.

Set the cache TTL to use for ServFail and Refused replies. TTL is not applied for successful replies. Subsequent rules are processed after this action.

Parameters:ttl (int) – Cache TTL for temporary failure replies