unbound Documentation

Unbound is a validating, recursive, and caching DNS resolver.

4,996 stars C C 41 files ยท ~104,401 tokens #dns#dns-privacy#dnssec#recursor#resolver
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy unbound on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name unbound --restart always nlnetlabs/unbound:latest

Technical Documentation: NLnetLabs/unbound

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

Unbound





Unbound is a validating, recursive, caching DNS resolver. It is designed to be
fast and lean and incorporates modern features based on open standards. If you
have any feedback, we would love to hear from you. Donโ€™t hesitate to
create an issue on Github
or post a message on our community forum.
You can learn more about Unbound by reading our
documentation.

Compiling

Make sure you have the C toolchain, OpenSSL and its include files, and libexpat
installed.
If building from the repository source you also need flex and bison installed.
Unbound can be compiled and installed using:

text
./configure && make && make install

You can use libevent if you want. libevent is useful when using many (e.g.,
10000) outgoing ports.
Use the --with-libevent configure option to compile Unbound with libevent
support.

If not, the default builtin alternative opens max 256 ports at the same time
and is equally capable and a little faster.

Unbound configuration

All of Unbound's configuration options are described in the unbound.conf(5)
man page, which will be installed and is also available on the Unbound
documentation page
for the latest version.

An example configuration file, with minimal documentation, is located in
doc/example.conf.


Doc README.Ipset (`doc/README.ipset.md`)

Created a module to support the ipset that could add the domain's ip to a list easily.

Purposes:

  • In my case, I can't access the facebook, twitter, youtube and thousands web site for some reason. VPN is a solution. But the internet too slow whether all traffics pass through the vpn.
    So, I set up a transparent proxy to proxy the traffic which has been blocked only.
    At the final step, I need to install a dns service which would work with ipset well to launch the system.
    I did some research for this. Unfortunately, Unbound, My favorite dns service doesn't support ipset yet. So, I decided to implement it by my self and contribute the patch. It's good for me and the community.
text
# unbound.conf
server:
  ...
  local-zone: "facebook.com" ipset
  local-zone: "twitter.com" ipset
  local-zone: "instagram.com" ipset
  more social website

ipset:
  name-v4: "gfwlist"
text
# iptables
iptables -A PREROUTING -p tcp -m set --match-set gfwlist dst -j REDIRECT --to-ports 10800
iptables -A OUTPUT -p tcp -m set --match-set gfwlist dst -j REDIRECT --to-ports 10800
  • This patch could work with iptables rules to batch block the IPs.
text
# unbound.conf
server:
  ...
  local-zone: "facebook.com" ipset
  local-zone: "twitter.com" ipset
  local-zone: "instagram.com" ipset
  more social website

ipset:
  name-v4: "blacklist"
  name-v6: "blacklist6"
text
# iptables
iptables -A INPUT -m set --set blacklist src -j DROP
ip6tables -A INPUT -m set --set blacklist6 src -j DROP

Notes:

  • To enable this module the root privileges is required.
  • Please create a set with ipset command first. eg. ipset -N blacklist iphash

How to use:

text
./configure --enable-ipset
make && make install

Configuration:

text
# unbound.conf
server:
  ...
  local-zone: "example.com" ipset

ipset:
  name-v4: "blacklist"

Doc Control Proto Spec (`doc/control_proto_spec.txt`)

Specification for the unbound-control protocol.

Server listens on 8953 TCP (localhost by default). Client connects,
SSLv3 or TLSv1 connection setup (server selfsigned certificate,
client has cert signed by server certificate).

Port 8953 is registered with IANA as:
ub-dns-control 8953/tcp unbound dns nameserver control

Wouter Wijngaards 10 May 2011

On may 11 2011, ticket [IANA #442315].

Query and Response

Client sends
UBCT[version] [commandline] \n
fixed string UBCT1 (for version 1), then an ascii text line,
with a command, some whitespace allowed. Line ends with '\n'.

Server executes command. And sends reply in ascii text over channel,
closes the channel when done.
in case of error the first line of the response is:
error \n
or the remainder is data of the response, for many commands the
response is 'ok\n'.

Queries and responses

stop
stops the server.
reload
reloads the config file, and flushes the cache.
verbosity
Change logging verbosity to new value.
stats
output is a list of [name]=[value] lines.
clears the counters.
dump_cache
output is a text representation of the cache contents.
data ends with a line 'EOF' before connection close.
load_cache
client sends cache contents (like from dump_cache), which is stored
in the cache. end of data indicated with a line with 'EOF' on it.
The data is sent after the query line.
flush
flushes some information regarding the name from the cache.
removes the A, AAAA, NS, SOA, CNAME, DNAME, MX, PTR, SRV, NAPTR types.
Does not remove other types.
flush_type
removes rrtype entry from the cache.
flush_zone
removes name and everything below that name from the cache.
has to search through the cache item by item, so this is slow.
lookup
see what servers would be queried for a lookup of the given name.
local_zone_remove
the local-zone entry is removed.
All data from the local zone is also deleted.
If it did not exist, nothing happens.
local_zone
As the config file entry. Adds new local zone or updates
existing zone type.
local_data_remove
Removes local-data (all types) name.
local_data
Add new local data record (on the rest of the line).
local_data_add www.example.com. IN A 192.0.2.2
if no local_zone exists for it; a transparent zone with the same
name as the data is created.
Other commands in the unbound-control manual page.


Doc Libunbound (`doc/libunbound.rst`)

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

libunbound(3)

Synopsis

.. only:: html

text
.. code-block:: c

    #include 

    struct ub_ctx * ub_ctx_create(void);

    void ub_ctx_delete(struct ub_ctx* ctx);

    int ub_ctx_set_option(struct ub_ctx* ctx, char* opt, char* val);

    int ub_ctx_get_option(struct ub_ctx* ctx, char* opt, char** val);

    int ub_ctx_config(struct ub_ctx* ctx, char* fname);

    int ub_ctx_set_fwd(struct ub_ctx* ctx, char* addr);

    int ub_ctx_set_stub(struct ub_ctx* ctx, char* zone, char* addr,
                        int isprime);

    int ub_ctx_set_tls(struct ub_ctx* ctx, int tls);

    int ub_ctx_resolvconf(struct ub_ctx* ctx, char* fname);

    int ub_ctx_hosts(struct ub_ctx* ctx, char* fname);

    int ub_ctx_add_ta(struct ub_ctx* ctx, char* ta);

    int ub_ctx_add_ta_autr(struct ub_ctx* ctx, char* fname);

    int ub_ctx_add_ta_file(struct ub_ctx* ctx, char* fname);

    int ub_ctx_trustedkeys(struct ub_ctx* ctx, char* fname);

    int ub_ctx_debugout(struct ub_ctx* ctx, FILE* out);

    int ub_ctx_debuglevel(struct ub_ctx* ctx, int d);

    int ub_ctx_async(struct ub_ctx* ctx, int dothread);

    int ub_poll(struct ub_ctx* ctx);

    int ub_wait(struct ub_ctx* ctx);

    int ub_fd(struct ub_ctx* ctx);

    int ub_process(struct ub_ctx* ctx);

    int ub_resolve(struct ub_ctx* ctx, char* name, int rrtype,
                   int rrclass, struct ub_result** result);

    int ub_resolve_async(struct ub_ctx* ctx, char* name, int rrtype,
                         int rrclass, void* mydata, ub_callback_type callback,
                         int* async_id);

    int ub_cancel(struct ub_ctx* ctx, int async_id);

    void ub_resolve_free(struct ub_result* result);

    const char * ub_strerror(int err);

    int ub_ctx_print_local_zones(struct ub_ctx* ctx);

    int ub_ctx_zone_add(struct ub_ctx* ctx, char* zone_name, char* zone_type);

    int ub_ctx_zone_remove(struct ub_ctx* ctx, char* zone_name);

    int ub_ctx_data_add(struct ub_ctx* ctx, char* data);

    int ub_ctx_data_remove(struct ub_ctx* ctx, char* data);

.. only:: man

text
**#include **

struct ub_ctx \* **ub_ctx_create**\ (void);

void **ub_ctx_delete**\ (struct ub_ctx\* ctx);

int **ub_ctx_set_option**\ (struct ub_ctx\* ctx, char\* opt, char\* val);

int **ub_ctx_get_option**\ (struct ub_ctx\* ctx, char\* opt, char\*\* val);

int **ub_ctx_config**\ (struct ub_ctx\* ctx, char* fname);

int **ub_ctx_set_fwd**\ (struct ub_ctx\* ctx, char\* addr);

int **ub_ctx_set_stub**\ (struct ub_ctx\* ctx, char\* zone, char\* addr,
    int isprime);

int **ub_ctx_set_tls**\ (struct ub_ctx\* ctx, int tls);

int **ub_ctx_resolvconf**\ (struct ub_ctx\* ctx, char\* fname);

int **ub_ctx_hosts**\ (struct ub_ctx\* ctx, char\* fname);

int **ub_ctx_add_ta**\ (struct ub_ctx\* ctx, char\* ta);

int **ub_ctx_add_ta_autr**\ (struct ub_ctx\* ctx, char\* fname);

int **ub_ctx_add_ta_file**\ (struct ub_ctx\* ctx, char\* fname);

int **ub_ctx_trustedkeys**\ (struct ub_ctx\* ctx, char\* fname);

int **ub_ctx_debugout**\ (struct ub_ctx\* ctx, FILE\* out);

int **ub_ctx_debuglevel**\ (struct ub_ctx\* ctx, int d);

int **ub_ctx_async**\ (struct ub_ctx\* ctx, int dothread);

int **ub_poll**\ (struct ub_ctx\* ctx);

int **ub_wait**\ (struct ub_ctx\* ctx);

int **ub_fd**\ (struct ub_ctx\* ctx);

int **ub_process**\ (struct ub_ctx\* ctx);

int **ub_resolve**\ (struct ub_ctx\* ctx, char\* name,
    int rrtype, int rrclass, struct ub_result\*\* result);

int **ub_resolve_async**\ (struct ub_ctx\* ctx, char\* name,
    int rrtype, int rrclass, void\* mydata,
    ub_callback_type\* callback, int\* async_id);

int **ub_cancel**\ (struct ub_ctx\* ctx, int async_id);

void **ub_resolve_free**\ (struct ub_result\* result);

const char \* **ub_strerror**\ (int err);

int **ub_ctx_print_local_zones**\ (struct ub_ctx\* ctx);

int **ub_ctx_zone_add**\ (struct ub_ctx\* ctx, char\* zone_name, char\* zone_type);

int **ub_ctx_zone_remove**\ (struct ub_ctx\* ctx, char\* zone_name);

int **ub_ctx_data_add**\ (struct ub_ctx\* ctx, char\* data);

int **ub_ctx_data_remove**\ (struct ub_ctx\* ctx, char\* data);

Description

Unbound is an implementation of a DNS resolver, that does caching and DNSSEC
validation.
This is the library API, for using the -lunbound library.
The server daemon is described in :doc:unbound(8)</manpages/unbound>.
The library works independent from a running unbound server, and can be used to
convert hostnames to ip addresses, and back, and obtain other information from
the DNS.
The library performs public-key validation of results with DNSSEC.

The library uses a variable of type struct ub_ctx to keep context between
calls.
The user must maintain it, creating it with ub_ctx_create and deleting it
with ub_ctx_delete.
It can be created and deleted at any time.
Creating it anew removes any previous configuration (such as trusted keys) and
clears any cached results.

The functions are thread-safe, and a context can be used in a threaded (as well
as in a non-threaded) environment.
Also resolution (and validation) can be performed blocking and non-blocking
(also called asynchronous).
The async method returns from the call immediately, so that processing can go
on, while the results become available later.

The functions are discussed in turn below.

Functions

.. glossary::

text
ub_ctx_create
    Create a new context, initialised with defaults.
    The information from :file:`/etc/resolv.conf` and :file:`/etc/hosts` is
    not utilised by default.
    Use **ub_ctx_resolvconf** and **ub_ctx_hosts** to read them.
    Before you call this, use the openssl functions
    **CRYPTO_set_id_callback** and **CRYPTO_set_locking_callback** to set
    up asynchronous operation if you use lib openssl (the application calls
    these functions once for initialisation).
    Openssl 1.0.0 or later uses the **CRYPTO_THREADID_set_callback**
    function.

ub_ctx_delete
    Delete validation context and free associated resources.
    Outstanding async queries are killed and callbacks are not called for
    them.

ub_ctx_set_option
    A power-user interface that lets you specify one of the options from
    the config file format, see :doc:`unbound.conf(5)</manpages/unbound.conf>`.
    Not all options are relevant.
    For some specific options, such as adding trust anchors, special
    routines exist.
    Pass the option name with the trailing ``':'``.

ub_ctx_get_option
    A power-user interface that gets an option value.
    Some options cannot be gotten, and others return a newline separated
    list.
    Pass the option name without trailing ``':'``.
    The returned value must be free(2)d by the caller.

ub_ctx_config
    A power-user interface that lets you specify an unbound config file,
    see :doc:`unbound.conf(5)</manpages/unbound.conf>`, which is read for
    configuration.
    Not all options are relevant.
    For some specific options, such as adding trust anchors, special
    routines exist.
    This function is thread-safe only if a single instance of **ub_ctx**\*
    exists in the application.
    If several instances exist the application has to ensure that
    **ub_ctx_config** is not called in parallel by the different instances.

ub_ctx_set_fwd
    Set machine to forward DNS queries to, the caching resolver to use.
    IP4 or IP6 address.
    Forwards all DNS requests to that machine, which is expected to run a
    recursive resolver.
    If the proxy is not DNSSEC capable, validation may fail.
    Can be called several times, in that case the addresses are used as
    backup servers.
    At this time it is only possible to set configuration before the first
    resolve is done.

ub_ctx_set_stub
    Set a stub zone, authoritative dns servers to use for a particular
    zone.
    IP4 or IP6 address.
    If the address is NULL the stub entry is removed.
    Set isprime true if you configure root hints with it.
    Otherwise similar to the stub zone item from unbound's config file.
    Can be called several times, for different zones, or to add multiple
    addresses for a particular zone.
    At this time it is only possible to set configuration before the first
    resolve is done.

ub_ctx_set_tls
    Enable DNS over TLS (DoT) for machines set with **ub_ctx_set_fwd**.
    At this time it is only possible to set configuration before the first
    resolve is done.

ub_ctx_resolvconf
    By default the root servers are queried and full resolver mode is used,
    but you can use this call to read the list of nameservers to use from
    the filename given.
    Usually :file:`"/etc/resolv.conf"`.
    Uses those nameservers as caching proxies.
    If they do not support DNSSEC, validation may fail.
    Only nameservers are picked up, the searchdomain, ndots and other
    settings from *resolv.conf(5)* are ignored.
    If fname NULL is passed, :file:`"/etc/resolv.conf"` is used (if on
    Windows, the system-wide configured nameserver is picked instead).
    At this time it is only possible to set configuration before the first
    resolve is done.

ub_ctx_hosts
    Read list of hosts from the filename given.
    Usually :file:`"/etc/hosts"`.
    When queried for, these addresses are not marked DNSSEC secure.
    If fname NULL is passed, :file:`"/etc/hosts"` is used (if on Windows,
    :file:`etc/hosts` from WINDIR is picked instead).
    At this time it is only possible to set configuration before the first
    resolve is done.

ub_ctx_add_ta
    Add a trust anchor to the given context.
    At this time it is only possible to add trusted keys before the first
    resolve is done.
    The format is a string, similar to the zone-file format,
    **[domainname]** **[type]** **[rdata contents]**.
    Both DS and DNSKEY records are accepted.

ub_ctx_add_ta_autr
    Add filename with automatically tracked trust anchor to the given
    context.
    Pass name of a file with the managed trust anchor.
    You can create this file with
    :doc:`unbound-anchor(8)</manpages/unbound-anchor>` for the root anchor.
    You can also create it with an initial file with one line with a DNSKEY
    or DS record.
    If the file is writable, it is updated when the trust anchor changes.
    At this time it is only possible to add trusted keys before the first
    resolve is done.

ub_ctx_add_ta_file
    Add trust anchors to the given context.
    Pass name of a file with DS and DNSKEY records in zone file format.
    At this time it is only possible to add trusted keys before the first
    resolve is done.

ub_ctx_trustedkeys
    Add trust anchors to the given context.
    Pass the name of a bind-style config file with ``trusted-keys{}``.
    At this time it is only possible to add trusted keys before the first
    resolve is done.

ub_ctx_debugout
    Set debug and error log output to the given stream.
    Pass NULL to disable output.
    Default is stderr.
    File-names or using syslog can be enabled using config options, this
    routine is for using your own stream.

ub_ctx_debuglevel
    Set debug verbosity for the context.
    Output is directed to stderr.
    Higher debug level gives more output.

ub_ctx_async
    Set a context behaviour for asynchronous action.
    if set to true, enables threading and a call to **ub_resolve_async**
    creates a thread to handle work in the background.
    If false, a process is forked to handle work in the background.
    Changes to this setting after **ub_resolve_async** calls have been made
    have no effect (delete and re-create the context to change).

ub_poll
    Poll a context to see if it has any new results.
    Do not poll in a loop, instead extract the **fd** below to poll for
    readiness, and then check, or wait using the wait routine.
    Returns 0 if nothing to read, or nonzero if a result is available.
    If nonzero, call **ub_process** to do callbacks.

ub_wait
    Wait for a context to finish with results.
    Calls **ub_process** after the wait for you.
    After the wait, there are no more outstanding asynchronous queries.

ub_fd 
    Get file descriptor.
    Wait for it to become readable, at this point answers are returned from
    the asynchronous validating resolver.
    Then call the **ub_process** to continue processing.

ub_process
    Call this routine to continue processing results from the validating
    resolver (when the **fd** becomes readable).
    Will perform necessary callbacks.

ub_resolve
    Perform resolution and validation of the target name.
    The name is a domain name in a zero terminated text string.
    The rrtype and rrclass are DNS type and class codes.
    The result structure is newly allocated with the resulting data.

ub_resolve_async
    Perform asynchronous resolution and validation of the target name.
    Arguments mean the same as for **ub_resolve** except no data is
    returned immediately, instead a callback is called later.
    The callback receives a copy of the mydata pointer, that you can use to
    pass information to the callback.
    The callback type is a function pointer to a function declared as:

    .. code-block:: c

        void my_callback_function(void* my_arg, int err,
                        struct ub_result* result);

    The **async_id** is returned so you can (at your option) decide to
    track it and cancel the request if needed.
    If you pass a NULL pointer the **async_id** is not returned.
    The context, created via **ub_ctx_create**, is in use during but also
    after the callback and it cannot be deleted during a callback.

ub_cancel
    Cancel an async query in progress.
    This may return an error if the query does not exist, or the query is
    already being delivered, in that case you may still get a callback for
    the query.

ub_resolve_free
    Free struct **ub_result** contents after use.

ub_strerror
    Convert error value from one of the unbound library functions to a
    human readable string.

ub_ctx_print_local_zones
    Debug printout the local authority information to debug output.

ub_ctx_zone_add
    Add new zone to local authority info, like local-zone
    :doc:`unbound.conf(5)</manpages/unbound.conf>` statement.

ub_ctx_zone_remove
    Delete zone from local authority info.

ub_ctx_data_add
    Add resource record data to local authority info, like local-data
    :doc:`unbound.conf(5)</manpages/unbound.conf>` statement.

ub_ctx_data_remove
    Delete local authority data from the name given.

Result Data structure

The result of the DNS resolution and validation is returned as struct
ub_result
.
The result structure contains the following entries:

.. code-block:: c

text
struct ub_result {
     char* qname;         /* text string, original question */
     int qtype;           /* type code asked for */
     int qclass;          /* class code asked for */
     char** data;         /* array of rdata items, NULL terminated*/
     int* len;            /* array with lengths of rdata items */
     char* canonname;     /* canonical name of result */
     int rcode;           /* additional error code in case of no data */
     void* answer_packet; /* full network format answer packet */
     int answer_len;      /* length of packet in octets */
     int havedata;        /* true if there is data */
     int nxdomain;        /* true if nodata because name does not exist */
     int secure;          /* true if result is secure */
     int bogus;           /* true if a security failure happened */
     char* why_bogus;     /* string with error if bogus */
     int was_ratelimited; /* true if the query was ratelimited (SERVFAIL) by unbound */
     int ttl;             /* number of seconds the result is valid */
};

If both secure and bogus are false, security was not enabled for the domain of
the query.
Else, they are not both true, one of them is true.

Return Values

Many routines return an error code.
The value 0 (zero) denotes no error happened.
Other values can be passed to ub_strerror to obtain a readable error
string.
ub_strerror returns a zero terminated string.
ub_ctx_create returns NULL on an error (a malloc failure).
ub_poll returns true if some information may be available, false otherwise.
ub_fd returns a file descriptor or -1 on error.
ub_ctx_config and ub_ctx_resolvconf attempt to leave errno informative
on a function return with file read failure.

See Also

:doc:unbound.conf(5)</manpages/unbound.conf>, :doc:unbound(8)</manpages/unbound>.


Doc Requirements (`doc/requirements.txt`)

Requirements for Recursive Caching Resolver
(a.k.a. Treeshrew, Unbound-C)
By W.C.A. Wijngaards, NLnet Labs, October 2006.

Contents

  1. Introduction

  2. History

  3. Goals

  4. Non-Goals

  5. Introduction


This is the requirements document for a DNS name server and aims to
document the goals and non-goals of the project. The DNS (the Domain
Name System) is a global, replicated database that uses a hierarchical
structure for queries.

Data in the DNS is stored in Resource Record sets (RR sets), and has a
time to live (TTL). During this time the data can be cached. It is
thus useful to cache data to speed up future lookups. A server that
looks up data in the DNS for clients and caches previous answers to
speed up processing is called a caching, recursive nameserver.

This project aims to develop such a nameserver in modular components, so
that also DNSSEC (secure DNS) validation and stub-resolvers (that do not
run as a server, but a linked into an application) are easily possible.

The main components are the Validator that validates the security
fingerprints on data sets, the Iterator that sends queries to the
hierarchical DNS servers that own the data and the Cache that stores
data from previous queries. The networking and query management code
then interface with the modules to perform the necessary processing.

In Section 2 the origins of the Unbound project are documented. Section
3 lists the goals, while Section 4 lists the explicit non-goals of the
project. Section 5 discusses choices made during development.

  1. History

The unbound resolver project started by Bill Manning, David Blacka, and
Matt Larson (from the University of California and from Verisign), that
created a Java based prototype resolver called Unbound. The basic
design decisions of clean modules was executed.

The Java prototype worked very well, with contributions from Geoff
Sisson and Roy Arends from Nominet. Around 2006 the idea came to create
a full-fledged C implementation ready for deployed use. NLnet Labs
volunteered to write this implementation.

  1. Goals

o A validating recursive DNS resolver.
o Code diversity in the DNS resolver monoculture.
o Drop-in replacement for BIND apart from config.
o DNSSEC support.
o Fully RFC compliant.
o High performance
* even with validation.
o Used as
* stub resolver.
* full caching name server.
* resolver library.
o Elegant design of validator, resolver, cache modules.
* provide the ability to pick and choose modules.
o Robust.
o In C, open source: The BSD license.
o Highly portable, targets include modern Unix systems, such as *BSD,
solaris, linux, and maybe also the windows platform.
o Smallest as possible component that does the job.
o Stub-zones can be configured (local data or AS112 zones).

  1. Non-Goals

o An authoritative name server.
o Too many Features.

  1. Choices

o rfc2181 discourages duplicates RRs in RRsets. unbound does not create
duplicates, but when presented with duplicates on the wire from the
authoritative servers, does not perform duplicate removal.
It does do some rrsig duplicate removal, in the msgparser, for dnssec qtype
rrsig and any, because of special rrsig processing in the msgparser.
o The harden-glue feature, when yes all out of zone glue is deleted, when
no out of zone glue is used for further resolving, is more complicated
than that, see below.
Main points:
* rfc2182 trust handling is used.
* data is let through only in very specific cases
* spoofability remains possible.
Not all glue is let through (despite the name of the option). Only glue
which is present in a delegation, of type A and AAAA, where the name is
present in the NS record in the authority section is let through.
The glue that is let through is stored in the cache (marked as 'from the
additional section'). And will then be used for sending queries to. It
will not be present in the reply to the client (if RD is off).
A direct query for that name will attempt to get a msg into the message
cache. Since A and AAAA queries are not synthesized by the unbound cache,
this query will be (eventually) sent to the authoritative server and its
answer will be put in the cache, marked as 'from the answer section' and
thus remove the 'from the additional section' data, and this record is
returned to the client.
The message has a TTL smaller or equal to the TTL of the answer RR.
If the cache memory is low; the answer RR may be dropped, and a glue
RR may be inserted, within the message TTL time, and thus return the
spoofed glue to a client. When the message expires, it is refetched and
the cached RR is updated with the correct content.
The server can be spoofed by getting it to visit a especially prepared
domain. This domain then inserts an address for another authoritative
server into the cache, when visiting that other domain, this address may
then be used to send queries to. And fake answers may be returned.
If the other domain is signed by DNSSEC, the fakes will be detected.

In summary, the harden glue feature presents a security risk if
disabled. Disabling the feature leads to possible better performance
as more glue is present for the recursive service to use. The feature
is implemented so as to minimise the security risk, while trying to
keep this performance gain.
o The method by which dnssec-lameness is detected is not secure. DNSSEC lame
is when a server has the zone in question, but lacks dnssec data, such as
signatures. The method to detect dnssec lameness looks at nonvalidated
data from the parent of a zone. This can be used, by spoofing the parent,
to create a false sense of dnssec-lameness in the child, or a false sense
or dnssec-non-lameness in the child. The first results in the server marked
lame, and not used for 900 seconds, and the second will result in a
validator failure (SERVFAIL again), when the query is validated later on.

Concluding, a spoof of the parent delegation can be used for many cases
of denial of service. I.e. a completely different NS set could be returned,
or the information withheld. All of these alterations can be caught by
the validator if the parent is signed, and result in 900 seconds bogus.
The dnssec-lameness detection is used to detect operator failures,
before the validator will properly verify the messages.

Also for zones for which no chain of trust exists, but a DS is given by the
parent, dnssec-lameness detection enables. This delivers dnssec to our
clients when possible (for client validators).

The following issue needs to be resolved:
a server that serves both a parent and child zone, where
parent is signed, but child is not. The server must not be marked
lame for the parent zone, because the child answer is not signed.
Instead of a false positive, we want false negatives; failure to
detect dnssec-lameness is less of a problem than marking honest
servers lame. dnssec-lameness is a config error and deserves the trouble.
So, only messages that identify the zone are used to mark the zone
lame. The zone is identified by SOA or NS RRsets in the answer/auth.
That includes almost all negative responses and also A, AAAA qtypes.
That would be most responses from servers.
For referrals, delegations that add a single label can be checked to be
from their zone, this covers most delegation-centric zones.

So possibly, for complicated setups, with multiple (parent-child) zones
on a server, dnssec-lameness detection does not work - no dnssec-lameness
is detected. Instead the zone that is dnssec-lame becomes bogus.

o authority features.
This is a recursive server, and authority features are out of scope.
However, some authority features are expected in a recursor. Things like
localhost, reverse lookup for 127.0.0.1, or blocking AS112 traffic.
Also redirection of domain names with fixed data is needed by service
providers. Limited support is added specifically to address this.

Adding full authority support, requires much more code, and more complex
maintenance.

The limited support allows adding some static data (for localhost and so),
and to respond with a fixed rcode (NXDOMAIN) for domains (such as AS112).

You can put authority data on a separate server, and set the server in
unbound.conf as stub for those zones, this allows clients to access data
from the server without making unbound authoritative for the zones.

o the access control denies queries before any other processing.
This denies queries that are not authoritative, or version.bind, or any.
And thus prevents cache-snooping (denied hosts cannot make non-recursive
queries and get answers from the cache).

o If a client makes a query without RD bit, in the case of a returned
message from cache which is:
answer section: empty
auth section: NS record present, no SOA record, no DS record,
maybe NSEC or NSEC3 records present.
additional: A records or other relevant records.
A SOA record would indicate that this was a NODATA answer.
A DS records would indicate a referral.
Absence of NS record would indicate a NODATA answer as well.

Then the receiver does not know whether this was a referral
with attempt at no-DS proof) or a nodata answer with attempt
at no-data proof. It could be determined by attempting to prove
either condition; and looking if only one is valid, but both
proofs could be valid, or neither could be valid, which creates
doubt. This case is validated by unbound as a 'referral' which
ascertains that RRSIGs are OK (and not omitted), but does not
check NSEC/NSEC3.

o Case preservation
Unbound preserves the casing received from authority servers as best
as possible. It compresses without case, so case can get lost there.
The casing from the query name is used in preference to the casing
of the authority server. This is the same as BIND. RFC4343 allows either
behaviour.

o Denial of service protection
If many queries are made, and they are made to names for which the
authority servers do not respond, then the requestlist for unbound
fills up fast. This results in denial of service for new queries.
To combat this the first 50% of the requestlist can run to completion.
The last 50% of the requestlist get (200 msec) at least and are replaced
by newer queries when older (LIFO).
When a new query comes in, and a place in the first 50% is available, this
is preferred. Otherwise, it can replace older queries out of the last 50%.
Thus, even long queries get a 50% chance to be resolved. And many 'short'
one or two round-trip resolves can be done in the last 50% of the list.
The timeout can be configured.

o EDNS fallback. Is done according to the EDNS RFC (and update draft-00).
Unbound assumes EDNS 0 support for the first query. Then it can detect
support (if the servers replies) or non-support (on a NOTIMPL or FORMERR).
Some middleboxes drop EDNS 0 queries, mainly when forwarding, not when
routing packets. To detect this, when timeouts keep happening, as the
timeout approached 5-10 seconds, and EDNS status has not been detected yet,
a single probe query is sent. This probe has a sub-second timeout, and
if the server responds (quickly) without EDNS, this is cached for 15 min.
This works very well when detecting an address that you use much - like
a forwarder address - which is where the middleboxes need to be detected.
Otherwise, it results in a 5 second wait time before EDNS timeout is
detected, which is slow but it works at least.
It minimizes the chances of a dropped query making a (DNSSEC) EDNS server
falsely EDNS-nonsupporting, and thus DNSSEC-bogus, works well with
middleboxes, and can detect the occasional authority that drops EDNS.
For some boxes it is necessary to probe for every failing query, a
reassurance that the DNS server does EDNS does not mean that path can
take large DNS answers.

o 0x20 backoff.
The draft describes to back off to the next server, and go through all
servers several times. Unbound goes on get the full list of nameserver
addresses, and then makes 3 * number of addresses queries.
They are sent to a random server, but no one address more than 4 times.
It succeeds if one has 0x20 intact, or else all are equal.
Otherwise, servfail is returned to the client.

o NXDOMAIN and SOA serial numbers.
Unbound keeps TTL values for message formats, and thus rcodes, such
as NXDOMAIN. Also it keeps the latest rrsets in the rrset cache.
So it will faithfully negative cache for the exact TTL as originally
specified for an NXDOMAIN message, but send a newer SOA record if
this has been found in the mean time. In point, this could lead to a
negative cached NXDOMAIN reply with a SOA RR where the serial number
indicates a zone version where this domain is not any longer NXDOMAIN.
These situations become consistent once the original TTL expires.
If the domain is DNSSEC signed, by the way, then NSEC records are
updated more carefully. If one of the NSEC records in an NXDOMAIN is
updated from another query, the NXDOMAIN is dropped from the cache,
and queried for again, so that its proof can be checked again.

o SOA records in negative cached answers for DS queries.
The current unbound code uses a negative cache for queries for type DS.
This speeds up building chains of trust, and uses NSEC and NSEC3
(optout) information to speed up lookups. When used internally,
the bare NSEC(3) information is sufficient, probably picked up from
a referral. When answering to clients, a SOA record is needed for
the correct message format, a SOA record is picked from the cache
(and may not actually match the serial number of the SOA for which the
NSEC and NSEC3 records were obtained) if available otherwise network
queries are performed to get the data.

o Parent and child with different nameserver information.
A misconfiguration that sometimes happens is where the parent and child
have different NS, glue information. The child is authoritative, and
unbound will not trust information from the parent nameservers as the
final answer. To help lookups, unbound will however use the parent-side
version of the glue as a last resort lookup. This resolves lookups for
those misconfigured domains where the servers reported by the parent
are the only ones working, and servers reported by the child do not.

o Failure of validation and probing.
Retries on a validation failure are now 5x to a different nameserver IP
(if possible), and then it gives up, for one name, type, class entry in
the message cache. If a DNSKEY or DS fails in the chain of trust in the
key cache additionally, after the probing, a bad key entry is created that
makes the entire zone bogus for 900 seconds. This is a fixed value at
this time and is conservative in sending probes. It makes the compound
effect of many resolvers less and easier to handle, but penalizes
individual resolvers by having less probes and a longer time before fixes
are picked up.


Doc Unbound Anchor (`doc/unbound-anchor.rst`)

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

.. program:: unbound-anchor

unbound-anchor(8)

Synopsis

unbound-anchor [opts]

Description

unbound-anchor performs setup or update of the root trust anchor for DNSSEC
validation.
The program fetches the trust anchor with the method from :rfc:7958 when
regular :rfc:5011 update fails to bring it up to date.
It can be run from the commandline, or run as part of startup scripts before
you start the :doc:unbound(8)</manpages/unbound> DNS server.

Note that if you want to use :rfc:5011 with Unbound (i.e., the
:ref:auto-trust-anchor-file option) so
that trust anchor information is automatically tracked by Unbound during
operation, the user that Unbound runs under (by default 'unbound') must have
write permissions to the file and the directory the file lives in (for creating
temporary files).
In this case you would probably want to run this program as the designated
Unbound user.

Suggested usage:

.. code-block:: text

in the init scripts.

provide or update the root anchor (if necessary)

unbound-anchor -a "@UNBOUND_ROOTKEY_FILE@"

Please note usage of this root anchor is at your own risk

and under the terms of our LICENSE (see source).

start validating resolver

the unbound.conf contains:

auto-trust-anchor-file: "@UNBOUND_ROOTKEY_FILE@"

unbound -c unbound.conf

This tool provides builtin default contents for the root anchor and root update
certificate files.

It tests if the root anchor file works, and if not, and an update is possible,
attempts to update the root anchor using the root update certificate.
It performs a https fetch of
root-anchors.xml <http://data.iana.org/root-anchors/root-anchors.xml>__
and checks the results (:rfc:7958); if all checks are successful, it updates
the root anchor file.
Otherwise the root anchor file is unchanged.
It performs :rfc:5011 tracking if the DNSSEC information available via the
DNS makes that possible.

It does not perform an update if the certificate is expired, if the network is
down or other errors occur.

The available options are:

.. option:: -a

text
The root anchor key file, that is read in and written out.
   Default is :file:`@UNBOUND_ROOTKEY_FILE@`.
   If the file does not exist, or is empty, a builtin root key is written
   to it.

.. option:: -c

text
The root update certificate file, that is read in.
   Default is :file:`@UNBOUND_ROOTCERT_FILE@`.
   If the file does not exist, or is empty, a builtin certificate is used.

.. option:: -l

text
List the builtin root key and builtin root update certificate on stdout.

.. option:: -u

text
The server name, it connects to ``https://name``.
   Specify without ``https://`` prefix.
   The default is ``"data.iana.org"``.
   It connects to the port specified with :option:`-P`.
   You can pass an IPv4 address or IPv6 address (no brackets) if you want.

.. option:: -S

text
Do not use SNI for the HTTPS connection.
   Default is to use SNI.

.. option:: -b

text
The source address to bind to for domain resolution and contacting the
   server on https.
   May be either an IPv4 address or IPv6 address (no brackets).

.. option:: -x

text
The pathname to the root-anchors.xml file on the server.
   (forms URL with :option:`-u`).
   The default is :file:`/root-anchors/root-anchors.xml`.

.. option:: -s

text
The pathname to the root-anchors.p7s file on the server.
   (forms URL with :option:`-u`).
   The default is :file:`/root-anchors/root-anchors.p7s`.
   This file has to be a PKCS7 signature over the xml file, using the pem
   file (:option:`-c`) as trust anchor.

.. option:: -n

text
The emailAddress for the Subject of the signer's certificate from the
   p7s signature file.
   Only signatures from this name are allowed.
   The default is ``[email protected]``.
   If you pass ``""`` then the emailAddress is not checked.

.. option:: -4

text
Use IPv4 for domain resolution and contacting the server on
   https.
   Default is to use IPv4 and IPv6 where appropriate.

.. option:: -6

text
Use IPv6 for domain resolution and contacting the server on https.
   Default is to use IPv4 and IPv6 where appropriate.

.. option:: -f <resolv.conf>

text
Use the given resolv.conf file.
   Not enabled by default, but you could try to pass
   :file:`/etc/resolv.conf` on some systems.
   It contains the IP addresses of the recursive nameservers to use.
   However, since this tool could be used to bootstrap that very recursive
   nameserver, it would not be useful (since that server is not up yet,
   since we are bootstrapping it).
   It could be useful in a situation where you know an upstream cache is
   deployed (and running) and in captive portal situations.

.. option:: -r <root.hints>

text
Use the given root.hints file (same syntax as the BIND and Unbound root
   hints file) to bootstrap domain resolution.
   By default a list of builtin root hints is used.
   unbound-anchor goes to the network itself for these roots, to resolve
   the server (:option:`-u` option) and to check the root DNSKEY records.
   It does so, because the tool when used for bootstrapping the recursive
   resolver, cannot use that recursive resolver itself because it is
   bootstrapping that server.

.. option:: -R

text
Allow fallback from :option:`-f` ``<resolv.conf>`` file to direct root
   servers query.
   It allows you to prefer local resolvers, but fallback automatically to
   direct root query if they do not respond or do not support DNSSEC.

.. option:: -v

text
More verbose.
   Once prints informational messages, multiple times may enable large
   debug amounts (such as full certificates or byte-dumps of downloaded
   files).
   By default it prints almost nothing.
   It also prints nothing on errors by default; in that case the original
   root anchor file is simply left undisturbed, so that a recursive server
   can start right after it.

.. option:: -C

text
Debug option to read :file:`` into the resolver process
   used.

.. option:: -P

text
Set the port number to use for the https connection.
   The default is 443.

.. option:: -F

text
Debug option to force update of the root anchor through downloading the
   xml file and verifying it with the certificate.
   By default it first tries to update by contacting the DNS, which uses
   much less bandwidth, is much faster (200 msec not 2 sec), and is nicer
   to the deployed infrastructure.
   With this option, it still attempts to do so (and may verbosely tell
   you), but then ignores the result and goes on to use the xml fallback
   method.

.. option:: -h

text
Show the version and commandline option help.

Exit Code

This tool exits with value 1 if the root anchor was updated using the
certificate or if the builtin root-anchor was used.
It exits with code 0 if no update was necessary, if the update was possible
with :rfc:5011 tracking, or if an error occurred.

You can check the exit value in this manner:

.. code-block:: text

text
unbound-anchor -a "root.key" || logger "Please check root.key"

Or something more suitable for your operational environment.

Trust

The root keys and update certificate included in this tool are provided for
convenience and under the terms of our license (see the LICENSE file in the
source distribution or https://github.com/NLnetLabs/unbound/blob/master/LICENSE
and might be stale or not suitable to your purpose.

By running :option:unbound-anchor -l the keys and certificate that are
configured in the code are printed for your convenience.

The built-in configuration can be overridden by providing a root-cert file and
a rootkey file.

Files

@UNBOUND_ROOTKEY_FILE@
The root anchor file, updated with 5011 tracking, and read and written
to.
The file is created if it does not exist.

@UNBOUND_ROOTCERT_FILE@
The trusted self-signed certificate that is used to verify the
downloaded DNSSEC root trust anchor.
You can update it by fetching it from
https://data.iana.org/root-anchors/icannbundle.pem (and validate it).
If the file does not exist or is empty, a builtin version is used.

https://data.iana.org/root-anchors/root-anchors.xml
Source for the root key information.

https://data.iana.org/root-anchors/root-anchors.p7s
Signature on the root key information.

See Also

:doc:unbound.conf(5)</manpages/unbound.conf>,
:doc:unbound(8)</manpages/unbound>.


Doc Unbound Checkconf (`doc/unbound-checkconf.rst`)

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

.. program:: unbound-checkconf

unbound-checkconf(8)

Synopsis

unbound-checkconf [-ahf] [-o option] [cfgfile]

Description

unbound-checkconf checks the configuration file for the
:doc:unbound(8)</manpages/unbound> DNS resolver for syntax and other errors.
The config file syntax is described in
:doc:unbound.conf(5)</manpages/unbound.conf>.

The available options are:

.. option:: -a

text
Also read the zonefiles for auth-zones and RPZ.
It checks if the syntax is okay of the zonefiles.

.. option:: -h

text
Show the version and commandline option help.

.. option:: -f

text
Print full pathname, with chroot applied to it.
Use with the :option:`-o` option.

.. option:: -q

text
Make the operation quiet, suppress output on success.

.. option:: -o

text
If given, after checking the config file the value of this option is
printed to stdout.
For ``""`` (disabled) options an empty line is printed.

.. option:: cfgfile

text
The config file to read with settings for Unbound.
It is checked.
If omitted, the config file at the default location is checked.

Exit Code

The unbound-checkconf program exits with status code 1 on error, 0 for a
correct config file.

Files

@ub_conf_file@
Unbound configuration file.

See Also

:doc:unbound.conf(5)</manpages/unbound.conf>,
:doc:unbound(8)</manpages/unbound>.


Doc Unbound Control (`doc/unbound-control.rst`)

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

.. program:: unbound-control

unbound-control(8)

Synopsis

unbound-control [-hq] [-c cfgfile] [-s server] command

Description

unbound-control performs remote administration on the
:doc:unbound(8)</manpages/unbound> DNS server.
It reads the configuration file, contacts the Unbound server over TLS sends the
command and displays the result.

The available options are:

.. option:: -h

text
Show the version and commandline option help.

.. option:: -c

text
The config file to read with settings.
If not given the default config file
:file:`@ub_conf_file@` is used.

.. option:: -s <server[@port]>

text
IPv4 or IPv6 address of the server to contact.
If not given, the address is read from the config file.

.. option:: -q

text
Quiet, if the option is given it does not print anything if it works ok.

Commands

There are several commands that the server understands.

@@[email protected]@start@@
Start the server.
Simply execs :doc:unbound(8)</manpages/unbound>.
The unbound executable is searched for in the PATH set in the
environment.
It is started with the config file specified using :option:-c or the
default config file.

@@[email protected]@stop@@
Stop the server.
The server daemon exits.

@@[email protected]@reload@@
Reload the server.
This flushes the cache and reads the config file fresh.

@@[email protected]@reload_keep_cache@@
Reload the server but try to keep the RRset and message cache if
(re)configuration allows for it.
That means the caches sizes and the number of threads must not change
between reloads.

@@[email protected]@fast_reload@@ [+dpv]
Reload the server, but keep downtime to a minimum, so that user queries
keep seeing service.
This needs the code compiled with threads.
The config is loaded in a thread, and prepared, then it briefly pauses the
existing server and updates config options.
The intent is that the pause does not impact the service of user queries.
The cache is kept.
Also user queries worked on are kept and continue, but with the new config
options.

text
.. note::
    This command is experimental at this time.

The amount of temporal memory needed during a fast_reload is twice the
amount needed for configuration.
This is because Unbound temporarily needs to store both current
configuration values and new ones while trying to fast_reload.
Zones loaded from disk (authority zones and RPZ zones) are included in such
memory needs.

Options that can be changed are for
:ref:`forwards`,
:ref:`stubs`,
:ref:`views`,
:ref:`authority zones`,
:ref:`RPZ zones` and
:ref:`local zones`.

Also
:ref:`access-control` and similar options,
:ref:`interface-action` and similar
options and
:ref:`tcp-connection-limit`.
It can reload some
:ref:`define-tag`
changes, more on that below.
Further options include
:ref:`insecure-lan-zones`,
:ref:`domain-insecure`,
:ref:`trust-anchor-file`,
:ref:`trust-anchor`,
:ref:`trusted-keys-file`,
:ref:`auto-trust-anchor-file`,
:ref:`edns-client-string`,
ipset,
:ref:`log-identity`,
:ref:`infra-cache-numhosts`,
:ref:`msg-cache-size`,
:ref:`rrset-cache-size`,
:ref:`key-cache-size`,
:ref:`ratelimit-size`,
:ref:`neg-cache-size`,
:ref:`num-queries-per-thread`,
:ref:`jostle-timeout`,
:ref:`use-caps-for-id`,
:ref:`unwanted-reply-threshold`,
:ref:`tls-use-sni`,
:ref:`outgoing-tcp-mss`,
:ref:`ip-dscp`,
:ref:`max-reuse-tcp-queries`,
:ref:`tcp-reuse-timeout`,
:ref:`tcp-auth-query-timeout`,
:ref:`delay-close`.
:ref:`iter-scrub-promiscuous`.
:ref:`tls-service-key`.
:ref:`tls-service-pem`.

It does not work with
:ref:`interface` and
:ref:`outgoing-interface` changes,
also not with
:ref:`remote control`,
:ref:`outgoing-port-permit`,
:ref:`outgoing-port-avoid`,
:ref:`msg-buffer-size`,
any **\*-slabs** options and
:ref:`statistics-interval` changes.

For :ref:`dnstap` these options can be changed:
:ref:`dnstap-log-resolver-query-messages`,
:ref:`dnstap-log-resolver-response-messages`,
:ref:`dnstap-log-client-query-messages`,
:ref:`dnstap-log-client-response-messages`,
:ref:`dnstap-log-forwarder-query-messages` and
:ref:`dnstap-log-forwarder-response-messages`.

It does not work with these options:
:ref:`dnstap-enable`,
:ref:`dnstap-bidirectional`,
:ref:`dnstap-socket-path`,
:ref:`dnstap-ip`,
:ref:`dnstap-tls`,
:ref:`dnstap-tls-server-name`,
:ref:`dnstap-tls-cert-bundle`,
:ref:`dnstap-tls-client-key-file` and
:ref:`dnstap-tls-client-cert-file`.

The options
:ref:`dnstap-send-identity`,
:ref:`dnstap-send-version`,
:ref:`dnstap-identity`, and
:ref:`dnstap-version` can be loaded
when ``+p`` is not used.

The ``+v`` option makes the output verbose which includes the time it took
to do the reload.
With ``+vv`` it is more verbose which includes the amount of memory that
was allocated temporarily to perform the reload; this amount of memory can
be big if the config has large contents.
In the timing output the 'reload' time is the time during which the server
was paused.

The ``+p`` option makes the reload not pause threads, they keep running.
Locks are acquired, but items are updated in sequence, so it is possible
for threads to see an inconsistent state with some options from the old
and some options from the new config, such as cache TTL parameters from the
old config and forwards from the new config.
The stubs and forwards are updated at the same time, so that they are
viewed consistently, either old or new values together.
The option makes the reload time take eg. 3 microseconds instead of 0.3
milliseconds during which the worker threads are interrupted.
So, the interruption is much shorter, at the expense of some inconsistency.
After the reload itself, every worker thread is briefly contacted to make
them release resources, this makes the delete timing a little longer, and
takes up time from the remote control servicing worker thread.

With the nopause option (``+p``), the reload does not work to reload some
options, that fast reload works on without the nopause option:
:ref:`val-bogus-ttl`,
:ref:`val-override-date`,
:ref:`val-sig-skew-min`,
:ref:`val-sig-skew-max`,
:ref:`val-max-restart`,
:ref:`val-nsec3-keysize-iterations`,
:ref:`target-fetch-policy`,
:ref:`outbound-msg-retry`,
:ref:`max-sent-count`,
:ref:`max-query-restarts`,
:ref:`do-not-query-address`,
:ref:`do-not-query-localhost`,
:ref:`private-address`,
:ref:`private-domain`,
:ref:`caps-exempt`,
:ref:`nat64-prefix`,
:ref:`do-nat64`,
:ref:`infra-host-ttl`,
:ref:`infra-keep-probing`,
:ref:`ratelimit`,
:ref:`ip-ratelimit`,
:ref:`ip-ratelimit-cookie`,
:ref:`wait-limit-netblock`,
:ref:`wait-limit-cookie-netblock`,
:ref:`ratelimit-below-domain`,
:ref:`ratelimit-for-domain`.

The ``+d`` option makes the reload drop queries that the worker threads are
working on.
This is like
:ref:`flush_requestlist`.
Without it the queries are kept so that users keep getting answers for
those queries that are currently processed.
The drop makes it so that queries during the life time of the
query processing see only old, or only new config options.

When there are changes to the config tags, from the
:ref:`define-tag` option,
then the ``+d`` option is implicitly turned on with a warning printout, and
queries are dropped.
This is to stop references to the old tag information, by the old
queries.
If the number of tags is increased in the newly loaded config, by
adding tags at the end, then the implicit ``+d`` option is not needed.

For response ip, that is actions associated with IP addresses, and perhaps
intersected with access control tag and action information, those settings
are stored with a query when it comes in based on its source IP address.
The old information is kept with the query until the queries are done.
This is gone when those queries are resolved and finished, or it is
possible to flush the requestlist with ``+d``.

@@[email protected]@verbosity@@ number
Change verbosity value for logging.
Same values as the verbosity: keyword in
:doc:unbound.conf(5)</manpages/unbound.conf>.
This new setting lasts until the server is issued a reload (taken from
config file again), or the next verbosity control command.

@@[email protected]@log_reopen@@
Reopen the logfile, close and open it.
Useful for logrotation to make the daemon release the file it is logging
to.
If you are using syslog it will attempt to close and open the syslog (which
may not work if chrooted).

@@[email protected]@stats@@
Print statistics.
Resets the internal counters to zero, this can be controlled using the
statistics-cumulative: config statement.
Statistics are printed with one [name]: [value] per line.

@@[email protected]@stats_noreset@@
Peek at statistics.
Prints them like the stats command does, but does not reset the internal
counters to zero.

@@[email protected]@status@@
Display server status.
Exit code 3 if not running (the connection to the port is refused), 1 on
error, 0 if running.

@@[email protected]@local_zone@@ name type
Add new local zone with name and type.
Like local-zone config statement.
If the zone already exists, the type is changed to the given argument.

@@[email protected]@local_zone_remove@@ name
Remove the local zone with the given name.
Removes all local data inside it.
If the zone does not exist, the command succeeds.

@@[email protected]@local_data@@ RR data...
Add new local data, the given resource record.
Like local-data: keyword, except for when no covering zone exists.
In that case this remote control command creates a transparent zone with
the same name as this record.

@@[email protected]@local_data_remove@@ name
Remove all RR data from local name.
If the name already has no items, nothing happens.
Often results in NXDOMAIN for the name (in a static zone), but if the name
has become an empty nonterminal (there is still data in domain names below
the removed name), NOERROR nodata answers are the result for that name.
With a specific RR instead of a domain name, that specific record is
removed from the local data, and not all the RR data.

@@[email protected]@local_zones@@
Add local zones read from stdin of unbound-control.
Input is read per line, with name space type on a line.
For bulk additions.

@@[email protected]@local_zones_remove@@
Remove local zones read from stdin of unbound-control.
Input is one name per line.
For bulk removals.

@@[email protected]@local_datas@@
Add local data RRs read from stdin of unbound-control.
Input is one RR per line.
For bulk additions.

@@[email protected]@local_datas_remove@@
Remove local data RRs read from stdin of unbound-control.
Input is one name per line.
For bulk removals.

@@[email protected]@dump_cache@@
The contents of the cache is printed in a text format to stdout.
You can redirect it to a file to store the cache in a file.
Not supported in remote Unbounds in multi-process operation.

@@[email protected]@load_cache@@
The contents of the cache is loaded from stdin.
Uses the same format as dump_cache uses.
Loading the cache with old, or wrong data can result in old or wrong data
returned to clients.
Loading data into the cache in this way is supported in order to aid with
debugging.
Not supported in remote Unbounds in multi-process operation.

@@[email protected]@cache_lookup@@ [+t] names
Print to stdout the RRsets and messages that are in the cache.
For every name listed the content at or under the name is printed.
Several names separated by spaces can be given, each is printed.
When subnetcache is enabled, also matching entries from the subnet
cache are printed.

text
The ``+t`` option allows tld and root names.
With it names like 'com' and '.' can be used, but it takes a lot of
effort to look up in the cache.

@@[email protected]@lookup@@ name
Print to stdout the name servers that would be used to look up the name
specified.

@@[email protected]@flush@@ [+c] name
Remove the name from the cache.
Removes the types A, AAAA, NS, SOA, CNAME, DNAME, MX, PTR, SRV, NAPTR,
SVCB and HTTPS.
Because that is fast to do.
Other record types can be removed using flush_type or flush_zone.

text
The ``+c`` option removes the items also from the cachedb cache.
If cachedb is in use.

@@[email protected]@flush_type@@ [+c] name type
Remove the name, type information from the cache.

text
The ``+c`` option removes the items also from the cachedb cache.
If cachedb is in use.

@@[email protected]@flush_zone@@ [+c] name
Remove all information at or below the name from the cache.
The rrsets and key entries are removed so that new lookups will be
performed.
This needs to walk and inspect the entire cache, and is a slow operation.
The entries are set to expired in the implementation of this command (so,
with serve-expired enabled, it'll serve that information but schedule a
prefetch for new information).

text
The ``+c`` option removes the items also from the cachedb cache.
If cachedb is in use.

@@[email protected]@flush_bogus@@ [+c]
Remove all bogus data from the cache.

text
The ``+c`` option removes the items also from the cachedb cache.
If cachedb is in use.

@@[email protected]@flush_negative@@ [+c]
Remove all negative data from the cache.
This is nxdomain answers, nodata answers and servfail answers.
Also removes bad key entries (which could be due to failed lookups) from
the dnssec key cache, and iterator last-resort lookup failures from the
rrset cache.

text
The ``+c`` option removes the items also from the cachedb cache.
If cachedb is in use.

@@[email protected]@flush_stats@@
Reset statistics to zero.

@@[email protected]@flush_requestlist@@
Drop the queries that are worked on.
Stops working on the queries that the server is working on now.
The cache is unaffected.
No reply is sent for those queries, probably making those users request
again later.
Useful to make the server restart working on queries with new settings,
such as a higher verbosity level.

@@[email protected]@dump_requestlist@@
Show what is worked on.
Prints all queries that the server is currently working on.
Prints the time that users have been waiting.
For internal requests, no time is printed.
And then prints out the module status.
This prints the queries from the first thread, and not queries that are
being serviced from other threads.

@@[email protected]@flush_infra@@ all|IP
If all then entire infra cache is emptied.
If a specific IP address, the entry for that address is removed from the
cache.
It contains EDNS, ping and lameness data.

@@[email protected]@dump_infra@@
Show the contents of the infra cache.

@@[email protected]@set_option@@ opt: val
Set the option to the given value without a reload.
The cache is therefore not flushed.
The option must end with a ':' and whitespace must be between the
option and the value.
Some values may not have an effect if set this way, the new values are not
written to the config file, not all options are supported.
This is different from the set_option call in libunbound, where all values
work because Unbound has not been initialized.

text
The values that work are: statistics-interval, statistics-cumulative,
do-not-query-localhost,  harden-short-bufsize, harden-large-queries,
harden-glue, harden-dnssec-stripped, harden-below-nxdomain,
harden-referral-path,  prefetch, prefetch-key, log-queries, hide-identity,
hide-version, identity, version, val-log-level, val-log-squelch,
ignore-cd-flag, add-holddown, del-holddown, keep-missing, tcp-upstream,
ssl-upstream, max-udp-size, ratelimit, ip-ratelimit, cache-max-ttl,
cache-min-ttl, cache-max-negative-ttl.

@@[email protected]@get_option@@ opt
Get the value of the option.
Give the option name without a trailing ':'.
The value is printed.
If the value is "", nothing is printed and the connection closes.
On error 'error ...' is printed (it gives a syntax error on unknown
option).
For some options a list of values, one on each line, is printed.
The options are shown from the config file as modified with set_option.
For some options an override may have been taken that does not show up with
this command, not results from e.g. the verbosity and forward control
commands.
Not all options work, see list_stubs, list_forwards, list_local_zones and
list_local_data for those.

@@[email protected]@list_stubs@@
List the stub zones in use.
These are printed one by one to the output.
This includes the root hints in use.

@@[email protected]@list_forwards@@
List the forward zones in use.
These are printed zone by zone to the output.

@@[email protected]@list_insecure@@
List the zones with domain-insecure.

@@[email protected]@list_local_zones@@
List the local zones in use.
These are printed one per line with zone type.

@@[email protected]@list_local_data@@
List the local data RRs in use.
The resource records are printed.

@@[email protected]@insecure_add@@ zone
Add a domain-insecure for the given zone, like the statement in
unbound.conf.
Adds to the running Unbound without affecting the cache
contents (which may still be bogus, use flush_zone to remove it), does not
affect the config file.

@@[email protected]@insecure_remove@@ zone
Removes domain-insecure for the given zone.

@@[email protected]@forward_add@@ [+it] zone addr ...
Add a new forward zone to running Unbound.
With +i option also adds a domain-insecure for the zone (so it can
resolve insecurely if you have a DNSSEC root trust anchor configured for
other names).
The addr can be IP4, IP6 or nameserver names, like forward-zone config in
unbound.conf.
The +t option sets it to use TLS upstream, like
:ref:forward-tls-upstream: yes.

@@[email protected]@forward_remove@@ [+i] zone
Remove a forward zone from running Unbound.
The +i also removes a domain-insecure for the zone.

@@[email protected]@stub_add@@ [+ipt] zone addr ...
Add a new stub zone to running Unbound.
With +i option also adds a domain-insecure for the zone.
With +p the stub zone is set to prime, without it it is set to
notprime.
The addr can be IP4, IP6 or nameserver names, like the stub-zone:
config in unbound.conf.
The +t option sets it to use TLS upstream, like
:ref:stub-tls-upstream: yes.

@@[email protected]@stub_remove@@ [+i] zone
Remove a stub zone from running Unbound.
The +i also removes a domain-insecure for the zone.

@@[email protected]@forward@@ [off | addr ... ]
Setup forwarding mode.
Configures if the server should ask other upstream nameservers, should go
to the internet root nameservers itself, or show the current config.
You could pass the nameservers after a DHCP update.

text
Without arguments the current list of addresses used to forward all queries
to is printed.
On startup this is from the forward-zone ``"."`` configuration.
Afterwards it shows the status.
It prints off when no forwarding is used.

If off is passed, forwarding is disabled and the root nameservers are
used.
This can be used to avoid to avoid buggy or non-DNSSEC supporting
nameservers returned from DHCP.
But may not work in hotels or hotspots.

If one or more IPv4 or IPv6 addresses are given, those are then used to
forward queries to.
The addresses must be separated with spaces.
With ``'@port'`` the port number can be set explicitly (default port is 53
(DNS)).

By default the forwarder information from the config file for the root
``"."`` is used.
The config file is not changed, so after a reload these changes are gone.
Other forward zones from the config file are not affected by this command.

@@[email protected]@ratelimit_list@@ [+a]
List the domains that are ratelimited.
Printed one per line with current estimated qps and qps limit from config.
With +a it prints all domains, not just the ratelimited domains, with
their estimated qps.
The ratelimited domains return an error for uncached (new) queries, but
cached queries work as normal.

@@[email protected]@ip_ratelimit_list@@ [+a]
List the ip addresses that are ratelimited.
Printed one per line with current estimated qps and qps limit from config.
With +a it prints all ips, not just the ratelimited ips, with their
estimated qps.
The ratelimited ips are dropped before checking the cache.

@@[email protected]@list_auth_zones@@
List the auth zones that are configured.
Printed one per line with a status, indicating if the zone is expired and
current serial number.
Configured RPZ zones are included.

@@[email protected]@auth_zone_reload@@ zone
Reload the auth zone (or RPZ zone) from zonefile.
The zonefile is read in overwriting the current contents of the zone in
memory.
This changes the auth zone contents itself, not the cache contents.
Such cache contents exists if you set Unbound to validate with
for-upstream: yes and that can be cleared with flush_zone zone.

@@[email protected]@auth_zone_transfer@@ zone
Transfer the auth zone (or RPZ zone) from master.
The auth zone probe sequence is started, where the masters are probed to
see if they have an updated zone (with the SOA serial check).
And then the zone is transferred for a newer zone version.

@@[email protected]@rpz_enable@@ zone
Enable the RPZ zone if it had previously been disabled.

@@[email protected]@rpz_disable@@ zone
Disable the RPZ zone.

@@[email protected]@view_list_local_zones@@ view
list_local_zones for given view.

@@[email protected]@view_local_zone@@ view name type
local_zone for given view.

@@[email protected]@view_local_zone_remove@@ view name
local_zone_remove for given view.

@@[email protected]@view_list_local_data@@ view
list_local_data for given view.

@@[email protected]@view_local_data@@ view RR data...
local_data for given view.

@@[email protected]@view_local_data_remove@@ view name
local_data_remove for given view.

@@[email protected]@view_local_datas_remove@@ view
Remove a list of local_data for given view from stdin.
Like local_datas_remove.

@@[email protected]@view_local_datas@@ view
Add a list of local_data for given view from stdin.
Like local_datas.

@@[email protected]@add_cookie_secret@@ secret
Add or replace a cookie secret persistently.
secret needs to be an 128 bit hex string.

text
Cookie secrets can be either **active** or **staging**.
**Active** cookie secrets are used to create DNS Cookies, but verification
of a DNS Cookie succeeds with any of the **active** or **staging** cookie
secrets.
The state of the current cookie secrets can be printed with the
:ref:`print_cookie_secrets`
command.

When there are no cookie secrets configured yet, the *secret* is added as
**active**.
If there is already an **active** cookie secret, the *secret* is added as
**staging** or replacing an existing **staging** secret.

To "roll" a cookie secret used in an anycast set.
The new secret has to be added as **staging** secret to **all** nodes in
the anycast set.
When **all** nodes can verify DNS Cookies with the new secret, the new
secret can be activated with the
:ref:`activate_cookie_secret`
command.
After **all** nodes have the new secret **active** for at least one hour,
the previous secret can be dropped with the
:ref:`drop_cookie_secret`
command.

Persistence is accomplished by writing to a file which is configured with
the
:ref:`cookie-secret-file`
option in the server section of the config file.
This is disabled by default, "".

@@[email protected]@drop_cookie_secret@@
Drop the staging cookie secret.

@@[email protected]@activate_cookie_secret@@
Make the current staging cookie secret active, and the current
active cookie secret staging.

@@[email protected]@print_cookie_secrets@@
Show the current configured cookie secrets with their status.

Exit Code

The unbound-control program exits with status code 1 on error, 0 on
success.

Set Up

The setup requires a self-signed certificate and private keys for both the
server and client.
The script unbound-control-setup generates these in the default run
directory, or with -d in another directory.
If you change the access control permissions on the key files you can decide
who can use unbound-control, by default owner and group but not all users.
Run the script under the same username as you have configured in
:file:unbound.conf or as root, so that the daemon is permitted to read the
files, for example with:

.. code-block:: bash

text
sudo -u unbound unbound-control-setup

If you have not configured a username in :file:unbound.conf, the keys need
read permission for the user credentials under which the daemon is started.
The script preserves private keys present in the directory.
After running the script as root, turn on
:ref:control-enable in
:file:unbound.conf.

Statistic Counters

The :ref:stats and
:ref:stats_noreset commands show a
number of statistic counters:

@@[email protected]@threadX.num.queries@@
number of queries received by thread

@@[email protected]@threadX.num.queries_ip_ratelimited@@
number of queries rate limited by thread

@@[email protected]@threadX.num.queries_cookie_valid@@
number of queries with a valid DNS Cookie by thread

@@[email protected]@threadX.num.queries_cookie_client@@
number of queries with a client part only DNS Cookie by thread

@@[email protected]@threadX.num.queries_cookie_invalid@@
number of queries with an invalid DNS Cookie by thread

@@[email protected]@threadX.num.queries_discard_timeout@@
number of queries removed due to discard-timeout by thread

@@[email protected]@threadX.num.queries_replyaddr_limit@@
number of queries removed due to replyaddr limits by thread

@@[email protected]@threadX.num.queries_wait_limit@@
number of queries removed due to wait-limit by thread

@@[email protected]@threadX.num.cachehits@@
number of queries that were successfully answered using a cache lookup

@@[email protected]@threadX.num.cachemiss@@
number of queries that needed recursive processing

@@[email protected]@threadX.num.dnscrypt.crypted@@
number of queries that were encrypted and successfully decapsulated by
dnscrypt.

@@[email protected]@threadX.num.dnscrypt.cert@@
number of queries that were requesting dnscrypt certificates.

@@[email protected]@threadX.num.dnscrypt.cleartext@@
number of queries received on dnscrypt port that were cleartext and not a
request for certificates.

@@[email protected]@threadX.num.dnscrypt.malformed@@
number of request that were neither cleartext, not valid dnscrypt messages.

@@[email protected]@threadX.num.dns_error_reports@@
number of DNS Error Reports generated by thread

@@[email protected]@threadX.num.prefetch@@
number of cache prefetches performed.
This number is included in cachehits, as the original query had the
unprefetched answer from cache, and resulted in recursive processing,
taking a slot in the requestlist.
Not part of the recursivereplies (or the histogram thereof) or cachemiss,
as a cache response was sent.

@@[email protected]@threadX.num.expired@@
number of replies that served an expired cache entry.

@@[email protected]@threadX.num.queries_timed_out@@
number of queries that are dropped because they waited in the UDP socket
buffer for too long.

@@[email protected]@threadX.query.queue_time_us.max@@
The maximum wait time for packets in the socket buffer, in microseconds.
This is only reported when
:ref:sock-queue-timeout is enabled.

@@[email protected]@threadX.num.recursivereplies@@
The number of replies sent to queries that needed recursive processing.
Could be smaller than threadX.num.cachemiss if due to timeouts no replies
were sent for some queries.

@@[email protected]@threadX.requestlist.avg@@
The average number of requests in the internal recursive processing request
list on insert of a new incoming recursive processing query.

@@[email protected]@threadX.requestlist.max@@
Maximum size attained by the internal recursive processing request list.

@@[email protected]@threadX.requestlist.overwritten@@
Number of requests in the request list that were overwritten by newer
entries.
This happens if there is a flood of queries that recursive processing and
the server has a hard time.
The counter is increased when during the flood the
:ref:jostle-timeout
allows a query to be removed in favor of a new incoming query.
The older query is then dropped to make space.

@@[email protected]@threadX.requestlist.exceeded@@
Queries that were dropped because the request list was full.
This happens if a flood of queries need recursive processing, and the
server can not keep up.
The counter is increased when during the flood there is no space
to be made with the jostle out of an older query, and the new query
is dropped.
Since no older queries are removed, see
:ref:jostle-timeout setting, there
is no space for the new query.

@@[email protected]@threadX.requestlist.current.all@@
Current size of the request list, includes internally generated queries
(such as priming queries and glue lookups).

@@[email protected]@threadX.requestlist.current.user@@
Current size of the request list, only the requests from client queries.

@@[email protected]@threadX.requestlist.current.replies@@
Current count of the number of reply entries waiting on request list
entries. Because a request list entry can send results to multiple reply
addresses, this number may be larger than the size of the request list.

@@[email protected]@threadX.recursion.time.avg@@
Average time it took to answer queries that needed recursive processing.
Note that queries that were answered from the cache are not in this average.

@@[email protected]@threadX.recursion.time.median@@
The median of the time it took to answer queries that needed recursive
processing.
The median means that 50% of the user queries were answered in less than
this time.
Because of big outliers (usually queries to non responsive servers), the
average can be bigger than the median.
This median has been calculated by interpolation from a histogram.

@@[email protected]@threadX.tcpusage@@
The currently held tcp buffers for incoming connections.
A spot value on the time of the request.
This helps you spot if the incoming-num-tcp buffers are full.

@@[email protected]@total.num.queries@@
summed over threads.

@@[email protected]@total.num.queries_ip_ratelimited@@
summed over threads.

@@[email protected]@total.num.queries_cookie_valid@@
summed over threads.

@@[email protected]@total.num.queries_cookie_client@@
summed over threads.

@@[email protected]@total.num.queries_cookie_invalid@@
summed over threads.

@@[email protected]@total.num.queries_discard_timeout@@
summed over threads.

@@[email protected]@total.num.queries_replyaddr_limit@@
summed over threads.

@@[email protected]@total.num.queries_wait_limit@@
summed over threads.

@@[email protected]@total.num.cachehits@@
summed over threads.

@@[email protected]@total.num.cachemiss@@
summed over threads.

@@[email protected]@total.num.dnscrypt.crypted@@
summed over threads.

@@[email protected]@total.num.dnscrypt.cert@@
summed over threads.

@@[email protected]@total.num.dnscrypt.cleartext@@
summed over threads.

@@[email protected]@total.num.dnscrypt.malformed@@
summed over threads.

@@[email protected]@total.num.dns_error_reports@@
summed over threads.

@@[email protected]@total.num.prefetch@@
summed over threads.

@@[email protected]@total.num.expired@@
summed over threads.

@@[email protected]@total.num.queries_timed_out@@
summed over threads.

@@[email protected]@total.query.queue_time_us.max@@
the maximum of the thread values.

@@[email protected]@total.num.recursivereplies@@
summed over threads.

@@[email protected]@total.requestlist.avg@@
averaged over threads.

@@[email protected]@total.requestlist.max@@
the maximum of the thread requestlist.max values.

@@[email protected]@total.requestlist.overwritten@@
summed over threads.

@@[email protected]@total.requestlist.exceeded@@
summed over threads.

@@[email protected]@total.requestlist.current.all@@
summed over threads.

@@[email protected]@total.requestlist.current.user@@
summed over threads.

@@[email protected]@total.requestlist.current.replies@@
summed over threads.

@@[email protected]@total.recursion.time.median@@
averaged over threads.

@@[email protected]@total.tcpusage@@
summed over threads.

@@[email protected]@time.now@@
current time in seconds since 1970.

@@[email protected]@time.up@@
uptime since server boot in seconds.

@@[email protected]@time.elapsed@@
time since last statistics printout, in seconds.

Extended Statistics

@@[email protected]@mem.cache.rrset@@
Memory in bytes in use by the RRset cache.

@@[email protected]@mem.cache.message@@
Memory in bytes in use by the message cache.

@@[email protected]@mem.cache.dnscrypt_shared_secret@@
Memory in bytes in use by the dnscrypt shared secrets cache.

@@[email protected]@mem.cache.dnscrypt_nonce@@
Memory in bytes in use by the dnscrypt nonce cache.

@@[email protected]@mem.mod.iterator@@
Memory in bytes in use by the iterator module.

@@[email protected]@mem.mod.validator@@
Memory in bytes in use by the validator module.
Includes the key cache and negative cache.

@@[email protected]@mem.streamwait@@
Memory in bytes in used by the TCP and TLS stream wait buffers.
These are answers waiting to be written back to the clients.

@@[email protected]@mem.http.query_buffer@@
Memory in bytes used by the HTTP/2 query buffers.
Containing (partial) DNS queries waiting for request stream completion.

@@[email protected]@mem.http.response_buffer@@
Memory in bytes used by the HTTP/2 response buffers.
Containing DNS responses waiting to be written back to the clients.

@@[email protected]@mem.quic@@
Memory in bytes used by QUIC.
Containing connection information, stream information, queries read and
responses written back to the clients.

@@[email protected]@histogram@@...to..
Shows a histogram, summed over all threads.
Every element counts the recursive queries whose reply time fit between the
lower and upper bound.
Times larger or equal to the lowerbound, and smaller than the upper bound.
There are 40 buckets, with bucket sizes doubling.

@@[email protected]@num.query.type.A@@
The total number of queries over all threads with query type A.
Printed for the other query types as well, but only for the types for which
queries were received, thus =0 entries are omitted for brevity.

@@[email protected]@num.query.type.other@@
Number of queries with query types 256-65535.

@@[email protected]@num.query.class.IN@@
The total number of queries over all threads with query class IN
(internet).
Also printed for other classes (such as CH (CHAOS) sometimes used for
debugging), or NONE, ANY, used by dynamic update.
num.query.class.other is printed for classes 256-65535.

@@[email protected]@num.query.opcode.QUERY@@
The total number of queries over all threads with query opcode QUERY.
Also printed for other opcodes, UPDATE, ...

@@[email protected]@num.query.tcp@@
Number of queries that were made using TCP towards the Unbound server.

@@[email protected]@num.query.tcpout@@
Number of queries that the Unbound server made using TCP outgoing towards
other servers.

@@[email protected]@num.query.udpout@@
Number of queries that the Unbound server made using UDP outgoing towards
other servers.

@@[email protected]@num.query.tls@@
Number of queries that were made using TLS towards the Unbound server.
These are also counted in num.query.tcp, because TLS uses TCP.

@@[email protected]@num.query.tls.resume@@
Number of TLS session resumptions, these are queries over TLS towards the
Unbound server where the client negotiated a TLS session resumption key.

@@[email protected]@num.query.https@@
Number of queries that were made using HTTPS towards the Unbound server.
These are also counted in num.query.tcp and num.query.tls, because HTTPS
uses TLS and TCP.

@@[email protected]@num.query.quic@@
Number of queries that were made using QUIC towards the Unbound server.
These are also counted in num.query.tls, because TLS is used for these
queries.

@@[email protected]@num.query.ipv6@@
Number of queries that were made using IPv6 towards the Unbound server.

@@[email protected]@num.query.flags.RD@@
The number of queries that had the RD flag set in the header.
Also printed for flags QR, AA, TC, RA, Z, AD, CD.
Note that queries with flags QR, AA or TC may have been rejected because of
that.

@@[email protected]@num.query.edns.present@@
number of queries that had an EDNS OPT record present.

@@[email protected]@num.query.edns.DO@@
number of queries that had an EDNS OPT record with the DO (DNSSEC OK) bit
set.
These queries are also included in the num.query.edns.present number.

@@[email protected]@num.query.ratelimited@@
The number of queries that are turned away from being send to nameserver
due to ratelimiting.

@@[email protected]@num.query.dnscrypt.shared_secret.cachemiss@@
The number of dnscrypt queries that did not find a shared secret in the
cache.
This can be use to compute the shared secret hitrate.

@@[email protected]@num.query.dnscrypt.replay@@
The number of dnscrypt queries that found a nonce hit in the nonce cache
and hence are considered a query replay.

@@[email protected]@num.answer.rcode.NXDOMAIN@@
The number of answers to queries, from cache or from recursion, that had
the return code NXDOMAIN.
Also printed for the other return codes.

@@[email protected]@num.answer.rcode.nodata@@
The number of answers to queries that had the pseudo return code nodata.
This means the actual return code was NOERROR, but additionally, no data
was carried in the answer (making what is called a NOERROR/NODATA answer).
These queries are also included in the num.answer.rcode.NOERROR number.
Common for AAAA lookups when an A record exists, and no AAAA.

@@[email protected]@num.answer.secure@@
Number of answers that were secure.
The answer validated correctly.
The AD bit might have been set in some of these answers, where the client
signalled (with DO or AD bit in the query) that they were ready to accept
the AD bit in the answer.

@@[email protected]@num.answer.bogus@@
Number of answers that were bogus.
These answers resulted in SERVFAIL to the client because the answer failed
validation.

@@[email protected]@num.rrset.bogus@@
The number of rrsets marked bogus by the validator.
Increased for every RRset inspection that fails.

@@[email protected]@num.valops@@
The number of validation operations performed by the validator.
Increased for every RRSIG verification operation regardless of the
validation result.
The RRSIG and key combination needs to first pass some sanity checks before
Unbound even performs the verification, e.g., length/protocol checks.

@@[email protected]@unwanted.queries@@
Number of queries that were refused or dropped because they failed the
access control settings.

@@[email protected]@unwanted.replies@@
Replies that were unwanted or unsolicited.
Could have been random traffic, delayed duplicates, very late answers, or
could be spoofing attempts.
Some low level of late answers and delayed duplicates are to be expected
with the UDP protocol.
Very high values could indicate a threat (spoofing).

@@[email protected]@msg.cache.count@@
The number of items (DNS replies) in the message cache.

@@[email protected]@rrset.cache.count@@
The number of RRsets in the rrset cache.
This includes rrsets used by the messages in the message cache, but also
delegation information.

@@[email protected]@infra.cache.count@@
The number of items in the infra cache.
These are IP addresses with their timing and protocol support information.

@@[email protected]@key.cache.count@@
The number of items in the key cache.
These are DNSSEC keys, one item per delegation point, and their validation
status.

@@[email protected]@msg.cache.max_collisions@@
The maximum number of hash table collisions in the msg cache.
This is the number of hashes that are identical when a new element is
inserted in the hash table.
If the value is very large, like hundreds, something is wrong with the
performance of the hash table, hash values are incorrect or malicious.

@@[email protected]@rrset.cache.max_collisions@@
The maximum number of hash table collisions in the rrset cache.
This is the number of hashes that are identical when a new element is
inserted in the hash table.
If the value is very large, like hundreds, something is wrong with the
performance of the hash table, hash values are incorrect or malicious.

@@[email protected]@dnscrypt_shared_secret.cache.count@@
The number of items in the shared secret cache.
These are precomputed shared secrets for a given client public key/server
secret key pair.
Shared secrets are CPU intensive and this cache allows Unbound to avoid
recomputing the shared secret when multiple dnscrypt queries are sent from
the same client.

@@[email protected]@dnscrypt_nonce.cache.count@@
The number of items in the client nonce cache.
This cache is used to prevent dnscrypt queries replay.
The client nonce must be unique for each client public key/server secret
key pair.
This cache should be able to host QPS * replay window interval keys to
prevent replay of a query during replay window seconds.

@@[email protected]@num.query.authzone.up@@
The number of queries answered from auth-zone data, upstream queries.
These queries would otherwise have been sent (with fallback enabled) to the
internet, but are now answered from the auth zone.

@@[email protected]@num.query.authzone.down@@
The number of queries for downstream answered from auth-zone data.
These queries are from downstream clients, and have had an answer from the
data in the auth zone.

@@[email protected]@num.query.aggressive.NOERROR@@
The number of queries answered using cached NSEC records with NODATA RCODE.
These queries would otherwise have been sent to the internet, but are now
answered using cached data.

@@[email protected]@num.query.aggressive.NXDOMAIN@@
The number of queries answered using cached NSEC records with NXDOMAIN
RCODE.
These queries would otherwise have been sent to the internet, but are now
answered using cached data.

@@[email protected]@num.query.subnet@@
Number of queries that got an answer that contained EDNS client subnet
data.

@@[email protected]@num.query.subnet_cache@@
Number of queries answered from the edns client subnet cache.
These are counted as cachemiss by the main counters, but hit the client
subnet specific cache after getting processed by the edns client subnet
module.

@@[email protected]@num.query.cachedb@@
Number of queries answered from the external cache of cachedb.
These are counted as cachemiss by the main counters, but hit the cachedb
external cache after getting processed by the cachedb module.

@@[email protected]@num.rpz.action@@.
Number of queries answered using configured RPZ policy, per RPZ action
type.
Possible actions are: nxdomain, nodata, passthru, drop, tcp-only,
local-data, disabled, and cname-override.

Files

@ub_conf_file@
Unbound configuration file.

@UNBOUND_RUN_DIR@
directory with private keys (:file:unbound_server.key and
:file:unbound_control.key) and self-signed certificates
(:file:unbound_server.pem and :file:unbound_control.pem).

See Also

:doc:unbound.conf(5)</manpages/unbound.conf>,
:doc:unbound(8)</manpages/unbound>.


Doc Unbound Host (`doc/unbound-host.rst`)

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

.. program:: unbound-host

unbound-host(1)

Synopsis

unbound-host [-C configfile] [-vdhr46D] [-c class]
[-t type] [-y key] [-f keyfile] [-F namedkeyfile] hostname

Description

unbound-host uses the Unbound validating resolver to query for the hostname
and display results.
With the :option:-v option it displays validation status: secure, insecure,
bogus (security failure).

By default it reads no configuration file whatsoever.
It attempts to reach the internet root servers.
With :option:-C an unbound config file and with :option:-r resolv.conf
can be read.

The available options are:

.. option:: hostname

text
This name is resolved (looked up in the DNS).
   If a IPv4 or IPv6 address is given, a reverse lookup is performed.

.. option:: -h

text
Show the version and commandline option help.

.. option:: -v

text
Enable verbose output and it shows validation results, on every line.
   Secure means that the NXDOMAIN (no such domain name), nodata (no such
   data) or positive data response validated correctly with one of the
   keys.
   Insecure means that that domain name has no security set up for it.
   Bogus (security failure) means that the response failed one or more
   checks, it is likely wrong, outdated, tampered with, or broken.

.. option:: -d

text
Enable debug output to stderr.
   One :option:`-d` shows what the resolver and validator are doing and may
   tell you what is going on.
   More times, :option:`-d` :option:`-d`, gives a lot of output, with every
   packet sent and received.

.. option:: -c

text
Specify the class to lookup for, the default is IN the internet
   class.

.. option:: -t

text
Specify the type of data to lookup.
   The default looks for IPv4, IPv6 and mail handler data, or domain name
   pointers for reverse queries.

.. option:: -y

text
Specify a public key to use as trust anchor.
   This is the base for a chain of trust that is built up from the trust
   anchor to the response, in order to validate the response message.
   Can be given as a DS or DNSKEY record.
   For example:

   .. code-block:: text

        -y "example.com DS 31560 5 1 1CFED84787E6E19CCF9372C1187325972FE546CD"

.. option:: -D

text
Enables DNSSEC validation.
   Reads the root anchor from the default configured root anchor at the
   default location, :file:`@UNBOUND_ROOTKEY_FILE@`.

.. option:: -f

text
Reads keys from a file.
   Every line has a DS or DNSKEY record, in the format as for :option:`-y`.
   The zone file format, the same as ``dig`` and ``drill`` produce.

.. option:: -F

text
Reads keys from a BIND-style :file:`named.conf` file.
   Only the ``trusted-key {};`` entries are read.

.. option:: -C

text
Uses the specified unbound.conf to prime :doc:`libunbound(3)</manpages/libunbound>`.
   Pass it as first argument if you want to override some options from the
   config file with further arguments on the commandline.

.. option:: -r

text
Read :file:`/etc/resolv.conf`, and use the forward DNS servers from
   there (those could have been set by DHCP).
   More info in *resolv.conf(5)*.
   Breaks validation if those servers do not support DNSSEC.

.. option:: -4

text
Use solely the IPv4 network for sending packets.

.. option:: -6

text
Use solely the IPv6 network for sending packets.

Examples

Some examples of use.
The keys shown below are fakes, thus a security failure is encountered.

.. code-block:: text

text
$ unbound-host www.example.com

   $ unbound-host -v -y "example.com DS 31560 5 1 1CFED84787E6E19CCF9372C1187325972FE546CD" www.example.com

   $ unbound-host -v -y "example.com DS 31560 5 1 1CFED84787E6E19CCF9372C1187325972FE546CD" 192.0.2.153

Exit Code

The unbound-host program exits with status code 1 on error, 0 on no error.
The data may not be available on exit code 0, exit code 1 means the lookup
encountered a fatal error.

See Also

:doc:unbound.conf(5)</manpages/unbound.conf>,
:doc:unbound(8)</manpages/unbound>.


Doc Unbound.Conf (`doc/unbound.conf.rst`)

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

unbound.conf(5)

Synopsis

unbound.conf

Description

unbound.conf is used to configure :doc:unbound(8)</manpages/unbound>.

The utility :doc:unbound-checkconf(8)</manpages/unbound-checkconf> can be
used to check unbound.conf prior to usage.

File Format

Whitespace is used to separate keywords.
Whitespace indentation is insignificant, but is still recommended for visual
clarity.
Comments start with # and last to the end of line.
Empty lines are ignored, as is whitespace at the beginning of a line.

Attribute keywords end with a colon (:) and they are either options or
section clauses (group options together).

The configuration file is logically divided into sections where each section
is introduced by a :ref:section clause.

Example

An example minimal config file is shown below; most settings are the defaults.
Copy this to @ub_conf_file@ and start the server with:

.. code-block:: text

text
$ unbound -c @ub_conf_file@

Stop the server with:

.. code-block:: text

text
$ kill `cat @UNBOUND_PIDFILE@`

The source distribution contains an extensive :file:example.conf file with
all the options.

.. code-block:: text

text
# unbound.conf(5) config file for unbound(8).
server:
    directory: "@UNBOUND_RUN_DIR@"
    username: unbound
    # make sure unbound can access entropy from inside the chroot.
    # e.g. on linux the use these commands (on BSD, devfs(8) is used):
    #      mount --bind -n /dev/urandom @UNBOUND_RUN_DIR@/dev/urandom
    # and  mount --bind -n /dev/log @UNBOUND_RUN_DIR@/dev/log
    chroot: "@UNBOUND_CHROOT_DIR@"
    # logfile: "@UNBOUND_RUN_DIR@/unbound.log"  #uncomment to use logfile.
    pidfile: "@UNBOUND_PIDFILE@"
    # verbosity: 1      # uncomment and increase to get more logging.
    # listen on all interfaces, answer queries from the local subnet.
    interface: 0.0.0.0
    interface: ::0
    access-control: 10.0.0.0/8 allow
    access-control: 2001:db8::/64 allow

.. _unbound.conf.clauses:

Section Clauses

The recognized section clauses are:

text
:ref:`server:`
    Most of the configuration is found in this section.

:ref:`remote-control:`
    Configuration for the facility used by
    :doc:`unbound-control(8)</manpages/unbound-control>`.

:ref:`stub-zone:`
    Configuration for a zone that redirects to specific authoritative name
    servers, e.g. for zones not generally available on the greater
    Internet.

:ref:`forward-zone:`
    Configuration for a zone that forwards to specific DNS resolvers.

:ref:`auth-zone:`
    Configuration for local authoritative zones.

:ref:`view:`
    Overriding a small subset of configuration for incoming requests.
    Requests are mapped to views with
    :ref:`access-control-view` and
    :ref:`interface-view`.

:ref:`python:`
    Configuration for the optional ``python`` script module.

:ref:`dynlib:`
    Configuration for the optional ``dynlib`` module that loads dynamic
    libraries into Unbound.

:ref:`dnscrypt:`
    Configuration for the optional DNSCrypt feature.

:ref:`cachedb:`
    Configuration for the optional ``cachedb`` module that can interface
    with second level caches, currently Redis or Redis-complatible
    databases.

:ref:`dnstap:`
    Configuration of the optional dnstap logging feature; a flexible,
    structured binary log format for DNS software.

:ref:`rpz:`
    Configuration for Response Policy Zones that allows for DNS filtering.
    Requires the ``respip`` module.

Section clauses can be repeated throughout the file (or included files) to
logically group options in one visually cohesive group.
This may be particularly useful for the server: clause with its myriad of
options.

.. _unbound.conf.include:

Including Files

Files can be included using the include: directive.
It can appear anywhere, it accepts a single file name as argument.
Processing continues as if the text from the included file was copied into the
config file at that point.
If also using :ref:chroot, using full path names for
the included files works, relative pathnames for the included names work if the
directory where the daemon is started equals its chroot/working directory or is
specified before the include statement with :ref:directory: dir.
Wildcards can be used to include multiple files, see glob(7).

.. _unbound.conf.include-toplevel:

For a more structural include option, the include-toplevel: directive can
be used.
This closes whatever section clause is currently active (if any) and forces the
use of section clauses in the included files and right after this directive.

.. _unbound.conf.server:

Server Options

These options are part of the server: section.

@@[email protected]@verbosity@@:
The verbosity level.

text
Level 0
    No verbosity, only errors.

Level 1
    Gives operational information.

Level 2
    Gives detailed operational information including short information per
    query.

Level 3
    Gives query level information, output per query.

Level 4
    Gives algorithm level information.

Level 5
    Logs client identification for cache misses.

The verbosity can also be increased from the command line and during run
time via remote control. See :doc:`unbound(8)</manpages/unbound>` and
:doc:`unbound-control(8)</manpages/unbound-control>` respectively.

Default: 1

@@[email protected]@statistics-interval@@:
The number of seconds between printing statistics to the log for every
thread.
Disable with value 0 or "".
The histogram statistics are only printed if replies were sent during the
statistics interval, requestlist statistics are printed for every interval
(but can be 0).
This is because the median calculation requires data to be present.

text
Default: 0 (disabled)

@@[email protected]@statistics-cumulative@@:
If enabled, statistics are cumulative since starting Unbound, without
clearing the statistics counters after logging the statistics.

text
Default: no

@@[email protected]@extended-statistics@@:
If enabled, extended statistics are printed from
:doc:unbound-control(8)</manpages/unbound-control>.
The counters are listed in
:doc:unbound-control(8)</manpages/unbound-control>.
Keeping track of more statistics takes time.

text
Default: no

@@[email protected]@statistics-inhibit-zero@@:
If enabled, selected extended statistics with a value of 0 are inhibited
from printing with
:doc:unbound-control(8)</manpages/unbound-control>.
These are query types, query classes, query opcodes, answer rcodes
(except NOERROR, FORMERR, SERVFAIL, NXDOMAIN, NOTIMPL, REFUSED)
and PRZ actions.

text
Default: yes

@@[email protected]@num-threads@@:
The number of threads to create to serve clients. Use 1 for no threading.

text
Default: 1

@@[email protected]@port@@: **
The port number on which the server responds to queries.

text
Default: 53

@@[email protected]@interface@@: **
Interface to use to connect to the network.
This interface is listened to for queries from clients, and answers to
clients are given from it.
Can be given multiple times to work on several interfaces.
If none are given the default is to listen on localhost.

text
If an interface name is used instead of an IP address, the list of IP
addresses on that interface are used.
The interfaces are not changed on a reload (``kill -HUP``) but only on
restart.

A port number can be specified with @port (without spaces between interface
and port number), if not specified the default port (from
:ref:`port`) is used.

@@[email protected]@ip-address@@: **
Same as :ref:interface (for ease of
compatibility with :external+nsd:doc:manpages/nsd.conf).

@@[email protected]@interface-automatic@@:
Listen on all addresses on all (current and future) interfaces, detect the
source interface on UDP queries and copy them to replies.
This is a lot like :ref:ip-transparent, but
this option services all interfaces whilst with
:ref:ip-transparent you can select which
(future) interfaces Unbound provides service on.
This feature is experimental, and needs support in your OS for particular
socket options.

text
Default: no

@@[email protected]@interface-automatic-ports@@: ""
List the port numbers that
:ref:interface-automatic listens on.
If empty, the default port is listened on.
The port numbers are separated by spaces in the string.

text
This can be used to have interface automatic to deal with the interface,
and listen on the normal port number, by including it in the list, and
also HTTPS or DNS-over-TLS port numbers by putting them in the list as
well.

Default: ""

@@[email protected]@outgoing-interface@@: **
Interface to use to connect to the network.
This interface is used to send queries to authoritative servers and receive
their replies.
Can be given multiple times to work on several interfaces.
If none are given the default (all) is used.
You can specify the same interfaces in
:ref:interface and
:ref:outgoing-interface lines, the
interfaces are then used for both purposes.
Outgoing queries are sent via a random outgoing interface to counter
spoofing.

text
If an IPv6 netblock is specified instead of an individual IPv6 address,
outgoing UDP queries will use a randomised source address taken from the
netblock to counter spoofing.
Requires the IPv6 netblock to be routed to the host running Unbound, and
requires OS support for unprivileged non-local binds (currently only
supported on Linux).
Several netblocks may be specified with multiple
:ref:`outgoing-interface` options, but do
not specify both an individual IPv6 address and an IPv6 netblock, or the
randomisation will be compromised.
Consider combining with :ref:`prefer-ip6: yes` to
increase the likelihood of IPv6 nameservers being selected for queries.
On Linux you need these two commands to be able to use the freebind socket
option to receive traffic for the ip6 netblock:

.. code-block:: text

    ip -6 addr add mynetblock/64 dev lo && \
    ip -6 route add local mynetblock/64 dev lo

@@[email protected]@outgoing-range@@:
Number of ports to open.
This number of file descriptors can be opened per thread.
Must be at least 1.
Default depends on compile options.
Larger numbers need extra resources from the operating system.
For performance a very large value is best, use libevent to make this
possible.
Should be higher (preferably double) than the value of
:ref:num-queries-per-thread to
account for cases where the request list is full and avoid file descriptor
starvation.

text
Default: 4096 (libevent) / 960 (minievent) / 48 (windows)

@@[email protected]@outgoing-port-permit@@: **
Permit Unbound to open this port or range of ports for use to send queries.
A larger number of permitted outgoing ports increases resilience against
spoofing attempts.
Make sure these ports are not needed by other daemons.
By default only ports above 1024 that have not been assigned by IANA are
used.
Give a port number or a range of the form "low-high", without spaces.

text
The :ref:`outgoing-port-permit` and
:ref:`outgoing-port-avoid` statements
are processed in the line order of the config file, adding the permitted
ports and subtracting the avoided ports from the set of allowed ports.
The processing starts with the non IANA allocated ports above 1024 in the
set of allowed ports.

@@[email protected]@outgoing-port-avoid@@: **
Do not permit Unbound to open this port or range of ports for use to send
queries.
Use this to make sure Unbound does not grab a port that another daemon
needs.
The port is avoided on all outgoing interfaces, both IPv4 and IPv6.
By default only ports above 1024 that have not been assigned by IANA are
used.
Give a port number or a range of the form "low-high", without spaces.

@@[email protected]@outgoing-num-tcp@@:
Number of outgoing TCP buffers to allocate per thread.
If set to 0, or if :ref:do-tcp: no is set, no TCP
queries to authoritative servers are done.
For larger installations increasing this value is a good idea.

text
Default: 10

@@[email protected]@incoming-num-tcp@@:
Number of incoming TCP buffers to allocate per thread.
If set to 0, or if :ref:do-tcp: no is set, no TCP
queries from clients are accepted.
For larger installations increasing this value is a good idea.

text
Default: 10

@@[email protected]@edns-buffer-size@@:
Number of bytes size to advertise as the EDNS reassembly buffer size.
This is the value put into datagrams over UDP towards peers.
The actual buffer size is determined by
:ref:msg-buffer-size (both for TCP and
UDP).
Do not set higher than that value.
Setting to 512 bypasses even the most stringent path MTU problems, but is
seen as extreme, since the amount of TCP fallback generated is excessive
(probably also for this resolver, consider tuning
:ref:outgoing-num-tcp).

text
Default: 1232 (`DNS Flag Day 2020 recommendation
<https://dnsflagday.net/2020/>`__)

@@[email protected]@max-udp-size@@:
Maximum UDP response size (not applied to TCP response).
65536 disables the UDP response size maximum, and uses the choice from the
client, always.
Suggested values are 512 to 4096.

text
Default: 1232 (same as :ref:`edns-buffer-size`)

@@[email protected]@stream-wait-size@@:
Number of bytes size maximum to use for waiting stream buffers.
A plain number is in bytes, append 'k', 'm' or 'g' for kilobytes, megabytes
or gigabytes (1024*1024 bytes in a megabyte).
As TCP and TLS streams queue up multiple results, the amount of memory used
for these buffers does not exceed this number, otherwise the responses are
dropped.
This manages the total memory usage of the server (under heavy use), the
number of requests that can be queued up per connection is also limited,
with further requests waiting in TCP buffers.

text
Default: 4m

@@[email protected]@msg-buffer-size@@:
Number of bytes size of the message buffers.
Default is 65552 bytes, enough for 64 Kb packets, the maximum DNS message
size.
No message larger than this can be sent or received.
Can be reduced to use less memory, but some requests for DNS data, such as
for huge resource records, will result in a SERVFAIL reply to the client.

text
Default: 65552

@@[email protected]@msg-cache-size@@:
Number of bytes size of the message cache.
A plain number is in bytes, append 'k', 'm' or 'g' for kilobytes, megabytes
or gigabytes (1024*1024 bytes in a megabyte).

text
Default: 4m

@@[email protected]@msg-cache-slabs@@:
Number of slabs in the message cache.
Slabs reduce lock contention by threads.
Must be set to a power of 2.
Setting (close) to the number of cpus is a fairly good setting.
If left unconfigured, it will be configured automatically to be a power of
2 close to the number of configured threads in multi-threaded environments.

text
Default: (unconfigured)

@@[email protected]@num-queries-per-thread@@:
The number of queries that every thread will service simultaneously.
If more queries arrive that need servicing, and no queries can be jostled
out (see :ref:jostle-timeout), then the
queries are dropped.
This forces the client to resend after a timeout; allowing the server time
to work on the existing queries.
Default depends on compile options.

text
Default: 2048 (libevent) / 512 (minievent) / 24 (windows)

@@[email protected]@jostle-timeout@@:
Timeout used when the server is very busy.
Set to a value that usually results in one roundtrip to the authority
servers.

text
If too many queries arrive, then 50% of the queries are allowed to run to
completion, and the other 50% are replaced with the new incoming query if
they have already spent more than their allowed time.
This protects against denial of service by slow queries or high query
rates.

The effect is that the qps for long-lasting queries is about:

.. code-block:: text

    (num-queries-per-thread / 2) / (average time for such long queries) qps

The qps for short queries can be about:

.. code-block:: text

    (num-queries-per-thread / 2) / (jostle-timeout in whole seconds) qps per thread

about (2048/2)*5 = 5120 qps by default.

Default: 200

@@[email protected]@delay-close@@:
Extra delay for timeouted UDP ports before they are closed, in msec.
This prevents very delayed answer packets from the upstream (recursive)
servers from bouncing against closed ports and setting off all sort of
close-port counters, with eg. 1500 msec.
When timeouts happen you need extra sockets, it checks the ID and remote IP
of packets, and unwanted packets are added to the unwanted packet counter.

text
Default: 0 (disabled)

@@[email protected]@udp-connect@@:
Perform connect(2) for UDP sockets that mitigates ICMP side channel
leakage.

text
Default: yes

@@[email protected]@unknown-server-time-limit@@:
The wait time in msec for waiting for an unknown server to reply.
Increase this if you are behind a slow satellite link, to eg. 1128.
That would then avoid re-querying every initial query because it times out.

text
Default: 376

@@[email protected]@discard-timeout@@:
The wait time in msec where recursion requests are dropped.
This is to stop a large number of replies from accumulating.
They receive no reply, the work item continues to recurse.
For UDP the replies are dropped, for stream connections the reply
is not dropped if the stream connection is still open ready to receive
answers.
It is nice to be a bit larger than
:ref:serve-expired-client-timeout
if that is enabled.
A value of 1900 msec is suggested.
The value 0 disables it.

text
Default: 1900

@@[email protected]@wait-limit@@:
The number of replies that can wait for recursion, for an IP address.
This makes a ratelimit per IP address of waiting replies for recursion.
It stops very large amounts of queries waiting to be returned to one
destination.
The value 0 disables all wait limits.

text
Default: 1000

@@[email protected]@wait-limit-cookie@@:
The number of replies that can wait for recursion, for an IP address
that sent the query with a valid DNS Cookie.
Since the cookie already validates the client address, this option allows
to override a configured
:ref:wait-limit value usually with a higher one
for cookie validated queries.
The value 0 disables wait limits for cookie validated queries.

text
Default: 10000

@@[email protected]@wait-limit-netblock@@:
The wait limit for the netblock.
If not given the
:ref:wait-limit
value is used.
The most specific netblock is used to determine the limit.
Useful for overriding the default for a specific, group or individual,
server.
The value -1 disables wait limits for the netblock.
By default the loopback has a wait limit netblock of -1, it is not
limited, because it is separated from the rest of network for spoofed
packets.
The loopback addresses 127.0.0.0/8 and ::1/128 are default at -1.

text
Default: (none)

@@[email protected]@wait-limit-cookie-netblock@@:
The wait limit for the netblock, when the query has a DNS Cookie.
If not given, the
:ref:wait-limit-cookie
value is used.
The value -1 disables wait limits for the netblock.
The loopback addresses 127.0.0.0/8 and ::1/128 are default at -1.

text
Default: (none)

@@[email protected]@so-rcvbuf@@:
If not 0, then set the SO_RCVBUF socket option to get more buffer space on
UDP port 53 incoming queries.
So that short spikes on busy servers do not drop packets (see counter in
netstat -su).
Otherwise, the number of bytes to ask for, try "4m" on a busy server.

text
The OS caps it at a maximum, on linux Unbound needs root permission to
bypass the limit, or the admin can use ``sysctl net.core.rmem_max``.

On BSD change ``kern.ipc.maxsockbuf`` in ``/etc/sysctl.conf``.

On OpenBSD change header and recompile kernel.

On Solaris ``ndd -set /dev/udp udp_max_buf 8388608``.

Default: 0 (use system value)

@@[email protected]@so-sndbuf@@:
If not 0, then set the SO_SNDBUF socket option to get more buffer space on
UDP port 53 outgoing responses.
This for very busy servers handles spikes in answer traffic, otherwise:

text
.. code-block:: text

    send: resource temporarily unavailable

can get logged, the buffer overrun is also visible by ``netstat -su``.
If set to 0 it uses the system value.
Specify the number of bytes to ask for, try "8m" on a very busy server.

It needs some space to be able to deal with packets that wait for local
address resolution, from like ARP and NDP discovery, before they are sent
out, hence it is elevated above the system default by default.

The OS caps it at a maximum, on linux Unbound needs root permission to
bypass the limit, or the admin can use ``sysctl net.core.wmem_max``.

On BSD, Solaris changes are similar to
:ref:`so-rcvbuf`.

Default: 4m

@@[email protected]@so-reuseport@@:
If yes, then open dedicated listening sockets for incoming queries for each
thread and try to set the SO_REUSEPORT socket option on each socket.
May distribute incoming queries to threads more evenly.

text
On Linux it is supported in kernels >= 3.9.

On other systems, FreeBSD, OSX it may also work.

You can enable it (on any platform and kernel), it then attempts to open
the port and passes the option if it was available at compile time, if that
works it is used, if it fails, it continues silently (unless verbosity 3)
without the option.

At extreme load it could be better to turn it off to distribute the queries
evenly, reported for Linux systems (4.4.x).

Default: yes

@@[email protected]@ip-transparent@@:
If yes, then use IP_TRANSPARENT socket option on sockets where Unbound is
listening for incoming traffic.
Allows you to bind to non-local interfaces.
For example for non-existent IP addresses that are going to exist later on,
with host failover configuration.

text
This is a lot like
:ref:`interface-automatic`, but that one
services all interfaces and with this option you can select which (future)
interfaces Unbound provides service on.

This option needs Unbound to be started with root permissions on some
systems.
The option uses IP_BINDANY on FreeBSD systems and SO_BINDANY on OpenBSD
systems.

Default: no

@@[email protected]@ip-freebind@@:
If yes, then use IP_FREEBIND socket option on sockets where Unbound is
listening to incoming traffic.
Allows you to bind to IP addresses that are nonlocal or do not exist, like
when the network interface or IP address is down.

text
Exists only on Linux, where the similar
:ref:`ip-transparent` option is also
available.

Default: no

@@[email protected]@ip-dscp@@:
The value of the Differentiated Services Codepoint (DSCP) in the
differentiated services field (DS) of the outgoing IP packet headers.
The field replaces the outdated IPv4 Type-Of-Service field and the IPv6
traffic class field.

@@[email protected]@rrset-cache-size@@:
Number of bytes size of the RRset cache.
A plain number is in bytes, append 'k', 'm' or 'g' for kilobytes, megabytes
or gigabytes (1024*1024 bytes in a megabyte).

text
Default: 4m

@@[email protected]@rrset-cache-slabs@@:
Number of slabs in the RRset cache.
Slabs reduce lock contention by threads.
Must be set to a power of 2.
Setting (close) to the number of cpus is a fairly good setting.
If left unconfigured, it will be configured automatically to be a power of
2 close to the number of configured threads in multi-threaded environments.

text
Default: (unconfigured)

@@[email protected]@cache-max-ttl@@:
Time to live maximum for RRsets and messages in the cache.
When the TTL expires, the cache item has expired.
Can be set lower to force the resolver to query for data often, and not
trust (very large) TTL values.
Downstream clients also see the lower TTL.

text
Default: 86400 (1 day)

@@[email protected]@cache-min-ttl@@:
Time to live minimum for RRsets and messages in the cache.
If the minimum kicks in, the data is cached for longer than the domain
owner intended, and thus less queries are made to look up the data.
Zero makes sure the data in the cache is as the domain owner intended,
higher values, especially more than an hour or so, can lead to trouble as
the data in the cache does not match up with the actual data any more.

text
Default: 0 (disabled)

@@[email protected]@cache-max-negative-ttl@@:
Time to live maximum for negative responses, these have a SOA in the
authority section that is limited in time.
This applies to NXDOMAIN and NODATA answers.

text
Default: 3600

@@[email protected]@cache-min-negative-ttl@@:
Time to live minimum for negative responses, these have a SOA in the
authority section that is limited in time.
If this is disabled and
:ref:cache-min-ttl
is configured, it will take effect instead.
In that case you can set this to 1 to honor the upstream TTL.
This applies to NXDOMAIN and NODATA answers.

text
Default: 0 (disabled)

@@[email protected]@infra-host-ttl@@:
Time to live for entries in the host cache.
The host cache contains roundtrip timing, lameness and EDNS support
information.

text
Default: 900

@@[email protected]@infra-cache-slabs@@:
Number of slabs in the infrastructure cache.
Slabs reduce lock contention by threads.
Must be set to a power of 2.
Setting (close) to the number of cpus is a fairly good setting.
If left unconfigured, it will be configured automatically to be a power of
2 close to the number of configured threads in multi-threaded environments.

text
Default: (unconfigured)

@@[email protected]@infra-cache-numhosts@@:
Number of hosts for which information is cached.

text
Default: 10000

@@[email protected]@infra-cache-min-rtt@@:
Lower limit for dynamic retransmit timeout calculation in infrastructure
cache.
Increase this value if using forwarders needing more time to do recursive
name resolution.

text
Default: 50

@@[email protected]@infra-cache-max-rtt@@:
Upper limit for dynamic retransmit timeout calculation in infrastructure
cache.

text
Default: 120000 (2 minutes)

@@[email protected]@infra-keep-probing@@:
If enabled the server keeps probing hosts that are down, in the one probe
at a time regime.
Hosts that are down, eg. they did not respond during the one probe at a
time period, are marked as down and it may take
:ref:infra-host-ttl time to get probed
again.

text
Default: no

@@[email protected]@define-tag@@: ""
Define the tags that can be used with
:ref:local-zone and
:ref:access-control.
Enclose the list between quotes ("") and put spaces between tags.

@@[email protected]@do-ip4@@:
Enable or disable whether IPv4 queries are answered or issued.

text
Default: yes

@@[email protected]@do-ip6@@:
Enable or disable whether IPv6 queries are answered or issued.
If disabled, queries are not answered on IPv6, and queries are not sent on
IPv6 to the internet nameservers.
With this option you can disable the IPv6 transport for sending DNS
traffic, it does not impact the contents of the DNS traffic, which may have
IPv4 (A) and IPv6 (AAAA) addresses in it.

text
Default: yes

@@[email protected]@prefer-ip4@@:
If enabled, prefer IPv4 transport for sending DNS queries to internet
nameservers.
Useful if the IPv6 netblock the server has, the entire /64 of that is not
owned by one operator and the reputation of the netblock /64 is an issue,
using IPv4 then uses the IPv4 filters that the upstream servers have.

text
Default: no

@@[email protected]@prefer-ip6@@:
If enabled, prefer IPv6 transport for sending DNS queries to internet
nameservers.

text
Default: no

@@[email protected]@do-udp@@:
Enable or disable whether UDP queries are answered or issued.

text
Default: yes

@@[email protected]@do-tcp@@:
Enable or disable whether TCP queries are answered or issued.

text
Default: yes

@@[email protected]@tcp-mss@@:
Maximum segment size (MSS) of TCP socket on which the server responds to
queries.
Value lower than common MSS on Ethernet (1220 for example) will address
path MTU problem.
Note that not all platform supports socket option to set MSS (TCP_MAXSEG).
Default is system default MSS determined by interface MTU and negotiation
between server and client.

@@[email protected]@outgoing-tcp-mss@@:
Maximum segment size (MSS) of TCP socket for outgoing queries (from Unbound
to other servers).
Value lower than common MSS on Ethernet (1220 for example) will address
path MTU problem.
Note that not all platform supports socket option to set MSS (TCP_MAXSEG).
Default is system default MSS determined by interface MTU and negotiation
between Unbound and other servers.

@@[email protected]@tcp-idle-timeout@@:
The period Unbound will wait for a query on a TCP connection.
If this timeout expires Unbound closes the connection.
When the number of free incoming TCP buffers falls below 50% of the total
number configured, the option value used is progressively reduced, first to
1% of the configured value, then to 0.2% of the configured value if the
number of free buffers falls below 35% of the total number configured, and
finally to 0 if the number of free buffers falls below 20% of the total
number configured.
A minimum timeout of 200 milliseconds is observed regardless of the option
value used.
It will be overridden by
:ref:edns-tcp-keepalive-timeout
if
:ref:edns-tcp-keepalive
is enabled.

text
Default: 30000 (30 seconds)

@@[email protected]@tcp-reuse-timeout@@:
The period Unbound will keep TCP persistent connections open to authority
servers.

text
Default: 60000 (60 seconds)

@@[email protected]@max-reuse-tcp-queries@@:
The maximum number of queries that can be sent on a persistent TCP
connection.

text
Default: 200

@@[email protected]@tcp-auth-query-timeout@@:
Timeout in milliseconds for TCP queries to auth servers.

text
Default: 3000 (3 seconds)

@@[email protected]@edns-tcp-keepalive@@:
Enable or disable EDNS TCP Keepalive.

text
Default: no

@@[email protected]@edns-tcp-keepalive-timeout@@:
Overrides
:ref:tcp-idle-timeout
when
:ref:edns-tcp-keepalive
is enabled.
If the client supports the EDNS TCP Keepalive option,
If the client supports the EDNS TCP Keepalive option, Unbound sends the
timeout value to the client to encourage it to close the connection before
the server times out.

text
Default: 120000 (2 minutes)

@@[email protected]@sock-queue-timeout@@:
UDP queries that have waited in the socket buffer for a long time can be
dropped.
The time is set in seconds, 3 could be a good value to ignore old queries
that likely the client does not need a reply for any more.
This could happen if the host has not been able to service the queries for
a while, i.e. Unbound is not running, and then is enabled again.
It uses timestamp socket options.
The socket option is available on the Linux and FreeBSD platforms.

text
Default: 0 (disabled)

@@[email protected]@tcp-upstream@@:
Enable or disable whether the upstream queries use TCP only for transport.
Useful in tunneling scenarios.
If set to no you can specify TCP transport only for selected forward or
stub zones using
:ref:forward-tcp-upstream or
:ref:stub-tcp-upstream
respectively.

text
Default: no

@@[email protected]@udp-upstream-without-downstream@@:
Enable UDP upstream even if :ref:do-udp: no is set.
Useful for TLS service providers, that want no UDP downstream but use UDP
to fetch data upstream.

text
Default: no (no changes)

@@[email protected]@tls-upstream@@:
Enabled or disable whether the upstream queries use TLS only for transport.
Useful in tunneling scenarios.
The TLS contains plain DNS in TCP wireformat.
The other server must support this (see
:ref:tls-service-key).

text
If you enable this, also configure a
:ref:`tls-cert-bundle` or use
:ref:`tls-win-cert` or
:ref:`tls-system-cert` to load CA certs,
otherwise the connections cannot be authenticated.

This option enables TLS for all of them, but if you do not set this you can
configure TLS specifically for some forward zones with
:ref:`forward-tls-upstream`.
And also with
:ref:`stub-tls-upstream`.
If the
:ref:`tls-upstream`
option is enabled, it is for all the forwards and stubs, where the
:ref:`forward-tls-upstream`
and
:ref:`stub-tls-upstream`
options are ignored, as if they had been set to yes.

Default: no

@@[email protected]@ssl-upstream@@:
Alternate syntax for :ref:tls-upstream.
If both are present in the config file the last is used.

@@[email protected]@tls-service-key@@:
If enabled, the server provides DNS-over-TLS or DNS-over-HTTPS service on
the TCP ports marked implicitly or explicitly for these services with
:ref:tls-port or
:ref:https-port.
The file must contain the private key for the TLS session, the public
certificate is in the :ref:tls-service-pem
file and it must also be specified if
:ref:tls-service-key is specified.
If the key is stored with root permissions or outside of chroot, then
a change or enabling or disabling requires a restart (a reload is not
enough).
But if the key file (and tls-service-pem file) are accessible, then they
are read in on reload, and fast_reload.
The server checks the modification time of the file (and the filename)
to see if the file has changed for reload.
The ports enabled implicitly or explicitly via
:ref:tls-port and
:ref:https-port do not provide normal DNS TCP
service.

text
.. note::
    Unbound needs to be compiled with libnghttp2 in order to provide
    DNS-over-HTTPS.

Default: "" (disabled)

@@[email protected]@ssl-service-key@@:
Alternate syntax for :ref:tls-service-key.

@@[email protected]@tls-service-pem@@:
The public key certificate pem file for the tls service.

text
Default: "" (disabled)

@@[email protected]@ssl-service-pem@@:
Alternate syntax for :ref:tls-service-pem.

@@[email protected]@tls-port@@:
The port number on which to provide TCP TLS service.
Only interfaces configured with that port number as @number get the TLS
service.

text
Default: 853

@@[email protected]@ssl-port@@:
Alternate syntax for :ref:tls-port.

@@[email protected]@tls-cert-bundle@@:
If null or "", no file is used.
Set it to the certificate bundle file, for example
:file:/etc/pki/tls/certs/ca-bundle.crt.
These certificates are used for authenticating connections made to outside
peers.
For example :ref:auth-zone urls, and also
DNS-over-TLS connections.
It is read at start up before permission drop and chroot.

text
Default: "" (disabled)

@@[email protected]@ssl-cert-bundle@@:
Alternate syntax for :ref:tls-cert-bundle.

@@[email protected]@tls-win-cert@@:
Add the system certificates to the cert bundle certificates for
authentication.
If no cert bundle, it uses only these certificates.
On windows this option uses the certificates from the cert store.
Use the :ref:tls-cert-bundle option on
other systems.
On other systems, this option enables the system certificates.

text
Default: no

@@[email protected]@tls-system-cert@@:
This the same as the
:ref:tls-win-cert option, under a
different name.
Because it is not windows specific.

@@[email protected]@tls-additional-port@@: **
List port numbers as
:ref:tls-additional-port, and when
interfaces are defined, eg. with the @port suffix, as this port number,
they provide DNS-over-TLS service.
Can list multiple, each on a new statement.

@@[email protected]@tls-session-ticket-keys@@:
If not "", lists files with 80 bytes of random contents that are used
to perform TLS session resumption for clients using the Unbound server.
These files contain the secret key for the TLS session tickets.
First key use to encrypt and decrypt TLS session tickets.
Other keys use to decrypt only.

text
With this you can roll over to new keys, by generating a new first file and
allowing decrypt of the old file by listing it after the first file for
some time, after the wait clients are not using the old key any more and
the old key can be removed.
One way to create the file is:

.. code-block:: text

    dd if=/dev/random bs=1 count=80 of=ticket.dat

The first 16 bytes should be different from the old one if you create a
second key, that is the name used to identify the key.
Then there is 32 bytes random data for an AES key and then 32 bytes random
data for the HMAC key.

Default: ""

@@[email protected]@tls-ciphers@@:
Set the list of ciphers to allow when serving TLS.
Use "" for default ciphers.

text
Default: ""

@@[email protected]@tls-ciphersuites@@:
Set the list of ciphersuites to allow when serving TLS.
This is for newer TLS 1.3 connections.
Use "" for default ciphersuites.

text
Default: ""

@@[email protected]@tls-use-sni@@:
Enable or disable sending the SNI extension on TLS connections.

text
.. note:: Changing the value requires a restart.

Default: yes

@@[email protected]@tls-protocols@@: ""
Specify the allowed TLS protocol versions to use, in no particular order.
Possible values are TLSv1.2 and TLSv1.3.
Enclose list of protocols in quotes ("") and put spaces between them.

text
.. note:: Changing the value requires a restart.

Default: "TLSv1.2 TLSv1.3"

@@[email protected]@pad-responses@@:
If enabled, TLS serviced queries that contained an EDNS Padding option will
cause responses padded to the closest multiple of the size specified in
:ref:pad-responses-block-size.

text
Default: yes

@@[email protected]@pad-responses-block-size@@:
The block size with which to pad responses serviced over TLS.
Only responses to padded queries will be padded.

text
Default: 468

@@[email protected]@pad-queries@@:
If enabled, all queries sent over TLS upstreams will be padded to the
closest multiple of the size specified in
:ref:pad-queries-block-size.

text
Default: yes

@@[email protected]@pad-queries-block-size@@:
The block size with which to pad queries sent over TLS upstreams.

text
Default: 128

@@[email protected]@https-port@@:
The port number on which to provide DNS-over-HTTPS service.
Only interfaces configured with that port number as @number get the HTTPS
service.

text
Default: 443

@@[email protected]@http-endpoint@@:
The HTTP endpoint to provide DNS-over-HTTPS service on.

text
Default: /dns-query

@@[email protected]@http-max-streams@@:
Number used in the SETTINGS_MAX_CONCURRENT_STREAMS parameter in the HTTP/2
SETTINGS frame for DNS-over-HTTPS connections.

text
Default: 100

@@[email protected]@http-query-buffer-size@@:
Maximum number of bytes used for all HTTP/2 query buffers combined.
These buffers contain (partial) DNS queries waiting for request stream
completion.
An RST_STREAM frame will be send to streams exceeding this limit.
A plain number is in bytes, append 'k', 'm' or 'g' for kilobytes, megabytes
or gigabytes (1024*1024 bytes in a megabyte).

text
Default: 4m

@@[email protected]@http-response-buffer-size@@:
Maximum number of bytes used for all HTTP/2 response buffers combined.
These buffers contain DNS responses waiting to be written back to the
clients.
An RST_STREAM frame will be send to streams exceeding this limit.
A plain number is in bytes, append 'k', 'm' or 'g' for kilobytes, megabytes
or gigabytes (1024*1024 bytes in a megabyte).

text
Default: 4m

@@[email protected]@http-nodelay@@:
Set TCP_NODELAY socket option on sockets used to provide DNS-over-HTTPS
service.
Ignored if the option is not available.

text
Default: yes

@@[email protected]@http-notls-downstream@@:
Disable use of TLS for the downstream DNS-over-HTTP connections.
Useful for local back end servers.

text
Default: no

@@[email protected]@proxy-protocol-port@@: **
List port numbers as
:ref:proxy-protocol-port, and when
interfaces are defined, eg. with the @port suffix, as this port number,
they support and expect PROXYv2.

text
In this case the proxy address will only be used for the network
communication and initial ACL (check if the proxy itself is denied/refused
by configuration).

The proxied address (if any) will then be used as the true client address
and will be used where applicable for logging, ACL, DNSTAP, RPZ and IP
ratelimiting.

PROXYv2 is supported for UDP and TCP/TLS listening interfaces.

There is no support for PROXYv2 on a DoH, DoQ or DNSCrypt listening interface.

Can list multiple, each on a new statement.

@@[email protected]@quic-port@@:
The port number on which to provide DNS-over-QUIC service.
Only interfaces configured with that port number as @number get the QUIC
service.
The interface uses QUIC for the UDP traffic on that port number.
If it is set to 0, the server does not init QUIC code, and QUIC is
disabled.
This is similar to if QUIC is not in use, but then explicitly.

text
Default: 853

@@[email protected]@quic-size@@:
Maximum number of bytes for all QUIC buffers and data combined.
A plain number is in bytes, append 'k', 'm' or 'g' for kilobytes, megabytes
or gigabytes (1024*1024 bytes in a megabyte).
New connections receive connection refused when the limit is exceeded.
New streams are reset when the limit is exceeded.

text
Default: 8m

@@[email protected]@use-systemd@@:
Enable or disable systemd socket activation.

text
Default: no

@@[email protected]@do-daemonize@@:
Enable or disable whether the Unbound server forks into the background as a
daemon.
Set the value to no when Unbound runs as systemd service.

text
Default: yes

@@[email protected]@tcp-connection-limit@@: * *
Allow up to limit simultaneous TCP connections from the given netblock.
When at the limit, further connections are accepted but closed immediately.
This option is experimental at this time.

text
Default: (disabled)

@@[email protected]@access-control@@: * *
Specify treatment of incoming queries from their originating IP address.
Queries can be allowed to have access to this server that gives DNS
answers, or refused, with other actions possible.
The IP address range can be specified as a netblock, it is possible to give
the statement several times in order to specify the treatment of different
netblocks.
The netblock is given as an IPv4 or IPv6 address with /size appended for a
classless network block.
The most specific netblock match is used, if none match
:ref:refuse is used.
The order of the access-control statements therefore does not matter.
The action can be
:ref:deny,
:ref:refuse,
:ref:allow,
:ref:allow_setrd,
:ref:allow_snoop,
:ref:allow_cookie,
:ref:deny_non_local or
:ref:refuse_non_local.

text
@@[email protected]@deny@@
    Stops queries from hosts from that netblock.

@@[email protected]@refuse@@
    Stops queries too, but sends a DNS rcode REFUSED error message back.

@@[email protected]@allow@@
    Gives access to clients from that netblock.
    It gives only access for recursion clients (which is what almost all
    clients need).
    Non-recursive queries are refused.

    The :ref:`allow` action does
    allow non-recursive queries to access the local-data that is
    configured.
    The reason is that this does not involve the Unbound server recursive
    lookup algorithm, and static data is served in the reply.
    This supports normal operations where non-recursive queries are made
    for the authoritative data.
    For non-recursive queries any replies from the dynamic cache are
    refused.

@@[email protected]@allow_setrd@@
    Ignores the recursion desired (RD) bit and treats all requests as if
    the recursion desired bit is set.

    Note that this behavior violates :rfc:`1034` which states that a name
    server should never perform recursive service unless asked via the RD
    bit since this interferes with trouble shooting of name servers and
    their databases.
    This prohibited behavior may be useful if another DNS server must
    forward requests for specific zones to a resolver DNS server, but only
    supports stub domains and sends queries to the resolver DNS server with
    the RD bit cleared.

@@[email protected]@allow_snoop@@
    Gives non-recursive access too.
    This gives both recursive and non recursive access.
    The name *allow_snoop* refers to cache snooping, a technique to use
    non-recursive queries to examine the cache contents (for malicious
    acts).
    However, non-recursive queries can also be a valuable debugging tool
    (when you want to examine the cache contents).

    In that case use
    :ref:`allow_snoop` for
    your administration host.

@@[email protected]@allow_cookie@@
    Allows access only to UDP queries that contain a valid DNS Cookie as
    specified in RFC 7873 and RFC 9018, when the
    :ref:`answer-cookie` option is enabled.
    UDP queries containing only a DNS Client Cookie and no Server Cookie,
    or an invalid DNS Cookie, will receive a BADCOOKIE response including a
    newly generated DNS Cookie, allowing clients to retry with that DNS
    Cookie.
    The *allow_cookie* action will also accept requests over stateful
    transports, regardless of the presence of an DNS Cookie and regardless
    of the :ref:`answer-cookie` setting.
    UDP queries without a DNS Cookie receive REFUSED responses with the TC
    flag set, that may trigger fall back to TCP for those clients.

@@[email protected]@deny_non_local@@
    The
    :ref:`deny_non_local`
    action is for hosts that are only allowed to query for the
    authoritative :ref:`local-data`, they are not
    allowed full recursion but only the static data.
    Messages that are disallowed are dropped.

@@[email protected]@refuse_non_local@@
    The
    :ref:`refuse_non_local`
    action is for hosts that are only allowed to query for the
    authoritative :ref:`local-data`, they are not
    allowed full recursion but only the static data.
    Messages that are disallowed receive error code REFUSED.


By default only localhost (the 127.0.0.0/8 IP netblock, not the loopback
interface) is implicitly *allowed*, the rest is refused.
The default is *refused*, because that is protocol-friendly.
The DNS protocol is not designed to handle dropped packets due to policy,
and dropping may result in (possibly excessive) retried queries.

@@[email protected]@access-control-tag@@: * ""*
Assign tags to :ref:access-control
elements.
Clients using this access control element use localzones that are tagged
with one of these tags.

text
Tags must be defined in :ref:`define-tag`.
Enclose list of tags in quotes (``""``) and put spaces between tags.

If :ref:`access-control-tag` is
configured for a netblock that does not have an
:ref:`access-control`, an access-control
element with action :ref:`allow`
is configured for this netblock.

@@[email protected]@access-control-tag-action@@: * *
Set action for particular tag for given access control element.
If you have multiple tag values, the tag used to lookup the action is the
first tag match between
:ref:access-control-tag and
:ref:local-zone-tag where "first" comes
from the order of the :ref:define-tag values.

@@[email protected]@access-control-tag-data@@: * ""*
Set redirect data for particular tag for given access control element.

@@[email protected]@access-control-view@@: * *
Set view for given access control element.

@@[email protected]@interface-action@@: * *
Similar to :ref:access-control but for
interfaces.

text
The action is the same as the ones defined under
:ref:`access-control`.

Default action for interfaces is
:ref:`refuse`.
By default only localhost (the 127.0.0.0/8 IP netblock, not the loopback
interface) is implicitly allowed through the default
:ref:`access-control` behavior.
This also means that any attempt to use the **interface-\*:** options for
the loopback interface will not work as they will be overridden by the
implicit default "access-control: 127.0.0.0/8 allow" option.

.. note::
    The interface needs to be already specified with
    :ref:`interface` and that any
    **access-control\*:** option overrides all **interface-\*:**
    options for targeted clients.

@@[email protected]@interface-tag@@: * <"list of tags">*
Similar to :ref:access-control-tag but
for interfaces.

text
.. note::
    The interface needs to be already specified with
    :ref:`interface` and that any
    **access-control\*:** option overrides all **interface-\*:**
    options for targeted clients.

@@[email protected]@interface-tag-action@@: * *
Similar to
:ref:access-control-tag-action
but for interfaces.

text
.. note::
    The interface needs to be already specified with
    :ref:`interface` and that any
    **access-control\*:** option overrides all **interface-\*:**
    options for targeted clients.

@@[email protected]@interface-tag-data@@: * <"resource record string">*
Similar to
:ref:access-control-tag-data but
for interfaces.

text
.. note::
    The interface needs to be already specified with
    :ref:`interface` and that any
    **access-control\*:** option overrides all **interface-\*:**
    options for targeted clients.

@@[email protected]@interface-view@@: * *
Similar to :ref:access-control-view
but for interfaces.

text
.. note::
    The interface needs to be already specified with
    :ref:`interface` and that any
    **access-control\*:** option overrides all **interface-\*:**
    options for targeted clients.

@@[email protected]@chroot@@:
If :ref:chroot is enabled, you should pass the
configfile (from the commandline) as a full path from the original root.
After the chroot has been performed the now defunct portion of the config
file path is removed to be able to reread the config after a reload.

text
All other file paths (working dir, logfile, roothints, and key files) can
be specified in several ways: as an absolute path relative to the new root,
as a relative path to the working directory, or as an absolute path
relative to the original root.
In the last case the path is adjusted to remove the unused portion.

The pidfile can be either a relative path to the working directory, or an
absolute path relative to the original root.
It is written just prior to chroot and dropping permissions.
This allows the pidfile to be :file:`/var/run/unbound.pid` and the chroot
to be :file:`/var/unbound`, for example.
Note that Unbound is not able to remove the pidfile after termination when
it is located outside of the chroot directory.

Additionally, Unbound may need to access :file:`/dev/urandom` (for entropy)
from inside the chroot.

If given, a *chroot(2)* is done to the given directory.
If you give ``""`` no *chroot(2)* is performed.

Default: @UNBOUND_CHROOT_DIR@

@@[email protected]@username@@:
If given, after binding the port the user privileges are dropped.
If you give username: "" no user change is performed.

text
If this user is not capable of binding the port, reloads (by signal HUP)
will still retain the opened ports.
If you change the port number in the config file, and that new port number
requires privileges, then a reload will fail; a restart is needed.

Default: @UNBOUND_USERNAME@

@@[email protected]@directory@@:
Sets the working directory for the program.
On Windows the string "%EXECUTABLE%" tries to change to the directory that
:command:unbound.exe resides in.
If you give a :ref:server: directory: \<directory\> before
:ref:include file statements then those includes
can be relative to the working directory.

text
Default: @UNBOUND_RUN_DIR@

@@[email protected]@logfile@@:
If "" is given, logging goes to stderr, or nowhere once daemonized.
The logfile is appended to, in the following format:

text
.. code-block:: text

    [seconds since 1970] unbound[pid:tid]: type: message.

If this option is given, the :ref:`use-syslog`
option is internally set to ``no``.

The logfile is reopened (for append) when the config file is reread, on
SIGHUP.

Default: "" (disabled)

@@[email protected]@use-syslog@@:
Sets Unbound to send log messages to the syslogd, using syslog(3).
The log facility LOG_DAEMON is used, with identity "unbound".
The logfile setting is overridden when
:ref:use-syslog: yes is set.

text
Default: yes

@@[email protected]@log-identity@@:
If "" is given, then the name of the executable, usually
"unbound" is used to report to the log.
Enter a string to override it with that, which is useful on systems that
run more than one instance of Unbound, with different configurations, so
that the logs can be easily distinguished against.

text
Default: ""

@@[email protected]@log-time-ascii@@:
Sets logfile lines to use a timestamp in UTC ASCII.
No effect if using syslog, in that case syslog formats the timestamp
printed into the log files.

text
Default: no (prints the seconds since 1970 in brackets)

@@[email protected]@log-time-iso@@:
Log time in ISO8601 format, if
:ref:log-time-ascii: yes
is also set.

text
Default: no

@@[email protected]@log-queries@@:
Prints one line per query to the log, with the log timestamp and IP
address, name, type and class.
Note that it takes time to print these lines which makes the server
(significantly) slower.
Odd (nonprintable) characters in names are printed as '?'.

text
Default: no

@@[email protected]@log-replies@@:
Prints one line per reply to the log, with the log timestamp and IP
address, name, type, class, return code, time to resolve, from cache and
response size.
Note that it takes time to print these lines which makes the server
(significantly) slower.
Odd (nonprintable) characters in names are printed as '?'.

text
Default: no

@@[email protected]@log-tag-queryreply@@:
Prints the word 'query' and 'reply' with
:ref:log-queries and
:ref:log-replies.
This makes filtering logs easier.

text
Default: no (backwards compatible)

@@[email protected]@log-destaddr@@:
Prints the destination address, port and type in the
:ref:log-replies output.
This disambiguates what type of traffic, eg. UDP or TCP, and to what local
port the traffic was sent to.

text
Default: no

@@[email protected]@log-local-actions@@:
Print log lines to inform about local zone actions.
These lines are like the :ref:local-zone type inform print outs, but they are also
printed for the other types of local zones.

text
Default: no

@@[email protected]@log-servfail@@:
Print log lines that say why queries return SERVFAIL to clients.
This is separate from the verbosity debug logs, much smaller, and printed
at the error level, not the info level of debug info from verbosity.

text
Default: no

@@[email protected]@log-thread-id@@:
(Only on Linux and only when threads are available)
Logs the system-wide Linux thread ID instead of Unbound's internal thread
counter.
Can be useful when debugging with system tools.

text
Default: no

@@[email protected]@pidfile@@:
The process id is written to the file.
Default is :file:"@UNBOUND_PIDFILE@".
So,

text
.. code-block:: text

    kill -HUP `cat @UNBOUND_PIDFILE@`

triggers a reload,

.. code-block:: text

    kill -TERM `cat @UNBOUND_PIDFILE@`

gracefully terminates.

Default: @UNBOUND_PIDFILE@

@@[email protected]@root-hints@@:
Read the root hints from this file.
Default is nothing, using builtin hints for the IN class.
The file has the format of zone files, with root nameserver names and
addresses only.
The default may become outdated, when servers change, and then it is
possible to use a root hints file with specific servers.

text
Default: ""

@@[email protected]@hide-identity@@:
If enabled 'id.server' and 'hostname.bind' queries are REFUSED.

text
Default: no

@@[email protected]@identity@@:
Set the identity to report.
If set to "", then the hostname of the server is returned.

text
Default: ""

@@[email protected]@hide-version@@:
If enabled 'version.server' and 'version.bind' queries are REFUSED.

text
Default: no

@@[email protected]@version@@:
Set the version to report.
If set to "", then the package version is returned.

text
Default: ""

@@[email protected]@hide-http-user-agent@@:
If enabled the HTTP header User-Agent is not set.
Use with caution as some webserver configurations may reject HTTP requests
lacking this header.
If needed, it is better to explicitly set the
:ref:http-user-agent below.

text
Default: no

@@[email protected]@http-user-agent@@:
Set the HTTP User-Agent header for outgoing HTTP requests.
If set to "", then the package name and version are used.

text
Default: ""

@@[email protected]@nsid@@:
Add the specified nsid to the EDNS section of the answer when queried with
an NSID EDNS enabled packet.
As a sequence of hex characters or with 'ascii_' prefix and then an ASCII
string.

text
Default: (disabled)

@@[email protected]@hide-trustanchor@@:
If enabled 'trustanchor.unbound' queries are REFUSED.

text
Default: no

@@[email protected]@target-fetch-policy@@: <"list of numbers">
Set the target fetch policy used by Unbound to determine if it should fetch
nameserver target addresses opportunistically.
The policy is described per dependency depth.

text
The number of values determines the maximum dependency depth that Unbound
will pursue in answering a query.
A value of -1 means to fetch all targets opportunistically for that
dependency depth.
A value of 0 means to fetch on demand only.
A positive value fetches that many targets opportunistically.

Enclose the list between quotes (``""``) and put spaces between numbers.
Setting all zeroes, "0 0 0 0 0" gives behaviour closer to that of BIND 9,
while setting "-1 -1 -1 -1 -1" gives behaviour rumoured to be closer to
that of BIND 8.

Default:  "3 2 1 0 0"

@@[email protected]@harden-short-bufsize@@:
Very small EDNS buffer sizes from queries are ignored and are instead
set to the normal UDP packet size (512 bytes).

text
Default: yes (per :rfc:`6891`)

@@[email protected]@harden-large-queries@@:
Very large queries are ignored.
The cutoff value is chosen to be the normal UDP packet size (512 bytes).
Default is no, since it is legal protocol wise to send these, and could be
necessary for operation if TSIG or EDNS payload is very large.

text
Default: no

@@[email protected]@harden-glue@@:
Will trust glue only if it is within the servers authority.

text
Default: yes

@@[email protected]@harden-unverified-glue@@:
Will trust only in-zone glue.
Will try to resolve all out of zone (unverified) glue.
Will fallback to the original glue if unable to resolve.

text
Default: no

@@[email protected]@harden-dnssec-stripped@@:
Require DNSSEC data for trust-anchored zones, if such data is absent, the
zone becomes bogus.
If turned off, and no DNSSEC data is received (or the DNSKEY data fails to
validate), then the zone is made insecure, this behaves like there is no
trust anchor.
You could turn this off if you are sometimes behind an intrusive firewall
(of some sort) that removes DNSSEC data from packets, or a zone changes
from signed to unsigned to badly signed often.
If turned off you run the risk of a downgrade attack that disables security
for a zone.

text
Default: yes

@@[email protected]@harden-below-nxdomain@@:
From :rfc:8020 (with title "NXDOMAIN: There Really Is Nothing
Underneath"), returns NXDOMAIN to queries for a name below another name
that is already known to be NXDOMAIN.
DNSSEC mandates NOERROR for empty nonterminals, hence this is possible.
Very old software might return NXDOMAIN for empty nonterminals (that
usually happen for reverse IP address lookups), and thus may be
incompatible with this.
To try to avoid this only DNSSEC-secure NXDOMAINs are used, because the old
software does not have DNSSEC.

text
.. note::
    The NXDOMAIN must be secure, this means NSEC3 with optout is
    insufficient.

Default: yes

@@[email protected]@harden-referral-path@@:
Harden the referral path by performing additional queries for
infrastructure data.
Validates the replies if trust anchors are configured and the zones are
signed.
This enforces DNSSEC validation on nameserver NS sets and the nameserver
addresses that are encountered on the referral path to the answer.
Default is off, because it burdens the authority servers, and it is not RFC
standard, and could lead to performance problems because of the extra query
load that is generated.
Experimental option.
If you enable it consider adding more numbers after the
:ref:target-fetch-policy to increase
the max depth that is checked to.

text
Default: no

@@[email protected]@harden-algo-downgrade@@:
Harden against algorithm downgrade when multiple algorithms are advertised
in the DS record.
This works by first choosing only the strongest DS digest type as per
:rfc:4509 (Unbound treats the highest algorithm as the strongest) and
then expecting signatures from all the advertised signing algorithms from
the chosen DS(es) to be present.
If no, allows any one supported algorithm to validate the zone, even if
other advertised algorithms are broken.
:rfc:6840 mandates that zone signers must produce zones signed with all
advertised algorithms, but sometimes they do not.
:rfc:6840 also clarifies that this requirement is not for validators and
validators should accept any single valid path.
It should thus be explicitly noted that this option violates :rfc:6840
for DNSSEC validation and should only be used to perform a signature
completeness test to support troubleshooting.

text
.. warning::
    Using this option may break DNSSEC resolution with non :rfc:`6840`
    conforming signers and/or in multi-signer configurations that don't
    send all the advertised signatures.

Default: no

@@[email protected]@harden-unknown-additional@@:
Harden against unknown records in the authority section and additional
section.
If no, such records are copied from the upstream and presented to the
client together with the answer.
If yes, it could hamper future protocol developments that want to add
records.

text
Default: no

@@[email protected]@harden-cname-follow@@:
Harden CNAME redirections by following them.
If no, then upstream CNAME and DNAME redirections are allowed in a
response without checking with further messages if those are valid.
It can only really be disabled safely on localhost net or encrypted
connectivity.
Default is on to protect the cache integrity.

text
Default: yes

@@[email protected]@use-caps-for-id@@:
Use 0x20-encoded random bits in the query to foil spoof attempts.
This perturbs the lowercase and uppercase of query names sent to authority
servers and checks if the reply still has the correct casing.
This feature is an experimental implementation of draft dns-0x20.

text
Default: no

@@[email protected]@caps-exempt@@:
Exempt the domain so that it does not receive caps-for-id perturbed
queries.
For domains that do not support 0x20 and also fail with fallback because
they keep sending different answers, like some load balancers.
Can be given multiple times, for different domains.

@@[email protected]@caps-whitelist@@:
Alternate syntax for :ref:caps-exempt.

@@[email protected]@qname-minimisation@@:
Send minimum amount of information to upstream servers to enhance privacy.
Only send minimum required labels of the QNAME and set QTYPE to A when
possible.
Best effort approach; full QNAME and original QTYPE will be sent when
upstream replies with a RCODE other than NOERROR, except when receiving
NXDOMAIN from a DNSSEC signed zone.

text
Default: yes

@@[email protected]@qname-minimisation-strict@@:
QNAME minimisation in strict mode.
Do not fall-back to sending full QNAME to potentially broken nameservers.
A lot of domains will not be resolvable when this option in enabled.
Only use if you know what you are doing.
This option only has effect when
:ref:qname-minimisation is enabled.

text
Default: no

@@[email protected]@aggressive-nsec@@:
Aggressive NSEC uses the DNSSEC NSEC chain to synthesize NXDOMAIN and other
denials, using information from previous NXDOMAINs answers.
It helps to reduce the query rate towards targets that get a very high
nonexistent name lookup rate.

text
Default: yes

@@[email protected]@private-address@@: **
Give IPv4 of IPv6 addresses or classless subnets.
These are addresses on your private network, and are not allowed to be
returned for public internet names.
Any occurrence of such addresses are removed from DNS answers.
Additionally, the DNSSEC validator may mark the answers bogus.
This protects against so-called DNS Rebinding, where a user browser is
turned into a network proxy, allowing remote access through the browser to
other parts of your private network.

text
The option removes resource records of types A, AAAA, SVCB and HTTPS
that match the filter.
Inside the SVCB and HTTPS records, the svcparams of type ipv4hint
and ipv6hint are checked for matches.

Some names can be allowed to contain your private addresses, by default all
the :ref:`local-data` that you configured is
allowed to, and you can specify additional names using
:ref:`private-domain`.
No private addresses are enabled by default.

We consider to enable this for the :rfc:`1918` private IP address space by
default in later releases.
That would enable private addresses for ``10.0.0.0/8``, ``172.16.0.0/12``,
``192.168.0.0/16``, ``169.254.0.0/16``, ``fd00::/8`` and ``fe80::/10``,
since the RFC standards say these addresses should not be visible on the
public internet.

Turning on ``127.0.0.0/8`` would hinder many spamblocklists as they use
that.
Adding ``::ffff:0:0/96`` stops IPv4-mapped IPv6 addresses from bypassing
the filter.

@@[email protected]@private-domain@@:
Allow this domain, and all its subdomains to contain private addresses.
Give multiple times to allow multiple domain names to contain private
addresses.

text
Default: (none)

@@[email protected]@unwanted-reply-threshold@@:
If set, a total number of unwanted replies is kept track of in every
thread.
When it reaches the threshold, a defensive action is taken and a warning is
printed to the log.
The defensive action is to clear the rrset and message caches, hopefully
flushing away any poison.
A value of 10 million is suggested.

text
It is useful to add 0.0.0.0/8 and '::' to the
:ref:`do-not-query-address` list.
Otherwise they may be answered, from localhost, and the different source
makes an unwanted reply that unnecessarily ticks up.
The :ref:`do-not-query-localhost`
option includes them, the zero subnets, when it is enabled.

Default: 0 (disabled)

@@[email protected]@do-not-query-address@@: **
Do not query the given IP address.
Can be IPv4 or IPv6.
Append /num to indicate a classless delegation netblock, for example like
10.2.3.4/24 or 2001::11/64.

text
Default: (none)

@@[email protected]@do-not-query-localhost@@:
If yes, localhost is added to the
:ref:do-not-query-address entries,
both IPv4 127.0.0.1/8 (also ::ffff:127.0.0.0/104) and IPv6 ::1.
Additionally, the zero subnets 0.0.0.0/8 (also ::ffff:0:0/96) and
:: are added to the list since on some systems they route to
localhost as well.
If no, then localhost can be used to send queries to.

text
Default: yes

@@[email protected]@prefetch@@:
If yes, cache hits on message cache elements that are on their last 10
percent of their TTL value trigger a prefetch to keep the cache up to date.
Turning it on gives about 10 percent more traffic and load on the machine,
but popular items do not expire from the cache.

text
Default: no

@@[email protected]@prefetch-key@@:
If yes, fetch the DNSKEYs earlier in the validation process, when a DS
record is encountered.
This lowers the latency of requests.
It does use a little more CPU.
Also if the cache is set to 0, it is no use.

text
Default: no

@@[email protected]@deny-any@@:
If yes, deny queries of type ANY with an empty response.
If disabled, Unbound responds with a short list of resource records if some
can be found in the cache and makes the upstream type ANY query if there
are none.
The option stops the DNSSEC validation from processing, possibly lengthy,
ANY responses, when the option is enabled.

text
Default: no

@@[email protected]@rrset-roundrobin@@:
If yes, Unbound rotates RRSet order in response (the random number is taken
from the query ID, for speed and thread safety).

text
Default: yes

@@[email protected]@minimal-responses@@:
If yes, Unbound does not insert authority/additional sections into response
messages when those sections are not required.
This reduces response size significantly, and may avoid TCP fallback for
some responses which may cause a slight speedup.
The default is yes, even though the DNS protocol RFCs mandate these
sections, and the additional content could save roundtrips for clients that
use the additional content.
However these sections are hardly used by clients.
Enabling prefetch can benefit clients that need the additional content
by trying to keep that content fresh in the cache.

text
Default: yes

@@[email protected]@disable-dnssec-lame-check@@:
If yes, disables the DNSSEC lameness check in the iterator.
This check sees if RRSIGs are present in the answer, when DNSSEC is
expected, and retries another authority if RRSIGs are unexpectedly missing.
The validator will insist in RRSIGs for DNSSEC signed domains regardless of
this setting, if a trust anchor is loaded.

text
Default: no

@@[email protected]@module-config@@: ""
Module configuration, a list of module names separated by spaces, surround
the string with quotes ("").
The modules can be respip, validator, or iterator (and possibly
more, see below).

text
.. note::
    The ordering of the modules is significant, the order decides the order
    of processing.

Setting this to just ``"iterator"`` results in a non-validating server.
Setting this to ``"validator iterator"`` (default) enables the DNSSEC
validator module but not DNSSEC validation.

.. note::
    To turn on DNSSEC validation you must configure trust-anchors.

Adding ``respip`` to the front will cause RPZ processing to be done on all
queries.

Most modules that need to be listed here have to be listed at the beginning
of the line.

The ``subnetcache`` module has to be listed just before the iterator.

The ``python`` module can be listed in different places, it then processes
the output of the module it is just before.

The ``dynlib`` module can be listed pretty much anywhere, it is only a very
thin wrapper that allows dynamic libraries to run in its place.

Default: "validator iterator"

@@[email protected]@trust-anchor-file@@:
File with trusted keys for validation.
Both DS and DNSKEY entries can appear in the file.
The format of the file is the standard DNS Zone file format.

text
Default: "" (no trust anchor file)

@@[email protected]@auto-trust-anchor-file@@:
File with trust anchor for one zone, which is tracked with :rfc:5011
probes.
The probes are run several times per month, thus the machine must be online
frequently.
The initial file can be one with contents as described in
:ref:trust-anchor-file.
The file is written to when the anchor is updated, so the Unbound user must
have write permission.
Write permission to the file, but also to the directory it is in (to create
a temporary file, which is necessary to deal with filesystem full events),
it must also be inside the :ref:chroot (if that is
used).

text
Default: "" (no auto trust anchor file)

@@[email protected]@trust-anchor@@: ""
A DS or DNSKEY RR for a key to use for validation.
Multiple entries can be given to specify multiple trusted keys, in addition
to the :ref:trust-anchor-file.
The resource record is entered in the same format as dig(1) or drill(1)
prints them, the same format as in the zone file.
Has to be on a single line, with "" around it.
A TTL can be specified for ease of cut and paste, but is ignored.
A class can be specified, but class IN is default.

text
Default: (none)

@@[email protected]@trusted-keys-file@@:
File with trusted keys for validation.
Specify more than one file with several entries, one file per entry.
Like :ref:trust-anchor-file but has a
different file format.
Format is BIND-9 style format, the trusted-keys { name flag proto algo "key"; }; clauses are read.
It is possible to use wildcards with this statement, the wildcard is
expanded on start and on reload.

text
A wildcard that matches no files is not an error: the entry loads no
trust anchors, and the condition is logged at operational verbosity.

Default: "" (no trusted keys file)

@@[email protected]@trust-anchor-signaling@@:
Send :rfc:8145 key tag query after trust anchor priming.

text
Default: yes

@@[email protected]@root-key-sentinel@@:
Root key trust anchor sentinel.

text
Default: yes

@@[email protected]@domain-insecure@@:
Sets to be insecure, DNSSEC chain of trust is ignored
towards the .
So a trust anchor above the domain name can not make the domain secure with
a DS record, such a DS record is then ignored.
Can be given multiple times to specify multiple domains that are treated as
if unsigned.
If you set trust anchors for the domain they override this setting (and the
domain is secured).

text
This can be useful if you want to make sure a trust anchor for external
lookups does not affect an (unsigned) internal domain.
A DS record externally can create validation failures for that internal
domain.

Default: (none)

@@[email protected]@val-override-date@@:
.. warning:: Debugging feature!

text
If enabled by giving a RRSIG style date, that date is used for verifying
RRSIG inception and expiration dates, instead of the current date.
Do not set this unless you are debugging signature inception and
expiration.
The value -1 ignores the date altogether, useful for some special
applications.

Default: 0 (disabled)

@@[email protected]@val-sig-skew-min@@:
Minimum number of seconds of clock skew to apply to validated signatures.
A value of 10% of the signature lifetime (expiration - inception) is used,
capped by this setting.
Default is 3600 (1 hour) which allows for daylight savings differences.
Lower this value for more strict checking of short lived signatures.

text
Default: 3600 (1 hour)

@@[email protected]@val-sig-skew-max@@:
Maximum number of seconds of clock skew to apply to validated signatures.
A value of 10% of the signature lifetime (expiration - inception) is used,
capped by this setting.
Default is 86400 (24 hours) which allows for timezone setting problems in
stable domains.
Setting both min and max very low disables the clock skew allowances.
Setting both min and max very high makes the validator check the signature
timestamps less strictly.

text
Default: 86400 (24 hours)

@@[email protected]@val-max-restart@@:
The maximum number the validator should restart validation with another
authority in case of failed validation.

text
Default: 5

@@[email protected]@val-bogus-ttl@@:
The time to live for bogus data.
This is data that has failed validation; due to invalid signatures or other
checks.
The TTL from that data cannot be trusted, and this value is used instead.
The time interval prevents repeated revalidation of bogus data.

text
Default: 60

@@[email protected]@val-clean-additional@@:
Instruct the validator to remove data from the additional section of secure
messages that are not signed properly.
Messages that are insecure, bogus, indeterminate or unchecked are not
affected.
Use this setting to protect the users that rely on this validator for
authentication from potentially bad data in the additional section.

text
Default: no

@@[email protected]@val-log-level@@:
Have the validator print validation failures to the log.
Regardless of the verbosity setting.

text
At 1, for every user query that fails a line is printed to the logs.
This way you can monitor what happens with validation.
Use a diagnosis tool, such as dig or drill, to find out why validation is
failing for these queries.

At 2, not only the query that failed is printed but also the reason why
Unbound thought it was wrong and which server sent the faulty data.

Default: 0 (disabled)

@@[email protected]@val-permissive-mode@@:
Instruct the validator to mark bogus messages as indeterminate.
The security checks are performed, but if the result is bogus (failed
security), the reply is not withheld from the client with SERVFAIL as
usual.
The client receives the bogus data.
For messages that are found to be secure the AD bit is set in replies.
Also logging is performed as for full validation.

text
Default: no

@@[email protected]@ignore-cd-flag@@:
Instruct Unbound to ignore the CD flag from clients and refuse to return
bogus answers to them.
Thus, the CD (Checking Disabled) flag does not disable checking any more.
This is useful if legacy (w2008) servers that set the CD flag but cannot
validate DNSSEC themselves are the clients, and then Unbound provides them
with DNSSEC protection.

text
Default: no

@@[email protected]@disable-edns-do@@:
Disable the EDNS DO flag in upstream requests.
It breaks DNSSEC validation for Unbound's clients.
This results in the upstream name servers to not include DNSSEC records in
their replies and could be helpful for devices that cannot handle DNSSEC
information.
When the option is enabled, clients that set the DO flag receive no EDNS
record in the response to indicate the lack of support to them.
If this option is enabled but Unbound is already configured for DNSSEC
validation (i.e., the validator module is enabled; default) this option is
implicitly turned off with a warning as to not break DNSSEC validation in
Unbound.

text
Default: no

@@[email protected]@serve-expired@@:
If enabled, Unbound attempts to serve old responses from cache with a TTL
of :ref:serve-expired-reply-ttl in
the response.
By default the expired answer will be used after a resolution attempt
errored out or is taking more than
:ref:serve-expired-client-timeout
to resolve.

text
Default: no

@@[email protected]@serve-expired-ttl@@:
Limit serving of expired responses to configured seconds after expiration.
0 disables the limit.
This option only applies when
:ref:serve-expired is enabled.
A suggested value per RFC 8767 is between 86400 (1 day) and 259200 (3 days).
The default is 86400.

text
Default: 86400

@@[email protected]@serve-expired-ttl-reset@@:
Set the TTL of expired records to the
:ref:serve-expired-ttl value after a
failed attempt to retrieve the record from upstream.
This makes sure that the expired records will be served as long as there
are queries for it.

text
Default: no

@@[email protected]@serve-expired-reply-ttl@@:
TTL value to use when replying with expired data.
If
:ref:serve-expired-client-timeout
is also used then it is RECOMMENDED to use 30 as the value (:rfc:8767).

text
This value is capped by the original TTL of the record.
This means that records with higher original TTL than this value will use
this value for expired replies.
Records with lower original TTL than this value will use their original TTL
for expired replies.

Default: 30

@@[email protected]@serve-expired-client-timeout@@:
Time in milliseconds before replying to the client with expired data.
This essentially enables the serve-stale behavior as specified in
:rfc:8767 that first tries to resolve before immediately responding with
expired data.
Setting this to 0 will disable this behavior and instead serve the
expired record immediately from the cache before attempting to refresh it
via resolution.

text
Default: 1800

@@[email protected]@serve-original-ttl@@:
If enabled, Unbound will always return the original TTL as received from
the upstream name server rather than the decrementing TTL as stored in the
cache.
This feature may be useful if Unbound serves as a front-end to a hidden
authoritative name server.

text
Enabling this feature does not impact cache expiry, it only changes the TTL
Unbound embeds in responses to queries.

.. note::
    Enabling this feature implicitly disables enforcement of the configured
    minimum and maximum TTL, as it is assumed users who enable this feature
    do not want Unbound to change the TTL obtained from an upstream server.

.. note::
    The values set using :ref:`cache-min-ttl`
    and :ref:`cache-max-ttl` are ignored.

Default: no

@@[email protected]@val-nsec3-keysize-iterations@@: <"list of values">
List of keysize and iteration count values, separated by spaces, surrounded
by quotes.
This determines the maximum allowed NSEC3 iteration count before a message
is simply marked insecure instead of performing the many hashing
iterations.
The list must be in ascending order and have at least one entry.
If you set it to "1024 65535" there is no restriction to NSEC3 iteration
values.

text
.. note::
    This table must be kept short; a very long list could cause slower
    operation.

Default: "1024 150 2048 150 4096 150"

@@[email protected]@zonemd-permissive-mode@@:
If enabled the ZONEMD verification failures are only logged and do not
cause the zone to be blocked and only return servfail.
Useful for testing out if it works, or if the operator only wants to be
notified of a problem without disrupting service.

text
Default: no

@@[email protected]@add-holddown@@:
Instruct the
:ref:auto-trust-anchor-file probe
mechanism for :rfc:5011 autotrust updates to add new trust anchors only
after they have been visible for this time.

text
Default: 2592000 (30 days as per the RFC)

@@[email protected]@del-holddown@@:
Instruct the
:ref:auto-trust-anchor-file probe
mechanism for :rfc:5011 autotrust updates to remove revoked trust anchors
after they have been kept in the revoked list for this long.

text
Default: 2592000 (30 days as per the RFC)

@@[email protected]@keep-missing@@:
Instruct the
:ref:auto-trust-anchor-file probe
mechanism for :rfc:5011 autotrust updates to remove missing trust anchors
after they have been unseen for this long.
This cleans up the state file if the target zone does not perform trust
anchor revocation, so this makes the auto probe mechanism work with zones
that perform regular (non-5011) rollovers.
The value 0 does not remove missing anchors, as per the RFC.

text
Default: 31622400 (366 days)

@@[email protected]@permit-small-holddown@@:
Debug option that allows the autotrust 5011 rollover timers to assume very
small values.

text
Default: no

@@[email protected]@key-cache-size@@:
Number of bytes size of the key cache.
A plain number is in bytes, append 'k', 'm' or 'g' for kilobytes, megabytes
or gigabytes (1024*1024 bytes in a megabyte).

text
Default: 4m

@@[email protected]@key-cache-slabs@@:
Number of slabs in the key cache.
Slabs reduce lock contention by threads.
Must be set to a power of 2.
Setting (close) to the number of cpus is a fairly good setting.
If left unconfigured, it will be configured automatically to be a power of
2 close to the number of configured threads in multi-threaded environments.

text
Default: (unconfigured)

@@[email protected]@neg-cache-size@@:
Number of bytes size of the aggressive negative cache.
A plain number is in bytes, append 'k', 'm' or 'g' for kilobytes, megabytes
or gigabytes (1024*1024 bytes in a megabyte).

text
Default: 1m

@@[email protected]@unblock-lan-zones@@:
If enabled, then for private address space, the reverse lookups are no
longer filtered.
This allows Unbound when running as dns service on a host where it provides
service for that host, to put out all of the queries for the 'lan'
upstream.
When enabled, only localhost, 127.0.0.1 reverse and ::1 reverse
zones are configured with default local zones.
Disable the option when Unbound is running as a (DHCP-) DNS network
resolver for a group of machines, where such lookups should be filtered
(RFC compliance), this also stops potential data leakage about the local
network to the upstream DNS servers.

text
Default: no

@@[email protected]@insecure-lan-zones@@:
If enabled, then reverse lookups in private address space are not
validated.
This is usually required whenever
:ref:unblock-lan-zones is used.

text
Default: no

@@[email protected]@local-zone@@:
Configure a local zone.
The type determines the answer to give if there is no match from
:ref:local-data.
The types are
:ref:deny,
:ref:refuse,
:ref:static,
:ref:transparent,
:ref:redirect,
:ref:nodefault,
:ref:typetransparent,
:ref:inform,
:ref:inform_deny,
:ref:inform_redirect,
:ref:always_transparent,
:ref:block_a,
:ref:block_aaaa,
:ref:block_a_wdata,
:ref:block_aaaa_wdata,
:ref:always_refuse,
:ref:always_nxdomain,
:ref:always_null,
:ref:noview,
and are explained below.
After that the default settings are listed.
Use :ref:local-data to enter data into the
local zone.
Answers for local zones are authoritative DNS answers.
By default the zones are class IN.

text
If you need more complicated authoritative data, with referrals,
wildcards, CNAME/DNAME support, or DNSSEC authoritative service,
setup a :ref:`stub-zone` for it as detailed in the
stub zone section below.
A :ref:`stub-zone` can be used to have unbound
send queries to another server, an authoritative server, to fetch the
information.
With a :ref:`forward-zone`, unbound sends
queries to a server that is a recursive server to fetch the information.
With an :ref:`auth-zone` a zone can be loaded from
file and used, it can be used like a local zone for users downstream, or
the :ref:`auth-zone` information can be used to fetch
information from when resolving like it is an upstream server.
The :ref:`forward-zone` and
:ref:`auth-zone` options are described in their
sections below.
If you want to perform filtering of the information that the users can
fetch, the :ref:`local-zone` and
:ref:`local-data` statements allow for this, but
also the :ref:`rpz` functionality can be used, described
in the RPZ section.

@@[email protected]@deny@@
    Do not send an answer, drop the query.
    If there is a match from local data, the query is answered.

@@[email protected]@refuse@@
    Send an error message reply, with rcode REFUSED.
    If there is a match from local data, the query is answered.

@@[email protected]@static@@
    If there is a match from local data, the query is answered.
    Otherwise, the query is answered with NODATA or NXDOMAIN.
    For a negative answer a SOA is included in the answer if present as
    :ref:`local-data` for the zone apex domain.

@@[email protected]@transparent@@
    If there is a match from :ref:`local-data`,
    the query is answered.
    Otherwise if the query has a different name, the query is resolved
    normally.
    If the query is for a name given in
    :ref:`local-data` but no such type of data is
    given in localdata, then a NOERROR NODATA answer is returned.
    If no :ref:`local-zone` is given
    :ref:`local-data` causes a transparent zone
    to be created by default.

@@[email protected]@typetransparent@@
    If there is a match from local data, the query is answered.
    If the query is for a different name, or for the same name but for a
    different type, the query is resolved normally.
    So, similar to
    :ref:`transparent` but types
    that are not listed in local data are resolved normally, so if an A
    record is in the local data that does not cause a NODATA reply for AAAA
    queries.

@@[email protected]@redirect@@
    The query is answered from the local data for the zone name.
    There may be no local data beneath the zone name.
    This answers queries for the zone, and all subdomains of the zone with
    the local data for the zone.
    It can be used to redirect a domain to return a different address
    record to the end user, with:

    .. code-block:: text

        local-zone: "example.com." redirect
        local-data: "example.com. A 127.0.0.1"

    queries for ``www.example.com`` and ``www.foo.example.com`` are
    redirected, so that users with web browsers cannot access sites with
    suffix example.com.

    A ``CNAME`` record can also be provided via local-data:

    .. code-block:: text

        local-zone: "example.com." redirect
        local-data: "example.com. CNAME www.example.org."

    In that case, the ``CNAME`` is resolved and the answer
    includes resolved target records as well.
    The ``CNAME`` record has to be with the zone name of the local-zone,
    and there can be one CNAME, not more.
    The ``CNAME`` record has to be at the zone apex of the
    ``redirect`` zone, then it is used for redirection.
    The resolution proceeds with upstream DNS resolution, and
    that does not include the lookup in local zones.
    So the record is not able to point in local zones, but it
    can point to upstream DNS answers.

    ``CNAME`` resolution is supported only in type ``redirect``
    local-zone, and in type ``inform_redirect`` local-zone.

    As different from ``CNAME`` records that are used elsewhere, in
    the ``redirect`` type local-zone, it is supported that in the target
    of the record a wildcard label gets expanded to the query name, with
    for example: ``example.com. CNAME *.foo.net.`` gets expanded
    to ``www.example.com. CNAME www.example.com.foo.net.``.

@@[email protected]@inform@@
    The query is answered normally, same as
    :ref:`transparent`.
    The client IP address (@portnumber) is printed to the logfile.
    The log message is:

    .. code-block:: text

        timestamp, unbound-pid, info: zonename inform IP@port queryname type class.

    This option can be used for normal resolution, but machines looking up
    infected names are logged, eg. to run antivirus on them.

@@[email protected]@inform_deny@@
    The query is dropped, like
    :ref:`deny`, and logged, like
    :ref:`inform`.
    Ie. find infected machines without answering the queries.

@@[email protected]@inform_redirect@@
    The query is redirected, like
    :ref:`redirect`, and logged,
    like :ref:`inform`.
    Ie. answer queries with fixed data and also log the machines that ask.

@@[email protected]@always_transparent@@
    Like :ref:`transparent`, but
    ignores local data and resolves normally.

@@[email protected]@block_a@@
    Like :ref:`transparent`, but
    ignores local data and resolves normally all query types excluding A.
    For A queries it unconditionally returns NODATA.
    Useful in cases when there is a need to explicitly force all apps to
    use IPv6 protocol and avoid any queries to IPv4.

@@[email protected]@block_aaaa@@
    Like :ref:`transparent` or
    :ref:`block_a`, but
    ignores local data and resolves normally all query types excluding AAAA.
    For AAAA queries it unconditionally returns NODATA.
    Useful in cases when there is a need to explicitly force all apps to
    use IPv4 protocol and avoid any queries to IPv6.

@@[email protected]@block_a_wdata@@
    Like :ref:`block_a`, but
    uses local data if present.
    If there is local data that is returned, and it acts like transparent.
    For A queries it returns NODATA.

@@[email protected]@block_aaaa_wdata@@
    Like :ref:`block_aaaa`, but
    uses local data if present.
    If there is local data that is returned, and it acts like transparent.
    For AAAA queries it returns NODATA.

@@[email protected]@always_refuse@@
    Like :ref:`refuse`, but ignores
    local data and refuses the query.
    This type also blocks queries of type DS for the zone name.
    That can break the DNSSEC chain of trust, but it is refused anyway.
    The block for type DS assists in more completely blocking the zone.

@@[email protected]@always_nxdomain@@
    Like :ref:`static`, but ignores
    local data and returns NXDOMAIN for the query.

@@[email protected]@always_nodata@@
    Like :ref:`static`, but ignores
    local data and returns NODATA for the query.

@@[email protected]@always_deny@@
    Like :ref:`deny`, but ignores local
    data and drops the query.

@@[email protected]@always_null@@
    Always returns ``0.0.0.0`` or ``::0`` for every name in the zone.
    Like :ref:`redirect` with zero
    data for A and AAAA.
    Ignores local data in the zone.
    Used for some block lists.

@@[email protected]@noview@@
    Breaks out of that view and moves towards the global local zones for
    answer to the query.
    If the :ref:`view-first` is no, it'll
    resolve normally.
    If :ref:`view-first` is enabled, it'll
    break perform that step and check the global answers.
    For when the view has view specific overrides but some zone has to be
    answered from global local zone contents.

@@[email protected]@nodefault@@
    Used to turn off default contents for AS112 zones.
    The other types also turn off default contents for the zone.
    The :ref:`nodefault` option has
    no other effect than turning off default contents for the given zone.
    Use :ref:`nodefault` if you use
    exactly that zone, if you want to use a subzone, use
    :ref:`transparent`.

The default zones are localhost, reverse ``127.0.0.1`` and ``::1``, the
``home.arpa``, ``resolver.arpa``, ``service.arpa``, ``onion``, ``test``,
``invalid`` and the AS112 zones.
The AS112 zones are reverse DNS zones for private use and reserved IP
addresses for which the servers on the internet cannot provide correct
answers.
They are configured by default to give NXDOMAIN (no reverse information)
answers.

The defaults can be turned off by specifying your own
:ref:`local-zone` of that name, or using the
:ref:`nodefault` type.
Below is a list of the default zone contents.

@@[email protected]@localhost@@
    The IPv4 and IPv6 localhost information is given.
    NS and SOA records are provided for completeness and to satisfy some
    DNS update tools.
    Default content:

    .. code-block:: text

        local-zone: "localhost." redirect
        local-data: "localhost. 10800 IN NS localhost."
        local-data: "localhost. 10800 IN SOA localhost. nobody.invalid. 1 3600 1200 604800 10800"
        local-data: "localhost. 10800 IN A 127.0.0.1"
        local-data: "localhost. 10800 IN AAAA ::1"

@@[email protected]@reverse IPv4 loopback@@
    Default content:

    .. code-block:: text

        local-zone: "127.in-addr.arpa." static
        local-data: "127.in-addr.arpa. 10800 IN NS localhost."
        local-data: "127.in-addr.arpa. 10800 IN SOA localhost. nobody.invalid. 1 3600 1200 604800 10800"
        local-data: "1.0.0.127.in-addr.arpa. 10800 IN PTR localhost."

@@[email protected]@reverse IPv6 loopback@@
    Default content:

    .. code-block:: text

        local-zone: "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa." static
        local-data: "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa. 10800 IN NS localhost."
        local-data: "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa. 10800 IN SOA localhost. nobody.invalid. 1 3600 1200 604800 10800"
        local-data: "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa. 10800 IN PTR localhost."

@@[email protected]@home.arpa@@ (:rfc:`8375`)
    Default content:

    .. code-block:: text

        local-zone: "home.arpa." static
        local-data: "home.arpa. 10800 IN NS localhost."
        local-data: "home.arpa. 10800 IN SOA localhost. nobody.invalid. 1 3600 1200 604800 10800"

@@[email protected]@resolver.arpa@@ (:rfc:`9462`)
    Default content:

    .. code-block:: text

        local-zone: "resolver.arpa." static
        local-data: "resolver.arpa. 10800 IN NS localhost."
        local-data: "resolver.arpa. 10800 IN SOA localhost. nobody.invalid. 1 3600 1200 604800 10800"

@@[email protected]@service.arpa@@ (draft-ietf-dnssd-srp-25)
    Default content:

    .. code-block:: text

        local-zone: "service.arpa." static
        local-data: "service.arpa. 10800 IN NS localhost."
        local-data: "service.arpa. 10800 IN SOA localhost. nobody.invalid. 1 3600 1200 604800 10800"

@@[email protected]@onion@@ (:rfc:`7686`)
    Default content:

    .. code-block:: text

        local-zone: "onion." static
        local-data: "onion. 10800 IN NS localhost."
        local-data: "onion. 10800 IN SOA localhost. nobody.invalid. 1 3600 1200 604800 10800"

@@[email protected]@test@@ (:rfc:`6761`)
    Default content:

    .. code-block:: text

        local-zone: "test." static
        local-data: "test. 10800 IN NS localhost."
        local-data: "test. 10800 IN SOA localhost. nobody.invalid. 1 3600 1200 604800 10800"

@@[email protected]@invalid@@ (:rfc:`6761`)
    Default content:

    .. code-block:: text

        local-zone: "invalid." static
        local-data: "invalid. 10800 IN NS localhost."
        local-data: "invalid. 10800 IN SOA localhost. nobody.invalid. 1 3600 1200 604800 10800"

@@[email protected]@reverse local use zones@@ (:rfc:`1918`)
    Reverse data for zones ``10.in-addr.arpa``, ``16.172.in-addr.arpa`` to
    ``31.172.in-addr.arpa``, ``168.192.in-addr.arpa``.
    The :ref:`local-zone` is set static and as
    :ref:`local-data` SOA and NS records are
    provided.

@@[email protected]@special-use IPv4 Addresses@@ (:rfc:`3330`)
    Reverse data for zones ``0.in-addr.arpa`` (this), ``254.169.in-addr.arpa`` (link-local),
    ``2.0.192.in-addr.arpa`` (TEST NET 1), ``100.51.198.in-addr.arpa``
    (TEST NET 2), ``113.0.203.in-addr.arpa`` (TEST NET 3),
    ``255.255.255.255.in-addr.arpa`` (broadcast).
    And from ``64.100.in-addr.arpa`` to ``127.100.in-addr.arpa`` (Shared
    Address Space).

@@[email protected]@reverse IPv6 unspecified@@ (:rfc:`4291`)
    Reverse data for zone
    ``0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa.``

@@[email protected]@reverse IPv6 Locally Assigned Local Addresses@@ (:rfc:`4193`)
    Reverse data for zone ``D.F.ip6.arpa``.

@@[email protected]@reverse IPv6 Link Local Addresses@@ (:rfc:`4291`)
    Reverse data for zones ``8.E.F.ip6.arpa`` to ``B.E.F.ip6.arpa``.

@@[email protected]@reverse IPv6 Example Prefix@@
    Reverse data for zone ``8.B.D.0.1.0.0.2.ip6.arpa``.
    This zone is used for tutorials and examples.
    You can remove the block on this zone with:

    .. code-block:: text

        local-zone: 8.B.D.0.1.0.0.2.ip6.arpa. nodefault

You can also selectively unblock a part of the zone by making that part
transparent with a :ref:`local-zone` statement.
This also works with the other default zones.

@@[email protected]@local-data@@: ""
Configure local data, which is served in reply to queries for it.
The query has to match exactly unless you configure the
:ref:local-zone as redirect.
If not matched exactly, the :ref:local-zone
type determines further processing.
If :ref:local-data is configured that is not a
subdomain of a :ref:local-zone, a
:ref:transparent local-zone is
configured.
For record types such as TXT, use single quotes, as in:

text
.. code-block:: text

    local-data: 'example. TXT "text"'

.. note::
    If you need more complicated authoritative data, with referrals,
    wildcards, CNAME/DNAME support, or DNSSEC authoritative service, setup
    a :ref:`stub-zone` for it as detailed in the stub
    zone section below.

@@[email protected]@local-data-ptr@@: "IPaddr name"
Configure local data shorthand for a PTR record with the reversed IPv4 or
IPv6 address and the host name.
For example "192.0.2.4 www.example.com".
TTL can be inserted like this: "2001:db8::4 7200 www.example.com"

@@[email protected]@local-zone-tag@@: <"list of tags">
Assign tags to local zones.
Tagged localzones will only be applied when the used
:ref:access-control element has a matching
tag.
Tags must be defined in :ref:define-tag.
Enclose list of tags in quotes ("") and put spaces between tags.
When there are multiple tags it checks if the intersection of the list of
tags for the query and :ref:local-zone-tag
is non-empty.

@@[email protected]@local-zone-override@@:
Override the local zone type for queries from addresses matching netblock.
Use this localzone type, regardless the type configured for the local zone
(both tagged and untagged) and regardless the type configured using
:ref:access-control-tag-action.

@@[email protected]@response-ip@@: * *
This requires use of the respip module.

text
If the IP address in an AAAA or A RR in the answer section of a response
matches the specified IP netblock, the specified action will apply.
*<action>* has generally the same semantics as that for
:ref:`access-control-tag-action`,
but there are some exceptions.

Actions for :ref:`response-ip` are different
from those for :ref:`local-zone` in that in case
of the former there is no point of such conditions as "the query matches it
but there is no local data".
Because of this difference, the semantics of
:ref:`response-ip` actions are modified or
simplified as follows: The *static*, *refuse*, *transparent*,
*typetransparent*, and *nodefault* actions are invalid for *response-ip*.
Using any of these will cause the configuration to be rejected as faulty.
The *deny* action is non-conditional, i.e. it always results in dropping
the corresponding query.
The resolution result before applying the *deny* action is still cached and
can be used for other queries.

@@[email protected]@response-ip-data@@: * <"resource record string">*
This requires use of the respip module.

text
This specifies the action data for
:ref:`response-ip` with action being to redirect
as specified by *<"resource record string">*.
*<"Resource record string">* is similar to that of
:ref:`access-control-tag-data`,
but it must be of either AAAA, A or CNAME types.
If the ** is an IPv6/IPv4 prefix, the record must be AAAA/A
respectively, unless it is a CNAME (which can be used for both versions of
IP netblocks).
If it is CNAME there must not be more than one
:ref:`response-ip-data` for the same
**.
Also, CNAME and other types of records must not coexist for the same
**, following the normal rules for CNAME records.
The textual domain name for the CNAME does not have to be explicitly
terminated with a dot (``"."``); the root name is assumed to be the origin
for the name.

@@[email protected]@response-ip-tag@@: * <"list of tags">*
This requires use of the respip module.

text
Assign tags to response **.
If the IP address in an AAAA or A RR in the answer section of a response
matches the specified **, the specified tags are assigned to
the IP address.
Then, if an :ref:`access-control-tag` is
defined for the client and it includes one of the tags for the response IP,
the corresponding
:ref:`access-control-tag-action`
will apply.
Tag matching rule is the same as that for
:ref:`access-control-tag` and
:ref:`local-zone`.
Unlike :ref:`local-zone-tag`,
:ref:`response-ip-tag` can be defined for an
** even if no :ref:`response-ip` is
defined for that netblock.
If multiple :ref:`response-ip-tag` options
are specified for the same ** in different statements, all but
the first will be ignored.
However, this will not be flagged as a configuration error, but the result
is probably not what was intended.

Actions specified in an
:ref:`access-control-tag-action`
that has a matching tag with
:ref:`response-ip-tag` can be those that are
"invalid" for :ref:`response-ip` listed above,
since
:ref:`access-control-tag-action`
can be shared with local zones.
For these actions, if they behave differently depending on whether local
data exists or not in case of local zones, the behavior for
:ref:`response-ip-data` will generally
result in NOERROR/NODATA instead of NXDOMAIN, since the
:ref:`response-ip` data are inherently type
specific, and non-existence of data does not indicate anything about the
existence or non-existence of the qname itself.
For example, if the matching tag action is static but there is no data for
the corresponding :ref:`response-ip`
configuration, then the result will be NOERROR/NODATA.
The only case where NXDOMAIN is returned is when an
:ref:`always_nxdomain`
action applies.

@@[email protected]@ratelimit@@: <number or 0>
Enable ratelimiting of queries sent to nameserver for performing recursion.
0 disables the feature.
This option is experimental at this time.

text
The ratelimit is in queries per second that are allowed.
More queries are turned away with an error (SERVFAIL).
Cached responses are not ratelimited by this setting.

This stops recursive floods, eg. random query names, but not spoofed
reflection floods.
The zone of the query is determined by examining the nameservers for it,
the zone name is used to keep track of the rate.
For example, 1000 may be a suitable value to stop the server from being
overloaded with random names, and keeps unbound from sending traffic to the
nameservers for those zones.

It is intended to count the number of queries towards the nameservers
for the zone, and keep those queries limited.
When there is a delegation that needs a lot of lookups, those are
charged in the counters for the destination, the target name, of
the NS records.
Since that is where the nameserver lookup queries are sent to.
That keeps the target, the victim domain, from having many queries.
With the :ref:`ratelimit-factor`, some
genuine queries that are also made to the target zone, can filter
through, and then end up in cache, where the genuine answers have
a chance to collect, keeping up service to some extent.

.. note:: Configured forwarders are excluded from ratelimiting.

Default: 0

@@[email protected]@ratelimit-size@@:
Give the size of the data structure in which the current ongoing rates are
kept track in.
In bytes or use m(mega), k(kilo), g(giga).
The ratelimit structure is small, so this data structure likely does not
need to be large.

text
Default: 4m

@@[email protected]@ratelimit-slabs@@:
Number of slabs in the ratelimit tracking data structure.
Slabs reduce lock contention by threads.
Must be set to a power of 2.
Setting (close) to the number of cpus is a fairly good setting.
If left unconfigured, it will be configured automatically to be a power of
2 close to the number of configured threads in multi-threaded environments.

text
Default: (unconfigured)

@@[email protected]@ratelimit-factor@@:
Set the amount of queries to rate limit when the limit is exceeded.
If set to 0, all queries are dropped for domains where the limit is
exceeded.
If set to another value, 1 in that number is allowed through to complete.
Default is 10, allowing 1/10 traffic to flow normally.
This can make ordinary queries complete (if repeatedly queried for), and
enter the cache, whilst also mitigating the traffic flow by the factor
given.

text
Default: 10

@@[email protected]@ratelimit-backoff@@:
If enabled, the ratelimit is treated as a hard failure instead of the
default maximum allowed constant rate.
When the limit is reached, traffic is ratelimited and demand continues to
be kept track of for a 2 second rate window.
No traffic is allowed, except for
:ref:ratelimit-factor, until demand
decreases below the configured ratelimit for a 2 second rate window.
Useful to set :ref:ratelimit to a suspicious
rate to aggressively limit unusually high traffic.

text
Default: no

@@[email protected]@ratelimit-for-domain@@: <number qps or 0>
Override the global :ref:ratelimit for an exact
match domain name with the listed number.
You can give this for any number of names.
For example, for a top-level-domain you may want to have a higher limit
than other names.
A value of 0 will disable ratelimiting for that domain.

@@[email protected]@ratelimit-below-domain@@: <number qps or 0>
Override the global :ref:ratelimit for a domain
name that ends in this name.
You can give this multiple times, it then describes different settings in
different parts of the namespace.
The closest matching suffix is used to determine the qps limit.
The rate for the exact matching domain name is not changed, use
:ref:ratelimit-for-domain to set
that, you might want to use different settings for a top-level-domain and
subdomains.
A value of 0 will disable ratelimiting for domain names that end in this
name.

@@[email protected]@ip-ratelimit@@: <number or 0>
Enable global ratelimiting of queries accepted per ip address.
This option is experimental at this time.
The ratelimit is in queries per second that are allowed.
More queries are completely dropped and will not receive a reply, SERVFAIL
or otherwise.
IP ratelimiting happens before looking in the cache.
This may be useful for mitigating amplification attacks.
Clients with a valid DNS Cookie will bypass the ratelimit.
If a ratelimit for such clients is still needed,
:ref:ip-ratelimit-cookie
can be used instead.

text
Default: 0 (disabled)

@@[email protected]@ip-ratelimit-cookie@@: <number or 0>
Enable global ratelimiting of queries accepted per IP address with a valid
DNS Cookie.
This option is experimental at this time.
The ratelimit is in queries per second that are allowed.
More queries are completely dropped and will not receive a reply, SERVFAIL
or otherwise.
IP ratelimiting happens before looking in the cache.
This option could be useful in combination with
:ref:allow_cookie, in an
attempt to mitigate other amplification attacks than UDP reflections (e.g.,
attacks targeting Unbound itself) which are already handled with DNS
Cookies.
If used, the value is suggested to be higher than
:ref:ip-ratelimit e.g., tenfold.

text
Default: 0 (disabled)

@@[email protected]@ip-ratelimit-size@@:
Give the size of the data structure in which the current ongoing rates are
kept track in.
In bytes or use m(mega), k(kilo), g(giga).
The IP ratelimit structure is small, so this data structure likely does not
need to be large.

text
Default: 4m

@@[email protected]@ip-ratelimit-slabs@@:
Number of slabs in the ip ratelimit tracking data structure.
Slabs reduce lock contention by threads.
Must be set to a power of 2.
Setting (close) to the number of cpus is a fairly good setting.
If left unconfigured, it will be configured automatically to be a power of
2 close to the number of configured threads in multi-threaded environments.

text
Default: (unconfigured)

@@[email protected]@ip-ratelimit-factor@@:
Set the amount of queries to rate limit when the limit is exceeded.
If set to 0, all queries are dropped for addresses where the limit is
exceeded.
If set to another value, 1 in that number is allowed through to complete.
Default is 10, allowing 1/10 traffic to flow normally.
This can make ordinary queries complete (if repeatedly queried for), and
enter the cache, whilst also mitigating the traffic flow by the factor
given.

text
Default: 10

@@[email protected]@ip-ratelimit-backoff@@:
If enabled, the rate limit is treated as a hard failure instead of the
default maximum allowed constant rate.
When the limit is reached, traffic is ratelimited and demand continues to
be kept track of for a 2 second rate window.
No traffic is allowed, except for
:ref:ip-ratelimit-factor, until demand
decreases below the configured ratelimit for a 2 second rate window.
Useful to set :ref:ip-ratelimit to a
suspicious rate to aggressively limit unusually high traffic.

text
Default: no

@@[email protected]@outbound-msg-retry@@:
The number of retries, per upstream nameserver in a delegation, that
Unbound will attempt in case a throwaway response is received.
No response (timeout) contributes to the retry counter.
If a forward/stub zone is used, this is the number of retries per
nameserver in the zone.

text
Default: 5

@@[email protected]@max-sent-count@@:
Hard limit on the number of outgoing queries Unbound will make while
resolving a name, making sure large NS sets do not loop.
Results in SERVFAIL when reached.
It resets on query restarts (e.g., CNAME) and referrals.

text
Default: 32

@@[email protected]@max-query-restarts@@:
Hard limit on the number of times Unbound is allowed to restart a query
upon encountering a CNAME record.
Results in SERVFAIL when reached.
This applies to chained CNAME records but not sporadic CNAME records that
could be encountered in the lifetime of the query's resolution effort.
When a CNAME chain concludes, the counter keeping track of this limit is
reset.
Changing this value needs caution as it can allow long CNAME chains to be
accepted, where Unbound needs to verify (resolve) each link individually.

text
Default: 11

@@[email protected]@iter-scrub-ns@@:
Limit on the number of NS records allowed in an rrset of type NS, from the
iterator scrubber.
This protects the internals of the resolver from overly large NS sets.

text
Default: 20

@@[email protected]@iter-scrub-cname@@:
Limit on the number of CNAME, DNAME records in an answer, from the iterator
scrubber.
This protects the internals of the resolver from overly long indirection
chains.
Clips off the remainder of the reply packet at that point.

text
Default: 11

@@[email protected]@iter-scrub-rrsig@@:
Limit on the number of RRSIGs allowed for an RRset, from the iterator
scrubber.
This protects against an overly large number of RRSIGs.
Clips off the remainder of the RRSIG list at that point.

text
Default: 8

@@[email protected]@max-global-quota@@:
Limit on the number of upstream queries sent out for an incoming query and
its subqueries from recursion.
It is not reset during the resolution.
When it is exceeded the query is failed and the lookup process stops.

text
Default: 200

@@[email protected]@iter-scrub-promiscuous@@:
Should the iterator scrubber remove promiscuous NS from positive answers.
This protects against poisonous contents, that could affect names in the
same zone as a spoofed packet.

text
Default: yes

@@[email protected]@val-validation-attempts@@:
Limit on the number of DNSSEC validation attempts for a query.
This protects against too large numbers of cryptographic operations,
like for a deep delegation chain.
This counts attempts to validate RRSIGs.
When it is exceeded, the query fails.

text
Default: 32

@@[email protected]@val-hash-attempts@@:
Limit on the number of DNSSEC hash attempts for a query.
This protects against too large numbers of cryptographic operations,
like for a deep delegation chain.
This counts DS hash attempts to match DNSKEYs.
When it is exceeded, the query fails.

text
Default: 32

@@[email protected]@fast-server-permil@@:
Specify how many times out of 1000 to pick from the set of fastest servers.
0 turns the feature off.
A value of 900 would pick from the fastest servers 90 percent of the time,
and would perform normal exploration of random servers for the remaining
time.
When :ref:prefetch is enabled (or
:ref:serve-expired), such prefetches are not
sped up, because there is no one waiting for it, and it presents a good
moment to perform server exploration.
The :ref:fast-server-num option can be
used to specify the size of the fastest servers set.

text
Default: 0

@@[email protected]@fast-server-num@@:
Set the number of servers that should be used for fast server selection.
Only use the fastest specified number of servers with the
:ref:fast-server-permil option, that
turns this on or off.

text
Default: 3

@@[email protected]@answer-cookie@@:
If enabled, Unbound will answer to requests containing DNS Cookies as
specified in RFC 7873 and RFC 9018.

text
Default: no

@@[email protected]@cookie-secret@@: "<128 bit hex string>"
Server's secret for DNS Cookie generation.
Useful to explicitly set for servers in an anycast deployment that need to
share the secret in order to verify each other's Server Cookies.
An example hex string would be "000102030405060708090a0b0c0d0e0f".

text
.. note::
    This option is ignored if a
    :ref:`cookie-secret-file` is present.
    In that case the secrets from that file are used in DNS Cookie
    calculations.

Default: 128 bits random secret generated at startup time

@@[email protected]@cookie-secret-file@@:
File from which the secrets are read used in DNS Cookie calculations.
When this file exists, the secrets in this file are used and the secret
specified by the
:ref:cookie-secret option is ignored.
Enable it by setting a filename, like
"/usr/local/etc/unbound_cookiesecrets.txt".
The content of this file must be manipulated with the
:ref:add_cookie_secret,
:ref:drop_cookie_secret and
:ref:activate_cookie_secret
commands to the :doc:unbound-control(8)</manpages/unbound-control> tool.
Please see that manpage on how to perform a safe cookie secret rollover.

text
Default: "" (disabled)

@@[email protected]@edns-client-string@@: * *
Include an EDNS0 option containing configured ASCII string in queries with
destination address matching the configured **.
This configuration option can be used multiple times.
The most specific match will be used.

@@[email protected]@edns-client-string-opcode@@:
EDNS0 option code for the
:ref:edns-client-string option, from 0
to 65535.
A value from the 'Reserved for Local/Experimental' range (65001-65534)
should be used.

text
Default: 65001

@@[email protected]@ede@@:
If enabled, Unbound will respond with Extended DNS Error codes
(:rfc:8914).
These EDEs provide additional information with a response mainly for, but
not limited to, DNS and DNSSEC errors.

text
When the :ref:`val-log-level` option is also
set to ``2``, responses with Extended DNS Errors concerning DNSSEC failures
will also contain a descriptive text message about the reason for the
failure.

Default: no

@@[email protected]@ede-serve-expired@@:
If enabled, Unbound will attach an Extended DNS Error (:rfc:8914) Code 3
- Stale Answer
as EDNS0 option to the expired response.

text
.. note::
    :ref:`ede: yes` needs to be set as well for this to
    work.

Default: no

@@[email protected]@dns-error-reporting@@:
If enabled, Unbound will send DNS Error Reports (:rfc:9567).
The name servers need to express support by attaching the Report-Channel
EDNS0 option on their replies specifying the reporting agent for the zone.
Any errors encountered during resolution that would result in Unbound
generating an Extended DNS Error (:rfc:8914) will be reported to the
zone's reporting agent.

text
The :ref:`ede` option does not need to be enabled for
this to work.

It is advised that the
:ref:`qname-minimisation` option is also
enabled to increase privacy on the outgoing reports.

Default: no

.. _unbound.conf.remote:

Remote Control Options

These options are part of the remote-control: section and are the
declarations for the remote control facility.

If this is enabled, the :doc:unbound-control(8)</manpages/unbound-control>
utility can be used to send commands to the running Unbound server.
The server uses these options to setup TLS security for the connection.
The :doc:unbound-control(8)</manpages/unbound-control> utility also reads
this remote-control: section for options.
To setup the correct self-signed certificates use the
unbound-control-setup(8) utility.

@@[email protected]@control-enable@@:
The option is used to enable remote control.
If turned off, the server does not listen for control commands.

text
Default: no

@@[email protected]@control-interface@@: **
Give IPv4 or IPv6 addresses or local socket path to listen on for control
commands.
If an interface name is used instead of an IP address, the list of IP
addresses on that interface are used.

text
By default localhost (``127.0.0.1`` and ``::1``) is listened to.
Use ``0.0.0.0`` and ``::0`` to listen to all interfaces.
If you change this and permissions have been dropped, you must restart the
server for the change to take effect.

If you set it to an absolute path, a unix domain socket is used.
This socket does not use the certificates and keys, so those files need not
be present.
To restrict access, Unbound sets permissions on the file to the user and
group that is configured, the access bits are set to allow the group
members to access the control socket file.
Put users that need to access the socket in the that group.
To restrict access further, create a directory to put the control socket in
and restrict access to that directory.

@@[email protected]@control-port@@: **
The port number to listen on for IPv4 or IPv6 control interfaces.

text
.. note::
    If you change this and permissions have been dropped, you must restart
    the server for the change to take effect.

Default: 8953

@@[email protected]@control-use-cert@@:
For localhost
:ref:control-interface you can
disable the use of TLS by setting this option to "no".
For local sockets, TLS is disabled and the value of this option is ignored.

text
Default: yes

@@[email protected]@server-key-file@@: **
Path to the server private key.
This file is generated by the
:doc:unbound-control-setup(8)</manpages/unbound-control> utility.
This file is used by the Unbound server, but not by
:doc:unbound-control(8)</manpages/unbound-control>.

text
Default: unbound_server.key

@@[email protected]@server-cert-file@@:
Path to the server self signed certificate.
This file is generated by the
:doc:unbound-control-setup(8)</manpages/unbound-control> utility.
This file is used by the Unbound server, and also by
:doc:unbound-control(8)</manpages/unbound-control>.

text
Default: unbound_server.pem

@@[email protected]@control-key-file@@: **
Path to the control client private key.
This file is generated by the
:doc:unbound-control-setup(8)</manpages/unbound-control> utility.
This file is used by :doc:unbound-control(8)</manpages/unbound-control>.

text
Default: unbound_control.key

@@[email protected]@control-cert-file@@:
Path to the control client certificate.
This certificate has to be signed with the server certificate.
This file is generated by the
:doc:unbound-control-setup(8)</manpages/unbound-control> utility.
This file is used by :doc:unbound-control(8)</manpages/unbound-control>.

text
Default: unbound_control.pem

.. _unbound.conf.stub:

Stub Zone Options

These options are part of the stub-zone: section.

There may be multiple stub-zone: sections.
Each with a :ref:name and zero or more hostnames or
IP addresses.
For the stub zone this list of nameservers is used.
Class IN is assumed.
The servers should be authority servers, not recursors; Unbound performs the
recursive processing itself for stub zones.

The stub zone can be used to configure authoritative data to be used by the
resolver that cannot be accessed using the public internet servers.
This is useful for company-local data or private zones.
Setup an authoritative server on a different host (or different port).
Enter a config entry for Unbound with:

.. code-block:: text

stub-addr:

The Unbound resolver can then access the data, without referring to the public
internet for it.

This setup allows DNSSEC signed zones to be served by that authoritative
server, in which case a trusted key entry with the public key can be put in
config, so that Unbound can validate the data and set the AD bit on replies for
the private zone (authoritative servers do not set the AD bit).
This setup makes Unbound capable of answering queries for the private zone, and
can even set the AD bit ('authentic'), but the AA ('authoritative') bit is not
set on these replies.

Consider adding :ref:server statements for
:ref:domain-insecure and for
:ref:local-zone: \<name\> nodefault
for the zone if it is a locally served zone.
The :ref:domain-insecure option stops DNSSEC
from invalidating the zone.
The :ref:local-zone: nodefault (or
:ref:transparent) option makes the
(reverse-) zone bypass Unbound's filtering of :rfc:1918 zones.

@@[email protected]@name@@:
Name of the stub zone.
This is the full domain name of the zone.

@@[email protected]@stub-host@@:
Name of stub zone nameserver.
Is itself resolved before it is used.

text
.. caution::
    If the domain (or a subdomain) from this zone is used as the host, it
    will unavoidably introduce a circular dependency on retrieving the IP
    addresses of the name server.
    In that case, it is suggested to use
    :ref:`stub-addr` instead.
    Alternatively,
    :ref:`stub-first: yes` can also work
    around the circular dependency by trying resolution outside of this
    zone.
    However this has the caveat that it would allow escaping this zone when
    any resolution attempt fails within this zone.

To use a non-default port for DNS communication append ``'@'`` with the
port number.

If TLS is enabled, then you can append a ``'#'`` and a name, then it'll
check the TLS authentication certificates with that name.

If you combine the ``'@'`` and ``'#'``, the ``'@'`` comes first.
If only ``'#'`` is used the default port is the configured
:ref:`tls-port`.

@@[email protected]@stub-addr@@: **
IP address of stub zone nameserver.
Can be IPv4 or IPv6.

text
To use a non-default port for DNS communication append ``'@'`` with the
port number.

If TLS is enabled, then you can append a ``'#'`` and a name, then it'll
check the tls authentication certificates with that name.

If you combine the ``'@'`` and ``'#'``, the ``'@'`` comes first.
If only ``'#'`` is used the default port is the configured
:ref:`tls-port`.

@@[email protected]@stub-prime@@:
If enabled it performs NS set priming, which is similar to root hints,
where it starts using the list of nameservers currently published by the
zone.
Thus, if the hint list is slightly outdated, the resolver picks up a
correct list online.

text
Default: no

@@[email protected]@stub-first@@:
If enabled, a query is attempted without this stub section if it fails.
The data could not be retrieved and would have caused SERVFAIL because the
servers are unreachable, instead it is tried without this stub section.
This can lead to using less specific configured forward/stub/auth zones if
any, or end up to otherwise normal recursive resolution for that particular
query.

text
Default: no

@@[email protected]@stub-tls-upstream@@:
Enabled or disable whether the queries to this stub use TLS for transport.

text
Default: no

@@[email protected]@stub-ssl-upstream@@:
Alternate syntax for
:ref:stub-tls-upstream.

@@[email protected]@stub-tcp-upstream@@:
If it is set to "yes" then upstream queries use TCP only for transport
regardless of global flag :ref:tcp-upstream.

text
Default: no

@@[email protected]@stub-no-cache@@:
If enabled, data inside the stub is not cached.
This is useful when you want immediate changes to be visible.

text
Default: no

.. _unbound.conf.forward:

Forward Zone Options

These options are part of the forward-zone: section.

There may be multiple forward-zone: sections.
Each with a :ref:name and zero or more hostnames
or IP addresses.
For the forward zone this list of nameservers is used to forward the queries
to.
The servers listed as :ref:forward-host
and :ref:forward-addr have to handle
further recursion for the query.
Thus, those servers are not authority servers, but are (just like Unbound is)
recursive servers too; Unbound does not perform recursion itself for the
forward zone, it lets the remote server do it.
Class IN is assumed.
CNAMEs are chased by Unbound itself, asking the remote server for every name in
the indirection chain, to protect the local cache from illegal indirect
referenced items.
A :ref:forward-zone entry with name
"." and a :ref:forward-addr target
will forward all queries to that other server (unless it can answer from the
cache).

@@[email protected]@name@@:
Name of the forward zone.
This is the full domain name of the zone.

@@[email protected]@forward-host@@:
Name of server to forward to.
Is itself resolved before it is used.

text
.. caution::
    If the domain (or a subdomain) from this zone is used as the host, it
    will unavoidably introduce a circular dependency on retrieving the IP
    addresses of the name server.
    In that case, it is suggested to use
    :ref:`forward-addr` instead.
    Alternatively,
    :ref:`forward-first: yes` can also
    work around the circular dependency by trying resolution outside of
    this zone.
    However this has the caveat that it would allow escaping this zone when
    any resolution attempt fails within this zone.

To use a non-default port for DNS communication append ``'@'`` with the
port number.

If TLS is enabled, then you can append a ``'#'`` and a name, then it'll
check the TLS authentication certificates with that name.

If you combine the ``'@'`` and ``'#'``, the ``'@'`` comes first.
If only ``'#'`` is used the default port is the configured
:ref:`tls-port`.

@@[email protected]@forward-addr@@: **
IP address of server to forward to.
Can be IPv4 or IPv6.

text
To use a non-default port for DNS communication append ``'@'`` with the
port number.

If TLS is enabled, then you can append a ``'#'`` and a name, then it'll
check the tls authentication certificates with that name.

If you combine the ``'@'`` and ``'#'``, the ``'@'`` comes first.
If only ``'#'`` is used the default port is the configured
:ref:`tls-port`.

At high verbosity it logs the TLS certificate, with TLS enabled.
If you leave out the ``'#'`` and auth name from the
:ref:`forward-addr`, any name is
accepted.
The cert must also match a CA from the
:ref:`tls-cert-bundle`.

@@[email protected]@forward-first@@:
If a forwarded query is met with a SERVFAIL error and this option is
enabled Unbound will fall back to less specific resolution.
This can lead to using less specific configured forward/stub/auth zones if
any, or end up to otherwise normal recursive resolution for that particular
query.

text
Default: no

@@[email protected]@forward-tls-upstream@@:
Enabled or disable whether the queries to this forwarder use TLS for
transport.
If you enable this, also configure a
:ref:tls-cert-bundle or use
:ref:tls-win-cert to load CA certs, otherwise
the connections cannot be authenticated.

text
Default: no

@@[email protected]@forward-ssl-upstream@@:
Alternate syntax for
:ref:forward-tls-upstream.

@@[email protected]@forward-tcp-upstream@@:
If it is set to "yes" then upstream queries use TCP only for transport
regardless of global flag :ref:tcp-upstream.

text
Default: no

@@[email protected]@forward-no-cache@@:
If enabled, data inside the forward is not cached.
This is useful when you want immediate changes to be visible.

text
Default: no

.. _unbound.conf.auth:

Authority Zone Options

These options are part of the auth-zone: section.

Authority zones are configured with auth-zone:, and each one must have a
:ref:name.
There can be multiple ones, by listing multiple auth-zone section clauses,
each with a different name, pertaining to that part of the namespace.
The authority zone with the name closest to the name looked up is used.
Authority zones can be processed on two distinct, non-exclusive, configurable
stages.

With :ref:for-downstream: yes (default),
authority zones are processed after local-zones and before cache.
When used in this manner, Unbound responds like an authority server with no
further processing other than returning an answer from the zone contents.
A notable example, in this case, is CNAME records which are returned verbatim
to downstream clients without further resolution.

With :ref:for-upstream: yes (default),
authority zones are processed after the cache lookup, just before going to the
network to fetch information for recursion.
When used in this manner they provide a local copy of an authority server
that speeds up lookups for that data during resolving.

If both options are enabled (default), client queries for an authority zone are
answered authoritatively from Unbound, while internal queries that require data
from the authority zone consult the local zone data instead of going to the
network.

An interesting configuration is
:ref:for-downstream: no,
:ref:for-upstream: yes
that allows for hyperlocal behavior where both client and internal queries
consult the local zone data while resolving.
In this case, the aforementioned CNAME example will result in a thoroughly
resolved answer.

Authority zones can be read from a zonefile.
And can be kept updated via AXFR and IXFR.
After update the zonefile is rewritten.
The update mechanism uses the SOA timer values and performs SOA UDP queries to
detect zone changes.

If the update fetch fails, the timers in the SOA record are used to time
another fetch attempt.
Until the SOA expiry timer is reached.
Then the zone is expired.
When a zone is expired, queries are SERVFAIL, and any new serial number is
accepted from the primary (even if older), and if fallback is enabled, the
fallback activates to fetch from the upstream instead of the SERVFAIL.

@@[email protected]@name@@:
Name of the authority zone.

@@[email protected]@primary@@: **
Where to download a copy of the zone from, with AXFR and IXFR.
Multiple primaries can be specified.
They are all tried if one fails.

text
To use a non-default port for DNS communication append ``'@'`` with the
port number.

You can append a ``'#'`` and a name, then AXFR over TLS can be used and the
TLS authentication certificates will be checked with that name.

If you combine the ``'@'`` and ``'#'``, the ``'@'`` comes first.
If you point it at another Unbound instance, it would not work because that
does not support AXFR/IXFR for the zone, but if you used
:ref:`url` to download the zonefile as a text file
from a webserver that would work.

.. caution::
    If you specify the hostname, you cannot use the domain from the
    zonefile, because it may not have that when retrieving that data,
    instead use a plain IP address to avoid a circular dependency on
    retrieving that IP address.

@@[email protected]@master@@: **
Alternate syntax for :ref:primary.

@@[email protected]@url@@: **
Where to download a zonefile for the zone.
With HTTP or HTTPS.
An example for the url is:

text
.. code-block:: text

    http://www.example.com/example.org.zone

Multiple url statements can be given, they are tried in turn.

If only urls are given the SOA refresh timer is used to wait for making new
downloads.
If also primaries are listed, the primaries are first probed with UDP SOA
queries to see if the SOA serial number has changed, reducing the number of
downloads.
If none of the urls work, the primaries are tried with IXFR and AXFR.

For HTTPS, the :ref:`tls-cert-bundle` and
the hostname from the url are used to authenticate the connection.

If you specify a hostname in the URL, you cannot use the domain from the
zonefile, because it may not have that when retrieving that data, instead
use a plain IP address to avoid a circular dependency on retrieving that IP
address.

Avoid dependencies on name lookups by using a notation like
``"http://192.0.2.1/unbound-primaries/example.com.zone"``, with an explicit
IP address.

@@[email protected]@allow-notify@@: **
With :ref:allow-notify you can specify
additional sources of notifies.
When notified, the server attempts to first probe and then zone transfer.
If the notify is from a primary, it first attempts that primary.
Otherwise other primaries are attempted.
If there are no primaries, but only urls, the file is downloaded when
notified.

text
.. note::
    The primaries from :ref:`primary` and
    :ref:`url` statements are allowed notify by
    default.

@@[email protected]@fallback-enabled@@:
If enabled, Unbound falls back to querying the internet as a resolver for
this zone when lookups fail.
For example for DNSSEC validation failures.

text
Default: no

@@[email protected]@for-downstream@@:
If enabled, Unbound serves authority responses to downstream clients for
this zone.
This option makes Unbound behave, for the queries with names in this zone,
like one of the authority servers for that zone.

text
Turn it off if you want Unbound to provide recursion for the zone but have
a local copy of zone data.

If :ref:`for-downstream: no` and
:ref:`for-upstream: yes` are set, then
Unbound will DNSSEC validate the contents of the zone before serving the
zone contents to clients and store validation results in the cache.

Default: yes

@@[email protected]@for-upstream@@:
If enabled, Unbound fetches data from this data collection for answering
recursion queries.
Instead of sending queries over the internet to the authority servers for
this zone, it'll fetch the data directly from the zone data.

text
Turn it on when you want Unbound to provide recursion for downstream
clients, and use the zone data as a local copy to speed up lookups.

Default: yes

@@[email protected]@zonemd-check@@:
Enable this option to check ZONEMD records in the zone.
The ZONEMD record is a checksum over the zone data.
This includes glue in the zone and data from the zone file, and excludes
comments from the zone file.
When there is a DNSSEC chain of trust, DNSSEC signatures are checked too.

text
Default: no

@@[email protected]@zonemd-reject-absence@@:
Enable this option to reject the absence of the ZONEMD record.
Without it, when ZONEMD is not there it is not checked.

text
It is useful to enable for a non-DNSSEC signed zone where the operator
wants to require the verification of a ZONEMD, hence a missing ZONEMD is a
failure.

The action upon failure is controlled by the
:ref:`zonemd-permissive-mode` option,
for log only or also block the zone.

Without the option, absence of a ZONEMD is only a failure when the zone is
DNSSEC signed, and we have a trust anchor, and the DNSSEC verification of
the absence of the ZONEMD fails.
With the option enabled, the absence of a ZONEMD is always a failure, also
for nonDNSSEC signed zones.

Default: no

@@[email protected]@zonefile@@:
The filename where the zone is stored.
If not given then no zonefile is used.
If the file does not exist or is empty, Unbound will attempt to fetch zone
data (eg. from the primary servers).

@@[email protected]@max-transfer-size@@:
Number of bytes size of the maximum zone transfer size.
Larger transfers, over AXFR, IXFR and HTTP, are not allowed.
A plain number is in bytes, append 'k', 'm' or 'g' for kilobytes, megabytes
or gigabytes (1024*1024 bytes in a megabyte).
The value 0 disables the feature.

text
Only consider for untrusted/misbehaving primaries that could hog resources
and bring down the resolver.

Default: 0

@@[email protected]@max-transfer-time@@:
Maximum time in milliseconds that a zone transfer is allowed to take from
the start.
The value 0 disables the feature.

text
Only consider for untrusted/misbehaving primaries that could hog resources
and bring down the resolver.

Default: 0

.. _unbound.conf.view:

View Options

These options are part of the view: section.

There may be multiple view: sections.
Each with a :ref:name and zero or more
:ref:local-zone and
:ref:local-data options.
Views can also contain :ref:view-first,
:ref:response-ip,
:ref:response-ip-data and
:ref:local-data-ptr options.
View can be mapped to requests by specifying the view name in an
:ref:access-control-view option.
Options from matching views will override global options.
Global options will be used if no matching view is found, or when the matching
view does not have the option specified.

@@[email protected]@name@@:
Name of the view.
Must be unique.
This name is used in the
:ref:access-control-view option.

@@[email protected]@local-zone@@:
View specific local zone elements.
Has the same types and behaviour as the global
:ref:local-zone elements.
When there is at least one local-zone: specified and :ref:view-first: no is set, the default local-zones will be
added to this view.
Defaults can be disabled using the nodefault type.
When :ref:view-first: yes is set or when a
view does not have a :ref:local-zone, the
global :ref:local-zone will be used including
it's default zones.

@@[email protected]@local-data@@: ""
View specific local data elements.
Has the same behaviour as the global
:ref:local-data elements.

@@[email protected]@local-data-ptr@@: "IPaddr name"
View specific local-data-ptr elements.
Has the same behaviour as the global
:ref:local-data-ptr elements.

@@[email protected]@response-ip@@: * *
This requires use of the respip module.

text
Similar to :ref:`response-ip` but
only applies to this view.

@@[email protected]@response-ip-data@@: * <"resource record string">*
This requires use of the respip module.

text
Similar to :ref:`response-ip-data` but
only applies to this view.

@@[email protected]@view-first@@:
If enabled, it attempts to use the global
:ref:local-zone and
:ref:local-data if there is no match in the
view specific options.

text
Default: no

.. _unbound.conf.python:

Python Module Options

These options are part of the python: section.

The python: section gives the settings for the python(1) script module.
This module acts like the iterator and validator modules do, on queries and
answers.
To enable the script module it has to be compiled into the daemon, and the word
python has to be put in the
:ref:module-config option (usually first, or
between the validator and iterator).
Multiple instances of the python module are supported by adding the word
python more than once.

If the :ref:chroot option is enabled, you should make
sure Python's library directory structure is bind mounted in the new root
environment, see mount(8).
Also the :ref:python-script path should
be specified as an absolute path relative to the new root, or as a relative
path to the working directory.

@@[email protected]@python-script@@: **
The script file to load.
Repeat this option for every python module instance added to the
:ref:module-config option.

.. _unbound.conf.dynlib:

Dynamic Library Module Options

These options are part of the dynlib: section.

The dynlib: section gives the settings for the dynlib module.
This module is only a very small wrapper that allows dynamic modules to be
loaded on runtime instead of being compiled into the application.
To enable the dynlib module it has to be compiled into the daemon, and the word
dynlib has to be put in the
:ref:module-config option.
Multiple instances of dynamic libraries are supported by adding the word
dynlib more than once.

The :ref:dynlib-file path should be
specified as an absolute path relative to the new path set by
:ref:chroot, or as a relative path to the working
directory.

@@[email protected]@dynlib-file@@:
The dynamic library file to load.
Repeat this option for every dynlib module instance added to the
:ref:module-config option.

DNS64 Module Options

These options are part of the server: section.

The dns64 module must be configured in the
:ref:module-config directive, e.g.:

.. code-block:: text

text
module-config: "dns64 validator iterator"

and be compiled into the daemon to be enabled.

.. note::
If combining the respip and dns64 modules, the respip module
needs to appear before the dns64 module in the
:ref:module-config
configuration option so that response IP and/or RPZ feeds can properly
filter responses regardless of DNS64 synthesis.

@@[email protected]@dns64-prefix@@: **
This sets the DNS64 prefix to use to synthesize AAAA records with.
It must be /96 or shorter.

text
Default: 64:ff9b::/96

@@[email protected]@dns64-synthall@@:
.. warning:: Debugging feature!

text
If enabled, synthesize all AAAA records despite the presence of actual AAAA
records.

Default: no

@@[email protected]@dns64-ignore-aaaa@@:
List domain for which the AAAA records are ignored and the A record is used
by DNS64 processing instead.
Can be entered multiple times, list a new domain for which it applies, one
per line.
Applies also to names underneath the name given.

NAT64 Options

These options are part of the server: section.

NAT64 operation allows using a NAT64 prefix for outbound requests to IPv4-only
servers.

@@[email protected]@do-nat64@@:
Use NAT64 to reach IPv4-only servers.
Consider also enabling :ref:prefer-ip6
to prefer native IPv6 connections to nameservers.

text
Default: no

@@[email protected]@nat64-prefix@@: **
Use a specific NAT64 prefix to reach IPv4-only servers.
The prefix length must be one of /32, /40, /48, /56, /64 or /96.

text
The NAT64 prefix is allowed by the
:ref:`do-not-query-address` option,
so that there is a clear outcome of addresses in both; the NAT64 prefix
is allowed.
The IPv4 address could be filtered by the
:ref:`do-not-query-address` option,
if needed.
Allowing the NAT64 prefix is useful when using do-not-query-address
for a cluster of machines that is IPv6-only and uses NAT64, but does
not have internet access.

Default: 64:ff9b::/96 (same as :ref:`dns64-prefix`)

.. _unbound.conf.dnscrypt:

DNSCrypt Options

These options are part of the dnscrypt: section.

The dnscrypt: section gives the settings of the dnscrypt channel.
While those options are available, they are only meaningful if Unbound was
compiled with --enable-dnscrypt.
Currently certificate and secret/public keys cannot be generated by Unbound.
You can use dnscrypt-wrapper to generate those:
https://github.com/cofyc/dnscrypt-wrapper/blob/master/README.md#usage

@@[email protected]@dnscrypt-enable@@:
Whether or not the dnscrypt config should be enabled.
You may define configuration but not activate it.

text
Default: no

@@[email protected]@dnscrypt-port@@: **
On which port should dnscrypt should be activated.

text
.. note::
    There should be a matching interface option defined in the
    :ref:`server:` section for this port.

@@[email protected]@dnscrypt-provider@@: **
The provider name to use to distribute certificates.
This is of the form:

text
.. code-block:: text

    2.dnscrypt-cert.example.com.

.. important:: The name *MUST* end with a dot.

@@[email protected]@dnscrypt-secret-key@@: **
Path to the time limited secret key file.
This option may be specified multiple times.

@@[email protected]@dnscrypt-provider-cert@@: **
Path to the certificate related to the
:ref:dnscrypt-secret-key.
This option may be specified multiple times.

@@[email protected]@dnscrypt-provider-cert-rotated@@: **
Path to a certificate that we should be able to serve existing connection
from but do not want to advertise over
:ref:dnscrypt-provider 's TXT
record certs distribution.

text
A typical use case is when rotating certificates, existing clients may
still use the client magic from the old cert in their queries until they
fetch and update the new cert.
Likewise, it would allow one to prime the new cert/key without distributing
the new cert yet, this can be useful when using a network of servers using
anycast and on which the configuration may not get updated at the exact
same time.

By priming the cert, the servers can handle both old and new certs traffic
while distributing only one.

This option may be specified multiple times.

@@[email protected]@dnscrypt-shared-secret-cache-size@@:
Give the size of the data structure in which the shared secret keys are
kept in.
In bytes or use m(mega), k(kilo), g(giga).
The shared secret cache is used when a same client is making multiple
queries using the same public key.
It saves a substantial amount of CPU.

text
Default: 4m

@@[email protected]@dnscrypt-shared-secret-cache-slabs@@:
Number of slabs in the dnscrypt shared secrets cache.
Slabs reduce lock contention by threads.
Must be set to a power of 2.
Setting (close) to the number of cpus is a fairly good setting.
If left unconfigured, it will be configured automatically to be a power of
2 close to the number of configured threads in multi-threaded environments.

text
Default: (unconfigured)

@@[email protected]@dnscrypt-nonce-cache-size@@:
Give the size of the data structure in which the client nonces are kept in.
In bytes or use m(mega), k(kilo), g(giga).
The nonce cache is used to prevent dnscrypt message replaying.
Client nonce should be unique for any pair of client pk/server sk.

text
Default: 4m

@@[email protected]@dnscrypt-nonce-cache-slabs@@:
Number of slabs in the dnscrypt nonce cache.
Slabs reduce lock contention by threads.
Must be set to a power of 2.
Setting (close) to the number of cpus is a fairly good setting.
If left unconfigured, it will be configured automatically to be a power of
2 close to the number of configured threads in multi-threaded environments.

text
Default: (unconfigured)

EDNS Client Subnet Module Options

These options are part of the server: section.

The ECS module must be configured in the
:ref:module-config directive, e.g.:

.. code-block:: text

text
module-config: "subnetcache validator iterator"

and be compiled into the daemon to be enabled.

If the destination address is allowed in the configuration Unbound will add the
EDNS0 option to the query containing the relevant part of the client's address.
When an answer contains the ECS option the response and the option are placed
in a specialized cache.
If the authority indicated no support, the response is stored in the regular
cache.

Additionally, when a client includes the option in its queries, Unbound will
forward the option when sending the query to addresses that are explicitly
allowed in the configuration using
:ref:send-client-subnet.
The option will always be forwarded, regardless the allowed addresses, when
:ref:client-subnet-always-forward: yes
is set.
In this case the lookup in the regular cache is skipped.

The maximum size of the ECS cache is controlled by
:ref:msg-cache-size in the configuration file.
On top of that, for each query only 100 different subnets are allowed to be
stored for each address family.
Exceeding that number, older entries will be purged from cache.

Note that due to the nature of how EDNS Client Subnet works, by segregating the
client IP space in order to try and have tailored responses for prefixes of
unknown sizes, resolution and cache response performance are impacted as a
result.
Usage of the subnetcache module should only be enabled in installations that
require such functionality where the resolver and the clients belong to
different networks.
An example of that is an open resolver installation.

This module does not interact with the
:ref:serve-expired\* and
:ref:prefetch options.

@@[email protected]@send-client-subnet@@: **
Send client source address to this authority.
Append /num to indicate a classless delegation netblock, for example like
10.2.3.4/24 or 2001::11/64.
Can be given multiple times.
Authorities not listed will not receive edns-subnet information, unless
domain in query is specified in
:ref:client-subnet-zone.

@@[email protected]@client-subnet-zone@@:
Send client source address in queries for this domain and its subdomains.
Can be given multiple times.
Zones not listed will not receive edns-subnet information, unless hosted by
authority specified in
:ref:send-client-subnet.

@@[email protected]@client-subnet-always-forward@@:
Specify whether the ECS address check (configured using
:ref:send-client-subnet) is applied
for all queries, even if the triggering query contains an ECS record, or
only for queries for which the ECS record is generated using the querier
address (and therefore did not contain ECS data in the client query).
If enabled, the address check is skipped when the client query contains an
ECS record.
And the lookup in the regular cache is skipped.

text
Default: no

@@[email protected]@max-client-subnet-ipv6@@:
Specifies the maximum prefix length of the client source address we are
willing to expose to third parties for IPv6.

text
Default: 56

@@[email protected]@max-client-subnet-ipv4@@:
Specifies the maximum prefix length of the client source address we are
willing to expose to third parties for IPv4.

text
Default: 24

@@[email protected]@min-client-subnet-ipv6@@:
Specifies the minimum prefix length of the IPv6 source mask we are willing
to accept in queries.
Shorter source masks result in REFUSED answers.
Source mask of 0 is always accepted.

text
Default: 0

@@[email protected]@min-client-subnet-ipv4@@:
Specifies the minimum prefix length of the IPv4 source mask we are willing
to accept in queries.
Shorter source masks result in REFUSED answers.
Source mask of 0 is always accepted.
Default: 0

@@[email protected]@max-ecs-tree-size-ipv4@@:
Specifies the maximum number of subnets ECS answers kept in the ECS radix
tree.
This number applies for each qname/qclass/qtype tuple.

text
Default: 100

@@[email protected]@max-ecs-tree-size-ipv6@@:
Specifies the maximum number of subnets ECS answers kept in the ECS radix
tree.
This number applies for each qname/qclass/qtype tuple.

text
Default: 100

Opportunistic IPsec Support Module Options

These options are part of the server: section.

The IPsec module must be configured in the
:ref:module-config directive, e.g.:

.. code-block:: text

text
module-config: "ipsecmod validator iterator"

and be compiled into Unbound by using --enable-ipsecmod to be enabled.

When Unbound receives an A/AAAA query that is not in the cache and finds a
valid answer, it will withhold returning the answer and instead will generate
an IPSECKEY subquery for the same domain name.
If an answer was found, Unbound will call an external hook passing the
following arguments:

QNAME
Domain name of the A/AAAA and IPSECKEY query.
In string format.

IPSECKEY TTL
TTL of the IPSECKEY RRset.

A/AAAA
String of space separated IP addresses present in the A/AAAA RRset.
The IP addresses are in string format.

IPSECKEY
String of space separated IPSECKEY RDATA present in the IPSECKEY RRset.
The IPSECKEY RDATA are in DNS presentation format.

The A/AAAA answer is then cached and returned to the client.
If the external hook was called the TTL changes to ensure it doesn't surpass
:ref:ipsecmod-max-ttl.

The same procedure is also followed when
:ref:prefetch: yes is set, but the A/AAAA answer is
given to the client before the hook is called.
:ref:ipsecmod-max-ttl ensures that the A/AAAA
answer given from cache is still relevant for opportunistic IPsec.

@@[email protected]@ipsecmod-enabled@@:
Specifies whether the IPsec module is enabled or not.
The IPsec module still needs to be defined in the
:ref:module-config directive.
This option facilitates turning on/off the module without
restarting/reloading Unbound.

text
Default: yes

@@[email protected]@ipsecmod-hook@@:
Specifies the external hook that Unbound will call with system(3).
The file can be specified as an absolute/relative path.
The file needs the proper permissions to be able to be executed by the same
user that runs Unbound.
It must be present when the IPsec module is defined in the
:ref:module-config directive.

@@[email protected]@ipsecmod-strict@@:
If enabled Unbound requires the external hook to return a success value of
0.
Failing to do so Unbound will reply with SERVFAIL.
The A/AAAA answer will also not be cached.

text
Default: no

@@[email protected]@ipsecmod-max-ttl@@:
Time to live maximum for A/AAAA cached records after calling the external
hook.

text
Default: 3600

@@[email protected]@ipsecmod-ignore-bogus@@:
Specifies the behaviour of Unbound when the IPSECKEY answer is bogus.
If set to yes, the hook will be called and the A/AAAA answer will be
returned to the client.
If set to no, the hook will not be called and the answer to the A/AAAA
query will be SERVFAIL.
Mainly used for testing.

text
Default: no

@@[email protected]@ipsecmod-allow@@:
Allow the IPsec module functionality for the domain so that the module
logic will be executed.
Can be given multiple times, for different domains.
If the option is not specified, all domains are treated as being allowed
(default).

@@[email protected]@ipsecmod-whitelist@@:
Alternate syntax for :ref:ipsecmod-allow.

.. _unbound.conf.cachedb:

Cache DB Module Options

These options are part of the cachedb: section.

The Cache DB module must be configured in the
:ref:module-config directive, e.g.:

.. code-block:: text

text
module-config: "validator cachedb iterator"

and be compiled into the daemon with --enable-cachedb.

If this module is enabled and configured, the specified backend database works
as a second level cache; when Unbound cannot find an answer to a query in its
built-in in-memory cache, it consults the specified backend.
If it finds a valid answer in the backend, Unbound uses it to respond to the
query without performing iterative DNS resolution.
If Unbound cannot even find an answer in the backend, it resolves the query as
usual, and stores the answer in the backend.

This module interacts with the serve-expired-* options and will reply with
expired data if Unbound is configured for that.

If Unbound was built with --with-libhiredis on a system that has installed
the hiredis C client library of Redis, then the redis backend can be used.
This backend communicates with the specified Redis server over a TCP connection
to store and retrieve cache data.
It can be used as a persistent and/or shared cache backend.

.. note::
Unbound never removes data stored in the Redis server, even if some data
have expired in terms of DNS TTL or the Redis server has cached too much
data; if necessary the Redis server must be configured to limit the cache
size, preferably with some kind of least-recently-used eviction policy.

Additionally, the
:ref:redis-expire-records option
can be used in order to set the relative DNS TTL of the message as timeout to
the Redis records; keep in mind that some additional memory is used per key and
that the expire information is stored as absolute Unix timestamps in Redis
(computer time must be stable).

This backend uses synchronous communication with the Redis server based on the
assumption that the communication is stable and sufficiently fast.
The thread waiting for a response from the Redis server cannot handle other DNS
queries.
Although the backend has the ability to reconnect to the server when the
connection is closed unexpectedly and there is a configurable timeout in case
the server is overly slow or hangs up, these cases are assumed to be very rare.
If connection close or timeout happens too often, Unbound will be effectively
unusable with this backend.
It's the administrator's responsibility to make the assumption hold.

The cachedb: section gives custom settings of the cache DB module.

@@[email protected]@backend@@: **
Specify the backend database name.
The default database is the in-memory backend named testframe, which,
as the name suggests, is not of any practical use.
Depending on the build-time configuration, redis backend may also be
used as described above.

text
Default: testframe

@@[email protected]@secret-seed@@: ""
Specify a seed to calculate a hash value from query information.
This value will be used as the key of the corresponding answer for the
backend database and can be customized if the hash should not be
predictable operationally.
If the backend database is shared by multiple Unbound instances, all
instances must use the same secret seed.

text
Default: "default"

@@[email protected]@cachedb-no-store@@:
If the backend should be read from, but not written to.
This makes this instance not store dns messages in the backend.
But if data is available it is retrieved.

text
Default: no

@@[email protected]@cachedb-check-when-serve-expired@@:
If enabled, the cachedb is checked before an expired response is returned.
When
:ref:serve-expired
is enabled, without
:ref:serve-expired-client-timeout
, it then does not immediately respond with an expired response from cache,
but instead first checks the cachedb for valid contents, and if so returns it.
If the cachedb also has no valid contents, the serve expired response is sent.
If also
:ref:serve-expired-client-timeout
is enabled, the expired response is delayed until the timeout expires.
Unless the lookup succeeds within the timeout.

text
Default: yes

The following cachedb: options are specific to the redis backend.

@@[email protected]@redis-server-host@@:
The IP (either v6 or v4) address or domain name of the Redis server.
In general an IP address should be specified as otherwise Unbound will have
to resolve the name of the server every time it establishes a connection to
the server.

text
Default: 127.0.0.1

@@[email protected]@redis-server-port@@: **
The TCP port number of the Redis server.

text
Default: 6379

@@[email protected]@redis-server-path@@: **
The unix socket path to connect to the Redis server.
Unix sockets may have better throughput than the IP address option.

text
Default: "" (disabled)

@@[email protected]@redis-server-password@@: ""
The Redis AUTH password to use for the Redis server.
Only relevant if Redis is configured for client password authorisation.

text
Default: "" (disabled)

@@[email protected]@redis-timeout@@:
The period until when Unbound waits for a response from the Redis server.
If this timeout expires Unbound closes the connection, treats it as if the
Redis server does not have the requested data, and will try to re-establish
a new connection later.

text
Default: 100

@@[email protected]@redis-command-timeout@@:
The timeout to use for Redis commands, in milliseconds.
If 0, it uses the
:ref:redis-timeout
value.

text
Default: 0

@@[email protected]@redis-connect-timeout@@:
The timeout to use for Redis connection set up, in milliseconds.
If 0, it uses the
:ref:redis-timeout
value.

text
Default: 0

@@[email protected]@redis-expire-records@@:
If Redis record expiration is enabled.
If yes, Unbound sets timeout for Redis records so that Redis can evict keys
that have expired automatically.
If Unbound is configured with
:ref:serve-expired and
:ref:serve-expired-ttl: 0, this option is
internally reverted to "no".

text
.. note::
    Redis "SET ... EX" support is required for this option (Redis >= 2.6.12).

Default: no

@@[email protected]@redis-logical-db@@:
The logical database in Redis to use.
These are databases in the same Redis instance sharing the same
configuration and persisted in the same RDB/AOF file.
If unsure about using this option, Redis documentation
(https://redis.io/commands/select/) suggests not to use a single Redis
instance for multiple unrelated applications.
The default database in Redis is 0 while other logical databases need to be
explicitly SELECT'ed upon connecting.

text
Default: 0

@@[email protected]@redis-replica-server-host@@:
The IP (either v6 or v4) address or domain name of the Redis server.
In general an IP address should be specified as otherwise Unbound will have
to resolve the name of the server every time it establishes a connection to
the server.

text
This server is treated as a read-only replica server
(https://redis.io/docs/management/replication/#read-only-replica).
If specified, all Redis read commands will go to this replica server, while
the write commands will go to the
:ref:`redis-server-host`.

Default: "" (disabled).

@@[email protected]@redis-replica-server-port@@: **
The TCP port number of the Redis replica server.

text
Default: 6379

@@[email protected]@redis-replica-server-path@@: **
The unix socket path to connect to the Redis replica server.
Unix sockets may have better throughput than the IP address option.

text
Default: "" (disabled)

@@[email protected]@redis-replica-server-password@@: ""
The Redis AUTH password to use for the Redis server.
Only relevant if Redis is configured for client password authorisation.

text
Default: "" (disabled)

@@[email protected]@redis-replica-timeout@@:
The period until when Unbound waits for a response from the Redis replica
server.
If this timeout expires Unbound closes the connection, treats it as if the
Redis server does not have the requested data, and will try to re-establish
a new connection later.

text
Default: 100

@@[email protected]@redis-replica-command-timeout@@:
The timeout to use for Redis replica commands, in milliseconds.
If 0, it uses the
:ref:redis-replica-timeout
value.

text
Default: 0

@@[email protected]@redis-replica-connect-timeout@@:
The timeout to use for Redis replica connection set up, in milliseconds.
If 0, it uses the
:ref:redis-replica-timeout
value.

text
Default: 0

@@[email protected]@redis-replica-logical-db@@:
Same as :ref:redis-logical-db but
for the Redis replica server.

text
Default: 0

.. _unbound.conf.dnstap:

DNSTAP Options

These options are part of the dnstap: section.

DNSTAP is a flexible, structured binary log format for DNS software.
When compiled in by using --enable-dnstap, it can be enabled in the
dnstap: section.
This starts an extra thread (when compiled with threading) that writes the log
information to the destination.
If Unbound is compiled without threading it does not spawn a thread, but
connects per-process to the destination.

@@[email protected]@dnstap-enable@@:
If dnstap is enabled.
If yes, it connects to the DNSTAP server and if any of the
dnstap-log-..-messages: options is enabled it sends logs for those
messages to the server.

text
Default: no

@@[email protected]@dnstap-bidirectional@@:
Use frame streams in bidirectional mode to transfer DNSTAP messages.

text
Default: yes

@@[email protected]@dnstap-socket-path@@:
Sets the unix socket file name for connecting to the server that is
listening on that socket.

text
Default: @DNSTAP_SOCKET_PATH@

@@[email protected]@dnstap-ip@@: **
If "", the unix socket is used, if set with an IP address (IPv4 or
IPv6) that address is used to connect to the server.

text
Default: ""

@@[email protected]@dnstap-tls@@:
Set this to use TLS to connect to the server specified in
:ref:dnstap-ip.
If set to no, TCP is used to connect to the server.

text
Default: yes

@@[email protected]@dnstap-tls-server-name@@:
The TLS server name to authenticate the server with.
Used when :ref:dnstap-tls: yes is set.
If "" it is ignored.

text
Default: ""

@@[email protected]@dnstap-tls-cert-bundle@@:
The pem file with certs to verify the TLS server certificate.
If "" the server default cert bundle is used, or the windows cert
bundle on windows.

text
Default: ""

@@[email protected]@dnstap-tls-client-key-file@@:
The client key file for TLS client authentication.
If "" client authentication is not used.

text
Default: ""

@@[email protected]@dnstap-tls-client-cert-file@@:
The client cert file for TLS client authentication.

text
Default: ""

@@[email protected]@dnstap-send-identity@@:
If enabled, the server identity is included in the log messages.

text
Default: no

@@[email protected]@dnstap-send-version@@:
If enabled, the server version if included in the log messages.

text
Default: no

@@[email protected]@dnstap-identity@@:
The identity to send with messages, if "" the hostname is used.

text
Default: ""

@@[email protected]@dnstap-version@@:
The version to send with messages, if "" the package version is used.

text
Default: ""

@@[email protected]@dnstap-sample-rate@@:
The sample rate for log of messages, it logs only 1/N messages.
With 0 it is disabled.
This is useful in a high volume environment, where log functionality would
otherwise not be reliable.
For example 10 would spend only 1/10th time on logging, and 100 would only
spend a hundredth of the time on logging.

text
Default: 0 (disabled)

@@[email protected]@dnstap-log-resolver-query-messages@@:
Enable to log resolver query messages.
These are messages from Unbound to upstream servers.

text
Default: no

@@[email protected]@dnstap-log-resolver-response-messages@@:
Enable to log resolver response messages.
These are replies from upstream servers to Unbound.

text
Default: no

@@[email protected]@dnstap-log-client-query-messages@@:
Enable to log client query messages.
These are client queries to Unbound.

text
Default: no

@@[email protected]@dnstap-log-client-response-messages@@:
Enable to log client response messages.
These are responses from Unbound to clients.

text
Default: no

@@[email protected]@dnstap-log-forwarder-query-messages@@:
Enable to log forwarder query messages.

text
Default: no

@@[email protected]@dnstap-log-forwarder-response-messages@@:
Enable to log forwarder response messages.

text
Default: no

.. _unbound.conf.rpz:

Response Policy Zone Options

These options are part of the rpz: section.

Response Policy Zones are configured with rpz: section clauses, and each
one must have a :ref:name option.
There can be multiple ones, by listing multiple rpz: section clauses, each
with a different name.
RPZ sections are applied in order of configuration and any match from an
earlier RPZ zone will terminate the RPZ lookup.
Note that a PASSTHRU action is still considered a match.

The respip module needs to be added to the
:ref:module-config, e.g.:

.. code-block:: text

text
module-config: "respip validator iterator"

.. note::
If combining the respip and dns64 modules, the respip module
needs to appear before the dns64 module in the
:ref:module-config
configuration option so that response IP and/or RPZ feeds can properly
filter responses regardless of DNS64 synthesis.

QNAME, Response IP Address, nsdname, nsip and clientip triggers are supported.
Supported actions are: NXDOMAIN, NODATA, PASSTHRU, DROP, Local Data, tcp-only
and drop.
RPZ QNAME triggers are applied after any
:ref:local-zone and before any
:ref:auth-zone.

The RPZ zone is a regular DNS zone formatted with a SOA start record as usual.
The items in the zone are entries, that specify what to act on (the trigger)
and what to do (the action).
The trigger to act on is recorded in the name, the action to do is recorded as
the resource record.
The names all end in the zone name, so you could type the trigger names without
a trailing dot in the zonefile.

An example RPZ record, that answers example.com with NXDOMAIN:

.. code-block:: text

text
example.com CNAME .

The triggers are encoded in the name on the left

.. code-block:: text

text
name                          query name
netblock.rpz-client-ip        client IP address
netblock.rpz-ip               response IP address in the answer
name.rpz-nsdname              nameserver name
netblock.rpz-nsip             nameserver IP address

The netblock is written as <netblocklen>..
For IPv6 use 'zz' for '::'.
Specify individual addresses with scope length of 32 or 128.
For example, 24.10.100.51.198.rpz-ip is 198.51.100.10/24 and
32.10.zz.db8.2001.rpz-ip is 2001:db8:0:0:0:0:0:10/32.

The actions are specified with the record on the right

.. code-block:: text

text
CNAME .                      nxdomain reply
CNAME *.                     nodata reply
CNAME rpz-passthru.          do nothing, allow to continue
CNAME rpz-drop.              the query is dropped
CNAME rpz-tcp-only.          answer over TCP
A 192.0.2.1                  answer with this IP address

Other records like AAAA, TXT and other CNAMEs (not rpz-..) can also be used to
answer queries with that content.

@@[email protected]@name@@:
Name of the authority zone.

@@[email protected]@primary@@: **
Where to download a copy of the zone from, with AXFR and IXFR.
Multiple primaries can be specified.
They are all tried if one fails.

text
To use a non-default port for DNS communication append ``'@'`` with the
port number.

You can append a ``'#'`` and a name, then AXFR over TLS can be used and the
TLS authentication certificates will be checked with that name.

If you combine the ``'@'`` and ``'#'``, the ``'@'`` comes first.
If you point it at another Unbound instance, it would not work because that
does not support AXFR/IXFR for the zone, but if you used
:ref:`url` to download the zonefile as a text file
from a webserver that would work.

If you specify the hostname, you cannot use the domain from the zonefile,
because it may not have that when retrieving that data, instead use a plain
IP address to avoid a circular dependency on retrieving that IP address.

Every number of IXFR transfers, a full AXFR is performed.
This is to consolidate the rpz memory, that would otherwise grow.
The fixed value is after 5 IXFR transfers.

@@[email protected]@master@@: **
Alternate syntax for :ref:primary.

@@[email protected]@url@@: **
Where to download a zonefile for the zone.
With HTTP or HTTPS.
An example for the url is:

text
.. code-block:: text

    http://www.example.com/example.org.zone

Multiple url statements can be given, they are tried in turn.

If only urls are given the SOA refresh timer is used to wait for making new
downloads.
If also primaries are listed, the primaries are first probed with UDP SOA
queries to see if the SOA serial number has changed, reducing the number of
downloads.
If none of the URLs work, the primaries are tried with IXFR and AXFR.

For HTTPS, the :ref:`tls-cert-bundle` and
the hostname from the url are used to authenticate the connection.

@@[email protected]@allow-notify@@: **
With :ref:allow-notify you can specify
additional sources of notifies.
When notified, the server attempts to first probe and then zone transfer.
If the notify is from a primary, it first attempts that primary.
Otherwise other primaries are attempted.
If there are no primaries, but only urls, the file is downloaded when
notified.

text
.. note::
    The primaries from :ref:`primary` and
    :ref:`url` statements are allowed notify by
    default.

@@[email protected]@zonefile@@:
The filename where the zone is stored.
If not given then no zonefile is used.
If the file does not exist or is empty, Unbound will attempt to fetch zone
data (eg. from the primary servers).

@@[email protected]@rpz-action-override@@:
Always use this RPZ action for matching triggers from this zone.
Possible actions are: nxdomain, nodata, passthru, drop, disabled
and cname.

@@[email protected]@rpz-cname-override@@:
The CNAME target domain to use if the cname action is configured for
:ref:rpz-action-override.

@@[email protected]@rpz-log@@:
Log all applied RPZ actions for this RPZ zone.

text
Default: no

@@[email protected]@rpz-log-name@@:
Specify a string to be part of the log line, for easy referencing.

@@[email protected]@rpz-signal-nxdomain-ra@@:
Signal when a query is blocked by the RPZ with NXDOMAIN with an unset RA
flag.
This allows certain clients, like dnsmasq, to infer that the domain is
externally blocked.

text
Default: no

@@[email protected]@for-downstream@@:
If enabled the zone is authoritatively answered for and queries for the RPZ
zone information are answered to downstream clients.
This is useful for monitoring scripts, that can then access the SOA
information to check if the RPZ information is up to date.

text
Default: no

@@[email protected]@tags@@: ""
Limit the policies from this RPZ section to clients with a matching tag.

text
Tags need to be defined in :ref:`define-tag` and
can be assigned to client addresses using
:ref:`access-control-tag` or
:ref:`interface-tag`.
Enclose list of tags in quotes (``""``) and put spaces between tags.

If no tags are specified the policies from this section will be applied for
all clients.

@@[email protected]@max-transfer-size@@:
Number of bytes size of the maximum zone transfer size.
Larger transfers, over AXFR, IXFR and HTTP, are not allowed.
A plain number is in bytes, append 'k', 'm' or 'g' for kilobytes, megabytes
or gigabytes (1024*1024 bytes in a megabyte).
The value 0 disables the feature.

text
Only consider for untrusted/misbehaving primaries that could hog resources
and bring down the resolver.

Default: 0

@@[email protected]@max-transfer-time@@:
Maximum time in milliseconds that a zone transfer is allowed to take from
the start.
The value 0 disables the feature.

text
Only consider for untrusted/misbehaving primaries that could hog resources
and bring down the resolver.

Default: 0

Memory Control Example

In the example config settings below memory usage is reduced.
Some service levels are lower, notable very large data and a high TCP load are
no longer supported.
Very large data and high TCP loads are exceptional for the DNS.
DNSSEC validation is enabled, just add trust anchors.
If you do not have to worry about programs using more than 3 Mb of memory, the
below example is not for you.
Use the defaults to receive full service, which on BSD-32bit tops out at 30-40
Mb after heavy usage.

.. code-block:: text

text
# example settings that reduce memory usage
    server:
        num-threads: 1
        outgoing-num-tcp: 1 # this limits TCP service, uses less buffers.
        incoming-num-tcp: 1
        outgoing-range: 60  # uses less memory, but less performance.
        msg-buffer-size: 8192   # note this limits service, 'no huge stuff'.
        msg-cache-size: 100k
        msg-cache-slabs: 1
        rrset-cache-size: 100k
        rrset-cache-slabs: 1
        infra-cache-numhosts: 200
        infra-cache-slabs: 1
        key-cache-size: 100k
        key-cache-slabs: 1
        neg-cache-size: 10k
        num-queries-per-thread: 30
        target-fetch-policy: "2 1 0 0 0 0"
        harden-large-queries: "yes"
        harden-short-bufsize: "yes"

Files

@UNBOUND_RUN_DIR@
default Unbound working directory.

@UNBOUND_CHROOT_DIR@
default chroot(2) location.

@ub_conf_file@
Unbound configuration file.

@UNBOUND_PIDFILE@
default Unbound pidfile with process ID of the running daemon.

unbound.log
Unbound log file.
Default is to log to syslog(3).

See Also

:doc:unbound(8)</manpages/unbound>,
:doc:unbound-checkonf(8)</manpages/unbound-checkconf>.


Doc Unbound (`doc/unbound.rst`)

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

..
WHEN EDITING MAKE SURE EACH SENTENCE STARTS ON A NEW LINE

..
IT HELPS RENDERERS TO DO THE RIGHT THING WRT SPACE

..
IT HELPS PEOPLE DIFFING THE CHANGES

.. program:: unbound

unbound(8)

Synopsis

unbound [-hdpVv] [-c <cfgfile>]

Description

unbound is a caching DNS resolver.

It uses a built in list of authoritative nameservers for the root zone (.),
the so called root hints.
On receiving a DNS query it will ask the root nameservers for an answer and
will in almost all cases receive a delegation to a top level domain (TLD)
authoritative nameserver.
It will then ask that nameserver for an answer.
It will recursively continue until an answer is found or no answer is available
(NXDOMAIN).
For performance and efficiency reasons that answer is cached for a certain time
(the answer's time-to-live or TTL).
A second query for the same name will then be answered from the cache.
Unbound can also do DNSSEC validation.

To use a locally running Unbound for resolving put:

.. code-block:: text

nameserver 127.0.0.1

into resolv.conf(5).

If authoritative DNS is needed as well using :external+nsd:doc:manpages/nsd,
careful setup is required because authoritative nameservers and resolvers are
using the same port number (53).

The available options are:

.. option:: -h

Show the version number and commandline option help, and exit.

.. option:: -c

Set the config file with settings for unbound to read instead of reading the
file at the default location, :file:@ub_conf_file@.
The syntax is described in :doc:unbound.conf(5)</manpages/unbound.conf>.

.. option:: -d

Debug flag: do not fork into the background, but stay attached to the
console.
This flag will also delay writing to the log file until the thread-spawn
time, so that most config and setup errors appear on stderr.
If given twice or more, logging does not switch to the log file or to
syslog, but the log messages are printed to stderr all the time.

.. option:: -p

Don't use a pidfile.
This argument should only be used by supervision systems which can ensure
that only one instance of Unbound will run concurrently.

.. option:: -v

Increase verbosity.
If given multiple times, more information is logged.
This is in addition to the verbosity (if any) from the config file.

.. option:: -V

Show the version number and build options, and exit.

See Also

:doc:unbound.conf(5)</manpages/unbound.conf>,
:doc:unbound-checkconf(8)</manpages/unbound-checkconf>,
:external+nsd:doc:manpages/nsd.


Pythonmod Doc Index (`pythonmod/doc/index.rst`)

Unbound scriptable interface

Python module for Unbound provides easy-to-use flexible solution,
for scripting query events and much more!

Along with extensible SWIG interface, it turns Unbound into dynamic DNS service
designed for rapid development of DNS based applications, like detailed (per query/domain) statistics,
monitoring with anything Python can offer (database backend, http server).

Key features

  • Rapid dynamic DNS-based application development in Python
  • Extensible interface with SWIG
  • Easy to use debugging and analysis tool
  • Capable to produce authoritative answers
  • Support for logging or doing detailed statistics
  • Allows to manipulate with content of cache memory

Contents

.. toctree::
:maxdepth: 2

install
examples/index
usecase
modules/index

Indices and tables

  • :ref:genindex
  • :ref:search

Pythonmod Doc Install (`pythonmod/doc/install.rst`)

Installation

Prerequisites

Python 2.4 or higher, SWIG 1.3 or higher, GNU make

Download

You can download the source codes here_.
The latest release is 1.1.1, Jan 15, 2009.

.. _here: unbound-1.1.1-py.tar.gz

Compiling

After downloading, you can compile the Unbound library by doing::

text
> tar -xzf unbound-1.1.1-py.tar.gz
> cd unbound-1.1.1
> ./configure --with-pythonmodule
> make

You need GNU make to compile sources.
SWIG and Python devel libraries to compile extension module.

Testing

If the compilation is successful, you can test the extension module by::

text
> cd pythonmod
> make sudo # or "make test" or "make suexec"

This will start unbound server with language dictionary service
(see :ref:Tutorials).
In order to test this service, type::

dig TXT @127.0.0.1 aught.en.dict.cz

Dig should print this message (czech equivalent of aught)::

; <<>> DiG 9.5.0-P2 <<>> TXT @127.0.0.1 aught.en.dict.cz
; (1 server found)
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 30085
;; flags: aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;aught.en.dict.cz. IN TXT

;; ANSWER SECTION:
aught.en.dict.cz. 300 IN TXT "nic"

;; Query time: 11 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Thu Jan 10 16:45:58 2009
;; MSG SIZE rcvd: 52

The pythonmod/examples directory contains simple applications written in
Python.


Pythonmod Doc Usecase (`pythonmod/doc/usecase.rst`)

Use cases (examples)

Dynamic DNS Service discovery (DNS-SD_)

Synchronized with database engine, for example MySQL.

.. _DNS-SD: http://www.dns-sd.org/

Firewall control

Control firewall (e.g. enable incoming SSH connection) with DNS query signed with private key.
So firewall can blocks every service during normal operation.

Scriptable DNS-based blacklist (DNS-BL_)

Scripted in Python with already provided features, takes advantage of DNS reply, because
almost every mail server supports DNS based blacklisting.

.. _DNS-BL: http://www.dnsbl.org

DNS based Wake-On-Lan

Controlled by secured queries secured with private key.

Dynamic translation service

DNS request can be translated to virtually any answer, that's easy to implement in client side
because of many DNS libraries available.

Examples :

  • Dictionary - using IDN for non-ascii strings transfer, dig TXT slovo.en._dict_.nic.cz returns translation of "slovo" to EN.
  • Translation - Extends DNS-SD, for example DNS to Jabber to find out people logged in.
  • Exchange rate calculator - dig TXT 1000.99.czk.eur._rates_.nic.cz returns the given sum (1000.99 CZK) in EURs.

Dynamic ENUM service

Support for redirection, synchronization, etc.


Libunbound Python Doc Index (`libunbound/python/doc/index.rst`)

PyUnbound documentation

This project contains an Unbound wrapper providing the thinnest layer over the library possible.
Everything you can do from the libUnbound C API, you can do from Python, even more.

Contents

.. toctree::
:maxdepth: 2

text
intro.rst
install.rst
examples/index.rst
modules/unbound

Module Documentation

  • Module :mod:unbound

Indices and tables

  • :ref:genindex
  • :ref:search

Libunbound Python Doc Install (`libunbound/python/doc/install.rst`)

Installation

Prerequisites

Python 2.4 or higher, SWIG 1.3 or higher, GNU make

Compiling

After downloading, you can compile the pyUnbound library by doing::

text
> tar -xzf unbound-x.x.x-py.tar.gz
> cd unbound-x.x.x
> ./configure --with-pyunbound
> make

You may want to enable --with-pythonmodule as well if you want to use
python as a module in the resolver.

You need GNU make to compile sources; SWIG and Python devel
libraries to compile extension module.

Testing

If the compilation is successful, you can test the python LDNS extension module
by::

text
> cd contrib/python
> make testenv
> ./dns-lookup.py

You may want to make install in the main directory since make testenv
is for debugging. In contrib/examples you can find simple applications written
in Python using the Unbound extension.


Libunbound Python Doc Intro (`libunbound/python/doc/intro.rst`)

Introduction

Unbound

Unbound_ is an implementation of a DNS resolver, that performs caching and
DNSSEC validation.
Together with unbound, the libunbound library is provided.
This library can be used to convert hostnames to ip addresses, and back, as
well as obtain other information.
Since the resolver allows to specify the class and type of a query (A record,
NS, MX, ...), this library offers powerful resolving tool.
The library also performs public-key validation of results with DNSSEC.

.. _Unbound: http://www.unbound.net/documentation

pyUnbound

The pyUnbound is an extension module for Python which provides an
object-oriented interface to libunbound.
It is the first Python module which offers thread-safe caching resolver.

The interface was designed with the emphasis on the simplicity of use.
There are two main classes :class:unbound.ub_ctx (a validation and resolution
context) and :class:unbound.ub_result which contains the validation and
resolution results.
The objects are thread-safe, and a context can be used in non-threaded as well
as threaded environment.
Resolution can be performed blocking and non-blocking (i.e. asynchronous).
The asynchronous method returns from the call immediately, so that processing
can go on, while the results become available later.

Features

  • Customizable caching validation resolver for synchronous and asynchronous
    lookups
  • Easy to use object interface
  • Easy to integrate extension module
  • Designed for thread environment (i.e. thread-safe)
  • Allows define and customize of local zone and its RR's during the operation
    (i.e. without restart)
  • Includes encoding functions to simplify the results retrieval
  • Internationalized domain name (IDN_) support

.. _IDN: http://en.wikipedia.org/wiki/Internationalized_domain_name

Application area

  • DNS-based applications performing DNS lookups; the caching resolver can
    reduce overhead
  • Applications where the validation of DNS records is required
  • Great solution for customizable and dynamic DNS-based white/blacklists (spam
    rejection, connection rejection, ...) using the dynamic local zone
    manipulation

Pythonmod Doc Examples Example0 (`pythonmod/doc/examples/example0.rst`)

.. _example_handler:

Fundamentals

This basic example shows how to create simple python module which will pass on the requests to the iterator.

How to enable python module

If you look into unbound configuration file, you can find the option module-config which specifies the names and the order of modules to be used.
Example configuration::

text
module-config: "validator python iterator"

As soon as the DNS query arrives, Unbound calls modules starting from leftmost - the validator (it is the first module on the list).
The validator does not know the answer (it can only validate), thus it will pass on the event to the next module.
Next module is python which can

text
a) generate answer *(response)*
	When python module generates the response unbound calls validator. Validator grabs the answer and determines the security flag.

b) pass on the event to the iterator.
	When iterator resolves the query, Unbound informs python module (event :data:`module_event_moddone`). In the end, when the python module is done, validator is called.

Note that the python module is called with :data:module_event_pass event, because new DNS event was already handled by validator.

Another situation occurs when we use the following configuration::

text
module-config: "python validator iterator"

Python module is the first module here, so it's invoked with :data:module_event_new event (new query).

On Python module initialization, module loads script from python-script option::

text
python-script: "/unbound/test/ubmodule.py"

Simple python module step by step

Script file must contain four compulsory functions:

.. function:: init(id, cfg)

Initialize module internals, like database etc.
Called just once on module load.

:param id: module identifier (integer)
:param cfg: :class:config_file configuration structure

::

def init(id, cfg):
log_info("pythonmod: init called, module id is %d port: %d script: %s" % (id, cfg.port, mod_env['script']))
return True

.. function:: init_standard(id, env)

Initialize module internals, like database etc.
Called just once on module load.

Preferred over the init() function above as this function's signature is the
same as the C counterpart and allows for extra functionality during init.
The previously accessible configuration options can now be found in env.cfg.

:param id: module identifier (integer)
:param env: :class:module_env module environment

::

text
def init_standard(id, env):
   log_info("pythonmod: init called, module id is %d port: %d script: %s" % (id, env.cfg.port, mod_env['script']))
   return True

.. function:: deinit(id)

Deinitialize module internals.
Called just once on module unload.

:param id: module identifier (integer)

::

def deinit(id):
log_info("pythonmod: deinit called, module id is %d" % id)
return True

.. function:: inform_super(id, qstate, superqstate, qdata)

Inform super querystate about the results from this subquerystate.
Is called when the querystate is finished.

:param id: module identifier (integer)
:param qstate: :class:module_qstate Query state
:param superqstate: :class:pythonmod_qstate Mesh state
:param qdata: :class:query_info Query data

::

def inform_super(id, qstate, superqstate, qdata):
return True

.. function:: operate(id, event, qstate, qdata)

Perform action on pending query. Accepts a new query, or work on pending query.

You have to set qstate.ext_state on exit.
The state informs unbound about result and controls the following states.

:param id: module identifier (integer)
:param qstate: :class:module_qstate query state structure
:param qdata: :class:query_info per query data, here you can store your own data

::

def operate(id, event, qstate, qdata):
log_info("pythonmod: operate called, id: %d, event:%s" % (id, strmodulevent(event)))
if event == MODULE_EVENT_NEW:
qstate.ext_state[id] = MODULE_WAIT_MODULE
return True

text
if event == MODULE_EVENT_MODDONE:
     qstate.ext_state[id] = MODULE_FINISHED 
     return True

  if event == MODULE_EVENT_PASS:
     qstate.ext_state[id] = MODULE_WAIT_MODULE 
     return True

  log_err("pythonmod: BAD event")
  qstate.ext_state[id] = MODULE_ERROR
  return True

Complete source code

.. literalinclude:: example0-1.py
:language: python

As you can see, the source code is much more flexible in contrast to C modules.
Moreover, compulsory functions called on appropriate module events allows to handle almost
anything from web control to query analysis.


Pythonmod Doc Examples Example1 (`pythonmod/doc/examples/example1.rst`)

.. _log_handler:

Packet logger

This example shows how to log and print details about query and response.
As soon as the iterator has finished (event is
:data:module_event_moddone), qstate.return_msg contains response packet
or None.
This packet will be send to a client that asked for it.

Complete source code

.. literalinclude:: ../../examples/log.py
:language: python

Testing

Run the unbound server:

root@localhost>unbound -dv -c ./test-log.conf

In case you use own configuration file, don't forget to enable python module:
module-config: "validator python iterator" and use valid script path:
python-script: "./examples/log.py".

Example of output::

[1231790168] unbound[7941:0] info: response for [1231790168] unbound[7941:0] info: reply from 192.5.6.31#53 [1231790168] unbound[7941:0] info: query response was ANSWER [1231790168] unbound[7941:0] info: pythonmod: operate called, id: 1, event:module_event_moddone

Query: f.gtld-servers.NET., type: AAAA (28), class: IN (1)

Return reply :: flags: 8080, QDcount: 1, Security:0, TTL=86400
qinfo :: qname: ['f', 'gtld-servers', 'NET', ''] f.gtld-servers.NET., qtype: AAAA, qclass: IN
Reply:
0 : ['gtld-servers', 'NET', ''] gtld-servers.NET. flags: 0000 type: SOA (6) class: IN (1)
0 : TTL= 86400
0x00 | 00 3A 02 41 32 05 4E 53 54 4C 44 03 43 4F 4D 00 05 | . : . A 2 . N S T L D . C O M . .
0x10 | 05 6E 73 74 6C 64 0C 76 65 72 69 73 69 67 6E 2D 67 | . n s t l d . v e r i s i g n - g
0x20 | 67 72 73 03 43 4F 4D 00 77 74 2D 64 00 00 0E 10 00 | g r s . C O M . w t - d . . . . .
0x30 | 00 00 03 84 00 12 75 00 00 01 51 80 | . . . . . . u . . . Q .


Pythonmod Doc Examples Example2 (`pythonmod/doc/examples/example2.rst`)

Response generation

This example shows how to handle queries and generate response packet.

.. note::
If the python module is the first module and validator module is enabled
(module-config: "python validator iterator"), a return_msg security flag
has to be set at least to 2. Leaving security flag untouched causes that the
response will be refused by unbound worker as unbound will consider it as
non-valid response.

Complete source code

.. literalinclude:: ../../examples/resgen.py
:language: python

Testing

Run the unbound server:

root@localhost>unbound -dv -c ./test-resgen.conf

Query for a A record ending with .localdomain

dig A test.xxx.localdomain @127.0.0.1

Dig produces the following output::

text
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 48426
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;test.xxx.localdomain.      IN  A

;; ANSWER SECTION:
test.xxx.localdomain.   10  IN  A   127.0.0.1

;; Query time: 2 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon Jan 01 12:46:02 2009
;; MSG SIZE  rcvd: 54

As we handle (override) in the python module only queries ending with
localdomain., unbound can still resolve host names.


Pythonmod Doc Examples Example3 (`pythonmod/doc/examples/example3.rst`)

Response modification

This example shows how to modify the response produced by the iterator module.

As soon as the iterator module returns the response, we :

  1. invalidate the data in cache
  2. modify the response TTL
  3. rewrite the data in cache
  4. return modified packet

Note that the steps 1 and 3 are necessary only in case, the python module is the first module in the processing chain.
In other cases, the validator module guarantees updating data which are produced by iterator module.

Complete source code

.. literalinclude:: ../../examples/resmod.py
:language: python

Testing

Run Unbound server:

root@localhost>unbound -dv -c ./test-resmod.conf

Issue a query for name ending with "nic.cz."

>>>dig A @127.0.0.1 www.nic.cz

::

text
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 48831
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 3, ADDITIONAL: 5

;; QUESTION SECTION:
;www.nic.cz.			IN	A

;; ANSWER SECTION:
www.nic.cz.		10	IN	A	217.31.205.50

;; AUTHORITY SECTION:
nic.cz.			10	IN	NS	e.ns.nic.cz.
nic.cz.			10	IN	NS	a.ns.nic.cz.
nic.cz.			10	IN	NS	c.ns.nic.cz.

;; ADDITIONAL SECTION:
a.ns.nic.cz.		10	IN	A	217.31.205.180
a.ns.nic.cz.		10	IN	AAAA	2001:1488:dada:176::180
c.ns.nic.cz.		10	IN	A	195.66.241.202
c.ns.nic.cz.		10	IN	AAAA	2a01:40:1000::2
e.ns.nic.cz.		10	IN	A	194.146.105.38

;; Query time: 166 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon Jan 02 13:39:43 2009
;; MSG SIZE  rcvd: 199

As you can see, TTL of all the records is set to 10.


Pythonmod Doc Examples Example4 (`pythonmod/doc/examples/example4.rst`)

DNS-based language dictionary

This example shows how to create a simple language dictionary based on DNS
service within 15 minutes. The translation will be performed using TXT resource
records.

Key parts

Initialization

text
On **init()** module loads dictionary from a text file containing records in
``word [tab] translation`` format.

::

   def init(id, cfg):
      log_info("pythonmod: dict init")
      f = open("examples/dict_data.txt", "r")
      ...

The suitable file can be found at http://slovnik.zcu.cz

DNS query and word lookup

Let's define the following format od DNS queries:
word1[.]word2[.] ... wordN[.]{en,cs}[._dict_.cz.].
Word lookup is done by simple dict lookup from broken DNS request.
Query name is divided into a list of labels. This list is accessible as
qname_list attribute.

::

aword = ' '.join(qstate.qinfo.qname_list[0:-4]) #skip last four labels
adict = qstate.qinfo.qname_list[-4] #get 4th label from the end

words = [] #list of words
if (adict == "en") and (aword in en_dict):
words = en_dict[aword]

if (adict == "cs") and (aword in cz_dict):
words = cz_dict[aword] # CS -> EN

In the first step, we get a string in the form:
word1[space]word2[space]...word[space].
In the second assignment, fourth label from the end is obtained. This label
should contains "cs" or "en". This label determines the direction of
translation.

Forming of a DNS reply

text
DNS reply is formed only on valid match and added as TXT answer.

::

    msg = DNSMessage(qstate.qinfo.qname_str, RR_TYPE_TXT, RR_CLASS_IN, PKT_AA)

    for w in words:
        msg.answer.append("%s 300 IN TXT \"%s\"" % (qstate.qinfo.qname_str, w.replace("\"", "\\\"")))

    if not msg.set_return_msg(qstate):
        qstate.ext_state[id] = MODULE_ERROR 
        return True

    qstate.return_rcode = RCODE_NOERROR
    qstate.ext_state[id] = MODULE_FINISHED 
    return True

In the first step, a :class:`DNSMessage` instance is created for a given query
*(type TXT)*.
The fourth argument specifies the flags *(authoritative answer)*.
In the second step, we append TXT records containing the translation *(on the
right side of RR)*.
Then, the response is finished and ``qstate.return_msg`` contains new response.
If no error, the module sets :attr:`module_qstate.return_rcode` and
:attr:`module_qstate.ext_state`.

**Steps:**

1. create :class:`DNSMessage` instance
2. append TXT records containing the translation
3. set response to ``qstate.return_msg``

Testing
-------

Run the Unbound server:

``root@localhost>unbound -dv -c ./test-dict.conf``

In case you use own configuration file, don't forget to enable Python module::

    module-config: "validator python iterator"

and use valid script path::

    python-script: "./examples/dict.py"

The translation from english word *"a bar fly"* to Czech can be done by doing:

``>>>dig TXT @127.0.0.1 a.bar.fly.en._dict_.cz``

::

    ; (1 server found)
    ;; global options:  printcmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 48691
    ;; flags: aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

    ;; QUESTION SECTION:
    ;a.bar.fly.en._dict_.cz.    IN  TXT

    ;; ANSWER SECTION:
    a.bar.fly.en._dict_.cz. 300 IN  TXT "barov\253 povale\232"

    ;; Query time: 5 msec
    ;; SERVER: 127.0.0.1#53(127.0.0.1)
    ;; WHEN: Mon Jan 01 17:44:18 2009
    ;; MSG SIZE  rcvd: 67

``>>>dig TXT @127.0.0.1 nic.cs._dict_.cz``

::
	
    ; <<>> DiG 9.5.0-P2 <<>> TXT @127.0.0.1 nic.cs._dict_.cz
    ; (1 server found)
    ;; global options:  printcmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 58710
    ;; flags: aa rd ra; QUERY: 1, ANSWER: 6, AUTHORITY: 0, ADDITIONAL: 0

    ;; QUESTION SECTION:
    ;nic.cs._dict_.cz.      IN  TXT

    ;; ANSWER SECTION:
    nic.cs._dict_.cz.   300 IN  TXT "aught"
    nic.cs._dict_.cz.   300 IN  TXT "naught"
    nic.cs._dict_.cz.   300 IN  TXT "nihil"
    nic.cs._dict_.cz.   300 IN  TXT "nix"
    nic.cs._dict_.cz.   300 IN  TXT "nothing"
    nic.cs._dict_.cz.   300 IN  TXT "zilch"

    ;; Query time: 0 msec
    ;; SERVER: 127.0.0.1#53(127.0.0.1)
    ;; WHEN: Mon Jan 01 17:45:39 2009
    ;; MSG SIZE  rcvd: 143

    Proof that the unbound still works as resolver.

``>>>dig A @127.0.0.1 www.nic.cz``

::

    ; (1 server found)
    ;; global options:  printcmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19996
    ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 3, ADDITIONAL: 5

    ;; QUESTION SECTION:
    ;www.nic.cz.            IN  A

    ;; ANSWER SECTION:
    www.nic.cz.     1662    IN  A   217.31.205.50

    ;; AUTHORITY SECTION:
    ...

Complete source code
--------------------

.. literalinclude:: ../../examples/dict.py
   :language: python

---

### Pythonmod Doc Examples Example5 (`pythonmod/doc/examples/example5.rst`)

EDNS options
============

This example shows how to interact with EDNS options.

When querying unbound with the EDNS option ``65001`` and data ``0xc001`` we
expect an answer with the same EDNS option code and data ``0xdeadbeef``.


Key parts
~~~~~~~~~

This example relies on the following functionalities:


Registering EDNS options
------------------------

By registering EDNS options we can tune unbound's behavior when encountering a
query with a known EDNS option. The two available options are:

- ``bypass_cache_stage``: If set to ``True`` unbound will not try to answer
  from cache. Instead execution is passed to the modules
- ``no_aggregation``: If set to ``True`` unbound will consider this query
  unique and will not aggregate it with similar queries

Both values default to ``False``.

.. code-block:: python

    if not register_edns_option(env, 65001, bypass_cache_stage=True,
                                no_aggregation=True):
        log_info("python: Could not register EDNS option {}".format(65001))


EDNS option lists
-----------------

EDNS option lists can be found in the :class:`module_qstate` class. There are
four available lists in total:

- :class:`module_qstate.edns_opts_front_in`: options that came from the client
  side. **Should not** be changed
- :class:`module_qstate.edns_opts_back_out`: options that will be sent to the
  server side. Can be populated by edns literate modules
- :class:`module_qstate.edns_opts_back_in`: options that came from the server
  side. **Should not** be changed
- :class:`module_qstate.edns_opts_front_out`: options that will be sent to the
  client side. Can be populated by edns literate modules

Each list element has the following members:

- ``code``: the EDNS option code;
- ``data``: the EDNS option data.


Reading an EDNS option list
...........................

The lists' contents can be accessed in python by their ``_iter`` counterpart as
an iterator:

.. code-block:: python

    if not edns_opt_list_is_empty(qstate.edns_opts_front_in):
        for o in qstate.edns_opts_front_in_iter:
            log_info("python:    Code: {}, Data: '{}'".format(o.code,
                            "".join('{:02x}'.format(x) for x in o.data)))


Writing to an EDNS option list
..............................

By appending to an EDNS option list we can add new EDNS options. The new
element is going to be allocated in :class:`module_qstate.region`. The data
**must** be represented with a python ``bytearray``:

.. code-block:: python

    b = bytearray.fromhex("deadbeef")
    if not edns_opt_list_append(qstate.edns_opts_front_out,
                           o.code, b, qstate.region):
        log_info("python: Could not append EDNS option {}".format(o.code))

We can also remove an EDNS option code from an EDNS option list.

.. code-block:: python

    if not edns_opt_list_remove(edns_opt_list, code):
        log_info("python: Option code {} was not found in the "
                 "list.".format(code))

.. note:: All occurrences of the EDNS option code will be removed from the list:


Controlling other modules' cache behavior
-----------------------------------------

During the modules' operation, some modules may interact with the cache
(e.g., iterator). This behavior can be controlled by using the following
:class:`module_qstate` flags:

- :class:`module_qstate.no_cache_lookup`: Modules *operating after* this module
  will not lookup the cache for an answer
- :class:`module_qstate.no_cache_store`: Modules *operating after* this module
  will not store the response in the cache

Both values default to ``0``.

.. code-block:: python

    def operate(id, event, qstate, qdata):
        if (event == MODULE_EVENT_NEW) or (event == MODULE_EVENT_PASS):
            # Detect if edns option code 56001 is present from the client side. If
            # so turn on the flags for cache management.
            if not edns_opt_list_is_empty(qstate.edns_opts_front_in):
                log_info("python: searching for edns option code 65001 during NEW "
                        "or PASS event ")
                for o in qstate.edns_opts_front_in_iter:
                    if o.code == 65001:
                        log_info("python: found edns option code 65001")
                        # Instruct other modules to not lookup for an
                        # answer in the cache.
                        qstate.no_cache_lookup = 1
                        log_info("python: enabled no_cache_lookup")

                        # Instruct other modules to not store the answer in
                        # the cache.
                        qstate.no_cache_store = 1
                        log_info("python: enabled no_cache_store")


Testing
~~~~~~~

Run the Unbound server: ::

    root@localhost$ unbound -dv -c ./test-edns.conf

In case you use your own configuration file, don't forget to enable the Python
module::

    module-config: "validator python iterator"

and use a valid script path::

    python-script: "./examples/edns.py"

Querying with EDNS option ``65001:0xc001``:

::

    root@localhost$ dig @localhost nlnetlabs.nl +ednsopt=65001:c001

    ; <<>> DiG 9.10.3-P4-Ubuntu <<>> @localhost nlnetlabs.nl +ednsopt=65001:c001
    ; (1 server found)
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33450
    ;; flags: qr rd ra ad; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 3

    ;; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 4096
    ; OPT=65001: de ad be ef ("....")
    ;; QUESTION SECTION:
    ;nlnetlabs.nl.                  IN      A

    ;; ANSWER SECTION:
    nlnetlabs.nl.           10200   IN      A       185.49.140.10

    ;; AUTHORITY SECTION:
    nlnetlabs.nl.           10200   IN      NS      anyns.pch.net.
    nlnetlabs.nl.           10200   IN      NS      ns.nlnetlabs.nl.
    nlnetlabs.nl.           10200   IN      NS      ns-ext1.sidn.nl.
    nlnetlabs.nl.           10200   IN      NS      sec2.authdns.ripe.net.

    ;; ADDITIONAL SECTION:
    ns.nlnetlabs.nl.        10200   IN      AAAA    2a04:b900::8:0:0:60
    ns.nlnetlabs.nl.        10200   IN      A       185.49.140.60

    ;; Query time: 10 msec
    ;; SERVER: 127.0.0.1#53(127.0.0.1)
    ;; WHEN: Mon Dec 05 14:50:56 CET 2016
    ;; MSG SIZE  rcvd: 212


Complete source code
~~~~~~~~~~~~~~~~~~~~

.. literalinclude:: ../../examples/edns.py
    :language: python

---

### Pythonmod Doc Examples Example6 (`pythonmod/doc/examples/example6.rst`)

Inplace callbacks
=================

This example shows how to register and use inplace callback functions. These
functions are going to be called just before unbound replies back to a client.
They can perform certain actions without interrupting unbound's execution flow
(e.g. add/remove EDNS options, manipulate the reply).

Two different scenarios will be shown:

- If answering from cache and the client used EDNS option code ``65002`` we
  will answer with the same code but with data ``0xdeadbeef``;
- When answering with a SERVFAIL we also add an empty EDNS option code
  ``65003``.


Key parts
~~~~~~~~~

This example relies on the following functionalities:


Registering inplace callback functions
--------------------------------------

There are seven types of inplace callback functions:

- `inplace callback reply functions`_
- `inplace callback reply_cache functions`_
- `inplace callback reply_local functions`_
- `inplace callback reply_servfail functions`_
- `inplace callback query functions`_
- `inplace callback query_response functions`_
- `inplace callback edns_back_parsed functions`_


Inplace callback reply functions
................................

Called when answering with a *resolved* query.

The callback function's prototype is the following:

.. code-block:: python

    def inplace_reply_callback(qinfo, qstate, rep, rcode, edns, opt_list_out,
                               region, **kwargs):
        """
        Function that will be registered as an inplace callback function.
        It will be called when answering with a resolved query.

        :param qinfo: query_info struct;
        :param qstate: module qstate. It contains the available opt_lists; It
                       SHOULD NOT be altered;
        :param rep: reply_info struct;
        :param rcode: return code for the query;
        :param edns: edns_data to be sent to the client side. It SHOULD NOT be
                     altered;
        :param opt_list_out: the list with the EDNS options that will be sent as a
                             reply. It can be populated with EDNS options;
        :param region: region to allocate temporary data. Needs to be used when we
                       want to append a new option to opt_list_out.
        :param **kwargs: Dictionary that may contain parameters added in a future
                         release. Current parameters:
            ``repinfo``: Reply information for a communication point (comm_reply).

        :return: True on success, False on failure. Failure terminates any further
                 callback processing. If this module is ephemeral it is advised
                 to clean up and return success instead.

        """

.. note:: The function's name is irrelevant.

We can register such function as:

.. code-block:: python

    if not register_inplace_cb_reply(inplace_reply_callback, env, id):
        log_info("python: Could not register inplace callback function.")


Inplace callback reply_cache functions
......................................

Called when answering *from cache*.

The callback function's prototype is the following:

.. code-block:: python

    def inplace_cache_callback(qinfo, qstate, rep, rcode, edns, opt_list_out,
                               region, **kwargs):
        """
        Function that will be registered as an inplace callback function.
        It will be called when answering from the cache.

        :param qinfo: query_info struct;
        :param qstate: module qstate. None;
        :param rep: reply_info struct;
        :param rcode: return code for the query;
        :param edns: edns_data sent from the client side. The list with the EDNS
                     options is accessible through edns.opt_list. It SHOULD NOT be
                     altered;
        :param opt_list_out: the list with the EDNS options that will be sent as a
                             reply. It can be populated with EDNS options;
        :param region: region to allocate temporary data. Needs to be used when we
                       want to append a new option to opt_list_out.
        :param **kwargs: Dictionary that may contain parameters added in a future
                         release. Current parameters:
            ``repinfo``: Reply information for a communication point (comm_reply).

        :return: True on success, False on failure. Failure terminates any further
                 callback processing. If this module is ephemeral it is advised
                 to clean up and return success instead.

        For demonstration purposes we want to see if EDNS option 65002 is present
        and reply with a new value.

        """

.. note:: The function's name is irrelevant.

We can register such function as:

.. code-block:: python

    if not register_inplace_cb_reply_cache(inplace_cache_callback, env, id):
        log_info("python: Could not register inplace callback function.")


Inplace callback reply_local functions
......................................

Called when answering with *local data* or a *Chaos(CH) reply*.

The callback function's prototype is the following:

.. code-block:: python

    def inplace_local_callback(qinfo, qstate, rep, rcode, edns, opt_list_out,
                               region, **kwargs):
        """
        Function that will be registered as an inplace callback function.
        It will be called when answering from local data.

        :param qinfo: query_info struct;
        :param qstate: module qstate. None;
        :param rep: reply_info struct;
        :param rcode: return code for the query;
        :param edns: edns_data sent from the client side. The list with the
                     EDNS options is accessible through edns.opt_list. It
                     SHOULD NOT be altered;
        :param opt_list_out: the list with the EDNS options that will be sent as a
                             reply. It can be populated with EDNS options;
        :param region: region to allocate temporary data. Needs to be used when we
                       want to append a new option to opt_list_out.
        :param **kwargs: Dictionary that may contain parameters added in a future
                         release. Current parameters:
            ``repinfo``: Reply information for a communication point (comm_reply).

        :return: True on success, False on failure. Failure terminates any further
                 callback processing. If this module is ephemeral it is advised
                 to clean up and return success instead.

        """

.. note:: The function's name is irrelevant.

We can register such function as:

.. code-block:: python

    if not register_inplace_cb_reply_local(inplace_local_callback, env, id):
        log_info("python: Could not register inplace callback function.")


Inplace callback reply_servfail functions
.........................................

Called when answering with *SERVFAIL*.

The callback function's prototype is the following:

.. code-block:: python

    def inplace_servfail_callback(qinfo, qstate, rep, rcode, edns, opt_list_out,
                                  region, **kwargs):
        """
        Function that will be registered as an inplace callback function.
        It will be called when answering with SERVFAIL.

        :param qinfo: query_info struct;
        :param qstate: module qstate. If not None the relevant opt_lists are
                       available here;
        :param rep: reply_info struct. None;
        :param rcode: return code for the query. LDNS_RCODE_SERVFAIL;
        :param edns: edns_data to be sent to the client side. If qstate is None
                     edns.opt_list contains the EDNS options sent from the client
                     side. It SHOULD NOT be altered;
        :param opt_list_out: the list with the EDNS options that will be sent as a
                             reply. It can be populated with EDNS options;
        :param region: region to allocate temporary data. Needs to be used when we
                       want to append a new option to opt_list_out.
        :param **kwargs: Dictionary that may contain parameters added in a future
                         release. Current parameters:
            ``repinfo``: Reply information for a communication point (comm_reply).

        :return: True on success, False on failure. Failure terminates any further
                 callback processing. If this module is ephemeral it is advised
                 to clean up and return success instead.

        For demonstration purposes we want to reply with an empty EDNS code '65003'
        and log the IP address(es) of the client(s).

        """

.. note:: The function's name is irrelevant.

We can register such function as:

.. code-block:: python

    if not register_inplace_cb_reply_servfail(inplace_servfail_callback, env, id):
        log_info("python: Could not register inplace callback function.")


Inplace callback query functions
................................

Called before sending a query to a backend server.

The callback function's prototype is the following:

.. code-block:: python

    def inplace_query_callback(qinfo, flags, qstate, addr, zone, region, **kwargs):
        """
        Function that will be registered as an inplace callback function.
        It will be called before sending a query to a backend server.

        :param qinfo: query_info struct;
        :param flags: flags of the query;
        :param qstate: module qstate. opt_lists are available here;
        :param addr: struct sockaddr_storage. Address of the backend server;
        :param zone: zone name in binary;
        :param region: region to allocate temporary data. Needs to be used when we
                       want to append a new option to opt_lists.
        :param **kwargs: Dictionary that may contain parameters added in a future
                         release.

        :return: True on success, False on failure. Failure terminates any further
                 callback processing. If this module is ephemeral it is advised
                 to clean up and return success instead.
        """

.. note:: The function's name is irrelevant.

We can register such function as:

.. code-block:: python

    if not register_inplace_cb_query(inplace_query_callback, env, id):
        log_info("python: Could not register inplace callback function.")


Inplace callback query_response functions
.........................................

Called after receiving a reply from a backend server.

The callback function's prototype is the following:

.. code-block:: python

    def inplace_query_response_callback(qstate, response, **kwargs):
        """
        Function that will be registered as an inplace callback function.
        It will be called after receiving a reply from a backend server.

        :param qstate: module qstate. opt_lists are available here;
        :param response: struct dns_msg. The reply received from the backend server;
        :param **kwargs: Dictionary that may contain parameters added in a future
                         release.

        :return: True on success, False on failure. Failure terminates any further
                 callback processing. If this module is ephemeral it is advised
                 to clean up and return success instead.
        """

.. note:: The function's name is irrelevant.

We can register such function as:

.. code-block:: python

    if not register_inplace_cb_query_response(inplace_query_response_callback, env, id):
        log_info("python: Could not register inplace callback function.")


Inplace callback edns_back_parsed functions
...........................................

Called after EDNS is parsed on a reply from a backend server.

The callback function's prototype is the following:

.. code-block:: python

    def inplace_edns_back_parsed_call(qstate, **kwargs):
        """
        Function that will be registered as an inplace callback function.
        It will be called after EDNS is parsed on a reply from a backend server.

        :param qstate: module qstate. opt_lists are available here;
        :param **kwargs: Dictionary that may contain parameters added in a future
                         release.

        :return: True on success, False on failure. Failure terminates any further
                 callback processing. If this module is ephemeral it is advised
                 to clean up and return success instead.
        """

.. note:: The function's name is irrelevant.

We can register such function as:

.. code-block:: python

    if not register_inplace_cb_edns_back_parsed_call(inplace_edns_back_parsed_call, env, id):
        log_info("python: Could not register inplace callback function.")


Testing
~~~~~~~

Run the Unbound server: ::

    root@localhost$ unbound -dv -c ./test-inplace_callbacks.conf

In case you use your own configuration file, don't forget to enable the Python
module::

    module-config: "validator python iterator"

and use a valid script path ::

    python-script: "./examples/inplace_callbacks.py"

On the first query for the nlnetlabs.nl A record we get no EDNS option back:

::

    root@localhost$ dig @localhost nlnetlabs.nl +ednsopt=65002

    ; <<>> DiG 9.10.3-P4-Ubuntu <<>> @localhost nlnetlabs.nl +ednsopt=65002
    ; (1 server found)
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 48057
    ;; flags: qr rd ra ad; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 3

    ;; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 4096
    ;; QUESTION SECTION:
    ;nlnetlabs.nl.                  IN      A

    ;; ANSWER SECTION:
    nlnetlabs.nl.           10200   IN      A       185.49.140.10

    ;; AUTHORITY SECTION:
    nlnetlabs.nl.           10200   IN      NS      ns.nlnetlabs.nl.
    nlnetlabs.nl.           10200   IN      NS      sec2.authdns.ripe.net.
    nlnetlabs.nl.           10200   IN      NS      anyns.pch.net.
    nlnetlabs.nl.           10200   IN      NS      ns-ext1.sidn.nl.

    ;; ADDITIONAL SECTION:
    ns.nlnetlabs.nl.        10200   IN      A       185.49.140.60
    ns.nlnetlabs.nl.        10200   IN      AAAA    2a04:b900::8:0:0:60

    ;; Query time: 813 msec
    ;; SERVER: 127.0.0.1#53(127.0.0.1)
    ;; WHEN: Mon Dec 05 16:15:32 CET 2016
    ;; MSG SIZE  rcvd: 204

When we issue the same query again we get a cached response and the expected
``65002: 0xdeadbeef`` EDNS option:

::

    root@localhost$ dig @localhost nlnetlabs.nl +ednsopt=65002

    ; <<>> DiG 9.10.3-P4-Ubuntu <<>> @localhost nlnetlabs.nl +ednsopt=65002
    ; (1 server found)
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26489
    ;; flags: qr rd ra ad; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 3

    ;; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 4096
    ; OPT=65002: de ad be ef ("....")
    ;; QUESTION SECTION:
    ;nlnetlabs.nl.                  IN      A

    ;; ANSWER SECTION:
    nlnetlabs.nl.           10197   IN      A       185.49.140.10

    ;; AUTHORITY SECTION:
    nlnetlabs.nl.           10197   IN      NS      ns.nlnetlabs.nl.
    nlnetlabs.nl.           10197   IN      NS      sec2.authdns.ripe.net.
    nlnetlabs.nl.           10197   IN      NS      anyns.pch.net.
    nlnetlabs.nl.           10197   IN      NS      ns-ext1.sidn.nl.

    ;; ADDITIONAL SECTION:
    ns.nlnetlabs.nl.        10197   IN      AAAA    2a04:b900::8:0:0:60
    ns.nlnetlabs.nl.        10197   IN      A       185.49.140.60

    ;; Query time: 0 msec
    ;; SERVER: 127.0.0.1#53(127.0.0.1)
    ;; WHEN: Mon Dec 05 16:50:04 CET 2016
    ;; MSG SIZE  rcvd: 212

By issuing a query for a bogus domain unbound replies with SERVFAIL and an
empty EDNS option code ``65003``. *For this example to work unbound needs to be
validating*:

::

    root@localhost$ dig @localhost bogus.nlnetlabs.nl txt

    ; <<>> DiG 9.10.3-P4-Ubuntu <<>> @localhost bogus.nlnetlabs.nl txt
    ; (1 server found)
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 19865
    ;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

    ;; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 4096
    ; OPT=65003
    ;; QUESTION SECTION:
    ;bogus.nlnetlabs.nl.            IN      TXT

    ;; Query time: 11 msec
    ;; SERVER: 127.0.0.1#53(127.0.0.1)
    ;; WHEN: Mon Dec 05 17:06:01 CET 2016
    ;; MSG SIZE  rcvd: 51


Complete source code
~~~~~~~~~~~~~~~~~~~~
.. literalinclude:: ../../examples/inplace_callbacks.py
    :language: python

---

### Pythonmod Doc Examples Index (`pythonmod/doc/examples/index.rst`)

.. _Tutorials:

Examples
========

Here you can find several tutorials which clarify the usage and capabilities of
the Unbound scriptable interface. 

Tutorials
---------

.. toctree::
    :maxdepth: 2
    :glob:

    example*

---

### Pythonmod Doc Modules Config (`pythonmod/doc/modules/config.rst`)

Configuration interface
=======================

Currently passed to Python module in init(module_id, cfg).

config_file
--------------------

.. class:: config_file

   This class provides these data attributes:

   .. attribute:: verbosity
   
      Verbosity level as specified in the config file.

   .. attribute:: stat_interval
   
      Statistics interval (in seconds).
   
   .. attribute:: stat_cumulative
   
      If false, statistics values are reset after printing them.
   
   .. attribute:: stat_extended
   
      If true, the statistics are kept in greater detail.

   .. attribute:: num_threads
   
      Number of threads to create.

   .. attribute:: port
   
      Port on which queries are answered.

   .. attribute:: do_ip4
   
      Do ip4 query support.

   .. attribute:: do_ip6
   
      Do ip6 query support.

   .. attribute:: do_udp
   
      Do udp query support.
   
   .. attribute:: do_tcp
   
      Do tcp query support.

   .. attribute:: outgoing_num_ports
   
      Outgoing port range number of ports (per thread).

   .. attribute:: outgoing_num_tcp
   
      Number of outgoing tcp buffers per (per thread).

   .. attribute:: incoming_num_tcp
   
      Number of incoming tcp buffers per (per thread).

   .. attribute:: outgoing_avail_ports
   
      Allowed udp port numbers, array with 0 if not allowed.

   .. attribute:: msg_buffer_size
   
      Number of bytes buffer size for DNS messages.

   .. attribute:: msg_cache_size
   
      Size of the message cache.
   
   .. attribute:: msg_cache_slabs
   
      Slabs in the message cache.
   
   .. attribute:: num_queries_per_thread
   
      Number of queries every thread can service.
   
   .. attribute:: jostle_time
   
      Number of msec to wait before items can be jostled out.
   
   .. attribute:: rrset_cache_size
   
      Size of the rrset cache.
   
   .. attribute:: rrset_cache_slabs
   
      Slabs in the rrset cache.
   
   .. attribute:: host_ttl
   
      Host cache ttl in seconds.

   .. attribute:: lame_ttl
   
      Host is lame for a zone ttl, in seconds.

   .. attribute:: infra_cache_slabs
   
      Number of slabs in the infra host cache.
   
   .. attribute:: infra_cache_numhosts
   
      Max number of hosts in the infra cache.
   
   .. attribute:: infra_cache_lame_size
   
      Max size of lame zones per host in the infra cache.

   .. attribute:: target_fetch_policy
   
      The target fetch policy for the iterator.

   .. attribute:: if_automatic
   
      Automatic interface for incoming messages. Uses ipv6 remapping,
      and recvmsg/sendmsg ancillary data to detect interfaces, boolean.
   
   .. attribute:: num_ifs
   
      Number of interfaces to open. If 0 default all interfaces.
   
   .. attribute:: ifs
   
      List of interface description strings (IP addresses).

   .. attribute:: num_out_ifs
   
      Number of outgoing interfaces to open. 
      If 0 default all interfaces.

   .. attribute:: out_ifs
   
      List of outgoing interface description strings (IP addresses).
      
   .. attribute:: root_hints
   
      The root hints.
   
   .. attribute:: stubs
   
      The stub definitions, linked list.
   
   .. attribute:: forwards
   
      The forward zone definitions, linked list.
   
   .. attribute:: donotqueryaddrs
   
      List of donotquery addresses, linked list.
   
   .. attribute:: acls
   
      List of access control entries, linked list.
   
   .. attribute:: donotquery_localhost
   
      Use default localhost donotqueryaddr entries.

   .. attribute:: harden_short_bufsize
   
      Harden against very small edns buffer sizes.
   
   .. attribute:: harden_large_queries
   
      Harden against very large query sizes.
   
   .. attribute:: harden_glue
   
      Harden against spoofed glue (out of zone data).
   
   .. attribute:: harden_unverified_glue

      Harden against unverified glue.

   .. attribute:: harden_dnssec_stripped
   
      Harden against receiving no DNSSEC data for trust anchor.
   
   .. attribute:: harden_referral_path
   
      Harden the referral path, query for NS,A,AAAA and validate.
   
   .. attribute:: use_caps_bits_for_id
   
      Use 0x20 bits in query as random ID bits.
   
   .. attribute:: private_address
   
      Strip away these private addrs from answers, no DNS Rebinding.
   
   .. attribute:: private_domain
   
      Allow domain (and subdomains) to use private address space.
   
   .. attribute:: unwanted_threshold
   
      What threshold for unwanted action.

   .. attribute:: chrootdir
   
      Chrootdir, if not "" or chroot will be done.
   
   .. attribute:: username
   
      Username to change to, if not "".
   
   .. attribute:: directory
   
      Working directory.
   
   .. attribute:: logfile
   
      Filename to log to.
   
   .. attribute:: pidfile
   
      Pidfile to write pid to.

   .. attribute:: use_syslog
   
      Should log messages be sent to syslogd.

   .. attribute:: hide_identity
   
      Do not report identity (id.server, hostname.bind).
   
   .. attribute:: hide_version
   
      Do not report version (version.server, version.bind).
   
   .. attribute:: identity
   
      Identity, hostname is returned if "".
   
   .. attribute:: version
   
      Version, package version returned if "".

   .. attribute:: module_conf
   
      The module configuration string.
   
   .. attribute:: trust_anchor_file_list
   
      Files with trusted DS and DNSKEYs in zonefile format, list.
   
   .. attribute:: trust_anchor_list
   
      List of trustanchor keys, linked list.
   
   .. attribute:: trusted_keys_file_list
   
      Files with trusted DNSKEYs in named.conf format, list.
   
   .. attribute:: max_ttl
   
      The number of seconds maximal TTL used for RRsets and messages.
   
   .. attribute:: val_date_override
   
      If not 0, this value is the validation date for RRSIGs.
   
   .. attribute:: bogus_ttl 
   
      This value sets the number of seconds before revalidating bogus.
   
   .. attribute:: val_clean_additional
   
      Should validator clean additional section for secure msgs.
   
   .. attribute:: val_permissive_mode
   
      Should validator allow bogus messages to go through.
   
   .. attribute:: val_nsec3_key_iterations
   
      Nsec3 maximum iterations per key size, string.
   
   .. attribute:: key_cache_size
   
      Size of the key cache.
   
   .. attribute:: key_cache_slabs
   
      Slabs in the key cache.
   
   .. attribute:: neg_cache_size
   
      Size of the neg cache.

   
   .. attribute:: local_zones
   
      Local zones config.
   
   .. attribute:: local_zones_nodefault
   
      Local zones nodefault list.
   
   .. attribute:: local_data
   
      Local data RRs configured.

   .. attribute:: remote_control_enable
   
      Remote control section. enable toggle.
   
   .. attribute:: control_ifs
   
      The interfaces the remote control should listen on.
   
   .. attribute:: control_port
   
      Port number for the control port.
   
   .. attribute:: server_key_file
   
      Private key file for server.
   
   .. attribute:: server_cert_file
   
      Certificate file for server.
   
   .. attribute:: control_key_file
   
      Private key file for unbound-control.
   
   .. attribute:: control_cert_file
   
      Certificate file for unbound-control.

   .. attribute:: do_daemonize
   
      Daemonize, i.e. fork into the background.

   .. attribute:: python_script
   
      Linked list of Python script files.
      Deprecated; `mod_env['script']` should be used instead.

---

### Pythonmod Doc Modules Env (`pythonmod/doc/modules/env.rst`)

Global environment
==================

Global variables
----------------

.. envvar:: mod_env

   Module environment, it is the 'data' pointer for module-specific data
   in :class:`pythonmod_env`.
   It is initialized as a dictionary with the 'script' key pointing to the
   module's python script.
   It can be further populated during runtime for module-specific data.


Predefined constants
-----------------------

Module extended state

.. data:: module_state_initial

Initial state - new DNS query.

.. data:: module_wait_reply

Waiting for reply to outgoing network query.

.. data:: module_wait_module

Module is waiting for another module.

.. data:: module_wait_subquery

Module is waiting for sub-query.

.. data:: module_error

Module could not finish the query.

.. data:: module_finished

Module is finished with query.

Module event

text
.. data:: module_event_new

   New DNS query.
   
.. data:: module_event_pass

   Query passed by other module.
   
.. data:: module_event_reply

   Reply inbound from server.
   
.. data:: module_event_noreply

   No reply, timeout or other error.
   
.. data:: module_event_capsfail

   Reply is there, but capitalisation check failed.
   
.. data:: module_event_moddone

   Next module is done, and its reply is awaiting you.
   
.. data:: module_event_error

   Error occurred.

Security status

.. data:: sec_status_unchecked

Means that object has yet to be validated.

.. data:: sec_status_bogus

Means that the object (RRset or message) failed to validate
(according to local policy), but should have validated.

.. data:: sec_status_indeterminate

Means that the object is insecure, but not
authoritatively so. Generally this means that the RRset is not
below a configured trust anchor.

.. data:: sec_status_insecure

Means that the object is authoritatively known to be
insecure. Generally this means that this RRset is below a trust
anchor, but also below a verified, insecure delegation.

.. data:: sec_status_secure

Means that the object (RRset or message) validated according to local policy.

Resource records (RR sets)

text
The different RR classes.

   .. data:: RR_CLASS_IN
   
      Internet.
      
   .. data:: RR_CLASS_CH
   
      Chaos.
      
   .. data:: RR_CLASS_HS
   
      Hesiod (Dyer 87)
      
   .. data:: RR_CLASS_NONE
   
      None class, dynamic update.
      
   .. data:: RR_CLASS_ANY
      
      Any class.
   

The different RR types.


   .. data:: RR_TYPE_A 
   
      A host address.
      
   .. data:: RR_TYPE_NS
   
      An authoritative name server.
      
   .. data:: RR_TYPE_MD 
      
      A mail destination (Obsolete - use MX).
      
   .. data:: RR_TYPE_MF 
   
      A mail forwarder (Obsolete - use MX).
      
   .. data:: RR_TYPE_CNAME 
      
      The canonical name for an alias.
      
   .. data:: RR_TYPE_SOA 
      
      Marks the start of a zone of authority.
      
   .. data:: RR_TYPE_MB 
      
      A mailbox domain name (EXPERIMENTAL).
      
   .. data:: RR_TYPE_MG 
      
      A mail group member (EXPERIMENTAL).
      
   .. data:: RR_TYPE_MR 
      
      A mail rename domain name (EXPERIMENTAL).
      
   .. data:: RR_TYPE_NULL
      
      A null RR (EXPERIMENTAL).
      
   .. data:: RR_TYPE_WKS
      
      A well known service description.
      
   .. data:: RR_TYPE_PTR
   
      A domain name pointer.
      
   .. data:: RR_TYPE_HINFO
   
      Host information.
      
   .. data:: RR_TYPE_MINFO
   
      Mailbox or mail list information.
      
   .. data:: RR_TYPE_MX
   
      Mail exchange.
      
   .. data:: RR_TYPE_TXT
   
      Text strings.
   
   .. data:: RR_TYPE_RP
   
      RFC1183.
      
   .. data:: RR_TYPE_AFSDB
      
      RFC1183.
      
   .. data:: RR_TYPE_X25
      
      RFC1183.
      
   .. data:: RR_TYPE_ISDN
   
      RFC1183.
      
   .. data:: RR_TYPE_RT
      
      RFC1183.
      
   .. data:: RR_TYPE_NSAP
      
      RFC1706.
      
   .. data:: RR_TYPE_NSAP_PTR
      
      RFC1348.
      
   .. data:: RR_TYPE_SIG
      
      2535typecode.
      
   .. data:: RR_TYPE_KEY
      
      2535typecode.
      
   .. data:: RR_TYPE_PX
      
      RFC2163.
      
   .. data:: RR_TYPE_GPOS
      
      RFC1712.
      
   .. data:: RR_TYPE_AAAA
      
      IPv6 address.
      
   .. data:: RR_TYPE_LOC
      
      LOC record  RFC1876.
      
   .. data:: RR_TYPE_NXT
      
      2535typecode.
      
   .. data:: RR_TYPE_EID
      
      draft-ietf-nimrod-dns-01.txt.
      
   .. data:: RR_TYPE_NIMLOC
      
      draft-ietf-nimrod-dns-01.txt.
      
   .. data:: RR_TYPE_SRV
      
      SRV record RFC2782.
      
   .. data:: RR_TYPE_ATMA
   
      http://www.jhsoft.com/rfc/af-saa-0069.000.rtf.
      
   .. data:: RR_TYPE_NAPTR
      
      RFC2915.
      
   .. data:: RR_TYPE_KX
      
      RFC2230.
      
   .. data:: RR_TYPE_CERT
      
      RFC2538.
      
   .. data:: RR_TYPE_A6
      
      RFC2874.
      
   .. data:: RR_TYPE_DNAME
      
      RFC2672.
      
   .. data:: RR_TYPE_SINK
      
      dnsind-kitchen-sink-02.txt.
      
   .. data:: RR_TYPE_OPT
      
      Pseudo OPT record.
      
   .. data:: RR_TYPE_APL
      
      RFC3123.
      
   .. data:: RR_TYPE_DS
      
      draft-ietf-dnsext-delegation.
      
   .. data:: RR_TYPE_SSHFP
      
      SSH Key Fingerprint.
   
   .. data:: RR_TYPE_IPSECKEY
      
      draft-richardson-ipseckey-rr-11.txt.
      
   .. data:: RR_TYPE_RRSIG
      
      draft-ietf-dnsext-dnssec-25.
      
   .. data:: RR_TYPE_NSEC      
   .. data:: RR_TYPE_DNSKEY
   .. data:: RR_TYPE_DHCID
   .. data:: RR_TYPE_NSEC3
   .. data:: RR_TYPE_NSEC3PARAMS
   .. data:: RR_TYPE_UINFO
   .. data:: RR_TYPE_UID
   .. data:: RR_TYPE_GID
   .. data:: RR_TYPE_UNSPEC
   .. data:: RR_TYPE_TSIG
   .. data:: RR_TYPE_IXFR
   .. data:: RR_TYPE_AXFR
   .. data:: RR_TYPE_MAILB
      
      A request for mailbox-related records (MB, MG or MR).
      
   .. data:: RR_TYPE_MAILA
      
      A request for mail agent RRs (Obsolete - see MX).
      
   .. data:: RR_TYPE_ANY
      
      Any type *(wildcard)*.
   
   .. data:: RR_TYPE_DLV
      
      RFC 4431, 5074, DNSSEC Lookaside Validation.
   
Return codes
~~~~~~~~~~~~

Return codes for packets.

.. data:: RCODE_NOERROR
.. data:: RCODE_FORMERR
.. data:: RCODE_SERVFAIL
.. data:: RCODE_NXDOMAIN
.. data:: RCODE_NOTIMPL
.. data:: RCODE_REFUSED
.. data:: RCODE_YXDOMAIN
.. data:: RCODE_YXRRSET
.. data:: RCODE_NXRRSET
.. data:: RCODE_NOTAUTH
.. data:: RCODE_NOTZONE
   
Packet data
~~~~~~~~~~~~

.. data:: PKT_QR

   Query - query flag.
   
.. data:: PKT_AA

   Authoritative Answer - server flag.
   
.. data:: PKT_TC
   
   Truncated - server flag.
   
.. data:: PKT_RD
   
   Recursion desired - query flag.
   
.. data:: PKT_CD

   Checking disabled - query flag.
   
.. data:: PKT_RA
   
   Recursion available - server flag.
   
.. data:: PKT_AD
   
   Authenticated data - server flag.


Verbosity value
~~~~~~~~~~~~~~~~

.. data:: NO_VERBOSE

   No verbose messages.
   
.. data:: VERB_OPS

   Operational information.
   
.. data:: VERB_DETAIL

   Detailed information.
   
.. data:: VERB_QUERY

   Query level information.
   
.. data:: VERB_ALGO

   Algorithm level information.

---

### Pythonmod Doc Modules Functions (`pythonmod/doc/modules/functions.rst`)

Scriptable functions
====================

Network
-------

.. function:: ntohs(netshort)

   This subroutine converts values between the host and network byte order. 
   Specifically, **ntohs()** converts 16-bit quantities from network byte order
   to host byte order.

   :param netshort: 16-bit short addr
   :rtype: converted addr


Cache
-----

.. function:: storeQueryInCache(qstate, qinfo, msgrep, is_referral)

   Store pending query in local cache.

   :param qstate: :class:`module_qstate`
   :param qinfo: :class:`query_info`
   :param msgrep: :class:`reply_info`
   :param is_referral: integer
   :rtype: boolean

.. function:: invalidateQueryInCache(qstate, qinfo)

   Invalidate record in local cache.

   :param qstate: :class:`module_qstate`
   :param qinfo: :class:`query_info`


EDNS options
------------

.. function:: register_edns_option(env, code, bypass_cache_stage=False, no_aggregation=False)

    Register EDNS option code.

    :param env: :class:`module_env`
    :param code: option code(integer)
    :param bypass_cache_stage: whether to bypass the cache response stage
    :param no_aggregation: whether this query should be unique
    :return: ``1`` if successful, ``0`` otherwise
    :rtype: integer

.. function:: edns_opt_list_find(list, code)

    Find the EDNS option code in the EDNS option list.

    :param list: linked list of :class:`edns_option`
    :param code: option code (integer)
    :return: the edns option if found or None
    :rtype: :class:`edns_option` or None

.. function:: edns_opt_list_remove(list, code);

    Remove an EDNS option code from the list.
    .. note:: All :class:`edns_option` with the code will be removed

    :param list: linked list of :class:`edns_option`
    :param code: option code (integer)
    :return: ``1`` if at least one :class:`edns_option` was removed, ``0`` otherwise
    :rtype: integer

.. function:: edns_opt_list_append(list, code, data, region)

    Append given EDNS option code with data to the list.

    :param list: linked list of :class:`edns_option`
    :param code: option code (integer)
    :param data: EDNS data. **Must** be a :class:`bytearray`
    :param region: :class:`regional`

.. function:: edns_opt_list_is_empty(list)

    Check if an EDNS option list is empty.

    :param list: linked list of :class:`edns_option`
    :return: ``1`` if list is empty, ``0`` otherwise
    :rtype: integer


Inplace callbacks
-----------------

.. function:: inplace_cb_reply(qinfo, qstate, rep, rcode, edns, opt_list_out, region, \*\*kwargs)

    Function prototype for callback functions used in
    `register_inplace_cb_reply`, `register_inplace_cb_reply_cache`,
    `register_inplace_cb_reply_local` and `register_inplace_cb_reply_servfail`.

    :param qinfo: :class:`query_info`
    :param qstate: :class:`module_qstate`
    :param rep: :class:`reply_info`
    :param rcode: return code (integer), check ``RCODE_`` constants.
    :param edns: :class:`edns_data`
    :param opt_list_out: :class:`edns_option`. EDNS option list to append options to.
    :param region: :class:`regional`
    :param \*\*kwargs: Dictionary that may contain parameters added in a future
        release. Current parameters:
        ``repinfo``: :class:`comm_reply`. Reply information for a communication point.

.. function:: inplace_cb_query(qinfo, flags, qstate, addr, zone, region)

    Function prototype for callback functions used in
    `register_inplace_cb_query`.

    :param qinfo: :class:`query_info`
    :param flags: query flags (integer)
    :param qstate: :class:`module_qstate`
    :param addr: :class:`sockaddr_storage`
    :param zone: zone name in wire format (bytes)
    :param region: :class:`regional`

.. function:: register_inplace_cb_reply(py_cb, env, id)

    Register py_cb as an inplace reply callback function.

    :param py_cb: Python function that follows `inplace_cb_reply`'s prototype. **Must** be callable.
    :param env: :class:`module_env`
    :param id: Module ID.
    :return: True on success, False otherwise
    :rtype: boolean

.. function:: register_inplace_cb_reply_cache(py_cb, env, id)

    Register py_cb as an inplace reply_cache callback function.

    :param py_cb: Python function that follows `inplace_cb_reply`'s prototype. **Must** be callable.
    :param env: :class:`module_env`
    :param id: Module ID.
    :return: True on success, False otherwise
    :rtype: boolean

.. function:: register_inplace_cb_reply_local(py_cb, env, id)

    Register py_cb as an inplace reply_local callback function.

    :param py_cb: Python function that follows `inplace_cb_reply`'s prototype. **Must** be callable.
    :param env: :class:`module_env`
    :param id: Module ID.
    :return: True on success, False otherwise
    :rtype: boolean

.. function:: register_inplace_cb_reply_servfail(py_cb, env, id)

    Register py_cb as an inplace reply_servfail callback function.

    :param py_cb: Python function that follows `inplace_cb_reply`'s prototype. **Must** be callable.
    :param env: :class:`module_env`
    :param id: Module ID.
    :return: True on success, False otherwise
    :rtype: boolean

.. function:: register_inplace_cb_query(py_cb, env, id)

    Register py_cb as an inplace query callback function.

    :param py_cb: Python function that follows `inplace_cb_query`'s prototype. **Must** be callable.
    :param env: :class:`module_env`
    :param id: Module ID.
    :return: True on success, False otherwise
    :rtype: boolean

Logging
-------

.. function:: verbose(level, msg)

   Log a verbose message, pass the level for this message.
   No trailing newline is needed.

   :param level: verbosity level for this message, compared to global verbosity setting.
   :param msg: string message

.. function:: log_info(msg)

   Log informational message. No trailing newline is needed.

   :param msg: string message

.. function:: log_err(msg)

   Log error message. No trailing newline is needed.

   :param msg: string message

.. function:: log_warn(msg)

   Log warning message. No trailing newline is needed.

   :param msg: string message

.. function:: log_hex(msg, data, length)

   Log a hex-string to the log. Can be any length.
   performs mallocs to do so, slow. But debug useful.

   :param msg: string desc to accompany the hexdump.
   :param data: data to dump in hex format.
   :param length: length of data.

.. function:: log_dns_msg(str, qinfo, reply)

   Log DNS message.

   :param str: string message
   :param qinfo: :class:`query_info`
   :param reply: :class:`reply_info`

.. function:: log_query_info(verbosity_value, str, qinf)

   Log query information.

   :param verbosity_value: see constants
   :param str: string message
   :param qinf: :class:`query_info`

.. function:: regional_log_stats(r)

   Log regional statistics.

   :param r: :class:`regional`


Debugging
---------

.. function:: strextstate(module_ext_state)

   Debug utility, module external qstate to string.

   :param module_ext_state: the state value.
   :rtype: descriptive string.

.. function:: strmodulevent(module_event)

   Debug utility, module event to string.

   :param module_event: the module event value.
   :rtype: descriptive string.

.. function:: ldns_rr_type2str(atype)

   Convert RR type to string.

.. function:: ldns_rr_class2str(aclass)

   Convert RR class to string.

---

### Pythonmod Doc Modules Index (`pythonmod/doc/modules/index.rst`)

Unbound module documentation
=======================================

.. toctree::
   :maxdepth: 2

   env
   struct
   functions
   config

---

### Pythonmod Doc Modules Struct (`pythonmod/doc/modules/struct.rst`)

Scriptable structures
=====================

module_qstate
-----------------------

.. class:: module_qstate

    Module state, per query.

    This class provides these data attributes:

    .. attribute:: qinfo

        (:class:`query_info`) Information about query being answered. Name, RR type, RR class.

    .. attribute:: query_flags

        (uint16) Flags for query. See QF_BIT\_ predefined constants.

    .. attribute:: is_priming

        If this is a (stub or root) priming query (with hints).

    .. attribute:: reply

        comm_reply contains server replies.

    .. attribute:: return_msg

        (:class:`dns_msg`) The reply message, with message for client and calling module (read-only attribute).
        Note that if you want to create of modify return_msg you should use :class:`DNSMessage`.

    .. attribute:: return_rcode

        The rcode, in case of error, instead of a reply message. Determines whether the return_msg contains reply.

    .. attribute:: region

        Region for this query. Cleared when query process finishes.

    .. attribute:: curmod

        Which module is executing.

    .. attribute:: ext_state[]

        Module states.

    .. attribute:: env

        Environment for this query.

    .. attribute:: mesh_info

        Mesh related information for this query.

    .. attribute:: edns_opts_front_in

        Incoming EDNS options from the front end.

    .. attribute:: edns_opts_front_in_iter

        Iterator for `edns_opts_front_in`.

    .. attribute:: edns_opts_back_out

        Outgoing EDNS options to the back end.

    .. attribute:: edns_opts_back_out_iter

        Iterator for `edns_opts_back_out`.

    .. attribute:: edns_opts_back_in

        Incoming EDNS options from the back end.

    .. attribute:: edns_opts_back_in_iter

        Iterator for `edns_opts_back_in`.

    .. attribute:: edns_opts_front_out

        Outgoing EDNS options to the front end.

    .. attribute:: edns_opts_front_out_iter

        Iterator for `edns_opts_front_out`.

    .. attribute:: no_cache_lookup

        Flag to indicate whether modules should answer from the cache.

    .. attribute:: no_cache_store

        Flag to indicate whether modules should store answer in the cache.

query_info
----------------

.. class:: query_info

   This class provides these data attributes:

   .. attribute:: qname
   
      The original question in the wireformat format (e.g. \\x03www\\x03nic\\x02cz\\x00 for www.nic.cz)
   
   .. attribute:: qname_len
   
      Length of question name (number of bytes).
	
   .. attribute:: qname_list[]
   
      The question ``qname`` converted into list of labels (e.g. ['www','nic','cz',''] for www.nic.cz)
   
   .. attribute:: qname_str
   
      The question ``qname`` converted into string (e.g. www.nic.cz. for www.nic.cz)

   .. attribute:: qtype
   
      The class type asked for. See RR_TYPE\_ predefined constants.
   
   .. attribute:: qtype_str
   
      The ``qtype`` in display presentation format (string) (e.g 'A' for RR_TYPE_A)

   .. attribute:: qclass
   
      The question class. See RR_CLASS\_ predefined constants.
   
   .. attribute:: qclass_str
   
      The ``qclass`` in display presentation format (string).

edns_data
---------

.. class:: edns_data

    This class represents the EDNS information parsed/encoded from/to a packet. It provides these data attributes:

    .. attribute:: edns_present

        If EDNS OPT record is present.

    .. attribute:: ext_rcode

        Extended RCODE.

    .. attribute:: edns_version

        The EDNS version number.

    .. attribute:: bits

        The EDNS bits field from ttl (host order): Z.

    .. attribute:: udp_size

        UDP reassembly size.

    .. attribute:: opt_list

        The EDNS option list.

    .. attribute:: opt_list_iter

        Iterator for `opt_list`.

edns_option
-----------

.. class:: edns_option

    This class represents an EDNS option (code, data) found in EDNS option lists. It provides these data attributes:

    .. attribute:: code

    The EDNS option code.

    .. attribute:: data

    The EDNS option data.

reply_info
--------------------

.. class:: reply_info

   This class provides these data attributes:

   .. attribute:: flags
   
      The flags for the answer, host byte order.
   
   .. attribute:: qdcount
   
      Number of RRs in the query section.
      If qdcount is not 0, then it is 1, and the data that appears
      in the reply is the same as the query_info.
      Host byte order.
   
   .. attribute:: ttl
   
      TTL of the entire reply (for negative caching).
      only for use when there are 0 RRsets in this message.
      if there are RRsets, check those instead.
   
   .. attribute:: security
   
      The security status from DNSSEC validation of this message. See sec_status\_ predefined constants.
   
   .. attribute:: an_numrrsets
   
      Number of RRsets in each section.
      The answer section. Add up the RRs in every RRset to calculate
      the number of RRs, and the count for the dns packet. 
      The number of RRs in RRsets can change due to RRset updates.
   
   .. attribute:: ns_numrrsets
   
      Count of authority section RRsets
   
   .. attribute:: ar_numrrsets
   
      Count of additional section RRsets 
   
   .. attribute:: rrset_count
   
      Number of RRsets: an_numrrsets + ns_numrrsets + ar_numrrsets 
   
   .. attribute:: rrsets[]
   
         (:class:`ub_packed_rrset_key`) List of RR sets in the order in which they appear in the reply message.  
         Number of elements is ancount + nscount + arcount RRsets.
   
   .. attribute:: ref[]
   
         (:class:`rrset_ref`) Packed array of ids (see counts) and pointers to packed_rrset_key.
         The number equals ancount + nscount + arcount RRsets. 
         These are sorted in ascending pointer, the locking order. So
         this list can be locked (and id, ttl checked), to see if 
         all the data is available and recent enough.
   

dns_msg
--------------

.. class:: dns_msg

   Region allocated message reply

   This class provides these data attributes:

   .. attribute:: qinfo
   
      (:class:`query_info`) Information about query.
   
   .. attribute:: rep
   
      (:class:`reply_info`) This attribute points to the packed reply structure.


packed_rrset_key
----------------------
   
.. class:: packed_rrset_key

   The identifying information for an RRset.

   This class provides these data attributes:

   .. attribute:: dname
   
      The domain name. If not empty (for ``id = None``) it is allocated, and
      contains the wireformat domain name. This dname is not canonicalized.
      E.g., the dname contains \\x03www\\x03nic\\x02cz\\x00 for www.nic.cz.
   
   .. attribute:: dname_len
   
      Length of the domain name, including last 0 root octet. 
      
   .. attribute:: dname_list[]
   
      The domain name ``dname`` converted into list of labels (see :attr:`query_info.qname_list`).
   
   .. attribute:: dname_str
   
      The domain name ``dname`` converted into string (see :attr:`query_info.qname_str`).

   .. attribute:: flags
   
      Flags.
      
   .. attribute:: type
   
      The rrset type in network format.

   .. attribute:: type_str
   
      The rrset type in display presentation format.
      
   .. attribute:: rrset_class
   
      The rrset class in network format.

   .. attribute:: rrset_class_str
   
      The rrset class in display presentation format.

ub_packed_rrset_key
-------------------------

.. class:: ub_packed_rrset_key

   This structure contains an RRset. A set of resource records that
   share the same domain name, type and class.
   Due to memory management and threading, the key structure cannot be
   deleted, although the data can be. The id can be set to 0 to store and the
   structure can be recycled with a new id.
   
   The :class:`ub_packed_rrset_key` provides these data attributes:
   
   .. attribute:: entry
      
      (:class:`lruhash_entry`) Entry into hashtable. Note the lock is never destroyed,
      even when this key is retired to the cache. 
      the data pointer (if not None) points to a :class:`packed_rrset`.
    
   .. attribute:: id
      
      The ID of this rrset. unique, based on threadid + sequenceno. 
      ids are not reused, except after flushing the cache.
      zero is an unused entry, and never a valid id.
      Check this value after getting entry.lock.
      The other values in this struct may only be altered after changing
      the id (which needs a writelock on entry.lock).
      
   .. attribute:: rk
   
      (:class:`packed_rrset_key`) RR set data.


lruhash_entry
-------------------------

.. class:: lruhash_entry

   The :class:`ub_packed_rrset_key` provides these data attributes:

   .. attribute:: lock

      rwlock for access to the contents of the entry. Note that you cannot change hash and key, if so, you have to delete it to change hash or key.

   .. attribute:: data

      (:class:`packed_rrset_data`) entry data stored in wireformat (RRs and RRsigs).

packed_rrset_data
-----------------------
   
.. class:: packed_rrset_data

   Rdata is stored in wireformat. The dname is stored in wireformat.
   
   TTLs are stored as absolute values (and could be expired).
   
   RRSIGs are stored in the arrays after the regular rrs.
   
   You need the packed_rrset_key to know dname, type, class of the
   resource records in this RRset. (if signed the rrsig gives the type too).

   The :class:`packed_rrset_data` provides these data attributes:

   .. attribute:: ttl
   
      TTL (in seconds like time()) of the RRset.
      Same for all RRs see rfc2181(5.2).
   
   .. attribute:: count
      
      Number of RRs.
   
   .. attribute:: rrsig_count
      
      Number of rrsigs, if 0 no rrsigs.
      
   .. attribute:: trust
   
      The trustworthiness of the RRset data.
      
   .. attribute:: security
   
      Security status of the RRset data. See sec_status\_ predefined constants.
      
   .. attribute:: rr_len[]
   
      Length of every RR's rdata, rr_len[i] is size of rr_data[i].
      
   .. attribute:: rr_ttl[]
   
      TTL of every rr. rr_ttl[i] ttl of rr i.
      
   .. attribute:: rr_data[]
   
      Array of RR's rdata (list of strings). The rdata is stored in uncompressed wireformat. 
      The first 16B of rr_data[i] is rdlength in network format.
   

DNSMessage
----------------
   
.. class:: DNSMessage

   Abstract representation of DNS message.
   
   **Usage**

      This example shows how to create an authoritative answer response
		
      ::

         msg = DNSMessage(qstate.qinfo.qname_str, RR_TYPE_A, RR_CLASS_IN, PKT_AA)

         #append RR
         if (qstate.qinfo.qtype == RR_TYPE_A) or (qstate.qinfo.qtype == RR_TYPE_ANY):
             msg.answer.append("%s 10 IN A 127.0.0.1" % qstate.qinfo.qname_str)
         
         #set qstate.return_msg 
         if not msg.set_return_msg(qstate):
             raise Exception("Can't create response")

   The :class:`DNSMessage` provides these methods and data attributes:
   
   .. method:: __init__(self, rr_name, rr_type, rr_class = RR_CLASS_IN, query_flags = 0, default_ttl = 0)
   
      Prepares an answer (DNS packet) from given information. Query flags are combination of PKT_xx constants.
      
   .. method:: set_return_msg(self, qstate)
   
      This method fills qstate return message according to the given information. 
		It takes lists of RRs in each section of answer, created necessary RRsets in wire format and store the result in :attr:`qstate.return_msg`.
		Returns 1 if OK.
   
   .. attribute:: rr_name
   
      RR name of question.
      
   .. attribute:: rr_type
   
      RR type of question.
      
   .. attribute:: rr_class
   
      RR class of question.
      
   .. attribute:: default_ttl
   
      Default time-to-live.
      
   .. attribute:: query_flags
   
      Query flags. See PKT\_ predefined constants.
      
   .. attribute:: question[]
   
      List of resource records that should appear (in the same order) in question section of answer.
      
   .. attribute:: answer[]
   
      List of resource records that should appear (in the same order) in answer section of answer.
     
   .. attribute:: authority[]
   
      List of resource records that should appear (in the same order) in authority section of answer.
      
   .. attribute:: additional[]
   
      List of resource records that should appear (in the same order) in additional section of answer.

pythonmod_env
-----------------------

.. class:: pythonmod_env

   Global state for the module. 

   This class provides these data attributes:

   .. attribute:: data
   
      Here you can keep your own data shared across each thread.

   .. attribute:: fname
   
   	Python script filename.
   
   .. attribute:: qstate
   
      Module query state.

pythonmod_qstate
-----------------------

.. class:: pythonmod_qstate

   Per query state for the iterator module.
	
   This class provides these data attributes:
	
   .. attribute:: data
	
	   Here you can keep your own private data (each thread has own data object).

sockaddr_storage
-------------------------

.. class:: sockaddr_storage

   The :class:`sockaddr_storage` provides these data attributes:

   .. attribute:: family

      Address family name as a string. Possible values are `ip4`, `ip6`, and `unix`.

   .. attribute:: addr

      Address in presentation format.

   .. attribute:: raw_addr

      Address in network wire format.

   .. attribute:: port

      Port number. Invalid for Unix address.

   .. attribute:: flowinfo

      Flow info value. Valid only for IPv6 address.

   .. attribute:: scope_id

      Scope ID value. Valid only for IPv6 address.

---

### Libunbound Python Doc Examples Example1a (`libunbound/python/doc/examples/example1a.rst`)

.. _example_resolve_name:

Resolve a name
==============

This basic example shows how to create a context and resolve a host address
(DNS record of A type).

Source code
-----------

::

    #!/usr/bin/python
    import unbound

    ctx = unbound.ub_ctx()
    ctx.resolvconf("/etc/resolv.conf")

    status, result = ctx.resolve("www.google.com")
    if status == 0 and result.havedata:
        print "Result.data:", result.data.address_list
    elif status != 0:
        print "Resolve error:", unbound.ub_strerror(status)

In contrast with the C API, the source code is more compact while the
performance of C implementation is preserved. 
The main advantage is that you need not take care about the deallocation and
allocation of context and result structures; pyUnbound module does it
automatically for you. 

If only domain name is given, the :meth:`unbound.ub_ctx.resolve` looks for
A records in IN class.

---

### Libunbound Python Doc Examples Example1b (`libunbound/python/doc/examples/example1b.rst`)

.. _example_reverse_lookup:

Reverse DNS lookup
==================

Reverse DNS lookup involves determining the hostname associated with a given IP
address.
This example shows how reverse lookup can be done using unbound module.

For the reverse DNS records, the special domain in-addr.arpa is reserved. 
For example, a host name for the IP address ``74.125.43.147`` can be obtained
by issuing a DNS query for the PTR record for address
``147.43.125.74.in-addr.arpa.``

Source code
-----------

::

    #!/usr/bin/python
    import unbound

    ctx = unbound.ub_ctx()
    ctx.resolvconf("/etc/resolv.conf")

    status, result = ctx.resolve(unbound.reverse("74.125.43.147") + ".in-addr.arpa.", unbound.RR_TYPE_PTR, unbound.RR_CLASS_IN)
    if status == 0 and result.havedata:
        print "Result.data:", result.data.domain_list
    elif status != 0:
        print "Resolve error:", unbound.ub_strerror(status)

In order to simplify the python code, unbound module contains the
:meth:`unbound.reverse` function which reverses the hostname components.
This function is defined as follows::

    def reverse(domain):
        return '.'.join([a for a in domain.split(".")][::-1])

---

### Libunbound Python Doc Examples Example2 (`libunbound/python/doc/examples/example2.rst`)

.. _example_setup_ctx:

Lookup from threads
===================

This example shows how to use unbound module from a threaded program.
In this example, three lookup threads are created which work in background.
Each thread resolves different DNS record.

Source code
-----------

::

    #!/usr/bin/python
    from unbound import ub_ctx, RR_TYPE_A, RR_CLASS_IN
    from threading import Thread

    ctx = ub_ctx()
    ctx.resolvconf("/etc/resolv.conf")

    class LookupThread(Thread):
        def __init__(self,ctx, name):
            Thread.__init__(self)
            self.ctx = ctx
            self.name = name

        def run(self):
            print "Thread lookup started:",self.name
            status, result = self.ctx.resolve(self.name, RR_TYPE_A, RR_CLASS_IN)
            if status == 0 and result.havedata:
                print "  Result:",self.name,":", result.data.address_list

    threads = []
    for name in ["www.fit.vutbr.cz","www.vutbr.cz","www.google.com"]:
        thread = LookupThread(ctx, name)
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()

---

### Libunbound Python Doc Examples Example3 (`libunbound/python/doc/examples/example3.rst`)

.. _example_asynch:

Asynchronous lookup
===================

This example performs the name lookup in the background. 
The main program keeps running while the name is resolved. 

Source code
-----------

::

	#!/usr/bin/python
	import time
	import unbound
	
	ctx = unbound.ub_ctx()
	ctx.resolvconf("/etc/resolv.conf")
	
	def call_back(my_data,status,result):
		print "Call_back:", my_data
		if status == 0 and result.havedata:
			print "Result:", result.data.address_list
			my_data['done_flag'] = True
	
	
	my_data = {'done_flag':False,'arbitrary':"object"}
	status, async_id = ctx.resolve_async("www.seznam.cz", my_data, call_back, unbound.RR_TYPE_A, unbound.RR_CLASS_IN)
	        
	while (status == 0) and (not my_data['done_flag']):
		status = ctx.process()
		time.sleep(0.1)
	
	if (status != 0):
		print "Resolve error:", unbound.ub_strerror(status)

The :meth:`unbound.ub_ctx.resolve_async` method is able to pass on any Python
object. In this example, we used a dictionary object ``my_data``.

---

### Libunbound Python Doc Examples Example4 (`libunbound/python/doc/examples/example4.rst`)

.. _example_examine:

DNSSEC validator
================

This example program performs DNSSEC validation of a DNS lookup.

Source code
-----------

::

    #!/usr/bin/python
    import os
    from unbound import ub_ctx,RR_TYPE_A,RR_CLASS_IN

    ctx = ub_ctx()
    ctx.resolvconf("/etc/resolv.conf")
    if (os.path.isfile("keys")):
        ctx.add_ta_file("keys") #read public keys for DNSSEC verification

    status, result = ctx.resolve("www.nic.cz", RR_TYPE_A, RR_CLASS_IN)
    if status == 0 and result.havedata:

        print "Result:", result.data.address_list

        if result.secure:
            print "Result is secure"
        elif result.bogus:
            print "Result is bogus"
        else:
            print "Result is insecure"

More detailed information can be seen in libUnbound DNSSEC tutorial `here`_.

.. _here: http://www.unbound.net/documentation/libunbound-tutorial-6.html

---

### Libunbound Python Doc Examples Example5 (`libunbound/python/doc/examples/example5.rst`)

.. _example_resolver_only:

Resolver only
=============

This example program shows how to perform DNS resolution only.
Unbound contains two basic modules: resolver and validator.
In case, the validator is not necessary, the validator module can be turned off
using "module-config" option.
This option contains a list of module names separated by the space char. This
list determined which modules should be employed and in what order.

Source code
-----------

::

	#!/usr/bin/python
	import os
	from unbound import ub_ctx,RR_TYPE_A,RR_CLASS_IN
	
	ctx = ub_ctx()
	ctx.set_option("module-config:","iterator")
	ctx.resolvconf("/etc/resolv.conf")
	
	status, result = ctx.resolve("www.google.com", RR_TYPE_A, RR_CLASS_IN)
	if status == 0 and result.havedata:
	
	    print "Result:", result.data.address_list

.. note::
   The :meth:`unbound.ub_ctx.set_option` method must be used before the first
   resolution (i.e. before :meth:`unbound.ub_ctx.resolve` or
   :meth:`unbound.ub_ctx.resolve_async` call).

---

### Libunbound Python Doc Examples Example6 (`libunbound/python/doc/examples/example6.rst`)

.. _example_localzone:

Local zone manipulation
=======================

This example program shows how to define local zone containing custom DNS
records.

Source code
-----------

.. literalinclude:: example6-1.py
    :language: python

---

### Libunbound Python Doc Examples Example7 (`libunbound/python/doc/examples/example7.rst`)

.. _example_idna:

Internationalized domain name support
=====================================

Unlike the libUnbound, pyUnbound is able to handle IDN queries.

Automatic IDN DNAME conversion
-------------------------------

If we use unicode string in :meth:`unbound.ub_ctx.resolve` method,
the IDN DNAME conversion (if it is necessary) is performed on background.

Source code
...........

.. literalinclude:: example7-1.py
    :language: python

IDN converted attributes
------------------------

The :class:`unbound.ub_data` class contains attributes suffix which converts
the dname to UTF string. These attributes have the ``_idn`` suffix.

Apart from this approach, two conversion functions exist
(:func:`unbound.idn2dname` and :func:`unbound.dname2idn`).

Source code
...........

.. literalinclude:: example7-2.py
    :language: python

---

### Libunbound Python Doc Examples Example8 (`libunbound/python/doc/examples/example8.rst`)

.. _example_mxlookup:

Lookup for MX and NS records
============================

The pyUnbound extension provides functions which are able to encode RAW RDATA
produces by unbound resolver (see :class:`unbound.ub_data`).

Source code
-----------

.. literalinclude:: example8-1.py
    :language: python

Output
------

The previous example produces the following output::

    Result:
        raw data: 00 0F 05 6D 61 69 6C 34 03 6E 69 63 02 63 7A 00;00 14 02 6D 78 05 63 7A 6E 69 63 03 6F 72 67 00;00 0A 04 6D 61 69 6C 03 6E 69 63 02 63 7A 00
        priority:15 address: mail4.nic.cz.
        priority:20 address: mx.cznic.org.
        priority:10 address: mail.nic.cz.

    Result:
        raw data: D9 1F CD 32
        address: 217.31.205.50

    Result:
        raw data: 01 61 02 6E 73 03 6E 69 63 02 63 7A 00;01 65 02 6E 73 03 6E 69 63 02 63 7A 00;01 63 02 6E 73 03 6E 69 63 02 63 7A 00
        host: a.ns.nic.cz.
        host: e.ns.nic.cz.
        host: c.ns.nic.cz.

---

### Libunbound Python Doc Examples Index (`libunbound/python/doc/examples/index.rst`)

Examples
========

Here you can find several examples which utilizes the unbound library in Python
environment. Unbound is a caching validator and resolver and can be linked into
an application, as a library where can answer DNS queries for the application.
This set of examples shows how to use the functions from Python environment.

Tutorials
---------

.. toctree::
    :maxdepth: 1
    :glob:

    example*

---

### Libunbound Python Doc Modules Unbound (`libunbound/python/doc/modules/unbound.rst`)

Unbound module documentation
================================

.. automodule:: unbound

Class ub_ctx
--------------
.. autoclass:: ub_ctx
	:members:
	:undoc-members:
	
	.. automethod:: __init__ 

Class ub_result
----------------------
.. autoclass:: ub_result
	:members:

	.. attribute:: qname

		The original question, name text string.

	.. attribute:: qtype

		The class asked for.

	.. attribute:: canonname

		Canonical name for the result (the final cname). May be empty if no canonical name exists.

	.. attribute:: answer_packet
		
		The DNS answer packet. Network formatted. Can contain DNSSEC types.

	.. attribute:: havedata
		
		If there is any data, this property is true. If false, there was no data (nxdomain may be true, rcode can be set).

	.. attribute:: secure
		
		True, if the result is validated securely.
	 	False, if validation failed or domain queried has no security info.
	 
	  	It is possible to get a result with no data (havedata is false),
	  	and secure is true. This means that the non-existence of the data
	  	was cryptographically proven (with signatures).

	.. attribute:: bogus
		
		If the result was not secure (secure==0), and this result is due  to a security failure, bogus is true.
	 	This means the data has been actively tampered with, signatures
	 	failed, expected signatures were not present, timestamps on 
	 	signatures were out of date and so on.
	 
	 	If secure==0 and bogus==0, this can happen if the data is not secure 
	 	because security is disabled for that domain name. 
	 	This means the data is from a domain where data is not signed.

	.. attribute:: nxdomain

		If there was no data, and the domain did not exist, this is true. 
		If it is false, and there was no data, then the domain name is purported to exist, but the requested data type is not available.

	.. attribute:: rcode
		
		DNS RCODE for the result. May contain additional error code if there was no data due to an error. 
		0 (RCODE_NOERROR) if okay. See predefined `RCODE_` constants.
	
		RCODE can be represented in display representation form (string) using :attr:`rcode_str` attribute.

Class ub_data
----------------------
.. autoclass:: ub_data
	:members:

Functions
----------------------
.. autofunction:: reverse
.. autofunction:: idn2dname
.. autofunction:: dname2idn

Predefined constants
-----------------------

**RCODE**
	* RCODE_FORMERR = 1
	* RCODE_NOERROR = 0
	* RCODE_NOTAUTH = 9
	* RCODE_NOTIMPL = 4
	* RCODE_NOTZONE = 10
	* RCODE_NXDOMAIN = 3
	* RCODE_NXRRSET = 8
	* RCODE_REFUSED = 5
	* RCODE_SERVFAIL = 2
	* RCODE_YXDOMAIN = 6
	* RCODE_YXRRSET = 7

**RR_CLASS**
	* RR_CLASS_ANY = 255
	* RR_CLASS_CH = 3
	* RR_CLASS_HS = 4
	* RR_CLASS_IN = 1
	* RR_CLASS_NONE = 254

**RR_TYPE**
	* RR_TYPE_A = 1
	* RR_TYPE_A6 = 38
	* RR_TYPE_AAAA = 28
	* RR_TYPE_AFSDB = 18
	* RR_TYPE_ANY = 255
	* RR_TYPE_APL = 42
	* RR_TYPE_ATMA = 34
	* RR_TYPE_AXFR = 252
	* RR_TYPE_CERT = 37
	* RR_TYPE_CNAME = 5
	* RR_TYPE_DHCID = 49
	* RR_TYPE_DLV = 32769
	* RR_TYPE_DNAME = 39
	* RR_TYPE_DNSKEY = 48
	* RR_TYPE_DS = 43
	* RR_TYPE_EID = 31
	* RR_TYPE_GID = 102
	* RR_TYPE_GPOS = 27
	* RR_TYPE_HINFO = 13
	* RR_TYPE_IPSECKEY = 45
	* RR_TYPE_ISDN = 20
	* RR_TYPE_IXFR = 251
	* RR_TYPE_KEY = 25
	* RR_TYPE_KX = 36
	* RR_TYPE_LOC = 29
	* RR_TYPE_MAILA = 254
	* RR_TYPE_MAILB = 253
	* RR_TYPE_MB = 7
	* RR_TYPE_MD = 3
	* RR_TYPE_MF = 4
	* RR_TYPE_MG = 8
	* RR_TYPE_MINFO = 14
	* RR_TYPE_MR = 9
	* RR_TYPE_MX = 15
	* RR_TYPE_NAPTR = 35
	* RR_TYPE_NIMLOC = 32
	* RR_TYPE_NS = 2
	* RR_TYPE_NSAP = 22
	* RR_TYPE_NSAP_PTR = 23
	* RR_TYPE_NSEC = 47
	* RR_TYPE_NSEC3 = 50
	* RR_TYPE_NSEC3PARAMS = 51
	* RR_TYPE_NULL = 10
	* RR_TYPE_NXT = 30
	* RR_TYPE_OPT = 41
	* RR_TYPE_PTR = 12
	* RR_TYPE_PX = 26
	* RR_TYPE_RP = 17
	* RR_TYPE_RRSIG = 46
	* RR_TYPE_RT = 21
	* RR_TYPE_SIG = 24
	* RR_TYPE_SINK = 40
	* RR_TYPE_SOA = 6
	* RR_TYPE_SRV = 33
	* RR_TYPE_SSHFP = 44
	* RR_TYPE_TSIG = 250
	* RR_TYPE_TXT = 16
	* RR_TYPE_UID = 101
	* RR_TYPE_UINFO = 100
	* RR_TYPE_UNSPEC = 103
	* RR_TYPE_WKS = 11
	* RR_TYPE_X25 = 19

---

--- METRICS ---
- Files Extracted: 41
- Estimated Token Budget: ~104321 tokens
- Canonical Reference: https://codewiki.google/github.com/NLnetLabs/unbound