Rule 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

Selectors can be combined via AndRule(), OrRule() and NotRule().

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

Changed in version 1.9.0: The nmg parameter now accepts a string or a list of strings in addition to a class:NetmaskGroup object.

Matches traffic from/to the network range specified in the nmg, which can be a string, a list of strings, or a NetmaskGroup object created via newNMG().

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 netmasks to match, can be a string, a list of strings or a NetmaskGroup object.
  • 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
PayloadSizeRule(comparison, size)

New in version 1.9.0.

Matches queries or responses whose DNS payload size fits the given comparison.

Parameters:
  • comparison (str) – The comparison operator to use. Supported values are equal, greater, greaterOrEqual, smaller and smallerOrEqual.
  • size (int) – The size to compare to.
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 QNameSuffixRule().

param DNSNameSet set:
 Set with qnames of type class:DNSNameSet created with newDNSNameSet().
QNameSuffixRule(suffixes[, quiet])

New in version 1.9.0.

Matches based on a group of domain suffixes for rapid testing of membership. The first parameter, suffixes, can be a string, list of strings or a class:SuffixMatchNode object created with newSuffixMatchNode(). Pass true as second parameter to prevent listing of all domains matched.

To match domain names exactly, see QNameSetRule().

This rule existed before 1.9.0 but was called SuffixMatchNodeRule(), only accepting a SuffixMatchNode parameter.

Parameters:
  • suffixes – A string, list of strings, or a SuffixMatchNode to match on
  • quiet (bool) –

    Do not display the list of matched domains in Rules. Default is false.

    Matches queries with the specified qname exactly.

    param string qname:
     Qname to match
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, or nghttp2 is used for incoming DoH instead (1.9.0+).

Parameters:name (str) – The exact SNI name to match.
SuffixMatchNodeRule(smn[, quiet])

Changed in version 1.9.0: The smn parameter now accepts a string or a list of strings in addition to a class:SuffixMatchNode object.

Matches based on a group of domain suffixes for rapid testing of membership. The first parameter, smn, can be a string, list of strings or a class:SuffixMatchNode object created with newSuffixMatchNode(). Pass true as second parameter to prevent listing of all domains matched.

To match domain names exactly, see QNameSetRule().

Since 1.9.0, this rule can also be used via the alias QNameSuffixRule().

Parameters:
  • smn (SuffixMatchNode) – A string, list of strings, or a 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

Objects

class DNSDistRuleAction

New in version 1.9.0.

Represents a rule composed of a DNSRule selector, to select the queries this applies to, and a DNSAction action to apply when the selector matches.

:getAction()

Return the DNSAction action of this rule.

:getSelector()

Return the DNSRule selector of this rule.

class DNSDistResponseRuleAction

New in version 1.9.0.

Represents a rule composed of a DNSRule selector, to select the responses this applies to, and a DNSResponseAction action to apply when the selector matches.

:getAction()

Return the DNSResponseAction action of this rule.

:getSelector()

Return the DNSRule selector of this rule.

class DNSRule

New in version 1.9.0.

:getMatches() → int

Return the number of times this selector matched a query or a response. Note that if the same selector is reused for different DNSDistRuleAction objects, the counter will be common to all these objects.