3 Configuration Reference
4 =======================
6 This page lists all configuration options for dnsdist.
10 When an IPv6 IP:PORT combination is needed, the bracketed syntax from :rfc:`RFC 3986 <3986#section-3.2.2>` should be used.
11 e.g. "[2001:DB8:14::C0FF:FEE]:5300".
16 Within dnsdist several core object types exist:
18 * :class:`Server`: generated with :func:`newServer`, represents a downstream server
19 * :class:`ComboAddress`: represents an IP address and port
20 * :class:`DNSName`: represents a domain name
21 * :class:`NetmaskGroup`: represents a group of netmasks
22 * :class:`QPSLimiter`: implements a QPS-based filter
23 * :class:`SuffixMatchNode`: represents a group of domain suffixes for rapid testing of membership
24 * :class:`DNSHeader`: represents the header of a DNS packet, see :ref:`DNSHeader`
25 * :class:`ClientState`: sometimes also called Bind or Frontend, represents the addresses and ports dnsdist is listening on
27 The existence of most of these objects can mostly be ignored, unless you plan to write your own hooks and policies, but it helps to understand an expressions like:
31 getServer(0).order=12 -- set order of server 0 to 12
32 getServer(0):addPool("abuse") -- add this server to the abuse pool
34 The ``.`` means ``order`` is a data member, while the ``:`` means ``addPool`` is a member function.
39 .. function:: includeDirectory(path)
41 Include configuration files from ``path``.
43 :param str path: The directory to load configuration files from. Each file must end in ``.conf``.
45 .. function:: reloadAllCertificates()
47 .. versionadded:: 1.4.0
49 Reload all DNSCrypt and TLS certificates, along with their associated keys.
51 .. function:: setSyslogFacility(facility)
53 .. versionadded:: 1.4.0
55 Set the syslog logging facility to ``facility``.
57 :param int facility: The new facility as a numeric value. Defaults to LOG_DAEMON.
62 .. function:: addLocal(address[, options])
64 .. versionadded:: 1.2.0
66 .. versionchanged:: 1.3.0
67 Added ``cpus`` to the options.
69 .. versionchanged:: 1.4.0
70 Removed ``doTCP`` from the options. A listen socket on TCP is always created.
72 Add to the list of listen addresses.
74 :param str address: The IP Address with an optional port to listen on.
75 The default port is 53.
76 :param table options: A table with key: value pairs with listen options.
80 * ``doTCP=true``: bool - Also bind on TCP on ``address``. Removed in 1.4.0.
81 * ``reusePort=false``: bool - Set the ``SO_REUSEPORT`` socket option.
82 * ``tcpFastOpenQueueSize=0``: int - Set the TCP Fast Open queue size, enabling TCP Fast Open when available and the value is larger than 0.
83 * ``interface=""``: str - Set the network interface to use.
84 * ``cpus={}``: table - Set the CPU affinity for this listener thread, asking the scheduler to run it on a single CPU id, or a set of CPU ids. This parameter is only available if the OS provides the pthread_setaffinity_np() function.
88 addLocal('0.0.0.0:5300', { reusePort=true })
90 This will bind to both UDP and TCP on port 5300 with SO_REUSEPORT enabled.
92 .. function:: addLocal(address[[[,do_tcp], so_reuseport], tcp_fast_open_qsize])
96 Add to the list of addresses listened on.
98 :param str address: The IP Address with an optional port to listen on.
99 The default port is 53.
100 :param bool do_tcp: Also bind a TCP port on ``address``, defaults to true.
101 :param bool so_reuseport: Use ``SO_REUSEPORT`` if it is available, defaults to false
102 :param int tcp_fast_open_qsize: The size of the TCP Fast Open queue. Set to a number
103 higher than 0 to enable TCP Fast Open when available.
106 .. function:: addDOHLocal(address, certFile(s), keyFile(s) [, urls [, options]])
108 .. versionadded:: 1.4.0
110 Listen on the specified address and TCP port for incoming DNS over HTTPS connections, presenting the specified X.509 certificate.
112 :param str address: The IP Address with an optional port to listen on.
113 The default port is 443.
114 :param str certFile(s): The path to a X.509 certificate file in PEM format, or a list of paths to such files.
115 :param str keyFile(s): The path to the private key file corresponding to the certificate, or a list of paths to such files, whose order should match the certFile(s) ones.
116 :param str-or-list urls: A base URL, or a list of base URLs, to accept queries on. Any query with a path under one of these will be treated as a DoH query. The default is /.
117 :param table options: A table with key: value pairs with listen options.
121 * ``reusePort=false``: bool - Set the ``SO_REUSEPORT`` socket option.
122 * ``tcpFastOpenQueueSize=0``: int - Set the TCP Fast Open queue size, enabling TCP Fast Open when available and the value is larger than 0.
123 * ``interface=""``: str - Set the network interface to use.
124 * ``cpus={}``: table - Set the CPU affinity for this listener thread, asking the scheduler to run it on a single CPU id, or a set of CPU ids. This parameter is only available if the OS provides the pthread_setaffinity_np() function.
125 * ``idleTimeout=30``: int - Set the idle timeout, in seconds.
126 * ``ciphers``: str - The TLS ciphers to use, in OpenSSL format. Ciphers for TLS 1.3 must be specified via ``ciphersTLS13``.
127 * ``ciphersTLS13``: str - The TLS ciphers to use for TLS 1.3, in OpenSSL format.
128 * ``serverTokens``: str - The content of the Server: HTTP header returned by dnsdist. The default is "h2o/dnsdist".
129 * ``customResponseHeaders={}``: table - Set custom HTTP header(s) returned by dnsdist.
131 .. function:: addTLSLocal(address, certFile(s), keyFile(s) [, options])
133 .. versionadded:: 1.3.0
134 .. versionchanged:: 1.3.1
135 ``certFile(s)`` and ``keyFile(s)`` parameters accept a list of files.
136 ``sessionTickets`` option added.
137 .. versionchanged:: 1.3.3
138 ``numberOfStoredSessions`` option added.
139 .. versionchanged:: 1.4.0
140 ``ciphersTLS13`` option added.
142 Listen on the specified address and TCP port for incoming DNS over TLS connections, presenting the specified X.509 certificate.
144 :param str address: The IP Address with an optional port to listen on.
145 The default port is 853.
146 :param str certFile(s): The path to a X.509 certificate file in PEM format, or a list of paths to such files.
147 :param str keyFile(s): The path to the private key file corresponding to the certificate, or a list of paths to such files, whose order should match the certFile(s) ones.
148 :param table options: A table with key: value pairs with listen options.
152 * ``reusePort=false``: bool - Set the ``SO_REUSEPORT`` socket option.
153 * ``tcpFastOpenQueueSize=0``: int - Set the TCP Fast Open queue size, enabling TCP Fast Open when available and the value is larger than 0.
154 * ``interface=""``: str - Set the network interface to use.
155 * ``cpus={}``: table - Set the CPU affinity for this listener thread, asking the scheduler to run it on a single CPU id, or a set of CPU ids. This parameter is only available if the OS provides the pthread_setaffinity_np() function.
156 * ``provider``: str - The TLS library to use between GnuTLS and OpenSSL, if they were available and enabled at compilation time.
157 * ``ciphers``: str - The TLS ciphers to use. The exact format depends on the provider used. When the OpenSSL provder is used, ciphers for TLS 1.3 must be specified via ``ciphersTLS13``.
158 * ``ciphersTLS13``: str - The ciphers to use for TLS 1.3, when the OpenSSL provider is used. When the GnuTLS provider is used, ``ciphers`` applies regardless of the TLS protocol and this setting is not used.
159 * ``numberOfTicketsKeys``: int - The maximum number of tickets keys to keep in memory at the same time, if the provider supports it (GnuTLS doesn't, OpenSSL does). Only one key is marked as active and used to encrypt new tickets while the remaining ones can still be used to decrypt existing tickets after a rotation. Default to 5.
160 * ``ticketKeyFile``: str - The path to a file from where TLS tickets keys should be loaded, to support RFC 5077. These keys should be rotated often and never written to persistent storage to preserve forward secrecy. The default is to generate a random key. The OpenSSL provider supports several tickets keys to be able to decrypt existing sessions after the rotation, while the GnuTLS provider only supports one key.
161 * ``ticketsKeysRotationDelay``: int - Set the delay before the TLS tickets key is rotated, in seconds. Default is 43200 (12h).
162 * ``sessionTickets``: bool - Whether session resumption via session tickets is enabled. Default is true, meaning tickets are enabled.
163 * ``numberOfStoredSessions``: int - The maximum number of sessions kept in memory at the same time. At this time this is only supported by the OpenSSL provider, as stored sessions are not supported with the GnuTLS one. Default is 20480. Setting this value to 0 disables stored session entirely.
165 .. function:: setLocal(address[, options])
167 .. versionadded:: 1.2.0
169 Remove the list of listen addresses and add a new one.
171 :param str address: The IP Address with an optional port to listen on.
172 The default port is 53.
173 :param table options: A table with key: value pairs with listen options.
175 The options that can be set are the same as :func:`addLocal`.
177 .. function:: setLocal(address[[[,do_tcp], so_reuseport], tcp_fast_open_qsize])
179 .. deprecated:: 1.2.0
181 Remove the list of listen addresses and add a new one.
183 :param str address: The IP Address with an optional port to listen on.
184 The default port is 53.
185 :param bool do_tcp: Also bind a TCP port on ``address``, defaults to true.
186 :param bool so_reuseport: Use ``SO_REUSEPORT`` if it is available, defaults to false
187 :param int tcp_fast_open_qsize: The size of the TCP Fast Open queue. Set to a number
188 higher than 0 to enable TCP Fast Open when available.
191 Control Socket, Console and Webserver
192 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
194 .. function:: addConsoleACL(netmask)
196 .. versionadded:: 1.3.0
198 Add a netmask to the existing console ACL, allowing remote clients to connect to the console. Please make sure that encryption
199 has been enabled with :func:`setKey` before doing so. The default is to only allow 127.0.0.1/8 and ::1/128.
201 :param str netmask: A CIDR netmask, e.g. ``"192.0.2.0/24"``. Without a subnetmask, only the specific address is allowed.
203 .. function:: controlSocket(address)
205 Bind to ``addr`` and listen for a connection for the console. Since 1.3.0 only connections from local users are allowed
206 by default, :func:`addConsoleACL` and :func:`setConsoleACL` can be used to enable remote connections. Please make sure
207 that encryption has been enabled with :func:`setKey` before doing so. Enabling encryption is also strongly advised for
208 local connections, since not enabling it allows any local user to connect to the console.
210 :param str address: An IP address with optional port. By default, the port is 5199.
212 .. function:: inClientStartup()
214 Returns true while the console client is parsing the configuration.
216 .. function:: makeKey()
218 Generate and print an encryption key.
220 .. function:: setConsoleConnectionsLogging(enabled)
222 .. versionadded:: 1.2.0
224 Whether to log the opening and closing of console connections.
226 :param bool enabled: Default to true.
228 .. function:: setKey(key)
230 Use ``key`` as shared secret between the client and the server
232 :param str key: An encoded key, as generated by :func:`makeKey`
234 .. function:: setConsoleACL(netmasks)
236 .. versionadded:: 1.3.0
238 Remove the existing console ACL and add the netmasks from the table, allowing remote clients to connect to the console. Please make sure that encryption
239 has been enabled with :func:`setKey` before doing so.
241 :param {str} netmasks: A table of CIDR netmask, e.g. ``{"192.0.2.0/24", "2001:DB8:14::/56"}``. Without a subnetmask, only the specific address is allowed.
243 .. function:: showConsoleACL()
245 Print a list of all netmasks allowed to connect to the console.
247 .. function:: testCrypto()
249 Test the crypto code, will report errors when something is not ok.
251 .. function:: setConsoleOutputMaxMsgSize(size)
253 .. versionadded:: 1.3.3
255 Set the maximum size in bytes of a single console message, default set to 10 MB.
257 :param int size: The new maximum size.
259 Webserver configuration
260 ~~~~~~~~~~~~~~~~~~~~~~~
262 .. function:: webserver(listen_address, password[, apikey[, custom_headers]])
264 Launch the :doc:`../guides/webserver` with statistics and the API.
266 :param str listen_address: The IP address and Port to listen on
267 :param str password: The password required to access the webserver
268 :param str apikey: The key required to access the API
269 :param {[str]=str,...} custom_headers: Allows setting custom headers and removing the defaults
271 .. function:: setAPIWritable(allow [,dir])
273 Allow modifications via the API.
274 Optionally saving these changes to disk.
275 Modifications done via the API will not be written to the configuration by default and will not persist after a reload
277 :param bool allow: Set to true to allow modification through the API
278 :param str dir: A valid directory where the configuration files will be written by the API.
280 .. function:: setWebserverConfig(options)
282 .. versionadded:: 1.3.3
284 Setup webserver configuration. See :func:`webserver`.
286 :param table options: A table with key: value pairs with webserver options.
290 * ``password=newPassword``: string - Changes the API password
291 * ``apikey=newKey``: string - Changes the API Key (set to an empty string do disable it)
292 * ``custom_headers={[str]=str,...}``: map of string - Allows setting custom headers and removing the defaults.
297 .. function:: addACL(netmask)
299 Add a netmask to the existing ACL controlling which clients can send UDP, TCP, DNS over TLS and DNS over HTTPS queries. See :ref:`ACL` for more information.
301 :param str netmask: A CIDR netmask, e.g. ``"192.0.2.0/24"``. Without a subnetmask, only the specific address is allowed.
303 .. function:: setACL(netmasks)
305 Remove the existing ACL and add the netmasks from the table of those allowed to send UDP, TCP, DNS over TLS and DNS over HTTPS queries. See :ref:`ACL` for more information.
307 :param {str} netmasks: A table of CIDR netmask, e.g. ``{"192.0.2.0/24", "2001:DB8:14::/56"}``. Without a subnetmask, only the specific address is allowed.
309 .. function:: showACL()
311 Print a list of all netmasks allowed to send queries over UDP, TCP, DNS over TLS and DNS over HTTPS. See :ref:`ACL` for more information.
316 .. function:: setECSOverride(bool)
318 When ``useClientSubnet`` in :func:`newServer` is set and dnsdist adds an EDNS Client Subnet Client option to the query, override an existing option already present in the query, if any
320 :param bool: Whether to override an existing EDNS Client Subnet option present in the query. Defaults to false
322 .. function:: setECSSourcePrefixV4(prefix)
324 When ``useClientSubnet`` in :func:`newServer` is set and dnsdist adds an EDNS Client Subnet Client option to the query, truncate the requestors IPv4 address to ``prefix`` bits
326 :param int prefix: The prefix length
328 .. function:: setECSSourcePrefixV6(prefix)
330 When ``useClientSubnet`` in :func:`newServer` is set and dnsdist adds an EDNS Client Subnet Client option to the query, truncate the requestor's IPv6 address to bits
332 :param int prefix: The prefix length
337 .. function:: setRingBuffersLockRetries(num)
339 .. versionadded:: 1.3.0
341 Set the number of shards to attempt to lock without blocking before giving up and simply blocking while waiting for the next shard to be available
343 :param int num: The maximum number of attempts. Defaults to 5 if there is more than one shard, 0 otherwise.
345 .. function:: setRingBuffersSize(num [, numberOfShards])
347 .. versionchanged:: 1.3.0
348 ``numberOfShards`` optional parameter added.
350 Set the capacity of the ringbuffers used for live traffic inspection to ``num``, and the number of shards to ``numberOfShards`` if specified.
352 :param int num: The maximum amount of queries to keep in the ringbuffer. Defaults to 10000
353 :param int numberOfShards: the number of shards to use to limit lock contention. Defaults to 1
358 .. function:: newServer(server_string)
359 newServer(server_table)
361 .. versionchanged:: 1.3.0
362 Added ``checkClass``, ``sockets`` and ``checkFunction`` to server_table.
364 .. versionchanged:: 1.4.0
365 Added ``checkInterval``, ``checkTimeout`` and ``rise`` to server_table.
367 Add a new backend server. Call this function with either a string::
370 "IP:PORT" -- IP and PORT of the backend server
376 address="IP:PORT", -- IP and PORT of the backend server (mandatory)
377 id=STRING, -- Use a pre-defined UUID instead of a random one
378 qps=NUM, -- Limit the number of queries per second to NUM, when using the `firstAvailable` policy
379 order=NUM, -- The order of this server, used by the `leastOutstanding` and `firstAvailable` policies
380 weight=NUM, -- The weight of this server, used by the `wrandom`, `whashed` and `chashed` policies, default: 1
381 -- Supported values are a minimum of 1, and a maximum of 2147483647.
382 pool=STRING|{STRING}, -- The pools this server belongs to (unset or empty string means default pool) as a string or table of strings
383 retries=NUM, -- The number of TCP connection attempts to the backend, for a given query
384 tcpConnectTimeout=NUM, -- The timeout (in seconds) of a TCP connection attempt
385 tcpSendTimeout=NUM, -- The timeout (in seconds) of a TCP write attempt
386 tcpRecvTimeout=NUM, -- The timeout (in seconds) of a TCP read attempt
387 tcpFastOpen=BOOL, -- Whether to enable TCP Fast Open
388 ipBindAddrNoPort=BOOL, -- Whether to enable IP_BIND_ADDRESS_NO_PORT if available, default: true
389 name=STRING, -- The name associated to this backend, for display purpose
390 checkClass=NUM, -- Use NUM as QCLASS in the health-check query, default: DNSClass.IN
391 checkName=STRING, -- Use STRING as QNAME in the health-check query, default: "a.root-servers.net."
392 checkType=STRING, -- Use STRING as QTYPE in the health-check query, default: "A"
393 checkFunction=FUNCTION,-- Use this function to dynamically set the QNAME, QTYPE and QCLASS to use in the health-check query (see :ref:`Healthcheck`)
394 checkTimeout=NUM, -- The timeout (in milliseconds) of a health-check query, default: 1000 (1s)
395 setCD=BOOL, -- Set the CD (Checking Disabled) flag in the health-check query, default: false
396 maxCheckFailures=NUM, -- Allow NUM check failures before declaring the backend down, default: 1
397 checkInterval=NUM -- The time in seconds between health checks
398 mustResolve=BOOL, -- Set to true when the health check MUST return a RCODE different from NXDomain, ServFail and Refused. Default is false, meaning that every RCODE except ServFail is considered valid
399 useClientSubnet=BOOL, -- Add the client's IP address in the EDNS Client Subnet option when forwarding the query to this backend
400 source=STRING, -- The source address or interface to use for queries to this backend, by default this is left to the kernel's address selection
401 -- The following formats are supported:
402 -- "address", e.g. "192.0.2.2"
403 -- "interface name", e.g. "eth0"
404 -- "address@interface", e.g. "192.0.2.2@eth0"
405 addXPF=NUM, -- Add the client's IP address and port to the query, along with the original destination address and port,
406 -- using the experimental XPF record from `draft-bellis-dnsop-xpf <https://datatracker.ietf.org/doc/draft-bellis-dnsop-xpf/>`_ and the specified option code. Default is disabled (0)
407 sockets=NUM, -- Number of sockets (and thus source ports) used toward the backend server, defaults to a single one
408 disableZeroScope=BOOL, -- Disable the EDNS Client Subnet 'zero scope' feature, which does a cache lookup for an answer valid for all subnets (ECS scope of 0) before adding ECS information to the query and doing the regular lookup
409 rise=NUM -- Require NUM consecutive successful checks before declaring the backend up, default: 1
412 :param str server_string: A simple IP:PORT string.
413 :param table server_table: A table with at least a 'name' key
415 .. function:: getServer(index) -> Server
417 Get a :class:`Server`
419 :param int index: The number of the server (as seen in :func:`showServers`).
420 :returns: The :class:`Server` object or nil
422 .. function:: getServers()
424 Returns a table with all defined servers.
426 .. function:: rmServer(index)
429 Remove a backend server.
431 :param int index: The number of the server (as seen in :func:`showServers`).
432 :param Server server: A :class:`Server` object as returned by e.g. :func:`getServer`.
436 A server object returned by :func:`getServer` can be manipulated with these functions.
440 This object represents a backend server. It has several methods.
442 .. method:: Server:addPool(pool)
444 Add this server to a pool.
446 :param str pool: The pool to add the server to
448 .. method:: Server:getName() -> string
450 Get the name of this server.
452 :returns: The name of the server, or an empty string if it does not have one
454 .. method:: Server:getNameWithAddr() -> string
456 Get the name plus IP address and port of the server
458 :returns: A string containing the server name if any plus the server address and port
460 .. method:: Server:getOutstanding() -> int
462 Get the number of outstanding queries for this server.
464 :returns: The number of outstanding queries
466 .. method:: Server:isUp() -> bool
468 Returns the up status of the server
470 :returns: true when the server is up, false otherwise
472 .. method:: Server:rmPool(pool)
474 Removes the server from the named pool
476 :param str pool: The pool to remove the server from
478 .. method:: Server:setAuto([status])
480 .. versionchanged:: 1.3.0
481 ``status`` optional parameter added.
483 Set the server in the default auto state.
484 This will enable health check queries that will set the server ``up`` and ``down`` appropriately.
486 :param bool status: Set the initial status of the server to ``up`` (true) or ``down`` (false) instead of using the last known status
488 .. method:: Server:setQPS(limit)
490 Limit the queries per second for this server.
492 :param int limit: The maximum number of queries per second
494 .. method:: Server:setDown()
496 Set the server in an ``DOWN`` state.
497 The server will not receive queries and the health checks are disabled
499 .. method:: Server:setUp()
501 Set the server in an ``UP`` state.
502 This server will still receive queries and health checks are disabled
504 Apart from the functions, a :class:`Server` object has these attributes:
506 .. attribute:: Server.name
508 The name of the server
510 .. attribute:: Server.upStatus
512 Whether or not this server is up or down
514 .. attribute:: Server.order
516 The order of the server
518 .. attribute:: Server.weight
520 The weight of the server
525 :class:`Server`\ s can be part of any number of pools.
526 Pools are automatically created when a server is added to a pool (with :func:`newServer`), or can be manually created with :func:`addPool`.
528 .. function:: addPool(name) -> ServerPool
530 Returns a :class:`ServerPool`.
532 :param string name: The name of the pool to create
534 .. function:: getPool(name) -> ServerPool
536 Returns a :class:`ServerPool` or nil.
538 :param string name: The name of the pool
540 .. function:: getPoolServers(name) -> [ Server ]
542 Returns a list of :class:`Server`\ s or nil.
544 :param string name: The name of the pool
546 .. function:: showPools()
548 Display the name, associated cache, server policy and associated servers for every pool.
550 .. class:: ServerPool
552 This represents the pool where zero or more servers are part of.
554 .. method:: ServerPool:getCache() -> PacketCache
556 Returns the :class:`PacketCache` for this pool or nil.
558 .. method:: ServerPool:getECS()
560 .. versionadded:: 1.3.0
562 Whether dnsdist will add EDNS Client Subnet information to the query before looking up into the cache,
563 when all servers from this pool are down. For more information see :meth:`ServerPool:setECS`.
565 .. method:: ServerPool:setCache(cache)
567 Adds ``cache`` as the pool's cache.
569 :param PacketCache cache: The new cache to add to the pool
571 .. method:: ServerPool:unsetCache()
573 Removes the cache from this pool.
575 .. method:: ServerPool:setECS()
577 .. versionadded:: 1.3.0
579 Set to true if dnsdist should add EDNS Client Subnet information to the query before looking up into the cache,
580 when all servers from this pool are down. If at least one server is up, the preference of the
581 selected server is used, this parameter is only useful if all the backends in this pool are down
582 and have EDNS Client Subnet enabled, since the queries in the cache will have been inserted with
583 ECS information. Default is false.
588 A Pool can have a packet cache to answer queries directly instead of going to the backend.
589 See :doc:`../guides/cache` for a how to.
591 .. function:: newPacketCache(maxEntries[, maxTTL=86400[, minTTL=0[, temporaryFailureTTL=60[, staleTTL=60[, dontAge=false[, numberOfShards=1[, deferrableInsertLock=true[, maxNegativeTTL=3600[, parseECS=false]]]]]]]) -> PacketCache
593 .. versionchanged:: 1.3.0
594 ``numberOfShards`` and ``deferrableInsertLock`` parameters added.
596 .. versionchanged:: 1.3.1
597 ``maxNegativeTTL`` and ``parseECS`` parameters added.
599 .. deprecated:: 1.4.0
601 Creates a new :class:`PacketCache` with the settings specified.
603 :param int maxEntries: The maximum number of entries in this cache
604 :param int maxTTL: Cap the TTL for records to his number
605 :param int minTTL: Don't cache entries with a TTL lower than this
606 :param int temporaryFailureTTL: On a SERVFAIL or REFUSED from the backend, cache for this amount of seconds
607 :param int staleTTL: When the backend servers are not reachable, and global configuration ``setStaleCacheEntriesTTL`` is set appropriately, TTL that will be used when a stale cache entry is returned
608 :param bool dontAge: Don't reduce TTLs when serving from the cache. Use this when :program:`dnsdist` fronts a cluster of authoritative servers
609 :param int numberOfShards: Number of shards to divide the cache into, to reduce lock contention
610 :param bool deferrableInsertLock: Whether the cache should give up insertion if the lock is held by another thread, or simply wait to get the lock
611 :param int maxNegativeTTL: Cache a NXDomain or NoData answer from the backend for at most this amount of seconds, even if the TTL of the SOA record is higher
612 :param bool parseECS: Whether any EDNS Client Subnet option present in the query should be extracted and stored to be able to detect hash collisions involving queries with the same qname, qtype and qclass but a different incoming ECS value. Enabling this option adds a parsing cost and only makes sense if at least one backend might send different responses based on the ECS value, so it's disabled by default
614 .. function:: newPacketCache(maxEntries, [options]) -> PacketCache
616 .. versionadded:: 1.4.0
618 Creates a new :class:`PacketCache` with the settings specified.
620 :param int maxEntries: The maximum number of entries in this cache
624 * ``deferrableInsertLock=true``: bool - Whether the cache should give up insertion if the lock is held by another thread, or simply wait to get the lock.
625 * ``dontAge=false``: bool - Don't reduce TTLs when serving from the cache. Use this when :program:`dnsdist` fronts a cluster of authoritative servers.
626 * ``keepStaleData=false``: bool - Whether to suspend the removal of expired entries from the cache when there is no backend available in at least one of the pools using this cache.
627 * ``maxNegativeTTL=3600``: int - Cache a NXDomain or NoData answer from the backend for at most this amount of seconds, even if the TTL of the SOA record is higher.
628 * ``maxTTL=86400``: int - Cap the TTL for records to his number.
629 * ``minTTL=0``: int - Don't cache entries with a TTL lower than this.
630 * ``numberOfShards=1``: int - Number of shards to divide the cache into, to reduce lock contention.
631 * ``parseECS=false``: bool - Whether any EDNS Client Subnet option present in the query should be extracted and stored to be able to detect hash collisions involving queries with the same qname, qtype and qclass but a different incoming ECS value. Enabling this option adds a parsing cost and only makes sense if at least one backend might send different responses based on the ECS value, so it's disabled by default.
632 * ``staleTTL=60``: int - When the backend servers are not reachable, and global configuration ``setStaleCacheEntriesTTL`` is set appropriately, TTL that will be used when a stale cache entry is returned.
633 * ``temporaryFailureTTL=60``: int - On a SERVFAIL or REFUSED from the backend, cache for this amount of seconds..
635 .. class:: PacketCache
637 Represents a cache that can be part of :class:`ServerPool`.
639 .. method:: PacketCache:dump(fname)
641 .. versionadded:: 1.3.1
643 Dump a summary of the cache entries to a file.
645 :param str fname: The path to a file where the cache summary should be dumped. Note that if the target file already exists, it will not be overwritten.
647 .. method:: PacketCache:expunge(n)
649 Remove entries from the cache, leaving at most ``n`` entries
651 :param int n: Number of entries to keep
653 .. method:: PacketCache:expungeByName(name [, qtype=DNSQType.ANY[, suffixMatch=false]])
655 .. versionchanged:: 1.2.0
656 ``suffixMatch`` parameter added.
658 Remove entries matching ``name`` and type from the cache.
660 :param DNSName name: The name to expunge
661 :param int qtype: The type to expunge, can be a pre-defined :ref:`DNSQType`
662 :param bool suffixMatch: When set to true, remove al entries under ``name``
664 .. method:: PacketCache:getStats()
666 .. versionadded:: 1.4.0
668 Return the cache stats (number of entries, hits, misses, deferred lookups, deferred inserts, lookup collisions, insert collisions and TTL too shorts) as a Lua table.
670 .. method:: PacketCache:isFull() -> bool
672 Return true if the cache has reached the maximum number of entries.
674 .. method:: PacketCache:printStats()
676 Print the cache stats (number of entries, hits, misses, deferred lookups, deferred inserts, lookup collisions, insert collisions and TTL too shorts).
678 .. method:: PacketCache:purgeExpired(n)
680 Remove expired entries from the cache until there is at most ``n`` entries remaining in the cache.
682 :param int n: Number of entries to keep
684 .. method:: PacketCache:toString() -> string
686 Return the number of entries in the Packet Cache, and the maximum number of entries
691 Also called frontend or bind, the Client State object returned by :func:`getBind` and listed with :func:`showBinds` represents an address and port dnsdist is listening on.
693 .. function:: getBind(index) -> ClientState
695 Return a :class:`ClientState` object.
697 :param int index: The object index
699 ClientState functions
700 ~~~~~~~~~~~~~~~~~~~~~
702 .. class:: ClientState
704 This object represents an address and port dnsdist is listening on. When ``reuseport`` is in use, several ClientState objects can be present for the same address and port.
706 .. method:: ClientState:attachFilter(filter)
708 Attach a BPF filter to this frontend.
710 :param BPFFilter filter: The filter to attach to this frontend
712 .. method:: ClientState:detachFilter()
714 Remove the BPF filter associated to this frontend, if any.
716 .. method:: ClientState:toString() -> string
718 Return the address and port this frontend is listening on.
720 :returns: The address and port this frontend is listening on
722 .. attribute:: ClientState.muted
724 If set to true, queries received on this frontend will be normally processed and sent to a backend if needed, but no response will be ever be sent to the client over UDP. TCP queries are processed normally and responses sent to the client.
726 Status, Statistics and More
727 ---------------------------
729 .. function:: dumpStats()
731 Print all statistics dnsdist gathers
733 .. function:: getDOHFrontend(idx)
735 .. versionadded:: 1.4.0
737 Return the DOHFrontend object for the DNS over HTTPS bind of index ``idx``.
739 .. function:: getTLSContext(idx)
741 .. versionadded:: 1.3.0
743 Return the TLSContext object for the context of index ``idx``.
745 .. function:: getTLSFrontend(idx)
747 .. versionadded:: 1.3.1
749 Return the TLSFrontend object for the TLS bind of index ``idx``.
751 .. function:: grepq(selector[, num])
752 grepq(selectors[, num])
754 Prints the last ``num`` queries matching ``selector`` or ``selectors``.
758 * a netmask (e.g. '192.0.2.0/24')
759 * a DNS name (e.g. 'dnsdist.org')
760 * a response time (e.g. '100ms')
762 :param str selector: Select queries based on this property.
763 :param {str} selectors: A lua table of selectors. Only queries matching all selectors are shown
764 :param int num: Show a maximum of ``num`` recent queries, default is 10.
766 .. function:: setVerboseHealthChecks(verbose)
768 Set whether health check errors should be logged. This is turned off by default.
770 :param bool verbose: Set to true if you want to enable health check errors logging
772 .. function:: showBinds()
774 Print a list of all the current addresses and ports dnsdist is listening on, also called ``frontends``
776 .. function:: showDOHFrontends()
778 .. versionadded:: 1.4.0
780 Print the list of all availables DNS over HTTPS frontends.
782 .. function:: showDOHResponseCodes()
784 .. versionadded:: 1.4.0
786 Print the HTTP response codes statistics for all availables DNS over HTTPS frontends.
788 .. function:: showResponseLatency()
790 Show a plot of the response time latency distribution
792 .. function:: showServers([options])
794 .. versionchanged:: 1.4.0
795 ``options`` optional parameter added
797 This function shows all backend servers currently configured and some statistics.
798 These statics have the following fields:
800 * ``#`` - The number of the server, can be used as the argument for :func:`getServer`
801 * ``UUID`` - The UUID of the backend. Can be set with the ``id`` option of :func:`newServer`
802 * ``Address`` - The IP address and port of the server
803 * ``State`` - The current state of the server
804 * ``Qps`` - Current number of queries per second
805 * ``Qlim`` - Configured maximum number of queries per second
806 * ``Ord`` - The order number of the server
807 * ``Wt`` - The weight of the server
808 * ``Queries`` - Total amount of queries sent to this server
809 * ``Drops`` - Number of queries that were dropped by this server
810 * ``Drate`` - Number of queries dropped per second by this server
811 * ``Lat`` - The latency of this server in milliseconds
812 * ``Pools`` - The pools this server belongs to
814 :param table options: A table with key: value pairs with display options.
818 * ``showUUIDs=false``: bool - Whether to display the UUIDs, defaults to false.
820 .. function:: showTCPStats()
822 Show some statistics regarding TCP
824 .. function:: showTLSContexts()
826 .. versionadded:: 1.3.0
828 Print the list of all availables DNS over TLS contexts.
830 .. function:: showVersion()
832 Print the version of dnsdist
834 .. function:: topBandwidth([num])
836 Print the top ``num`` clients that consume the most bandwidth.
838 :param int num: Number to show, defaults to 10.
840 .. function:: topClients([num])
842 Print the top ``num`` clients sending the most queries over length of ringbuffer
844 :param int num: Number to show, defaults to 10.
846 .. function:: topQueries([num[, labels]])
848 Print the ``num`` most popular QNAMEs from queries.
849 Optionally grouped by the rightmost ``labels`` DNS labels.
851 :param int num: Number to show, defaults to 10
852 :param int label: Number of labels to cut down to
854 .. function:: topResponses([num[, rcode[, labels]]])
856 Print the ``num`` most seen responses with an RCODE of ``rcode``.
857 Optionally grouped by the rightmost ``labels`` DNS labels.
859 :param int num: Number to show, defaults to 10
860 :param int rcode: :ref:`Response code <DNSRCode>`, defaults to 0 (No Error)
861 :param int label: Number of labels to cut down to
863 .. function:: topSlow([num[, limit[, labels]]])
865 Print the ``num`` slowest queries that are slower than ``limit`` milliseconds.
866 Optionally grouped by the rightmost ``labels`` DNS labels.
868 :param int num: Number to show, defaults to 10
869 :param int limit: Show queries slower than this amount of milliseconds, defaults to 2000
870 :param int label: Number of labels to cut down to
877 .. function:: addDynBlocks(addresses, message[, seconds=10[, action]])
879 .. versionchanged:: 1.2.0
880 ``action`` parameter added.
882 Block a set of addresses with ``message`` for (optionally) a number of seconds.
883 The default number of seconds to block for is 10.
885 :param addresses: set of Addresses as returned by an exceed function
886 :param string message: The message to show next to the blocks
887 :param int seconds: The number of seconds this block to expire
888 :param int action: The action to take when the dynamic block matches, see :ref:`here <DNSAction>`. (default to DNSAction.None, meaning the one set with :func:`setDynBlocksAction` is used)
890 Please see the documentation for :func:`setDynBlocksAction` to confirm which actions are supported by the action paramater.
892 .. function:: clearDynBlocks()
894 Remove all current dynamic blocks.
896 .. function:: showDynBlocks()
898 List all dynamic blocks in effect.
900 .. function:: setDynBlocksAction(action)
902 .. versionchanged:: 1.3.3
903 ``DNSAction.NXDomain`` action added.
905 Set which action is performed when a query is blocked.
906 Only DNSAction.Drop (the default), DNSAction.NoOp, DNSAction.NXDomain, DNSAction.Refused, DNSAction.Truncate and DNSAction.NoRecurse are supported.
910 Getting addresses that exceeded parameters
911 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
913 .. function:: exceedServFails(rate, seconds)
915 Get set of addresses that exceed ``rate`` servfails/s over ``seconds`` seconds
917 :param int rate: Number of Servfails per second to exceed
918 :param int seconds: Number of seconds the rate has been exceeded
920 .. function:: exceedNXDOMAINs(rate, seconds)
922 get set of addresses that exceed ``rate`` NXDOMAIN/s over ``seconds`` seconds
924 :param int rate: Number of NXDOMAIN per second to exceed
925 :param int seconds: Number of seconds the rate has been exceeded
927 .. function:: exceedRespByterate(rate, seconds)
929 get set of addresses that exceeded ``rate`` bytes/s answers over ``seconds`` seconds
931 :param int rate: Number of bytes per second to exceed
932 :param int seconds: Number of seconds the rate has been exceeded
934 .. function:: exceedQRate(rate, seconds)
936 Get set of address that exceed ``rate`` queries/s over ``seconds`` seconds
938 :param int rate: Number of queries per second to exceed
939 :param int seconds: Number of seconds the rate has been exceeded
941 .. function:: exceedQTypeRate(type, rate, seconds)
943 Get set of address that exceed ``rate`` queries/s for queries of QType ``type`` over ``seconds`` seconds
945 :param int type: QType
946 :param int rate: Number of QType queries per second to exceed
947 :param int seconds: Number of seconds the rate has been exceeded
952 Instead of using several `exceed*()` lines, dnsdist 1.3.0 introduced a new `DynBlockRulesGroup` object
953 which can be used to group dynamic block rules.
955 See :doc:`../guides/dynblocks` for more information about the case where using a `DynBlockRulesGroup` might be
956 faster than the existing rules.
958 .. function:: dynBlockRulesGroup() -> DynBlockRulesGroup
960 .. versionadded:: 1.3.0
962 Creates a new :class:`DynBlockRulesGroup` object.
964 .. class:: DynBlockRulesGroup
966 Represents a group of dynamic block rules.
968 .. method:: DynBlockRulesGroup:setQueryRate(rate, seconds, reason, blockingTime [, action [, warningRate]])
970 .. versionchanged:: 1.3.3
971 ``warningRate`` parameter added.
973 Adds a query rate-limiting rule, equivalent to:
975 addDynBlocks(exceedQRate(rate, seconds), reason, blockingTime, action)
978 :param int rate: Number of queries per second to exceed
979 :param int seconds: Number of seconds the rate has been exceeded
980 :param string reason: The message to show next to the blocks
981 :param int blockingTime: The number of seconds this block to expire
982 :param int action: The action to take when the dynamic block matches, see :ref:`here <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
983 :param int warningRate: If set to a non-zero value, the rate above which a warning message will be issued and a no-op block inserted
985 .. method:: DynBlockRulesGroup:setRCodeRate(rcode, rate, seconds, reason, blockingTime [, action [, warningRate]])
987 .. versionchanged:: 1.3.3
988 ``warningRate`` parameter added.
990 Adds a rate-limiting rule for responses of code ``rcode``, equivalent to:
992 addDynBlocks(exceedServfails(rcode, rate, seconds), reason, blockingTime, action)
995 :param int rcode: The response code
996 :param int rate: Number of responses per second to exceed
997 :param int seconds: Number of seconds the rate has been exceeded
998 :param string reason: The message to show next to the blocks
999 :param int blockingTime: The number of seconds this block to expire
1000 :param int action: The action to take when the dynamic block matches, see :ref:`here <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
1001 :param int warningRate: If set to a non-zero value, the rate above which a warning message will be issued and a no-op block inserted
1003 .. method:: DynBlockRulesGroup:setQTypeRate(qtype, rate, seconds, reason, blockingTime [, action [, warningRate]])
1005 .. versionchanged:: 1.3.3
1006 ``warningRate`` parameter added.
1008 Adds a rate-limiting rule for queries of type ``qtype``, equivalent to:
1010 addDynBlocks(exceedQTypeRate(type, rate, seconds), reason, blockingTime, action)
1013 :param int qtype: The qtype
1014 :param int rate: Number of queries per second to exceed
1015 :param int seconds: Number of seconds the rate has been exceeded
1016 :param string reason: The message to show next to the blocks
1017 :param int blockingTime: The number of seconds this block to expire
1018 :param int action: The action to take when the dynamic block matches, see :ref:`here <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
1019 :param int warningRate: If set to a non-zero value, the rate above which a warning message will be issued and a no-op block inserted
1021 .. method:: DynBlockRulesGroup:setResponseByteRate(rate, seconds, reason, blockingTime [, action [, warningRate]])
1023 .. versionchanged:: 1.3.3
1024 ``warningRate`` parameter added.
1026 Adds a bandwidth rate-limiting rule for responses, equivalent to:
1028 addDynBlocks(exceedRespByterate(rate, seconds), reason, blockingTime, action)
1031 :param int rate: Number of bytes per second to exceed
1032 :param int seconds: Number of seconds the rate has been exceeded
1033 :param string reason: The message to show next to the blocks
1034 :param int blockingTime: The number of seconds this block to expire
1035 :param int action: The action to take when the dynamic block matches, see :ref:`here <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
1036 :param int warningRate: If set to a non-zero value, the rate above which a warning message will be issued and a no-op block inserted
1038 .. method:: DynBlockRulesGroup:apply()
1040 Walk the in-memory query and response ring buffers and apply the configured rate-limiting rules, adding dynamic blocks when the limits have been exceeded.
1042 .. method:: DynBlockRulesGroup:excludeRange(netmasks)
1044 .. versionadded:: 1.3.1
1046 Exclude this range, or list of ranges, meaning that no dynamic block will ever be inserted for clients in that range. Default to empty, meaning rules are applied to all ranges. When used in combination with :meth:`DynBlockRulesGroup:includeRange`, the more specific entry wins.
1048 :param int netmasks: A netmask, or list of netmasks, as strings, like for example "192.0.2.1/24"
1050 .. method:: DynBlockRulesGroup:includeRange(netmasks)
1052 .. versionadded:: 1.3.1
1054 Include this range, or list of ranges, meaning that rules will be applied to this range. When used in combination with :meth:`DynBlockRulesGroup:excludeRange`, the more specific entry wins.
1056 :param int netmasks: A netmask, or list of netmasks, as strings, like for example "192.0.2.1/24"
1058 .. method:: DynBlockRulesGroup:toString()
1060 .. versionadded:: 1.3.1
1062 Return a string describing the rules and range exclusions of this DynBlockRulesGroup.
1067 A SuffixMatchNode can be used to quickly check whether a given name belongs to a set or not. This is achieved
1068 using an efficient tree structure based on DNS labels, making lookups cheap.
1069 Be careful that Suffix Node matching will match for any sub-domain, regardless of the depth, under the name added to the set. For example,
1070 if 'example.com.' is added to the set, 'www.example.com.' and 'sub.www.example.com.' will match as well.
1071 If you are looking for exact name matching, your might want to consider using a :class:`DNSNameSet` instead.
1073 .. function:: newSuffixMatchNode()
1075 Creates a new :class:`SuffixMatchNode`.
1077 .. class:: SuffixMatchNode
1079 Represent a set of DNS suffixes for quick matching.
1081 .. method:: SuffixMatchNode:add(name)
1082 .. versionchanged:: 1.4.0
1083 This method now accepts strings, lists of DNSNames and lists of strings.
1085 Add a suffix to the current set.
1087 :param DNSName name: The suffix to add to the set.
1088 :param string name: The suffix to add to the set.
1089 :param table name: The suffixes to add to the set. Elements of the table should be of the same type, either DNSName or string.
1091 .. method:: SuffixMatchNode:check(name) -> bool
1093 Return true if the given name is a sub-domain of one of those in the set, and false otherwise.
1095 :param DNSName name: The name to test against the set.
1100 .. function:: maintenance()
1102 If this function exists, it is called every second to so regular tasks.
1103 This can be used for e.g. :doc:`Dynamic Blocks <../guides/dynblocks>`.
1105 .. function:: setAllowEmptyResponse()
1107 .. versionadded:: 1.4.0
1109 Set to true (defaults to false) to allow empty responses (qdcount=0) with a NoError or NXDomain rcode (default) from backends. dnsdist drops these responses by default because it can't match them against the initial query since they don't contain the qname, qtype and qclass, and therefore the risk of collision is much higher than with regular responses.
1111 .. function:: makeIPCipherKey(password) -> string
1113 .. versionadded:: 1.4.0
1115 Hashes the password to generate a 16-byte key that can be used to pseudonymize IP addresses with IP cipher.
1120 .. class:: DOHFrontend
1122 .. versionadded:: 1.4.0
1124 This object represents an address and port dnsdist is listening on for DNS over HTTPS queries.
1126 .. method:: DOHFrontend:reloadCertificates()
1128 Reload the current TLS certificate and key pairs.
1133 .. class:: TLSContext
1135 .. versionadded:: 1.3.0
1137 This object represents an address and port dnsdist is listening on for DNS over TLS queries.
1139 .. method:: TLSContext:rotateTicketsKey()
1141 Replace the current TLS tickets key by a new random one.
1143 .. method:: TLSContext:loadTicketsKeys(ticketsKeysFile)
1145 Load new tickets keys from the selected file, replacing the existing ones. These keys should be rotated often and never written to persistent storage to preserve forward secrecy. The default is to generate a random key. The OpenSSL provider supports several tickets keys to be able to decrypt existing sessions after the rotation, while the GnuTLS provider only supports one key.
1147 :param str ticketsKeysFile: The path to a file from where TLS tickets keys should be loaded.
1152 .. class:: TLSFrontend
1154 .. versionadded:: 1.3.1
1156 This object represents the configuration of a listening frontend for DNS over TLS queries. To each frontend is associated a TLSContext.
1158 .. method:: TLSContext:loadNewCertificatesAndKeys(certFile(s), keyFile(s))
1160 Create and switch to a new TLS context using the same options than were passed to the corresponding `addTLSLocal()` directive, but loading new certificates and keys from the selected files, replacing the existing ones.
1162 :param str certFile(s): The path to a X.509 certificate file in PEM format, or a list of paths to such files.
1163 :param str keyFile(s): The path to the private key file corresponding to the certificate, or a list of paths to such files, whose order should match the certFile(s) ones.
1165 EDNS on Self-generated answers
1166 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1168 There are several mechanisms in dnsdist that turn an existing query into an answer right away,
1169 without reaching out to the backend, including :func:`SpoofAction`, :func:`RCodeAction`, :func:`TCAction`
1170 and returning a response from ``Lua``. Those responses should, according to :rfc:`6891`, contain an ``OPT``
1171 record if the received request had one, which is the case by default and can be disabled using
1172 :func:`setAddEDNSToSelfGeneratedResponses`.
1174 We must, however, provide a responder's maximum payload size in this record, and we can't easily know the
1175 maximum payload size of the actual backend so we need to provide one. The default value is 1500 and can be
1176 overriden using :func:`setPayloadSizeOnSelfGeneratedAnswers`.
1178 .. function:: setAddEDNSToSelfGeneratedResponses(add)
1180 .. versionadded:: 1.3.3
1182 Whether to add EDNS to self-generated responses, provided that the initial query had EDNS.
1184 :param bool add: Whether to add EDNS, default is true.
1186 .. function:: setPayloadSizeOnSelfGeneratedAnswers(payloadSize)
1188 .. versionadded:: 1.3.3
1190 Set the UDP payload size advertised via EDNS on self-generated responses. In accordance with
1191 :rfc:`RFC 6891 <6891#section-6.2.5>`, values lower than 512 will be treated as equal to 512.
1193 :param int payloadSize: The responder's maximum UDP payload size, in bytes. Default is 1500.
1198 PowerDNS products can poll the security status of their respective versions. This polling, naturally,
1199 happens over DNS. If the result is that a given version has a security problem, the software will
1200 report this at level ‘Error’ during startup, and repeatedly during operations, every
1201 :func:`setSecurityPollInterval` seconds.
1203 By default, security polling happens on the domain ‘secpoll.powerdns.com’, but this can be changed with
1204 the :func:`setSecurityPollSuffix` function. If this setting is made empty, no polling will take place.
1205 Organizations wanting to host their own security zones can do so by changing this setting to a domain name
1206 under their control.
1208 To enable distributors of PowerDNS to signal that they have backported versions, the PACKAGEVERSION
1209 compilation-time macro can be used to set a distributor suffix.
1211 .. function:: setSecurityPollInterval(interval)
1213 .. versionadded:: 1.3.3
1215 Set the interval, in seconds, between two security pollings.
1217 :param int interval: The interval, in seconds, between two pollings. Default is 3600.
1219 .. function:: setSecurityPollSuffix(suffix)
1221 .. versionadded:: 1.3.3
1223 Domain name from which to query security update notifications. Setting this to an empty string disables secpoll.
1225 :param string suffix: The suffix to use, default is 'secpoll.powerdns.com.'.