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:`Netmask`: represents a netmask
22 * :class:`NetmaskGroup`: represents a group of netmasks
23 * :class:`QPSLimiter`: implements a QPS-based filter
24 * :class:`SuffixMatchNode`: represents a group of domain suffixes for rapid testing of membership
25 * :class:`DNSHeader`: represents the header of a DNS packet, see :ref:`DNSHeader`
26 * :class:`ClientState`: sometimes also called Bind or Frontend, represents the addresses and ports dnsdist is listening on
28 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:
32 getServer(0).order=12 -- set order of server 0 to 12
33 getServer(0):addPool("abuse") -- add this server to the abuse pool
35 The ``.`` means ``order`` is a data member, while the ``:`` means ``addPool`` is a member function.
40 .. function:: addCapabilitiesToRetain(capabilities)
42 .. versionadded:: 1.7.0
44 Accept a Linux capability as a string, or a list of these, to retain after startup so that privileged operations can still be performed at runtime.
45 Keeping ``CAP_BPF`` on kernel 5.8+ for example allows loading eBPF programs and altering eBPF maps at runtime even if the ``kernel.unprivileged_bpf_disabled`` sysctl is set.
46 Note that this does not grant the capabilities to the process, doing so might be done by running it as root which we don't advise, or by adding capabilities via the systemd unit file, for example.
47 Please also be aware that switching to a different user via ``--uid`` will still drop all capabilities.
49 .. function:: includeDirectory(path)
51 Include configuration files from ``path``.
53 :param str path: The directory to load configuration files from. Each file must end in ``.conf``.
55 .. function:: reloadAllCertificates()
57 .. versionadded:: 1.4.0
59 Reload all DNSCrypt and TLS certificates, along with their associated keys.
61 .. function:: setSyslogFacility(facility)
63 .. versionadded:: 1.4.0
65 .. versionchanged:: 1.6.0
66 ``facility`` can now be a string.
68 Set the syslog logging facility to ``facility``.
70 :param int or str facility: The new facility as a numeric value (raw value as defined in syslog.h), or as a case-insensitive string ("LOCAL0", or "daemon", for example). Defaults to LOG_DAEMON.
75 .. function:: addLocal(address[, options])
77 .. versionchanged:: 1.4.0
78 Removed ``doTCP`` from the options. A listen socket on TCP is always created.
80 .. versionchanged:: 1.5.0
81 Added ``tcpListenQueueSize`` parameter.
83 .. versionchanged:: 1.6.0
84 Added ``maxInFlight`` and ``maxConcurrentTCPConnections`` parameters.
86 Add to the list of listen addresses.
88 :param str address: The IP Address with an optional port to listen on.
89 The default port is 53.
90 :param table options: A table with key: value pairs with listen options.
94 * ``doTCP=true``: bool - Also bind on TCP on ``address``. Removed in 1.4.0.
95 * ``reusePort=false``: bool - Set the ``SO_REUSEPORT`` socket option.
96 * ``tcpFastOpenQueueSize=0``: int - Set the TCP Fast Open queue size, enabling TCP Fast Open when available and the value is larger than 0.
97 * ``interface=""``: str - Set the network interface to use.
98 * ``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.
99 * ``tcpListenQueueSize=SOMAXCONN``: int - Set the size of the listen queue. Default is ``SOMAXCONN``.
100 * ``maxInFlight=0``: int - Maximum number of in-flight queries. The default is 0, which disables out-of-order processing.
101 * ``maxConcurrentTCPConnections=0``: int - Maximum number of concurrent incoming TCP connections. The default is 0 which means unlimited.
105 addLocal('0.0.0.0:5300', { reusePort=true })
107 This will bind to both UDP and TCP on port 5300 with SO_REUSEPORT enabled.
109 .. function:: addDOHLocal(address, [certFile(s) [, keyFile(s) [, urls [, options]]]])
111 .. versionadded:: 1.4.0
113 .. versionchanged:: 1.5.0
114 ``internalPipeBufferSize``, ``sendCacheControlHeaders``, ``sessionTimeout``, ``trustForwardedForHeader`` options added.
115 ``url`` now defaults to ``/dns-query`` instead of ``/``, and does exact matching instead of accepting sub-paths. Added ``tcpListenQueueSize`` parameter.
117 .. versionchanged:: 1.6.0
118 ``enableRenegotiation``, ``exactPathMatching``, ``maxConcurrentTCPConnections`` and ``releaseBuffers`` options added.
119 ``internalPipeBufferSize`` now defaults to 1048576 on Linux.
121 .. versionchanged:: 1.8.0
122 ``certFile`` now accepts a TLSCertificate object or a list of such objects (see :func:`newTLSCertificate`)
124 Listen on the specified address and TCP port for incoming DNS over HTTPS connections, presenting the specified X.509 certificate.
125 If no certificate (or key) files are specified, listen for incoming DNS over HTTP connections instead.
127 :param str address: The IP Address with an optional port to listen on.
128 The default port is 443.
129 :param str certFile(s): The path to a X.509 certificate file in PEM format, a list of paths to such files, or a TLSCertificate object.
130 :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. Ignored if ``certFile`` contains TLSCertificate objects.
131 :param str-or-list urls: The path part of a URL, or a list of paths, to accept queries on. Any query with a path matching exactly one of these will be treated as a DoH query (sub-paths can be accepted by setting the ``exactPathMatching`` to false). The default is /dns-query.
132 :param table options: A table with key: value pairs with listen options.
136 * ``reusePort=false``: bool - Set the ``SO_REUSEPORT`` socket option.
137 * ``tcpFastOpenQueueSize=0``: int - Set the TCP Fast Open queue size, enabling TCP Fast Open when available and the value is larger than 0.
138 * ``interface=""``: str - Set the network interface to use.
139 * ``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.
140 * ``idleTimeout=30``: int - Set the idle timeout, in seconds.
141 * ``ciphers``: str - The TLS ciphers to use, in OpenSSL format. Ciphers for TLS 1.3 must be specified via ``ciphersTLS13``.
142 * ``ciphersTLS13``: str - The TLS ciphers to use for TLS 1.3, in OpenSSL format.
143 * ``serverTokens``: str - The content of the Server: HTTP header returned by dnsdist. The default is "h2o/dnsdist".
144 * ``customResponseHeaders={}``: table - Set custom HTTP header(s) returned by dnsdist.
145 * ``ocspResponses``: list - List of files containing OCSP responses, in the same order than the certificates and keys, that will be used to provide OCSP stapling responses.
146 * ``minTLSVersion``: str - Minimum version of the TLS protocol to support. Possible values are 'tls1.0', 'tls1.1', 'tls1.2' and 'tls1.3'. Default is to require at least TLS 1.0.
147 * ``numberOfTicketsKeys``: int - The maximum number of tickets keys to keep in memory at the same time. 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.
148 * ``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. dnsdist supports several tickets keys to be able to decrypt existing sessions after the rotation. See :doc:`../advanced/tls-sessions-management` for more information.
149 * ``ticketsKeysRotationDelay``: int - Set the delay before the TLS tickets key is rotated, in seconds. Default is 43200 (12h).
150 * ``sessionTimeout``: int - Set the TLS session lifetime in seconds, this is used both for TLS ticket lifetime and for sessions kept in memory.
151 * ``sessionTickets``: bool - Whether session resumption via session tickets is enabled. Default is true, meaning tickets are enabled.
152 * ``numberOfStoredSessions``: int - The maximum number of sessions kept in memory at the same time. Default is 20480. Setting this value to 0 disables stored session entirely.
153 * ``preferServerCiphers``: bool - Whether to prefer the order of ciphers set by the server instead of the one set by the client. Default is true, meaning that the order of the server is used. For OpenSSL >= 1.1.1, setting this option also enables the temporary re-prioritization of the ChaCha20-Poly1305 cipher if the client prioritizes it.
154 * ``keyLogFile``: str - Write the TLS keys in the specified file so that an external program can decrypt TLS exchanges, in the format described in https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. Note that this feature requires OpenSSL >= 1.1.1.
155 * ``sendCacheControlHeaders``: bool - Whether to parse the response to find the lowest TTL and set a HTTP Cache-Control header accordingly. Default is true.
156 * ``trustForwardedForHeader``: bool - Whether to parse any existing X-Forwarded-For header in the HTTP query and use the right-most value as the client source address and port, for ACL checks, rules, logging and so on. Default is false.
157 * ``tcpListenQueueSize=SOMAXCONN``: int - Set the size of the listen queue. Default is ``SOMAXCONN``.
158 * ``internalPipeBufferSize=0``: int - Set the size in bytes of the internal buffer of the pipes used internally to pass queries and responses between threads. Requires support for ``F_SETPIPE_SZ`` which is present in Linux since 2.6.35. The actual size might be rounded up to a multiple of a page size. 0 means that the OS default size is used. The default value is 0, except on Linux where it is 1048576 since 1.6.0.
159 * ``exactPathMatching=true``: bool - Whether to do exact path matching of the query path against the paths configured in ``urls`` (true, the default since 1.5.0) or to accepts sub-paths (false, and was the default before 1.5.0).
160 * ``maxConcurrentTCPConnections=0``: int - Maximum number of concurrent incoming TCP connections. The default is 0 which means unlimited.
161 * ``releaseBuffers=true``: bool - Whether OpenSSL should release its I/O buffers when a connection goes idle, saving roughly 35 kB of memory per connection.
162 * ``enableRenegotiation=false``: bool - Whether secure TLS renegotiation should be enabled. Disabled by default since it increases the attack surface and is seldom used for DNS.
164 .. function:: addTLSLocal(address, certFile(s), keyFile(s) [, options])
166 .. versionchanged:: 1.4.0
167 ``ciphersTLS13``, ``minTLSVersion``, ``ocspResponses``, ``preferServerCiphers``, ``keyLogFile`` options added.
168 .. versionchanged:: 1.5.0
169 ``sessionTimeout`` and ``tcpListenQueueSize`` options added.
170 .. versionchanged:: 1.6.0
171 ``enableRenegotiation``, ``maxConcurrentTCPConnections``, ``maxInFlight`` and ``releaseBuffers`` options added.
172 .. versionchanged:: 1.8.0
173 ``tlsAsyncMode`` option added.
174 .. versionchanged:: 1.8.0
175 ``certFile`` now accepts a TLSCertificate object or a list of such objects (see :func:`newTLSCertificate`)
177 Listen on the specified address and TCP port for incoming DNS over TLS connections, presenting the specified X.509 certificate.
179 :param str address: The IP Address with an optional port to listen on.
180 The default port is 853.
181 :param str certFile(s): The path to a X.509 certificate file in PEM format, a list of paths to such files, or a TLSCertificate object.
182 :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. Ignored if ``certFile`` contains TLSCertificate objects.
183 :param table options: A table with key: value pairs with listen options.
187 * ``reusePort=false``: bool - Set the ``SO_REUSEPORT`` socket option.
188 * ``tcpFastOpenQueueSize=0``: int - Set the TCP Fast Open queue size, enabling TCP Fast Open when available and the value is larger than 0.
189 * ``interface=""``: str - Set the network interface to use.
190 * ``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.
191 * ``provider``: str - The TLS library to use between GnuTLS and OpenSSL, if they were available and enabled at compilation time. Default is to use OpenSSL when available.
192 * ``ciphers``: str - The TLS ciphers to use. The exact format depends on the provider used. When the OpenSSL provider is used, ciphers for TLS 1.3 must be specified via ``ciphersTLS13``.
193 * ``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.
194 * ``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.
195 * ``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. See :doc:`../advanced/tls-sessions-management` for more information.
196 * ``ticketsKeysRotationDelay``: int - Set the delay before the TLS tickets key is rotated, in seconds. Default is 43200 (12h).
197 * ``sessionTimeout``: int - Set the TLS session lifetime in seconds, this is used both for TLS ticket lifetime and for sessions kept in memory.
198 * ``sessionTickets``: bool - Whether session resumption via session tickets is enabled. Default is true, meaning tickets are enabled.
199 * ``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.
200 * ``ocspResponses``: list - List of files containing OCSP responses, in the same order than the certificates and keys, that will be used to provide OCSP stapling responses.
201 * ``minTLSVersion``: str - Minimum version of the TLS protocol to support. Possible values are 'tls1.0', 'tls1.1', 'tls1.2' and 'tls1.3'. Default is to require at least TLS 1.0. Note that this value is ignored when the GnuTLS provider is in use, and the ``ciphers`` option should be set accordingly instead. For example, 'NORMAL:!VERS-TLS1.0:!VERS-TLS1.1' will disable TLS 1.0 and 1.1.
202 * ``preferServerCiphers``: bool - Whether to prefer the order of ciphers set by the server instead of the one set by the client. Default is true, meaning that the order of the server is used. For OpenSSL >= 1.1.1, setting this option also enables the temporary re-prioritization of the ChaCha20-Poly1305 cipher if the client prioritizes it.
203 * ``keyLogFile``: str - Write the TLS keys in the specified file so that an external program can decrypt TLS exchanges, in the format described in https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. Note that this feature requires OpenSSL >= 1.1.1.
204 * ``tcpListenQueueSize=SOMAXCONN``: int - Set the size of the listen queue. Default is ``SOMAXCONN``.
205 * ``maxInFlight=0``: int - Maximum number of in-flight queries. The default is 0, which disables out-of-order processing.
206 * ``maxConcurrentTCPConnections=0``: int - Maximum number of concurrent incoming TCP connections. The default is 0 which means unlimited.
207 * ``releaseBuffers=true``: bool - Whether OpenSSL should release its I/O buffers when a connection goes idle, saving roughly 35 kB of memory per connection.
208 * ``enableRenegotiation=false``: bool - Whether secure TLS renegotiation should be enabled (OpenSSL only, the GnuTLS provider does not support it). Disabled by default since it increases the attack surface and is seldom used for DNS.
209 * ``tlsAsyncMode=false``: bool - Whether to enable experimental asynchronous TLS I/O operations if OpenSSL is used as the TLS provider and an asynchronous capable SSL engine is loaded. See also :func:`loadTLSEngine` to load the engine.
211 .. function:: setLocal(address[, options])
213 Remove the list of listen addresses and add a new one.
215 :param str address: The IP Address with an optional port to listen on.
216 The default port is 53.
217 :param table options: A table with key: value pairs with listen options.
219 The options that can be set are the same as :func:`addLocal`.
221 Control Socket, Console and Webserver
222 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
224 .. function:: addConsoleACL(netmask)
226 Add a netmask to the existing console ACL, allowing remote clients to connect to the console. Please make sure that encryption
227 has been enabled with :func:`setKey` before doing so. The default is to only allow 127.0.0.1/8 and ::1/128.
229 :param str netmask: A CIDR netmask, e.g. ``"192.0.2.0/24"``. Without a subnetmask, only the specific address is allowed.
231 .. function:: clearConsoleHistory()
233 .. versionadded:: 1.6.0
235 Clear the internal (in-memory) buffers of console commands. These buffers are used to provide the :func:`delta` command and
236 console completion and history, and can end up being quite large when a lot of commands are issued via the console, consuming
237 a noticeable amount of memory.
239 .. function:: controlSocket(address)
241 Bind to ``addr`` and listen for a connection for the console. Since 1.3.0 only connections from local users are allowed
242 by default, :func:`addConsoleACL` and :func:`setConsoleACL` can be used to enable remote connections. Please make sure
243 that encryption has been enabled with :func:`setKey` before doing so. Enabling encryption is also strongly advised for
244 local connections, since not enabling it allows any local user to connect to the console.
246 :param str address: An IP address with optional port. By default, the port is 5199.
248 .. function:: delta()
250 Issuing `delta` on the console will print the changes to the configuration that have been made since startup.
252 .. function:: inClientStartup()
254 Returns true while the console client is parsing the configuration.
256 .. function:: inConfigCheck()
258 .. versionadded:: 1.5.0
260 Returns true while the configuration is being checked, ie when run with ``--check-config``.
262 .. function:: makeKey()
264 Generate and print an encryption key.
266 .. function:: setConsoleConnectionsLogging(enabled)
268 Whether to log the opening and closing of console connections.
270 :param bool enabled: Default to true.
272 .. function:: setConsoleMaximumConcurrentConnections(max)
274 .. versionadded:: 1.6.0
276 Set the maximum number of concurrent console connections.
278 :param int max: The maximum number of concurrent console connections, or 0 which means an unlimited number. Defaults to 100
280 .. function:: setKey(key)
282 Use ``key`` as shared secret between the client and the server
284 :param str key: An encoded key, as generated by :func:`makeKey`
286 .. function:: setConsoleACL(netmasks)
288 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
289 has been enabled with :func:`setKey` before doing so.
291 :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.
293 .. function:: showConsoleACL()
295 Print a list of all netmasks allowed to connect to the console.
297 .. function:: testCrypto()
299 Test the crypto code, will report errors when something is not ok.
301 .. function:: setConsoleOutputMaxMsgSize(size)
303 Set the maximum size in bytes of a single console message, default set to 10 MB.
305 :param int size: The new maximum size.
307 Webserver configuration
308 ~~~~~~~~~~~~~~~~~~~~~~~
310 .. function:: hashPassword(password [, workFactor])
312 .. versionadded:: 1.7.0
314 Hash the supplied password using a random salt, and returns a string that can be used with :func:`setWebserverConfig`.
316 :param string - password: The password to hash
317 :param int - workFactor: The work factor to use for the hash function (currently scrypt), as a power of two. Default is 1024.
319 .. function:: webserver(listen_address [, password[, apikey[, customHeaders[, acl]]]])
321 .. versionchanged:: 1.5.0
322 ``acl`` optional parameter added.
324 .. versionchanged:: 1.6.0
325 The ``password`` parameter is now optional.
326 The use of optional parameters is now deprecated. Please use :func:`setWebserverConfig` instead.
328 .. versionchanged:: 1.7.0
329 The ``password``, ``apikey``, ``customHeaders`` and ``acl`` parameters is no longer supported.
330 Please use :func:`setWebserverConfig` instead.
332 Launch the :doc:`../guides/webserver` with statistics and the API. Note that the parameters are global, so the parameter from the last ``webserver`` will override any existing ones. For this reason :func:`setWebserverConfig` should be used instead of specifying optional parameters here.
334 :param str listen_address: The IP address and Port to listen on
335 :param str password: The password required to access the webserver
336 :param str apikey: The key required to access the API
337 :param {[str]=str,...} customHeaders: Allows setting custom headers and removing the defaults
338 :param str acl: List of netmasks, as a string, that are allowed to open a connection to the web server. Defaults to "127.0.0.1, ::1". It accepts the same syntax that :func:`NetmaskGroup:addMask` does
340 .. function:: setAPIWritable(allow [,dir])
342 Allow modifications via the API.
343 Optionally saving these changes to disk.
344 Modifications done via the API will not be written to the configuration by default and will not persist after a reload
346 :param bool allow: Set to true to allow modification through the API
347 :param str dir: A valid directory where the configuration files will be written by the API.
349 .. function:: setWebserverConfig(options)
351 .. versionchanged:: 1.5.0
352 ``acl`` optional parameter added.
354 .. versionchanged:: 1.6.0
355 ``statsRequireAuthentication``, ``maxConcurrentConnections`` optional parameters added.
357 .. versionchanged:: 1.7.0
358 The optional ``password`` and ``apiKey`` parameters now accept hashed passwords.
359 The optional ``hashPlaintextCredentials`` parameter has been added.
361 .. versionchanged:: 1.6.0
362 ``apiRequiresAuthentication`` optional parameters added.
364 Setup webserver configuration. See :func:`webserver`.
366 :param table options: A table with key: value pairs with webserver options.
370 * ``password=newPassword``: string - Set the password used to access the internal webserver. Since 1.7.0 the password should be hashed and salted via the :func:`hashPassword` command.
371 * ``apiKey=newKey``: string - Changes the API Key (set to an empty string do disable it). Since 1.7.0 the key should be hashed and salted via the :func:`hashPassword` command.
372 * ``customHeaders={[str]=str,...}``: map of string - Allows setting custom headers and removing the defaults.
373 * ``acl=newACL``: string - List of IP addresses, as a string, that are allowed to open a connection to the web server. Defaults to "127.0.0.1, ::1".
374 * ``apiRequiresAuthentication``: bool - Whether access to the API (/api endpoints) require a valid API key. Defaults to true.
375 * ``statsRequireAuthentication``: bool - Whether access to the statistics (/metrics and /jsonstat endpoints) require a valid password or API key. Defaults to true.
376 * ``maxConcurrentConnections``: int - The maximum number of concurrent web connections, or 0 which means an unlimited number. Defaults to 100.
377 * ``hashPlaintextCredentials``: bool - Whether passwords and API keys provided in plaintext should be hashed during startup, to prevent the plaintext versions from staying in memory. Doing so increases significantly the cost of verifying credentials. Defaults to false.
379 .. function:: registerWebHandler(path, handler)
381 .. versionadded: 1.6.0
383 Register a function named ``handler`` that will be called for every query sent to the exact ``path`` path. The function will receive a :class:`WebRequest` object
384 and a :class:`WebResponse` object, representing respectively the HTTP request received and the HTTP response to send.
385 For example a handler registered for '/foo' will receive these queries:
389 - ``GET /foo?param=1``
391 But not queries for /foobar or /foo/bar.
393 A sample handler function could be:
397 function customHTTPHandler(req, resp)
398 local get = req.getvars
399 local headers = req.headers
401 if req.path ~= '/foo' or req.version ~= 11 or req.method ~= 'GET' or get['param'] ~= '42' or headers['custom'] ~= 'foobar' then
407 resp.body = 'It works!'
408 resp.headers = { ['Foo']='Bar'}
411 registerWebHandler('/foo', customHTTPHandler)
413 :param str path: Path to register the handler for.
414 :param function handler: The Lua function to register.
416 .. function:: showWebserverConfig()
418 .. versionadded:: 1.7.0
420 Show the current webserver configuration. See :func:`webserver`.
426 .. function:: addACL(netmask)
428 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.
430 :param str netmask: A CIDR netmask, e.g. ``"192.0.2.0/24"``. Without a subnetmask, only the specific address is allowed.
432 .. function:: rmACL(netmask)
434 Remove a network from the existing ACL controlling which clients can send UDP, TCP, DNS over TLS and DNS over HTTPS queries. See :ref:`ACL` for more information.
435 This function only removes previously added entries, it does not remove subnets of entries.
437 :param str netmask: A CIDR netmask, e.g. ``"192.0.2.0/24"``. Without a subnetmask, only the specific address is allowed.
441 addACL("192.0.2.0/24") -- for example add subnet to the ACL
442 rmACL("192.0.2.10") -- does NOT work, the ACL is unchanged
443 rmACL("192.0.2.0/24") -- does work, the exact match is removed from the ACL
445 .. function:: setACL(netmasks)
447 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.
449 :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.
451 .. function:: setACLFromFile(fname)
453 .. versionadded:: 1.6.0
455 Reset the ACL to the list of netmasks from the given file. See :ref:`ACL` for more information.
457 :param str fname: The path to a file containing a list of netmasks. Empty lines or lines starting with "#" are ignored.
459 .. function:: setProxyProtocolACL(netmasks)
461 .. versionadded:: 1.6.0
463 Set the list of netmasks from which a Proxy Protocol header will be accepted, over UDP, TCP and DNS over TLS. The default is empty. Note that, if :func:`setProxyProtocolApplyACLToProxiedClients` is set (default is false), the general ACL will be applied to the source IP address as seen by dnsdist first, but also to the source IP address provided in the Proxy Protocol header.
465 :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.
467 .. function:: setProxyProtocolApplyACL(apply)
469 .. versionadded:: 1.6.0
471 Whether the general ACL should be applied to the source IP address provided in the Proxy Protocol header, in addition to being applied to the source IP address as seen by dnsdist first.
473 :param bool apply: Whether it should be applied or not (default is false).
475 .. function:: showACL()
477 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.
482 .. function:: setECSOverride(bool)
484 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.
485 Note that it's not recommended to enable ``setECSOverride`` in front of an authoritative server responding with EDNS Client Subnet information as mismatching data (ECS scopes) can confuse clients and lead to SERVFAIL responses on downstream nameservers.
487 :param bool: Whether to override an existing EDNS Client Subnet option present in the query. Defaults to false
489 .. function:: setECSSourcePrefixV4(prefix)
491 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
493 :param int prefix: The prefix length
495 .. function:: setECSSourcePrefixV6(prefix)
497 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
499 :param int prefix: The prefix length
504 .. function:: setRingBuffersLockRetries(num)
506 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
508 :param int num: The maximum number of attempts. Defaults to 5 if there is more than one shard, 0 otherwise.
510 .. function:: setRingBuffersSize(num [, numberOfShards])
512 .. versionchanged:: 1.6.0
513 ``numberOfShards`` defaults to 10.
515 Set the capacity of the ringbuffers used for live traffic inspection to ``num``, and the number of shards to ``numberOfShards`` if specified.
516 Increasing the number of entries comes at both a memory cost (around 250 MB for 1 million entries) and a CPU processing cost, so we strongly advise not going over 1 million entries.
518 :param int num: The maximum amount of queries to keep in the ringbuffer. Defaults to 10000
519 :param int numberOfShards: the number of shards to use to limit lock contention. Default is 10, used to be 1 before 1.6.0
524 .. function:: newServer(server_string)
525 newServer(server_table)
527 .. versionchanged:: 1.4.0
528 Added ``checkInterval``, ``checkTimeout`` and ``rise`` to server_table.
530 .. versionchanged:: 1.5.0
531 Added ``useProxyProtocol`` to server_table.
533 .. versionchanged:: 1.6.0
534 Added ``maxInFlight`` to server_table.
536 .. versionchanged:: 1.7.0
537 Added ``addXForwardedHeaders``, ``caStore``, ``checkTCP``, ``ciphers``, ``ciphers13``, ``dohPath``, ``enableRenegotiation``, ``releaseBuffers``, ``subjectName``, ``tcpOnly``, ``tls`` and ``validateCertificates`` to server_table.
539 .. versionchanged:: 1.8.0
540 Added ``autoUpgrade``, ``autoUpgradeDoHKey``, ``autoUpgradeInterval``, ``autoUpgradeKeep``, ``autoUpgradePool`` and ``subjectAddr`` to server_table.
542 Add a new backend server. Call this function with either a string::
545 "IP:PORT" -- IP and PORT of the backend server
551 address="IP:PORT", -- IP and PORT of the backend server (mandatory)
552 id=STRING, -- Use a pre-defined UUID instead of a random one
553 qps=NUM, -- Limit the number of queries per second to NUM, when using the `firstAvailable` policy
554 order=NUM, -- The order of this server, used by the `leastOutstanding` and `firstAvailable` policies
555 weight=NUM, -- The weight of this server, used by the `wrandom`, `whashed` and `chashed` policies, default: 1
556 -- Supported values are a minimum of 1, and a maximum of 2147483647.
557 pool=STRING|{STRING}, -- The pools this server belongs to (unset or empty string means default pool) as a string or table of strings
558 retries=NUM, -- The number of TCP connection attempts to the backend, for a given query
559 tcpConnectTimeout=NUM, -- The timeout (in seconds) of a TCP connection attempt
560 tcpSendTimeout=NUM, -- The timeout (in seconds) of a TCP write attempt
561 tcpRecvTimeout=NUM, -- The timeout (in seconds) of a TCP read attempt
562 tcpFastOpen=BOOL, -- Whether to enable TCP Fast Open
563 ipBindAddrNoPort=BOOL, -- Whether to enable IP_BIND_ADDRESS_NO_PORT if available, default: true
564 name=STRING, -- The name associated to this backend, for display purpose
565 checkClass=NUM, -- Use NUM as QCLASS in the health-check query, default: DNSClass.IN
566 checkName=STRING, -- Use STRING as QNAME in the health-check query, default: "a.root-servers.net."
567 checkType=STRING, -- Use STRING as QTYPE in the health-check query, default: "A"
568 checkFunction=FUNCTION, -- Use this function to dynamically set the QNAME, QTYPE and QCLASS to use in the health-check query (see :ref:`Healthcheck`)
569 checkTimeout=NUM, -- The timeout (in milliseconds) of a health-check query, default: 1000 (1s)
570 setCD=BOOL, -- Set the CD (Checking Disabled) flag in the health-check query, default: false
571 maxCheckFailures=NUM, -- Allow NUM check failures before declaring the backend down, default: 1
572 checkInterval=NUM -- The time in seconds between health checks
573 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
574 useClientSubnet=BOOL, -- Add the client's IP address in the EDNS Client Subnet option when forwarding the query to this backend
575 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
576 -- The following formats are supported:
577 -- "address", e.g. "192.0.2.2"
578 -- "interface name", e.g. "eth0"
579 -- "address@interface", e.g. "192.0.2.2@eth0"
580 addXPF=NUM, -- Add the client's IP address and port to the query, along with the original destination address and port,
581 -- 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). This is a deprecated feature that will be removed in the near future.
582 sockets=NUM, -- Number of UDP sockets (and thus source ports) used toward the backend server, defaults to a single one. Note that for backends which are multithreaded, this setting will have an effect on the number of cores that will be used to process traffic from dnsdist. For example you may want to set 'sockets' to a number somewhat higher than the number of worker threads configured in the backend, particularly if the Linux kernel is being used to distribute traffic to multiple threads listening on the same socket (via `reuseport`).
583 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. This requires the ``parseECS`` option of the corresponding cache to be set to true
584 rise=NUM, -- Require NUM consecutive successful checks before declaring the backend up, default: 1
585 useProxyProtocol=BOOL, -- Add a proxy protocol header to the query, passing along the client's IP address and port along with the original destination address and port. Default is disabled.
586 reconnectOnUp=BOOL, -- Close and reopen the sockets when a server transits from Down to Up. This helps when an interface is missing when dnsdist is started. Default is disabled.
587 maxInFlight=NUM, -- Maximum number of in-flight queries. The default is 0, which disables out-of-order processing. It should only be enabled if the backend does support out-of-order processing. As of 1.6.0, out-of-order processing needs to be enabled on the frontend as well, via :func:`addLocal` and/or :func:`addTLSLocal`. Note that out-of-order is always enabled on DoH frontends.
588 tcpOnly=BOOL, -- Always forward queries to that backend over TCP, never over UDP. Always enabled for TLS backends. Default is false.
589 checkTCP=BOOL, -- Whether to do healthcheck queries over TCP, instead of UDP. Always enabled for DNS over TLS backend. Default is false.
590 tls=STRING, -- Enable DNS over TLS communications for this backend, or DNS over HTTPS if ``dohPath`` is set, using the TLS provider ("openssl" or "gnutls") passed in parameter. Default is an empty string, which means this backend is used for plain UDP and TCP.
591 caStore=STRING, -- Specifies the path to the CA certificate file, in PEM format, to use to check the certificate presented by the backend. Default is an empty string, which means to use the system CA store. Note that this directive is only used if ``validateCertificates`` is set.
592 ciphers=STRING, -- The TLS ciphers to use. The exact format depends on the provider used. When the OpenSSL provider is used, ciphers for TLS 1.3 must be specified via ``ciphersTLS13``.
593 ciphersTLS13=STRING, -- 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.
594 subjectName=STRING, -- The subject name passed in the SNI value of the TLS handshake, and against which to validate the certificate presented by the backend. Default is empty. If set this value supersedes any ``subjectAddr`` one.
595 subjectAddr=STRING, -- The subject IP address passed in the SNI value of the TLS handshake, and against which to validate the certificate presented by the backend. Default is empty.
596 validateCertificates=BOOL,-- Whether the certificate presented by the backend should be validated against the CA store (see ``caStore``). Default is true.
597 dohPath=STRING, -- Enable DNS over HTTPS communication for this backend, using POST queries to the HTTP host supplied as ``subjectName`` and the HTTP path supplied in this parameter.
598 addXForwardedHeaders=BOOL,-- Whether to add X-Forwarded-For, X-Forwarded-Port and X-Forwarded-Proto headers to a DNS over HTTPS backend.
599 releaseBuffers=BOOL, -- Whether OpenSSL should release its I/O buffers when a connection goes idle, saving roughly 35 kB of memory per connection. Default to true.
600 enableRenegotiation=BOOL, -- Whether secure TLS renegotiation should be enabled. Disabled by default since it increases the attack surface and is seldom used for DNS.
601 autoUpgrade=BOOL, -- Whether to use the 'Discovery of Designated Resolvers' mechanism to automatically upgrade a Do53 backend to DoT or DoH, depending on the priorities present in the SVCB record returned by the backend. Default to false.
602 autoUpgradeInterval=NUM, -- If ``autoUpgrade`` is set, how often to check if an upgrade is available, in seconds. Default is 3600 seconds.
603 autoUpgradeKeep=BOOL, -- If ``autoUpgrade`` is set, whether to keep the existing Do53 backend around after an upgrade. Default is false which means the Do53 backend will be replaced by the upgraded one.
604 autoUpgradePool=STRING, -- If ``autoUpgrade`` is set, in which pool to place the newly upgraded backend. Default is empty which means the backend is placed in the default pool.
605 autoUpgradeDoHKey=NUM -- If ``autoUpgrade`` is set, the value to use for the SVC key corresponding to the DoH path. Default is 7.
608 :param str server_string: A simple IP:PORT string.
609 :param table server_table: A table with at least a 'name' key
611 .. function:: getServer(index) -> Server
613 .. versionchanged:: 1.5.0
614 ``index`` might be an UUID.
616 Get a :class:`Server`
618 :param int or str index: The number of the server (as seen in :func:`showServers`) or its UUID as a string.
619 :returns: The :class:`Server` object or nil
621 .. function:: getServers()
623 Returns a table with all defined servers.
625 .. function:: rmServer(index)
629 .. versionchanged:: 1.5.0
630 ``uuid`` selection added.
632 Remove a backend server.
634 :param int or str index: The number of the server (as seen in :func:`showServers`), its UUID as a string, or a server object.
635 :param Server server: A :class:`Server` object as returned by e.g. :func:`getServer`.
639 A server object returned by :func:`getServer` can be manipulated with these functions.
643 This object represents a backend server. It has several methods.
645 .. method:: Server:addPool(pool)
647 Add this server to a pool.
649 :param str pool: The pool to add the server to
651 .. method:: Server:getLatency() -> double
653 .. versionadded:: 1.6.0
655 Return the average latency of this server over the last 128 UDP queries, in microseconds.
657 :returns: The number of outstanding queries
659 .. method:: Server:getName() -> string
661 Get the name of this server.
663 :returns: The name of the server, or an empty string if it does not have one
665 .. method:: Server:getNameWithAddr() -> string
667 Get the name plus IP address and port of the server
669 :returns: A string containing the server name if any plus the server address and port
671 .. method:: Server:getDrops() -> int
673 .. versionadded:: 1.6.0
675 Get the number of dropped queries for this server.
677 :returns: The number of dropped queries
679 .. method:: Server:getOutstanding() -> int
681 Get the number of outstanding queries for this server.
683 :returns: The number of outstanding queries
685 .. method:: Server:isUp() -> bool
687 Returns the up status of the server
689 :returns: true when the server is up, false otherwise
691 .. method:: Server:rmPool(pool)
693 Removes the server from the named pool
695 :param str pool: The pool to remove the server from
697 .. method:: Server:setAuto([status])
699 Set the server in the default auto state.
700 This will enable health check queries that will set the server ``up`` and ``down`` appropriately.
702 :param bool status: Set the initial status of the server to ``up`` (true) or ``down`` (false) instead of using the last known status
704 .. method:: Server:setQPS(limit)
706 Limit the queries per second for this server.
708 :param int limit: The maximum number of queries per second
710 .. method:: Server:setDown()
712 Set the server in an ``DOWN`` state.
713 The server will not receive queries and the health checks are disabled
715 .. method:: Server:setUp()
717 Set the server in an ``UP`` state.
718 This server will still receive queries and health checks are disabled
720 Apart from the functions, a :class:`Server` object has these attributes:
722 .. attribute:: Server.name
724 The name of the server
726 .. attribute:: Server.upStatus
728 Whether or not this server is up or down
730 .. attribute:: Server.order
732 The order of the server
734 .. attribute:: Server.weight
736 The weight of the server
741 :class:`Server`\ s can be part of any number of pools.
742 Pools are automatically created when a server is added to a pool (with :func:`newServer`), or can be manually created with :func:`getPool`.
743 Servers that are not assigned to a specific pool get assigned to the default pool that is always present, identified by the empty string ``''``.
745 .. function:: getPool(name) -> ServerPool
747 Returns a :class:`ServerPool`. If the pool does not exist yet, it is created.
749 :param string name: The name of the pool
751 .. function:: getPoolServers(name) -> [ Server ]
753 Returns a list of :class:`Server`\ s or nil.
755 :param string name: The name of the pool
757 .. function:: showPools()
759 Display the name, associated cache, server policy and associated servers for every pool.
761 .. class:: ServerPool
763 This represents the pool where zero or more servers are part of.
765 .. method:: ServerPool:getCache() -> PacketCache
767 Returns the :class:`PacketCache` for this pool or nil.
769 .. method:: ServerPool:getECS()
771 Whether dnsdist will add EDNS Client Subnet information to the query before looking up into the cache,
772 when all servers from this pool are down. For more information see :meth:`ServerPool:setECS`.
774 .. method:: ServerPool:setCache(cache)
776 Adds ``cache`` as the pool's cache.
778 :param PacketCache cache: The new cache to add to the pool
780 .. method:: ServerPool:unsetCache()
782 Removes the cache from this pool.
784 .. method:: ServerPool:setECS()
786 Set to true if dnsdist should add EDNS Client Subnet information to the query before looking up into the cache,
787 when all servers from this pool are down. If at least one server is up, the preference of the
788 selected server is used, this parameter is only useful if all the backends in this pool are down
789 and have EDNS Client Subnet enabled, since the queries in the cache will have been inserted with
790 ECS information. Default is false.
795 A Pool can have a packet cache to answer queries directly instead of going to the backend.
796 See :doc:`../guides/cache` for a how to.
798 .. function:: newPacketCache(maxEntries[, maxTTL=86400[, minTTL=0[, temporaryFailureTTL=60[, staleTTL=60[, dontAge=false[, numberOfShards=1[, deferrableInsertLock=true[, maxNegativeTTL=3600[, parseECS=false]]]]]]]) -> PacketCache
800 .. deprecated:: 1.4.0
802 Creates a new :class:`PacketCache` with the settings specified.
804 :param int maxEntries: The maximum number of entries in this cache
805 :param int maxTTL: Cap the TTL for records to his number
806 :param int minTTL: Don't cache entries with a TTL lower than this
807 :param int temporaryFailureTTL: On a SERVFAIL or REFUSED from the backend, cache for this amount of seconds
808 :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
809 :param bool dontAge: Don't reduce TTLs when serving from the cache. Use this when :program:`dnsdist` fronts a cluster of authoritative servers
810 :param int numberOfShards: Number of shards to divide the cache into, to reduce lock contention
811 :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
812 :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
813 :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
815 .. function:: newPacketCache(maxEntries, [options]) -> PacketCache
817 .. versionadded:: 1.4.0
819 .. versionchanged:: 1.6.0
820 ``cookieHashing`` parameter added.
821 ``numberOfShards`` now defaults to 20.
823 .. versionchanged:: 1.7.0
824 ``skipOptions`` parameter added.
826 Creates a new :class:`PacketCache` with the settings specified.
828 :param int maxEntries: The maximum number of entries in this cache
832 * ``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.
833 * ``dontAge=false``: bool - Don't reduce TTLs when serving from the cache. Use this when :program:`dnsdist` fronts a cluster of authoritative servers.
834 * ``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.
835 * ``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.
836 * ``maxTTL=86400``: int - Cap the TTL for records to his number.
837 * ``minTTL=0``: int - Don't cache entries with a TTL lower than this.
838 * ``numberOfShards=20``: int - Number of shards to divide the cache into, to reduce lock contention. Used to be 1 (no shards) before 1.6.0, and is now 20.
839 * ``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. Enabling this option is required for the 'zero scope' option to work
840 * ``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.
841 * ``temporaryFailureTTL=60``: int - On a SERVFAIL or REFUSED from the backend, cache for this amount of seconds..
842 * ``cookieHashing=false``: bool - Whether EDNS Cookie values will be hashed, resulting in separate entries for different cookies in the packet cache. This is required if the backend is sending answers with EDNS Cookies, otherwise a client might receive an answer with the wrong cookie.
843 * ``skipOptions={}``: Extra list of EDNS option codes to skip when hashing the packet (if ``cookieHashing`` above is false, EDNS cookie option number will already be added to this list).
845 .. class:: PacketCache
847 Represents a cache that can be part of :class:`ServerPool`.
849 .. method:: PacketCache:dump(fname)
851 Dump a summary of the cache entries to a file.
853 :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.
855 .. method:: PacketCache:expunge(n)
857 Remove entries from the cache, leaving at most ``n`` entries
859 :param int n: Number of entries to keep
861 .. method:: PacketCache:expungeByName(name [, qtype=DNSQType.ANY[, suffixMatch=false]])
863 .. versionchanged:: 1.6.0
864 ``name`` can now also be a string
866 Remove entries matching ``name`` and type from the cache.
868 :param DNSName name: The name to expunge
869 :param int qtype: The type to expunge, can be a pre-defined :ref:`DNSQType`
870 :param bool suffixMatch: When set to true, remove all entries under ``name``
872 .. method:: PacketCache:getStats()
874 .. versionadded:: 1.4.0
876 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.
878 .. method:: PacketCache:isFull() -> bool
880 Return true if the cache has reached the maximum number of entries.
882 .. method:: PacketCache:printStats()
884 Print the cache stats (number of entries, hits, misses, deferred lookups, deferred inserts, lookup collisions, insert collisions and TTL too shorts).
886 .. method:: PacketCache:purgeExpired(n)
888 Remove expired entries from the cache until there is at most ``n`` entries remaining in the cache.
890 :param int n: Number of entries to keep
892 .. method:: PacketCache:toString() -> string
894 Return the number of entries in the Packet Cache, and the maximum number of entries
899 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.
901 .. function:: getBind(index) -> ClientState
903 Return a :class:`ClientState` object.
905 :param int index: The object index
907 .. function:: getBindCount()
909 .. versionadded:: 1.5.0
911 Return the number of binds (Do53, DNSCrypt, DoH and DoT).
913 ClientState functions
914 ~~~~~~~~~~~~~~~~~~~~~
916 .. class:: ClientState
918 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.
920 .. method:: ClientState:attachFilter(filter)
922 Attach a BPF filter to this frontend.
924 :param BPFFilter filter: The filter to attach to this frontend
926 .. method:: ClientState:detachFilter()
928 Remove the BPF filter associated to this frontend, if any.
930 .. method:: ClientState:getEffectiveTLSProvider() -> string
932 .. versionadded:: 1.7.0
934 Return the name of the TLS provider actually used.
936 .. method:: ClientState:getRequestedTLSProvider() -> string
938 .. versionadded:: 1.7.0
940 Return the name of the TLS provider requested in the configuration.
942 .. method:: ClientState:getType() -> string
944 .. versionadded:: 1.7.0
946 Return the type of the frontend: UDP, UDP (DNSCrypt), TCP, TCP (DNSCrypt), TCP (DNS over TLS) or TCP (DNS over HTTPS).
948 .. method:: ClientState:toString() -> string
950 Return the address and port this frontend is listening on.
952 :returns: The address and port this frontend is listening on
954 .. attribute:: ClientState.muted
956 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.
958 Status, Statistics and More
959 ---------------------------
961 .. function:: dumpStats()
963 Print all statistics dnsdist gathers
965 .. function:: getDOHFrontend(idx)
967 .. versionadded:: 1.4.0
969 Return the DOHFrontend object for the DNS over HTTPS bind of index ``idx``.
971 .. function:: getDOHFrontendCount()
973 .. versionadded:: 1.5.0
975 Return the number of DOHFrontend binds.
977 .. function:: getListOfAddressesOfNetworkInterface(itf)
979 .. versionadded:: 1.8.0
981 Return the list of addresses configured on a given network interface, as strings.
982 This function requires support for ``getifaddrs``, which is known to be present on FreeBSD, Linux, and OpenBSD at least.
984 :param str itf: The name of the network interface
986 .. function:: getListOfNetworkInterfaces()
988 .. versionadded:: 1.8.0
990 Return the list of network interfaces configured on the system, as strings.
991 This function requires support for ``getifaddrs``, which is known to be present on FreeBSD, Linux, and OpenBSD at least.
993 .. function:: getMACAddress(ip) -> str
995 .. versionadded:: 1.8.0
997 Return the link-level address (MAC) corresponding to the supplied neighbour IP address, if known by the kernel.
998 The link-level address is returned as a raw binary string. An empty string is returned if no matching entry has been found.
999 This function is only implemented on Linux.
1001 :param str ip: The IP address, IPv4 or IPv6, to look up the corresponding link-level address for.
1003 .. function:: getOutgoingTLSSessionCacheSize()
1005 .. versionadded:: 1.7.0
1007 Return the number of TLS sessions (for outgoing connections) currently cached.
1009 .. function:: getTLSContext(idx)
1011 Return the TLSContext object for the context of index ``idx``.
1013 .. function:: getTLSFrontend(idx)
1015 Return the TLSFrontend object for the TLS bind of index ``idx``.
1017 .. function:: getTLSFrontendCount()
1019 .. versionadded:: 1.5.0
1021 Return the number of TLSFrontend binds.
1023 .. function:: getTopCacheHitResponseRules([top])
1025 .. versionadded:: 1.6.0
1027 Return the cache-hit response rules that matched the most.
1029 :param int top: How many response rules to return.
1031 .. function:: getTopResponseRules([top])
1033 .. versionadded:: 1.6.0
1035 Return the response rules that matched the most.
1037 :param int top: How many response rules to return.
1039 .. function:: getTopRules([top])
1041 .. versionadded:: 1.6.0
1043 Return the rules that matched the most.
1045 :param int top: How many rules to return.
1047 .. function:: getTopSelfAnsweredRules([top])
1049 .. versionadded:: 1.6.0
1051 Return the self-answered rules that matched the most.
1053 :param int top: How many rules to return.
1055 .. function:: grepq(selector[, num])
1056 grepq(selectors[, num])
1058 Prints the last ``num`` queries and responses matching ``selector`` or ``selectors``.
1059 Queries and responses are accounted in separate ring buffers, and answers from the packet cache are not stored in the response ring buffer.
1060 Therefore, the ``num`` queries and ``num`` responses in the output may not always match up.
1062 The selector can be:
1064 * a netmask (e.g. '192.0.2.0/24')
1065 * a DNS name (e.g. 'dnsdist.org')
1066 * a response time (e.g. '100ms')
1068 :param str selector: Select queries based on this property.
1069 :param {str} selectors: A lua table of selectors. Only queries matching all selectors are shown
1070 :param int num: Show a maximum of ``num`` recent queries+responses, default is 10.
1072 .. function:: setVerbose(verbose)
1074 .. versionadded:: 1.8.0
1076 Set whether log messages issued at the verbose level should be logged. This is turned off by default.
1078 :param bool verbose: Set to true if you want to enable verbose logging
1080 .. function:: getVerbose()
1082 .. versionadded:: 1.8.0
1084 Get whether log messages issued at the verbose level should be logged. This is turned off by default.
1086 .. function:: setVerboseHealthChecks(verbose)
1088 Set whether health check errors should be logged. This is turned off by default.
1090 :param bool verbose: Set to true if you want to enable health check errors logging
1092 .. function:: showBinds()
1094 Print a list of all the current addresses and ports dnsdist is listening on, also called ``frontends``
1096 .. function:: showDOHFrontends()
1098 .. versionadded:: 1.4.0
1100 Print the list of all available DNS over HTTPS frontends.
1102 .. function:: showDOHResponseCodes()
1104 .. versionadded:: 1.4.0
1106 Print the HTTP response codes statistics for all available DNS over HTTPS frontends.
1108 .. function:: showResponseLatency()
1110 Show a plot of the response time latency distribution
1112 .. function:: showServers([options])
1114 .. versionchanged:: 1.4.0
1115 ``options`` optional parameter added
1117 This function shows all backend servers currently configured and some statistics.
1118 These statics have the following fields:
1120 * ``#`` - The number of the server, can be used as the argument for :func:`getServer`
1121 * ``UUID`` - The UUID of the backend. Can be set with the ``id`` option of :func:`newServer`
1122 * ``Address`` - The IP address and port of the server
1123 * ``State`` - The current state of the server
1124 * ``Qps`` - Current number of queries per second
1125 * ``Qlim`` - Configured maximum number of queries per second
1126 * ``Ord`` - The order number of the server
1127 * ``Wt`` - The weight of the server
1128 * ``Queries`` - Total amount of queries sent to this server
1129 * ``Drops`` - Number of queries that were dropped by this server
1130 * ``Drate`` - Number of queries dropped per second by this server
1131 * ``Lat`` - The latency of this server in milliseconds
1132 * ``Pools`` - The pools this server belongs to
1134 :param table options: A table with key: value pairs with display options.
1138 * ``showUUIDs=false``: bool - Whether to display the UUIDs, defaults to false.
1140 .. function:: showTCPStats()
1142 Show some statistics regarding TCP
1144 .. function:: showTLSContexts()
1146 Print the list of all available DNS over TLS contexts.
1148 .. function:: showTLSErrorCounters()
1150 .. versionadded:: 1.4.0
1152 Display metrics about TLS handshake failures.
1154 .. function:: showVersion()
1156 Print the version of dnsdist
1158 .. function:: topBandwidth([num])
1160 Print the top ``num`` clients that consume the most bandwidth.
1162 :param int num: Number to show, defaults to 10.
1164 .. function:: topCacheHitResponseRules([top [, options]])
1166 .. versionadded:: 1.6.0
1168 This function shows the cache-hit response rules that matched the most.
1170 :param int top: How many rules to show.
1171 :param table options: A table with key: value pairs with display options.
1175 * ``showUUIDs=false``: bool - Whether to display the UUIDs, defaults to false.
1177 .. function:: topClients([num])
1179 Print the top ``num`` clients sending the most queries over length of ringbuffer
1181 :param int num: Number to show, defaults to 10.
1183 .. function:: topQueries([num[, labels]])
1185 Print the ``num`` most popular QNAMEs from queries.
1186 Optionally grouped by the rightmost ``labels`` DNS labels.
1188 :param int num: Number to show, defaults to 10
1189 :param int label: Number of labels to cut down to
1191 .. function:: topResponses([num[, rcode[, labels]]])
1193 Print the ``num`` most seen responses with an RCODE of ``rcode``.
1194 Optionally grouped by the rightmost ``labels`` DNS labels.
1196 :param int num: Number to show, defaults to 10
1197 :param int rcode: :ref:`Response code <DNSRCode>`, defaults to 0 (No Error)
1198 :param int label: Number of labels to cut down to
1200 .. function:: topResponseRules([top [, options]])
1202 .. versionadded:: 1.6.0
1204 This function shows the response rules that matched the most.
1206 :param int top: How many rules to show.
1207 :param table options: A table with key: value pairs with display options.
1211 * ``showUUIDs=false``: bool - Whether to display the UUIDs, defaults to false.
1213 .. function:: topRules([top [, options]])
1215 .. versionadded:: 1.6.0
1217 This function shows the rules that matched the most.
1219 :param int top: How many rules to show.
1220 :param table options: A table with key: value pairs with display options.
1224 * ``showUUIDs=false``: bool - Whether to display the UUIDs, defaults to false.
1226 .. function:: topSelfAnsweredResponseRules([top [, options]])
1228 .. versionadded:: 1.6.0
1230 This function shows the self-answered response rules that matched the most.
1232 :param int top: How many rules to show.
1233 :param table options: A table with key: value pairs with display options.
1237 * ``showUUIDs=false``: bool - Whether to display the UUIDs, defaults to false.
1239 .. function:: topSlow([num[, limit[, labels]]])
1241 Print the ``num`` slowest queries that are slower than ``limit`` milliseconds.
1242 Optionally grouped by the rightmost ``labels`` DNS labels.
1244 :param int num: Number to show, defaults to 10
1245 :param int limit: Show queries slower than this amount of milliseconds, defaults to 2000
1246 :param int label: Number of labels to cut down to
1253 .. function:: addDynBlocks(addresses, message[, seconds=10[, action]])
1255 Block a set of addresses with ``message`` for (optionally) a number of seconds.
1256 The default number of seconds to block for is 10.
1258 :param addresses: set of Addresses as returned by an exceed function
1259 :param string message: The message to show next to the blocks
1260 :param int seconds: The number of seconds this block to expire
1261 :param int action: The action to take when the dynamic block matches, see :ref:`DNSAction <DNSAction>`. (default to DNSAction.None, meaning the one set with :func:`setDynBlocksAction` is used)
1263 Please see the documentation for :func:`setDynBlocksAction` to confirm which actions are supported by the action paramater.
1265 .. function:: clearDynBlocks()
1267 Remove all current dynamic blocks.
1269 .. function:: showDynBlocks()
1271 List all dynamic blocks in effect.
1273 .. function:: setDynBlocksAction(action)
1275 Set which action is performed when a query is blocked.
1276 Only DNSAction.Drop (the default), DNSAction.NoOp, DNSAction.NXDomain, DNSAction.Refused, DNSAction.Truncate and DNSAction.NoRecurse are supported.
1278 .. function:: setDynBlocksPurgeInterval(sec)
1280 .. versionadded:: 1.6.0
1282 Set at which interval, in seconds, the expired dynamic blocks entries will be effectively removed from the tree. Entries are not applied anymore as
1283 soon as they expire, but they remain in the tree for a while for performance reasons. Removing them makes the addition of new entries faster and
1284 frees up the memory they use.
1285 Setting this value to 0 disable the purging mechanism, so entries will remain in the tree.
1287 :param int sec: The interval between two runs of the cleaning algorithm, in seconds. Default is 60 (1 minute), 0 means disabled.
1291 Getting addresses that exceeded parameters
1292 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1294 .. function:: exceedServFails(rate, seconds)
1296 Get set of addresses that exceed ``rate`` servfails/s over ``seconds`` seconds
1298 :param int rate: Number of Servfails per second to exceed
1299 :param int seconds: Number of seconds the rate has been exceeded
1301 .. function:: exceedNXDOMAINs(rate, seconds)
1303 get set of addresses that exceed ``rate`` NXDOMAIN/s over ``seconds`` seconds
1305 :param int rate: Number of NXDOMAIN per second to exceed
1306 :param int seconds: Number of seconds the rate has been exceeded
1308 .. function:: exceedRespByterate(rate, seconds)
1310 get set of addresses that exceeded ``rate`` bytes/s answers over ``seconds`` seconds
1312 :param int rate: Number of bytes per second to exceed
1313 :param int seconds: Number of seconds the rate has been exceeded
1315 .. function:: exceedQRate(rate, seconds)
1317 Get set of address that exceed ``rate`` queries/s over ``seconds`` seconds
1319 :param int rate: Number of queries per second to exceed
1320 :param int seconds: Number of seconds the rate has been exceeded
1322 .. function:: exceedQTypeRate(type, rate, seconds)
1324 Get set of address that exceed ``rate`` queries/s for queries of QType ``type`` over ``seconds`` seconds
1326 :param int type: QType
1327 :param int rate: Number of QType queries per second to exceed
1328 :param int seconds: Number of seconds the rate has been exceeded
1333 Instead of using several `exceed*()` lines, dnsdist 1.3.0 introduced a new `DynBlockRulesGroup` object
1334 which can be used to group dynamic block rules.
1336 See :doc:`../guides/dynblocks` for more information about the case where using a `DynBlockRulesGroup` might be
1337 faster than the existing rules.
1339 .. function:: dynBlockRulesGroup() -> DynBlockRulesGroup
1341 Creates a new :class:`DynBlockRulesGroup` object.
1343 .. class:: DynBlockRulesGroup
1345 Represents a group of dynamic block rules.
1347 .. method:: DynBlockRulesGroup:setMasks(v4, v6, port)
1349 .. versionadded:: 1.7.0
1351 Set the number of bits to keep in the IP address when inserting a block. The default is 32 for IPv4 and 128 for IPv6, meaning
1352 that only the exact address is blocked, but in some scenarios it might make sense to block a whole /64 IPv6 range instead of a
1353 single address, for example.
1354 It is also possible to take the IPv4 UDP and TCP ports into account, for CGNAT deployments, by setting the number of bits of the port
1355 to consider. For example passing 2 as the last parameter, which only makes sense if the previous parameters are respectively 32
1356 and 128, will split a given IP address into four port ranges: 0-16383, 16384-32767, 32768-49151 and 49152-65535.
1358 :param int v4: Number of bits to keep for IPv4 addresses. Default is 32
1359 :param int v6: Number of bits to keep for IPv6 addresses. Default is 128
1360 :param int port: Number of bits of port to consider over IPv4. Default is 0 meaning that the port is not taken into account
1362 .. method:: DynBlockRulesGroup:setQueryRate(rate, seconds, reason, blockingTime [, action [, warningRate]])
1364 Adds a query rate-limiting rule, equivalent to:
1366 addDynBlocks(exceedQRate(rate, seconds), reason, blockingTime, action)
1369 :param int rate: Number of queries per second to exceed
1370 :param int seconds: Number of seconds the rate has been exceeded
1371 :param string reason: The message to show next to the blocks
1372 :param int blockingTime: The number of seconds this block to expire
1373 :param int action: The action to take when the dynamic block matches, see :ref:`DNSAction <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
1374 :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
1376 .. method:: DynBlockRulesGroup:setRCodeRate(rcode, rate, seconds, reason, blockingTime [, action [, warningRate]])
1378 Adds a rate-limiting rule for responses of code ``rcode``, equivalent to:
1380 addDynBlocks(exceedServfails(rcode, rate, seconds), reason, blockingTime, action)
1383 :param int rcode: The response code
1384 :param int rate: Number of responses per second to exceed
1385 :param int seconds: Number of seconds the rate has been exceeded
1386 :param string reason: The message to show next to the blocks
1387 :param int blockingTime: The number of seconds this block to expire
1388 :param int action: The action to take when the dynamic block matches, see :ref:`DNSAction <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
1389 :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
1391 .. method:: DynBlockRulesGroup:setRCodeRatio(rcode, ratio, seconds, reason, blockingTime, minimumNumberOfResponses [, action [, warningRate]])
1393 .. versionadded:: 1.5.0
1395 Adds a rate-limiting rule for the ratio of responses of code ``rcode`` over the total number of responses for a given client.
1397 :param int rcode: The response code
1398 :param int ratio: Ratio of responses per second of the given rcode over the total number of responses for this client to exceed
1399 :param int seconds: Number of seconds the ratio has been exceeded
1400 :param string reason: The message to show next to the blocks
1401 :param int blockingTime: The number of seconds this block to expire
1402 :param int minimumNumberOfResponses: How many total responses is required for this rule to apply
1403 :param int action: The action to take when the dynamic block matches, see :ref:`DNSAction <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
1404 :param int warningRatio: If set to a non-zero value, the ratio above which a warning message will be issued and a no-op block inserted
1406 .. method:: DynBlockRulesGroup:setQTypeRate(qtype, rate, seconds, reason, blockingTime [, action [, warningRate]])
1408 Adds a rate-limiting rule for queries of type ``qtype``, equivalent to:
1410 addDynBlocks(exceedQTypeRate(type, rate, seconds), reason, blockingTime, action)
1413 :param int qtype: The qtype
1414 :param int rate: Number of queries per second to exceed
1415 :param int seconds: Number of seconds the rate has been exceeded
1416 :param string reason: The message to show next to the blocks
1417 :param int blockingTime: The number of seconds this block to expire
1418 :param int action: The action to take when the dynamic block matches, see :ref:`DNSAction <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
1419 :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
1421 .. method:: DynBlockRulesGroup:setResponseByteRate(rate, seconds, reason, blockingTime [, action [, warningRate]])
1423 Adds a bandwidth rate-limiting rule for responses, equivalent to:
1425 addDynBlocks(exceedRespByterate(rate, seconds), reason, blockingTime, action)
1428 :param int rate: Number of bytes per second to exceed
1429 :param int seconds: Number of seconds the rate has been exceeded
1430 :param string reason: The message to show next to the blocks
1431 :param int blockingTime: The number of seconds this block to expire
1432 :param int action: The action to take when the dynamic block matches, see :ref:`DNSAction <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
1433 :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
1435 .. method:: DynBlockRulesGroup:setSuffixMatchRule(seconds, reason, blockingTime, action , visitor)
1437 .. versionadded:: 1.4.0
1439 .. versionchanged:: 1.7.0
1440 This visitor function can now optionally return an additional string which will be set as the ``reason`` for the dynamic block.
1442 Set a Lua visitor function that will be called for each label of every domain seen in queries and responses. The function receives a `StatNode` object representing the stats of the parent, a second one with the stats of the current label and one with the stats of the current node plus all its children.
1443 Note that this function will not be called if a FFI version has been set using :meth:`DynBlockRulesGroup:setSuffixMatchRuleFFI`
1444 If the function returns true, the current label will be blocked according to the `seconds`, `reason`, `blockingTime` and `action` parameters. Since 1.7.0, the function can return an additional string, in addition to the boolean, which will be set as the ``reason`` for the dynamic block.
1445 Selected domains can be excluded from this processing using the :meth:`DynBlockRulesGroup:excludeDomains` method.
1447 This replaces the existing :func:`addDynBlockSMT` function.
1449 :param int seconds: Number of seconds the rate has been exceeded
1450 :param string reason: The message to show next to the blocks
1451 :param int blockingTime: The number of seconds this block to expire
1452 :param int action: The action to take when the dynamic block matches, see :ref:`DNSAction <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
1453 :param function visitor: The Lua function to call.
1455 .. method:: DynBlockRulesGroup:setSuffixMatchRuleFFI(seconds, reason, blockingTime, action , visitor)
1457 .. versionadded:: 1.4.0
1459 Set a Lua FFI visitor function that will be called for each label of every domain seen in queries and responses. The function receives a `dnsdist_ffi_stat_node_t` object containing the stats of the parent, a second one with the stats of the current label and one with the stats of the current node plus all its children.
1460 If the function returns true, the current label will be blocked according to the `seconds`, `reason`, `blockingTime` and `action` parameters.
1461 Selected domains can be excluded from this processing using the :meth:`DynBlockRulesGroup:excludeDomains` method.
1463 :param int seconds: Number of seconds the rate has been exceeded
1464 :param string reason: The message to show next to the blocks
1465 :param int blockingTime: The number of seconds this block to expire
1466 :param int action: The action to take when the dynamic block matches, see :ref:`DNSAction <DNSAction>`. (default to the one set with :func:`setDynBlocksAction`)
1467 :param function visitor: The Lua FFI function to call.
1469 .. method:: DynBlockRulesGroup:apply()
1471 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.
1473 .. method:: DynBlockRulesGroup:setQuiet(quiet)
1475 .. versionadded:: 1.4.0
1477 Set whether newly blocked clients or domains should be logged.
1479 :param bool quiet: True means that insertions will not be logged, false that they will. Default is false.
1481 .. method:: DynBlockRulesGroup:excludeDomains(domains)
1483 .. versionadded:: 1.4.0
1485 Exclude this domain, or list of domains, meaning that no dynamic block will ever be inserted for this domain via :meth:`DynBlockRulesGroup:setSuffixMatchRule` or :meth:`DynBlockRulesGroup:setSuffixMatchRuleFFI`. Default to empty, meaning rules are applied to all domains.
1487 :param str domain: A domain, or list of domains, as strings, like for example "powerdns.com"
1489 .. method:: DynBlockRulesGroup:excludeRange(netmasks)
1491 .. versionchanged:: 1.6.0
1492 This method now accepts a :class:`NetmaskGroup` object.
1494 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.
1496 :param list netmasks: A :class:`NetmaskGroup` object, or a netmask or list of netmasks as strings, like for example "192.0.2.1/24"
1498 .. method:: DynBlockRulesGroup:includeRange(netmasks)
1500 .. versionchanged:: 1.6.0
1501 This method now accepts a :class:`NetmaskGroup` object.
1503 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.
1505 :param list netmasks: A :class:`NetmaskGroup` object, or a netmask or list of netmasks as strings, like for example "192.0.2.1/24"
1507 .. method:: DynBlockRulesGroup:toString()
1509 Return a string describing the rules and range exclusions of this DynBlockRulesGroup.
1516 Represent metrics about a given node, for the visitor functions used with :meth:`DynBlockRulesGroup:setSuffixMatchRule` and :meth:`DynBlockRulesGroup:setSuffixMatchRuleFFI`. Note that some nodes includes the metrics for their children as well as their own.
1518 .. attribute:: StatNode.bytes
1520 The number of bytes for all responses returned for that node.
1522 .. attribute:: StatNode.drops
1524 The number of drops for that node.
1526 .. attribute:: StatNode.fullname
1528 The complete name of that node, ie 'www.powerdns.com'.
1530 .. attribute:: StatNode.labelsCount
1532 The number of labels in that node, for example 3 for 'www.powerdns.com'.
1534 .. attribute:: StatNode.noerrors
1536 The number of No Error answers returned for that node.
1538 .. attribute:: StatNode.nxdomains
1540 The number of NXDomain answers returned for that node.
1542 .. attribute:: StatNode.queries
1544 The number of queries for that node.
1546 .. attribute:: StatNode.servfails
1548 The number of Server Failure answers returned for that node.
1550 .. method:: StatNode:numChildren
1552 The number of children of that node.
1557 A SuffixMatchNode can be used to quickly check whether a given name belongs to a set or not. This is achieved
1558 using an efficient tree structure based on DNS labels, making lookups cheap.
1559 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,
1560 if 'example.com.' is added to the set, 'www.example.com.' and 'sub.www.example.com.' will match as well.
1561 If you are looking for exact name matching, your might want to consider using a :class:`DNSNameSet` instead.
1563 .. function:: newSuffixMatchNode()
1565 Creates a new :class:`SuffixMatchNode`.
1567 .. class:: SuffixMatchNode
1569 Represent a set of DNS suffixes for quick matching.
1571 .. method:: SuffixMatchNode:add(name)
1573 .. versionchanged:: 1.4.0
1574 This method now accepts strings, lists of DNSNames and lists of strings.
1576 Add a suffix to the current set.
1578 :param DNSName name: The suffix to add to the set.
1579 :param string name: The suffix to add to the set.
1580 :param table name: The suffixes to add to the set. Elements of the table should be of the same type, either DNSName or string.
1582 .. method:: SuffixMatchNode:remove(name)
1584 .. versionadded:: 1.5.0
1586 Remove a suffix from the current set.
1588 :param DNSName name: The suffix to remove from the set.
1589 :param string name: The suffix to remove from the set.
1590 :param table name: The suffixes to remove from the set. Elements of the table should be of the same type, either DNSName or string.
1592 .. method:: SuffixMatchNode:check(name) -> bool
1594 Return true if the given name is a sub-domain of one of those in the set, and false otherwise.
1596 :param DNSName name: The name to test against the set.
1598 Outgoing TLS tickets cache management
1599 -------------------------------------
1601 Since 1.7, dnsdist supports securing the connection toward backends using DNS over TLS. For these connections, it keeps a cache of TLS tickets to be able to resume a TLS session quickly. By default that cache contains up to 20 TLS tickets per-backend, is cleaned up every every 60s, and TLS tickets expire if they have not been used after 600 seconds.
1602 These values can be set at configuration time via:
1604 .. function:: setOutgoingTLSSessionsCacheMaxTicketsPerBackend(num)
1606 .. versionadded: 1.7.0
1608 Set the maximum number of TLS tickets to keep, per-backend, to be able to quickly resume outgoing TLS connections to a backend. Keeping more tickets might provide a better TLS session resumption rate if there is a sudden peak of outgoing connections, at the cost of using a bit more memory.
1610 :param int num: The number of TLS tickets to keep, per-backend. The default is 20.
1612 .. function:: setOutgoingTLSSessionsCacheCleanupDelay(delay)
1614 .. versionadded: 1.7.0
1616 Set the number of seconds between two scans of the TLS sessions cache, removing expired tickets and freeing up memory. Decreasing that value will lead to more scans, freeing up memory more quickly but using a bit more CPU doing so.
1618 :param int delay: The number of seconds between two scans of the cache. The default is 60.
1620 .. function:: setOutgoingTLSSessionsCacheMaxTicketValidity(validity)
1622 .. versionadded: 1.7.0
1624 Set the number of seconds that a given TLS ticket can be kept inactive in the TLS sessions cache. After that delay the ticket will be removed during the next cleanup of the cache. Increasing that value might increase the TLS resumption rate if new connections are not often created, but it might also lead to trying to reuse a ticket that the server will consider too old and refuse.
1626 :param int validity: The number of seconds a ticket is considered valid. The default is 600, which matches the default lifetime of TLS tickets set by OpenSSL.
1631 .. function:: maintenance()
1633 If this function exists, it is called every second to do regular tasks.
1634 This can be used for e.g. :doc:`Dynamic Blocks <../guides/dynblocks>`.
1636 .. function:: threadmessage(cmd, dict)
1638 .. versionadded:: 1.7.0
1640 This function, if it exists, is called when a separate thread (made with :func:`newThread`) calls :func:`submitToMainThread`.
1642 .. function:: newThread(code)
1644 .. versionadded:: 1.7.0
1646 Spawns a separate thread running the supplied code.
1647 Code is supplied as a string, not as a function object.
1648 Note that this function does nothing in 'client' or 'config-check' modes.
1650 .. function:: submitToMainThread(cmd, dict)
1652 .. versionadded:: 1.7.0
1654 Must be called from a separate thread (made with :func:`newThread`), submits data to the main thread by calling :func:`threadmessage` in it.
1655 If no ``threadmessage`` receiver is present in the main thread, ``submitToMainThread`` logs an error but returns normally.
1657 The ``cmd`` argument is a string.
1658 The ``dict`` argument is a Lua table.
1660 .. function:: setAllowEmptyResponse()
1662 .. versionadded:: 1.4.0
1664 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.
1666 .. function:: setDropEmptyQueries(drop)
1668 .. versionadded:: 1.6.0
1670 Set to true (defaults to false) to drop empty queries (qdcount=0) right away, instead of answering with a NotImp rcode. dnsdist used to drop these queries by default because most rules and existing Lua code expects a query to have a qname, qtype and qclass. However :rfc:`7873` uses these queries to request a server cookie, and :rfc:`8906` as a conformance test, so answering these queries with NotImp is much better than not answering at all.
1672 :param bool drop: Whether to drop these queries (defaults to false)
1674 .. function:: setProxyProtocolMaximumPayloadSize(size)
1676 .. versionadded:: 1.6.0
1678 Set the maximum size of a Proxy Protocol payload that dnsdist is willing to accept, in bytes. The default is 512, which is more than enough except for very large TLV data. This setting can't be set to a value lower than 16 since it would deny of Proxy Protocol headers.
1680 :param int size: The maximum size in bytes (default is 512)
1682 .. function:: setTCPFastOpenKey(key)
1684 .. versionadded:: 1.8.0
1686 Set the supplied ``TCP Fast Open`` key on all frontends. This can for example be used to allow all dnsdist instances in an anycast cluster to use the same ``TCP Fast Open`` key, reducing round-trips.
1688 :param string key: The format of the key can be found in ``/proc/sys/net/ipv4/tcp_fastopen_key``
1690 .. function:: makeIPCipherKey(password) -> string
1692 .. versionadded:: 1.4.0
1694 Hashes the password to generate a 16-byte key that can be used to pseudonymize IP addresses with IP cipher.
1696 .. function:: generateOCSPResponse(pathToServerCertificate, pathToCACertificate, pathToCAPrivateKey, outputFile, numberOfDaysOfValidity, numberOfMinutesOfValidity)
1698 .. versionadded:: 1.4.0
1700 When a local PKI is used to issue the certificate, or for testing purposes, :func:`generateOCSPResponse` can be used to generate an OCSP response file for a certificate, using the certificate and private key of the certification authority that signed that certificate.
1701 The resulting file can be directly used with the :func:`addDOHLocal` or the :func:`addTLSLocal` functions.
1703 :param string pathToServerCertificate: Path to a file containing the certificate used by the server.
1704 :param string pathToCACertificate: Path to a file containing the certificate of the certification authority that was used to sign the server certificate.
1705 :param string pathToCAPrivateKey: Path to a file containing the private key corresponding to the certification authority certificate.
1706 :param string outputFile: Path to a file where the resulting OCSP response will be written to.
1707 :param int numberOfDaysOfValidity: Number of days this OCSP response should be valid.
1708 :param int numberOfMinutesOfValidity: Number of minutes this OCSP response should be valid, in addition to the number of days.
1710 .. function:: loadTLSEngine(engineName [, defaultString])
1712 .. versionadded:: 1.8.0
1714 Load the OpenSSL engine named ``engineName``, setting the engine default string to ``defaultString`` if supplied. Engines can be used to accelerate cryptographic operations, like for example Intel QAT.
1715 At the moment up to a maximum of 32 loaded engines are supported, and that support is experimental.
1716 Some engines might actually degrade performance unless the TLS asynchronous mode of OpenSSL is enabled. To enable it see the ``tlsAsyncMode`` parameter on :func:`addTLSLocal`.
1718 :param string engineName: The name of the engine to load.
1719 :param string defaultString: The default string to pass to the engine. The exact value depends on the engine but represents the algorithms to register with the engine, as a list of comma-separated keywords. For example "RSA,EC,DSA,DH,PKEY,PKEY_CRYPTO,PKEY_ASN1".
1721 .. function:: newTLSCertificate(pathToCert[, options])
1723 .. versionadded:: 1.8.0
1725 Creates a TLSCertificate object suited to be used with functions like :func:`addDOHLocal` and :func:`addTLSLocal` for TLS certificate configuration.
1727 PKCS12 files are only supported by the ``openssl`` provider, password-protected or not.
1729 :param string pathToCert: Path to a file containing the certificate or a PCKS12 file containing both a certificate and a key.
1730 :param table options: A table with key: value pairs with additional options.
1734 * ``key="path/to/key"``: string - Path to a file containing the key corresponding to the certificate.
1735 * ``password="pass"``: string - Password protecting the PCKS12 file if appropriate.
1739 newTLSCertificate("path/to/pub.crt", {key="path/to/private.pem"})
1740 newTLSCertificate("path/to/domain.p12", {password="passphrase"}) -- use a password protected PCKS12 file
1745 .. class:: DOHFrontend
1747 .. versionadded:: 1.4.0
1749 This object represents an address and port dnsdist is listening on for DNS over HTTPS queries.
1751 .. method:: DOHFrontend:getAddressAndPort() -> string
1753 .. versionadded:: 1.7.1
1755 Return the address and port this frontend is listening on.
1757 .. method:: DOHFrontend:loadNewCertificatesAndKeys(certFile(s), keyFile(s))
1759 .. versionadded:: 1.6.1
1761 .. versionchanged:: 1.8.0
1762 ``certFile`` now accepts a TLSCertificate object or a list of such objects (see :func:`newTLSCertificate`)
1764 :param str certFile(s): The path to a X.509 certificate file in PEM format, a list of paths to such files, or a TLSCertificate object.
1765 :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. Ignored if ``certFile`` contains TLSCertificate objects.
1767 .. method:: DOHFrontend:loadTicketsKeys(ticketsKeysFile)
1769 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. dnsdist supports several tickets keys to be able to decrypt existing sessions after the rotation.
1770 See :doc:`../advanced/tls-sessions-management` for more information.
1772 :param str ticketsKeysFile: The path to a file from where TLS tickets keys should be loaded.
1774 .. method:: DOHFrontend:reloadCertificates()
1776 Reload the current TLS certificate and key pairs.
1778 .. method:: DOHFrontend:rotateTicketsKey()
1780 Replace the current TLS tickets key by a new random one.
1782 .. method:: DOHFrontend:setResponsesMap(rules)
1784 Set a list of HTTP response rules allowing to intercept HTTP queries very early, before the DNS payload has been processed, and send custom responses including error pages, redirects and static content.
1786 :param list of DOHResponseMapEntry objects rules: A list of DOHResponseMapEntry objects, obtained with :func:`newDOHResponseMapEntry`.
1789 .. function:: newDOHResponseMapEntry(regex, status, content [, headers]) -> DOHResponseMapEntry
1791 .. versionadded:: 1.4.0
1793 Return a DOHResponseMapEntry that can be used with :meth:`DOHFrontend:setResponsesMap`. Every query whose path is listed in the ``urls`` parameter to :func:`addDOHLocal` and matches the regular expression supplied in ``regex`` will be immediately answered with a HTTP response.
1794 The status of the HTTP response will be the one supplied by ``status``, and the content set to the one supplied by ``content``, except if the status is a redirection (3xx) in which case the content is expected to be the URL to redirect to.
1796 :param str regex: A regular expression to match the path against.
1797 :param int status: The HTTP code to answer with.
1798 :param str content: The content of the HTTP response, or a URL if the status is a redirection (3xx).
1799 :param table of headers: The custom headers to set for the HTTP response, if any. The default is to use the value of the ``customResponseHeaders`` parameter passed to :func:`addDOHLocal`.
1804 .. class:: TLSContext
1806 This object represents an address and port dnsdist is listening on for DNS over TLS queries.
1808 .. method:: TLSContext:loadTicketsKeys(ticketsKeysFile)
1810 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.
1811 See :doc:`../advanced/tls-sessions-management` for more information.
1813 :param str ticketsKeysFile: The path to a file from where TLS tickets keys should be loaded.
1815 .. method:: TLSContext:rotateTicketsKey()
1817 Replace the current TLS tickets key by a new random one.
1822 .. class:: TLSFrontend
1824 This object represents the configuration of a listening frontend for DNS over TLS queries. To each frontend is associated a TLSContext.
1826 .. method:: TLSFrontend:getAddressAndPort() -> string
1828 .. versionadded:: 1.7.1
1830 Return the address and port this frontend is listening on.
1832 .. method:: TLSFrontend:loadNewCertificatesAndKeys(certFile(s), keyFile(s))
1834 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.
1836 :param str certFile(s): The path to a X.509 certificate file in PEM format, or a list of paths to such files.
1837 :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.
1839 .. method:: TLSFrontend:loadTicketsKeys(ticketsKeysFile)
1841 .. versionadded:: 1.6.0
1843 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.
1844 See :doc:`../advanced/tls-sessions-management` for more information.
1846 :param str ticketsKeysFile: The path to a file from where TLS tickets keys should be loaded.
1848 .. method:: TLSFrontend:reloadCertificates()
1850 .. versionadded:: 1.6.0
1852 Reload the current TLS certificate and key pairs.
1854 .. method:: TLSFrontend:rotateTicketsKey()
1856 .. versionadded:: 1.6.0
1858 Replace the current TLS tickets key by a new random one.
1860 EDNS on Self-generated answers
1861 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1863 There are several mechanisms in dnsdist that turn an existing query into an answer right away,
1864 without reaching out to the backend, including :func:`SpoofAction`, :func:`RCodeAction`, :func:`TCAction`
1865 and returning a response from ``Lua``. Those responses should, according to :rfc:`6891`, contain an ``OPT``
1866 record if the received request had one, which is the case by default and can be disabled using
1867 :func:`setAddEDNSToSelfGeneratedResponses`.
1869 We must, however, provide a responder's maximum payload size in this record, and we can't easily know the
1870 maximum payload size of the actual backend so we need to provide one. The default value is 1232 since 1.6.0,
1871 and can be overridden using :func:`setPayloadSizeOnSelfGeneratedAnswers`.
1873 .. function:: setAddEDNSToSelfGeneratedResponses(add)
1875 Whether to add EDNS to self-generated responses, provided that the initial query had EDNS.
1877 :param bool add: Whether to add EDNS, default is true.
1879 .. function:: setPayloadSizeOnSelfGeneratedAnswers(payloadSize)
1881 .. versionchanged:: 1.6.0
1882 Default value changed from 1500 to 1232.
1884 Set the UDP payload size advertised via EDNS on self-generated responses. In accordance with
1885 :rfc:`RFC 6891 <6891#section-6.2.5>`, values lower than 512 will be treated as equal to 512.
1887 :param int payloadSize: The responder's maximum UDP payload size, in bytes. Default is 1232 since 1.6.0, it was 1500 before.
1892 PowerDNS products can poll the security status of their respective versions. This polling, naturally,
1893 happens over DNS. If the result is that a given version has a security problem, the software will
1894 report this at level ‘Error’ during startup, and repeatedly during operations, every
1895 :func:`setSecurityPollInterval` seconds.
1897 By default, security polling happens on the domain ‘secpoll.powerdns.com’, but this can be changed with
1898 the :func:`setSecurityPollSuffix` function. If this setting is made empty, no polling will take place.
1899 Organizations wanting to host their own security zones can do so by changing this setting to a domain name
1900 under their control.
1902 To enable distributors of PowerDNS to signal that they have backported versions, the PACKAGEVERSION
1903 compilation-time macro can be used to set a distributor suffix.
1905 .. function:: setSecurityPollInterval(interval)
1907 Set the interval, in seconds, between two security polls.
1909 :param int interval: The interval, in seconds, between two polls. Default is 3600.
1911 .. function:: setSecurityPollSuffix(suffix)
1913 Domain name from which to query security update notifications. Setting this to an empty string disables secpoll.
1915 :param string suffix: The suffix to use, default is 'secpoll.powerdns.com.'.