Unbound DNS — Local Cache and Resolver

Install the package.

Additionally, the package is required for #DNSSEC validation.

Unbound is a validating, recursive, and caching DNS resolver. According to Wikipedia:

Unbound has supplanted the Berkeley Internet Name Domain (BIND) as the default, base-system name server in several open source projects, where it is perceived as smaller, more modern, and more secure for most applications.

DNS is a crucial component of network infrastructure and allows access to network resources, locally and across the Internet, using friendly names instead of IP addresses. There are many different DNS server solutions you can install.

This post will discuss setting up and configuring Unbound DNS, a robust and secure DNS server that can act as a local DNS server and a recursive DNS resolver. We will also cover the installation process, configuration, and essential aspects like DNSSEC validation and DNS over TLS.

Состояние перевода: На этой странице представлен перевод статьи Unbound. Дата последней синхронизации: 4 августа 2021. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

Unbound это удостоверяющий, рекурсивный и кеширующий DNS сервер. Согласно Википедии:

Unbound вытеснил Berkeley Internet Name Domain (BIND) став стандартом как именной сервер в множестве open source проектах, в которых рассматриваются такие преимущества как маленький размер, современность и безопасность.

Most DNS servers are by default configured with a «root file» (a.k.a. «hints file») pointing to «legacy root servers» which are controlled by ICANN.

This gives you access to the «legacy domain name space» which includes .com, .net, .org, two letter country codes, etc.

If the DNS server does not know the address of the requested site, then it will forward the request to another DNS server. In order to do so, the DNS server must know of the IP address of another DNS server that it can forward the request to. This is the job of root hints. Root hints provides a list of IP addresses of DNS servers that are considered to be authoritative at the root level of the DNS hierarchy(also known as root name server).

If you want to go back to the original file, just delete the current file and restart the DNS server. It will automatically regenerate the original.

Source:Some of the info was obtained from DNS and BIND, 5th Edition

Содержание
  1. Issues concerning num-threads
  2. Remotely control Unbound
  3. Setting up unbound-control
  4. Local DNS server
  5. Allow local network to use DNS
  6. Forward all remaining requests
  7. Forwarding using DNS over TLS
  8. What are the root hints?
  9. Why do we need root hints?
  10. What is root priming?
  11. Do I need to configure a root hints zone myself?
  12. Doesn’t the built-in root hint zone get out of date?
  13. I keep seeing warnings in my logs from checkhints — what should I do about them?
  14. When does root priming occur after starting named?
  15. Does named ever refresh the primed roots?
  16. Do all BIND nameservers do root priming?
  17. Can having only a few root servers in cache cause problems?
  18. Do I need a root hint zone if I’m using global forwarding?
  19. Forwarding using DNS over TLS
  20. Testing validation
  21. Советы и приёмы
  22. Черный список доменов
  23. Использование вместе с авторитетный DNS сервером
  24. Доступ к DNS серверу через WAN интерфейс
  25. Служба systemd для обновления корневых подсказок
  26. What is Unbound DNS Server?
  27. Validating our setup
  28. Manually specifying DNS servers
  29. Setting up unbound-control for remote control
  30. Testing DNSSEC
  31. Testing DNS lookup
  32. DNS change in Drakconnect
  33. Using Docker Compose
  34. Root hints systemd timer
  35. Unbound configuration file
  36. Installing Unbound DNS using Docker
  37. Using Unbound DNS Server in conjunction with Pi-Hole
  38. DNSSEC validation
  39. Root servers
  40. Using openresolv
  41. Определение нужного количества потоков (num-threads)
  42. Локальный DNS сервер
  43. Корневые подсказки (Root hints)
  44. Проверка достоверности DNSSEC
  45. Доступ локальной сети к DNS
  46. Переадресация остальных запросов
  47. Переадресация через DNS over TLS
  48. How does DNS work?
  49. Installing Unbound DNS using apt install
  50. How does Unbound work?
  51. Удаленное управление Unbound
  52. Using Docker run command
  53. Local DNS server
  54. Tips and tricks
  55. WAN facing DNS
  56. Roothints systemd timer
  57. Keeping DNS cache always up to date

Issues concerning num-threads

mentions:

     outgoing-range: <number>
             Number of ports to open. This number of file  descriptors  can  be  opened  per thread.

and some sources suggest that the num-threads parameter should be set to the number of cpu cores. The sample unbound.conf.example file merely has:

       # number of threads to create. 1 disables threading.
       # num-threads: 1
Set num-threads equal to the number of CPU cores on the system. E.g. for 4 CPUs with 2 cores each, use 8.

Set the outgoing-range to as large a value as possible, see the sections in the referred web page above on how to overcome the limit of 1024 in total. This services more clients at a time. With 1 core, try 950. With 2 cores, try 450. With 4 cores try 200. The num-queries-per-thread is best set at half the number of the outgoing-range.

Because of the limit on outgoing-range thus also limits num-queries-per-thread, it is better to compile with , so that there is no 1024 limit on outgoing-range. If you need to compile this way for a heavy duty DNS server then you will need to compile the programme from source instead of using the package.

Start/enable the unbound.service systemd service.

Remotely control Unbound

Setting up unbound-control

# unbound-control-setup

which will generate a self-signed certificate and private key for the server, as well as the client. These files will be created in the /etc/unbound directory.

remote-control:
    # Enable remote control with unbound-control(8) here.
    # set up the keys and certificates with unbound-control-setup.
    control-enable: yes
   
    # what interfaces are listened to for remote control.
    # give 0.0.0.0 and ::0 to listen to all interfaces.
    control-interface: 127.0.0.1
   
    # port number for remote control operations.
    control-port: 8953
   
    # unbound server key file.
    server-key-file: "/etc/unbound/unbound_server.key"
   
    # unbound server certificate file.
    server-cert-file: "/etc/unbound/unbound_server.pem"
   
    # unbound-control key file.
    control-key-file: "/etc/unbound/unbound_control.key"
   
    # unbound-control certificate file.
    control-cert-file: "/etc/unbound/unbound_control.pem"

Some of the commands that can be used with unbound-control are:

  • print statistics without resetting them
 # unbound-control stats_noreset
  • dump cache to stdout
 # unbound-control dump_cache
  • flush cache and reload configuration
 # unbound-control reload

Please refer to for a detailed look at the operations it supports.

Unless otherwise specified, any options listed in this section are to be placed under the server section in the configuration like so:

/etc/unbound/unbound.conf
server:
  ...
  setting: value
  ...

Local DNS server

If you want to use unbound as your local DNS server, set your nameserver to the loopback addresses ::1 and 127.0.0.1 in /etc/resolv.conf:

/etc/resolv.conf
nameserver ::1
nameserver 127.0.0.1
options trust-ad

Make sure to protect /etc/resolv.conf from modification as described in Domain name resolution#Overwriting of /etc/resolv.conf.

Tip: A simple way to do this is to install openresolv and configure /etc/resolvconf.conf:

/etc/resolvconf.conf
name_servers="::1 127.0.0.1"
resolv_conf_options="trust-ad"

Then run resolvconf -u to generate /etc/resolv.conf.

See Domain name resolution#Lookup utilities on how to test your settings.

Check specifically that the server being used is ::1 or 127.0.0.1 after making permanent changes to resolv.conf.

You can now setup unbound such that it is #Forwarding queries, perhaps all queries, to the DNS servers of your choice.

For recursively querying a host that is not cached as an address, the resolver needs to start at the top of the server tree and query the root servers, to know where to go for the top level domain for the address being queried. Unbound comes with default builtin hints. Therefore, if the package is updated regularly, no manual intervention is required. Otherwise, it is good practice to use a root-hints file since the builtin hints may become outdated.

First point unbound to the root.hints file:

root-hints: root.hints

Then, put a root hints file into the unbound configuration directory. The simplest way to do this is to run the command:

# curl --output /etc/unbound/root.hints https://www.internic.net/domain/named.cache

When actually using this file, and not the builtin hints, it is a good idea to update root.hints every six months or so in order to make sure the list of root servers is up to date. This can be done manually or by using a systemd timer. See #Roothints systemd timer for an example.

/etc/unbound/unbound.conf
  trust-anchor-file: trusted-key.key

DNSSEC validation will only be done if the DNS server being queried supports it. If general #Forwarding queries have been set to DNS servers that do not support DNSSEC, their answers, whatever they are, should be considered insecure since no DNSSEC validation could be preformed.

Note: Including DNSSEC checking significantly increases DNS lookup times for initial lookups before the address is cached.

To test if DNSSEC is working, after starting unbound.service, do:

$ unbound-host -C /etc/unbound/unbound.conf -v go.dnscheck.tools

The response should be the ip address with the word (secure) next to it.

$ unbound-host -C /etc/unbound/unbound.conf -v badsig.go.dnscheck.tools

Here the response should include (BOGUS (security failure)).

$ drill badsig.go.dnscheck.tools
$ drill go.dnscheck.tools

The first command should give an rcode of SERVFAIL. The second should give an rcode of NOERROR.

If you only want to forward queries to an external DNS server, skip ahead to #Forward all remaining requests.

Allow local network to use DNS

If your network manager supports openresolv, you can configure it to provide local DNS servers and search domains to Unbound:

/etc/resolvconf.conf
...
private_interfaces="*"

# Write out unbound configuration file
unbound_conf=/etc/unbound/resolvconf.conf

Run resolvconf -u to generate the file.

/etc/unbound/unbound.conf
include: "/etc/unbound/resolvconf.conf"
...
server:
...
	private-domain: "intranet"
	private-domain: "internal"
	private-domain: "private"
	private-domain: "corp"
	private-domain: "home"
	private-domain: "lan"

	unblock-lan-zones: yes
	insecure-lan-zones: yes
...

Additionally you may want to disable DNSSEC validation for private DNS namespaces (see RFC 6762 Appendix G):

/etc/unbound/unbound.conf
...
server:
...
	domain-insecure: "intranet"
	domain-insecure: "internal"
	domain-insecure: "private"
	domain-insecure: "corp"
	domain-insecure: "home"
	domain-insecure: "lan"
...
Exclude local subnets from answers

Will be useful to exclude local networks from DNS answers because it would protect against DNS rebinding attacks. By default this feature is not active but you can add any subnet you want in configuration file:

private-address: local_subnet/subnet_mask

You can add all private and link-local subnets by this strings:

private-address:  10.0.0.0/8
private-address:  172.16.0.0/12
private-address:  192.168.0.0/16
private-address:  169.254.0.0/16
private-address:  fd00::/8
private-address:  fe80::/10

Note that Unbound may have adresses from excluded subnets in answers if they belong to domains from private-domain or specifed by local-data, so you need to define private-domain how described at #Using openresolv to able query local domains adresses.

Include local DNS server

To include a local DNS server for both forward and reverse local addresses a set of lines similar to these below is necessary with a forward and reverse lookup (choose the IP address of the server providing DNS for the local network accordingly by changing 10.0.0.1 in the lines below):

local-zone: "10.in-addr.arpa." transparent

This line above is important to get the reverse lookup to work correctly.

forward-zone:
name: "mynetwork.com."
forward-addr: 10.0.0.1
forward-zone:
name: "10.in-addr.arpa."
forward-addr: 10.0.0.1

Note: There is a difference between forward zones and stub zones — stub zones will only work when connected to an authoritative DNS server directly. This would work for lookups from a BIND DNS server if it is providing authoritative DNS — but if you are referring queries to an unbound server in which internal lookups are forwarded on to another DNS server, then defining the referral as a stub zone in the machine here will not work. In that case it is necessary to define a forward zone as above, since forward zones can have daisy chain lookups onward to other DNS servers. i.e. forward zones can refer queries to recursive DNS servers. This distinction is important as you do not get any error messages indicating what the problem is if you use a stub zone inappropriately.

local-zone: "localhost." static
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-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. 2 3600 1200 604800 10800"
local-data: "1.0.0.127.in-addr.arpa. 10800 IN PTR localhost."

Forward all remaining requests

If your network manager supports openresolv, you can configure it to provide upstream DNS servers to Unbound.

Дополнительно:  Как на android проверить есть ли root права на android

/etc/resolvconf.conf
...
# Write out unbound configuration file
unbound_conf=/etc/unbound/resolvconf.conf

Run resolvconf -u to generate the file.

include: "/etc/unbound/resolvconf.conf"
Manually specifying DNS servers

To use specific servers for default forward zones that are outside of the local machine and outside of the local network add a forward zone with the name . to the configuration file. In this example, all requests are forwarded to Google’s DNS servers:

forward-zone:
  name: "."
  forward-addr: 8.8.8.8
  forward-addr: 8.8.4.4

Forwarding using DNS over TLS

To use DNS over TLS, you will need to enable the tls-system-cert option, allow unbound to forward TLS requests and also specify any number of servers that allow DNS over TLS.

/etc/unbound/unbound.conf
...
server:
...
	tls-system-cert: yes
...
forward-zone:
        name: "."
        forward-tls-upstream: yes
        forward-addr: 1.1.1.1@853#cloudflare-dns.com

You can specify the interfaces to answer queries from by IP address. The default, is to listen on localhost.

interface: 0.0.0.0

To control which systems can access the server by IP address, use the access-control option:

access-control: subnet action
access-control: 192.168.1.0/24 allow

action can be one of deny (drop message), refuse (polite error reply), allow (recursive ok), or allow_snoop (recursive and nonrecursive ok). By default everything is refused except for localhost.

Thanks for sharing your feedback!

What are the root hints?

The root hints are a list of the servers that are authoritative for the root domain «.», along with their IPv4 and IPv6 addresses. In other words, this is a collection of NS, A, and AAAA records for the root nameservers.

Why do we need root hints?

When handling a client query for which it has no answer, a recursive server needs to know which authoritative server is responsible for the domain of the name it has been asked to resolve. So for example, if a client queries for hostname.example.com, a recursive server that has just been restarted will not know where to find the authoritative servers for example.com, nor the authoritative servers for com. It will need to start at the ‘top’, which it does by sending the query for hostname.example.com to one of the root nameservers.

What is root priming?

There is a subtle clue in the name we give the root hint zone — the word ‘hint’. Although the names and addresses for the root nameservers don’t change very often, there are occasional updates. Thus the root hint zone is assumed to be mostly accurate, but it is not treated as the authoritative list of the roots. Instead, named will query the servers in the root hints list in turn, asking them for the NS records for «.». When an authoritative response is received, the answer is added to cache, and it is the newly primed set of root nameservers that is used, rather than the set from the hints file.

Do I need to configure a root hints zone myself?

It is only installations that are completely separate from the Internet name space who need to
configure their own private set of root nameservers.

Doesn’t the built-in root hint zone get out of date?

It doesn’t matter if the root hint zone is a little out of date — this is because root priming takes care of any recent changes and makes sure that the most recent authoritative data is obtained and loaded into named‘s cache. It is the set of root servers obtained as a result of root priming that is actually used for resolution of client queries. As long as at least one of the servers listed in the root hint zone is still correct, named will be able to prime itself. 

I keep seeing warnings in my logs from checkhints — what should I do about them?

10-Aug-2013 14:27:37.216 general: warning: checkhints: d.root-servers.net/A (199.7.91.13) missing from hints
10-Aug-2013 14:27:37.216 general: warning: checkhints: d.root-servers.net/A (128.8.10.90) extra record in hints

These warnings are harmless. 

  • If using built-in roots you can ignore the warnings (and should plan to upgrade to a more current version of BIND when available).
  • Administrators relying on built-in root hints who want to eliminate the warnings right away could, if they choose, update the built-in roots in lib/dns/rootns.c by hand, rebuild BIND, and then run the new named binary until they are able to upgrade.
  • Administrators using their own root hint zone should update it manually.

These warnings may be seen more frequently than expected based on the TTL of the root nameserver records

A defect in older versions of BIND may cause named to send root priming queries as often as once per second

Fixed in 9.12.0, 9.11.3, 9.10.7 and 9.9.12, bug RT #45241 could cause named to send unnecessary and frequent priming queries.  This re-priming can occur no more frequently than once per second due to the way BIND holds learned NS/A/AAAA RRsets during processing of client queries in case they need to be re-used, and in most cases would be seen less often than this.

When does root priming occur after starting named?

Root priming is done for the first time, only when named needs to send a query to one of the root nameservers. If your nameserver never needs to do this, then the roots will never be primed.  For example. recursive nameservers that are configured with a global forwarders list and the option ‘forward only;’ should never need to send queries to the root nameservers directly, so wouldn’t be expected to initiate root priming.

Why do I sometimes see the root priming queries being sent after a client query has been sent to one of the hint root servers?

If you take a network packet trace of recursive server that has just been started up you will notice that on receipt of the first client query that requires recursion, named will do two things in parallel. The first is that it will initiate a ‘best effort’ attempt to try to get an answer for the client. Since it does not yet have a primed set of roots, it will send the client query to one of the root hint servers.  At the same time, root priming is initiated (as a separate task).

Does named ever refresh the primed roots?

Yes — named will re-prime the roots that it has in cache if and when the last authoritative server for «.» expires or is otherwise removed from cache. Reasons why named may no longer have a set of authoritative servers for «.» in cache include:

  • The records originally obtained by priming have expired (reached the end of their time to live — TTL). Priming is initiated to refresh the roots.
  • Sometimes it happens that a recursive server ‘learns’ a new RRset for the root servers as a result of something like an upward delegation by an old DNS server. Clearly this information is not as trustworthy as the list of root nameservers obtained directly from the root nameservers themselves — so just in case, named goes back and re-primes its list.
  • The records are deleted from cache because the cache size limit has been reached, and the Least Recently Used (LRU) algorithm has selected the roots and removed them to make space for new entries that need to be added to cache.

Isn’t deleting the roots from cache due to LRU cache management a bad thing?

This is not necessarily a bad thing — it depends on what your nameserver is being used for. Having the roots deleted from cache and having to re-prime them very frequently and soon afterwards suggests that the configured cache size is too small for the rate and breadth of the query load that the server is handling and you should consider increasing your provisioning. Having the roots deleted from cache, but not needing to prime them again soon, would be an indication that they are seldom needed — very likely because when handling new client queries, named already has in cache a list of the servers authoritative for the TLD within which the domain name being queried falls.

Do all BIND nameservers do root priming?

You can start named with built-in or manually-configured root hints and they will never be used at all if:

  • Your nameserver is authoritative-only and never needs to make any recursive queries (but see: Why does my authoritative-only nameserver try to query the root nameservers?).
  • You are running a nameserver that exclusively uses forwarding to resolve all client queries.
  • You are running a recursive nameserver that never receives any queries at all (this last one included for completeness only — we are not sure why you would be running a recursive nameserver that does not receive any queries).

The first time named needs to resolve a client query or to look up a nameserver that it needs to contact (as part of managing its authoritative zones) it will always initiate root priming.

Can having only a few root servers in cache cause problems?

In most cases no. What happens is that named will re-prime the root server list as and when needed.

Ensure that if your server is IPv6-capable, it is properly configured

If it then happens that all of the IPv4 root nameserver records have expired from cache, but the IPv6 records remain, then named will not yet refresh via re-priming because it believes that it still has servers that are contactable. This situation will persist until the IPv6 server records have also been removed from cache.

(The same scenario is possible with other domains that advertise both IPv4 and IPv6 addresses for their authoritative servers.)

Do I need a root hint zone if I’m using global forwarding?

BIND expects there to be a root hint zone, even if it doesn’t need to use it. 

The combination of forwarding and root hints may produce unexpected or unreliable results

There are some situations where the combination of root hints and forwarding may work well, and some where it will very definitely lead to unpredictable failures. It is important to consider whether the answers to queries will differ depending on the way they are obtained. If it’s possible that different answers are obtained via the two different resolution methods (iteration versus forwarding), and that both are likely to be used in different circumstances to populate the same cache, then we strongly recommend that you do not implement this type of configuration.

Дополнительно:  Не Работает Клавиатура На Ноутбуке - Что Делать? Советы 2018 года

If you are using global forwarding, root priming will anyway most likely fail

When priming the roots, what is needed is a query response from a server that is authoritative for the root zone «.». If your configuration includes global forwarding, the query for the NS records for «.» will be sent to the global forwarders instead of to the servers listed in the hint zone. The global forwarders may be authoritative for «.», or they may instead return a non-authoritative answer from their own caches. In this latter case, the answer will not be authoritative and named will need to try again (only to fail again, etc.).

Forwarding using DNS over TLS

forward-zone: name: "." forward-tls-upstream: yes forward-addr: <Upstream DNS server with TLS support>

Testing validation

To test DNSSEC validation, you can use the dig command with the +dnssec flag:

dig @localhost example.com +dnssec

If the response includes the “ad” flag, it indicates that Unbound has successfully validated the DNSSEC data.

Советы и приёмы

Черный список доменов

Для добавления домена в черный список, используйте строку local-zone: "домен" always_refuse.

Сохраните черный список как отдельный файл (например /etc/unbound/blacklist.conf) для удобности и включите его в файл конфигурации /etc/unbound/unbound.conf, например:

/etc/unbound/blacklist.conf
local-zone: "blacklisted.example" always_refuse
local-zone: "anotherblacklisted.example" always_refuse
/etc/unbound/unbound.conf
server:
...
  include: /etc/unbound/blacklist.conf
  • Если вы хотите возвращать статус OK на определенные имена, вы можете поменять переадресацию с 127.0.0.1 на ваш HTTP сервер который будет отвечать пустым ответом 204, подробнее здесь.
  • Для конвертации стороннего hosts файла в формат unbound, воспользуйтесь следующей командой:
    $ grep '^0\.0\.0\.0' путь_к_hosts_файлу | awk '{print "local-zone: \""$2"\" always_refuse"}' > /etc/unbound/blacklist.conf
  • Список источников для черного списка можно взять со страницы пакета adblock для OpenWrt.

Использование вместе с авторитетный DNS сервером

Важно: Использование двух DNS серверов вместо одного по своей сути не делает систему более безопасной, как описано ниже. Это тема для спора о безопасности использования определенных приложений (в частности BIND) и решений (использующих BIND) затронутых в этом разделе.

Для пользователей, которые желают иметь подтверждающий, рекурсивный и кеширующий DNS сервер вместе с авторитетным на одной машине, может быть полезно обратиться к странице NSD в которой описан пример такой конфигурации. Наличие одного сервера как авторитетный и отдельного для выполнения подтверждения, рекурсии и кеширования повышает уровень безопасности по отношению к единому DNS серверу выполняющему эти функции. Многие пользователи используют Bind в этом случае как единый DNS сервер, и пример для миграции на комбинацию Bind и NDS серверов предоставлен на странице NSD.

Доступ к DNS серверу через WAN интерфейс

Вы можете поменять настройки и прослушиваемые интерфейсы для нужного сервера, чтобы машины за пределами локальной сети могли получить доступ к определенным машинам внутри локальной сети. Это будет полезно для различных веб-сервисов которым нужен доступ извне. Похожий способ использовался с помощью сервера bind в комбинации с использованием перенаправления портов на машинах принимающих запросы для переадресации запросов на нужные машины.

Служба systemd для обновления корневых подсказок

Можете использовать эти примеры для создания systemd службы которая будет обновлять root.hints ежемесячно методом, описанным в разделе #Корневые подсказки (Root hints):

/etc/systemd/system/roothints.service
[Unit]
Description=Update root hints for unbound
After=network.target

[Service]
ExecStart=/usr/bin/curl -o /etc/unbound/root.hints https://www.internic.net/domain/named.cache
/etc/systemd/system/roothints.timer
[Unit]
Description=Run root.hints monthly

[Timer]
OnCalendar=monthly
Persistent=true
 
[Install]
WantedBy=timers.target

Запустите и включите службу roothints.timer.

What is Unbound DNS Server?

With a commitment to enhancing online privacy, Unbound supports DNS-over-TLS and DNS-over-HTTPS, enabling clients to encrypt their communications. Moreover, it embraces various cutting-edge standards that minimize data exchange with authoritative servers, resulting in improved privacy and a more robust DNS. Key advancements include Query Name Minimisation, Aggressive Use of DNSSEC-Validated Cache, and support for authority zones, which facilitate loading a root zone copy.

Validating our setup

dig @localhost example.com

If the response contains an IP address for example.com, your Unbound server is functioning correctly.

Установите пакет .

Дополнительно, пакет требуется для #Проверка достоверности DNSSEC.

Manually specifying DNS servers

forward-zone: name: "." forward-addr: <DNS server 1> forward-addr: <DNS server 2>

Replace <DNS server 1> and <DNS server 2> with the IP addresses of the desired DNS servers.

Setting up unbound-control for remote control

  1. Install the unbound-control package if it’s not already installed.
  2. Run sudo unbound-control-setup to generate the necessary SSL certificates and keys.
    unbound config
  3. Add the following configuration lines to the /etc/unbound/unbound.conf file:
    remote-control: control-enable: yes control-interface: 127.0.0.1 control-port: 8953 server-key-file: "/etc/unbound/unbound_server.key" server-cert-file: "/etc/unbound/unbound_server.pem" control-key-file: "/etc/unbound/unbound_control.key" control-cert-file: "/etc/unbound/unbound_control.pem"
  4. Restart the Unbound server to apply the changes. Now you can use the unbound-control command to manage your Unbound server remotely.

Testing DNSSEC

To test if your Unbound server is correctly performing DNSSEC validation, use the dig command with the +dnssec flag:

dig @localhost example.com +dnssec

If the response contains the “ad” flag, it indicates that Unbound has successfully validated the DNSSEC data for the queried domain.

Testing DNS lookup

After making changes to the Unbound configuration file, testing the DNS lookup functionality is essential to ensure everything works as expected. You can use the dig command to perform a DNS lookup:

dig @localhost example.com

If you receive a valid IP address in the response, your Unbound server is functioning correctly.

DNS change in Drakconnect

nameserver 127.0.0.1

This will configure the system to use the local Unbound server for DNS resolution once you have Unbound installed and configured on the local Mandriva Linux server.

Using Docker Compose

version: '3'

services:

unbound:

image: mvance/unbound

container_name: unbound

volumes:

- /path/to/unbound/config:/opt/unbound/etc/unbound

ports:

- "53:53/tcp"

- "53:53/udp"

restart: always

Replace /path/to/unbound/config with the desired path on your host machine.

docker-compose up -d

These examples demonstrate how to run Unbound DNS with a persistent volume mount using Docker run command and Docker Compose. This ensures that your Unbound configuration files and logs are stored on the host machine and persist even if the container is removed or recreated.

Root hints systemd timer

Keeping the root hints file up-to-date is essential for ensuring the accuracy and efficiency of the DNS resolution process.

  1. Create a script that downloads the latest root hints file:
    ```bash #!/bin/bash wget -O /etc/unbound/root.hints https://www.internic.net/domain/named.cache
  2. Save this script as /usr/local/bin/update-root-hints.sh and make it executable:
    sudo chmod +x /usr/local/bin/update-root-hints.sh
  3. Create a systemd service file /etc/systemd/system/update-root-hints.service with the following content:
    [Unit] Description=Update Unbound root hints [Service] Type=oneshot ExecStart=/usr/local/bin/update-root-hints.sh
  4. Create a systemd timer file /etc/systemd/system/update-root-hints.timer with the following content:
    [Unit] Description=Timer for updating Unbound root hints [Timer] OnCalendar=monthly Persistent=true [Install] WantedBy=timers.target
  5. Enable and start the timer:
    sudo systemctl enable --now update-root-hints.timer
  6. The root hints file will now be updated automatically monthly.

Unbound configuration file

The main configuration file for Unbound is typically located at /etc/unbound/unbound.conf. This file contains various settings and options that control the behavior of the Unbound server. You can customize this file according to your requirements, such as specifying upstream DNS servers, enabling DNS over TLS, and setting access control rules.

Installing Unbound DNS using Docker

Let’s look at how to install Unbound DNS servers using Docker containers. You can use a simple Docker run command or Docker Compose code.

Using Unbound DNS Server in conjunction with Pi-Hole

You can use Unbound as the upstream DNS server for Pi-Hole since Pi-Hole can’t do DNS over HTTPS natively. Both can be run on the same host by way of Docker containers. In your Pi-Hole configuration, you specify Unbound as your upstream DNS server.

Below is a Pi-Hole server pointed to a local Unbound DNS server.

DNSSEC validation

Looking more closely at DNSSEC, what is it exactly? DNSSEC (Domain Name System Security Extensions) is a set of extensions designed to add a layer of security to DNS, providing cryptographic signatures for DNS data. This ensures the authenticity and integrity of the DNS responses.

Root servers

The next important idea to understand with DNS infrastructure is the root server. Root servers, also known as primary root servers, are upstream servers serving as the backbone of the Internet DNS system. They are responsible for providing the initial direction to locate the appropriate authoritative server for the requested domain. There are 13 root servers worldwide, operated by various organizations, and they play a vital role in the functioning of the global DNS system.

Below is an example of the root hints list on a Windows DNS Server. You can see this if you look at the properties of the DNS server and click the Root Hints tab.

Root hints servers on a Windows DNS server

Root servers play a vital role in DNS as they operate in the root zone, the starting point of all DNS lookups. These servers can respond directly to queries for records stored or cached within the root zone and guide other requests to the appropriate Top Level Domain (TLD) server. TLD servers, positioned just below root servers in the DNS hierarchy, are crucial in resolving DNS queries.

Using openresolv

include: /etc/resolvconf/run/resolv.conf resolvconf: yes

Определение нужного количества потоков (num-threads)

В странице man руководства для unbound.conf говорится:

     outgoing-range: <кол-во>
       Количество портов для работы. Это число файлов-дескрипторов которые могут быть использованы на один поток.
       # количество потоков для использования. 1 отключает многопоточность.
       # num-threads: 1

Тем не менее невозможно установить количество потоков больше 1 в строке num-threads без вызывания предупреждений в логах от unbound о превышении количества файлов-дескрипторов. На самом деле для пользователей, использующих unbound для небольших сетей или на одной системе, нет необходимости стремится к увеличению производительности путем включения многопоточности параметром num-threads. Но если вы все таки желаете это сделать, рекомендуется обратиться к официальной документации и выбрать подходящие параметры:

Установите num-threads равное количеству ядер процессора в вашей системе. Например для систем с 4 физическими ядрами поддерживающих гиперпоточность (hyper-threading) используйте 8.

Установите параметр outgoing-range насколько можно большим, смотрите упомянутую выше страницу каким можно преодолеть лимит в 1024. Это позволяет обслуживать большее количество клиентов в единицу времени. Для одного ядра попробуйте 950, для двух 450, для четырех 200. Параметр num-queries-per-thread лучше всего установить в половину от велечины outgoing-range.

Потому как ограничение outgoing-range также ограничивает num-queries-per-thread, лучше всего использовать unbound вместе с библиотекой , тогда не будет ограничения в 1024 параметра outgoing-range. Если вам нужен DNS сервер для большой нагрузки, вам потребуется скомпилировать собственный экземпляр, вместо использования из репозиториев.

Стандартные настройки уже находятся в файле /etc/unbound/unbound.conf. Следующие разделы освещают различные настройки для файла конфигурации. Подробности и другие настройки смотреть в .

Если не указано другое, все нижеописанные опции находятся в секции server конфигурационного файла таким образом:

/etc/unbound/unbound.conf
server:
  ...
  setting: value
  ...

Локальный DNS сервер

Если вы хотите использовать unbound как ваш локальный DNS сервер, установите в строке nameserver loopback адреса 127.0.0.1 и ::1:

/etc/resolv.conf
nameserver ::1
nameserver 127.0.0.1
options trust-ad

Удостоверьтесь, что файл /etc/resolv.conf защищен от записи как описано в Domain name resolution (Русский)#Перезапись файла /etc/resolv.conf.

Дополнительно:  Приложения для root устройств

Совет: Простейший способ сделать это, установить Openresolv (Русский) и настроить /etc/resolvconf.conf данным образом:

/etc/resolvconf.conf
name_servers="::1 127.0.0.1"
resolv_conf_options="trust-ad"

Затем выполнить resolvconf -u чтобы сгенерировать /etc/resolv.conf.

Просмотрите Domain name resolution (Русский)#Утилиты для различных способов проверить ваши настройки

При проверке, удостоверьтесь, что используемый сервер имеет адрес 127.0.0.1 или ::1 после применения изменений в resolv.conf.

В разделе #Переадресация запросов вы можете настроить unbound для переадресации запросов к нужным DNS серверам, если требуется.

Корневые подсказки (Root hints)

Для рекурсивных запросов хоста который не имеет требуемого адреса в кеше, вашему DNS серверу нужно знать адреса корневых DNS серверов, у которых он будет запрашивать адреса DNS серверов доменов верхнего уровня и далее по цепочке, пока не будет достигнут именной сервер, обслуживающий запрашиваемый домен. Для этого требуются корневые подсказки (Root hints), файл содержащий в себе IP адреса корневых DNS серверов. Unbound имеет встроенные корневые подсказки, и если он обновляется регулярно, вмешательства не требуется. С другой стороны хорошей практикой является самостоятельное сопровождение корневых подсказок, так как встроенные могут потерять актуальность.

Для начала укажите unbound путь к файлу root.hints:

root-hints: root.hints

Затем, поместите файл root.hints в директорию unbound. Простой способ сделать это можно этой командой:

# curl --output /etc/unbound/root.hints https://www.internic.net/domain/named.cache

Если вы все таки используете этот файл вместо встроенных корневых подсказок, для поддержания актуальности нужно обновлять root.hints как минимум раз в шесть месяцев. Вы можете делать это вручную или используя Systemd/Timers. Смотрите пример файла службы в разделе #Служба systemd для обновления корневых подсказок.

Проверка достоверности DNSSEC

Для того, чтобы проверять достоверность домена с помощью DNSSEC, в файле конфигурации требуется указать путь файла trust anchor:

/etc/unbound/unbound.conf
  trust-anchor-file: trusted-key.key

Проверка достоверности DNSSEC будет выполнятся только если запрашиваемый DNS сервер поддерживает эту технологию. Если в #Переадресация запросов были указаны сервера, не поддерживающие DNSSEC, все их ответы на запросы будут рассматриваться как небезопасные, так как невозможно доказать обратное.

Примечание: Проверка DNSSEC увеличивает задержку DNS запросов, которые еще не были кешированы.

Для проверки работоспособности DNSSEC, после запуска службы unbound.service выполните:

$ unbound-host -C /etc/unbound/unbound.conf -v sigok.verteiltesysteme.net

В ответе должен быть IP адрес и (secure) после него.

$ unbound-host -C /etc/unbound/unbound.conf -v sigfail.verteiltesysteme.net

Этот ответ должен содержать (BOGUS (security failure)).

Так же вы можете использовать drill для проверки вашего сервера следующими командами:

$ drill sigfail.verteiltesysteme.net
$ drill sigok.verteiltesysteme.net

Первая команда должна в переменной rcode выдать SERVFAIL. Вторая команда должна выдать NOERROR.

Доступ локальной сети к DNS

Если ваш сетевой менеджер поддерживает Openresolv (Русский), вы можете настроить его для предоставления доступа локальных DNS серверов и доменов к Unbound:

/etc/resolvconf.conf
...
private_interfaces="*"

# Путь к конфигурационному файлу для Unbound
unbound_conf=/etc/unbound/resolvconf.conf

Выполните resolvconf -u для внесения изменений.

/etc/unbound/unbound.conf
include: "/etc/unbound/resolvconf.conf"
...
server:
...
	private-domain: "intranet"
	private-domain: "internal"
	private-domain: "private"
	private-domain: "corp"
	private-domain: "home"
	private-domain: "lan"

	unblock-lan-zones: yes
	insecure-lan-zones: yes
...

Вы также можете выключить проверку достоверности DNSSEC для локальных доменов, так как они не могут подтвердить свою достоверность (подробнее RFC 6762 Appendix G):

/etc/unbound/unbound.conf
...
server:
...
	domain-insecure: "intranet"
	domain-insecure: "internal"
	domain-insecure: "private"
	domain-insecure: "corp"
	domain-insecure: "home"
	domain-insecure: "lan"
...
Исключение приватных диапазонов IP адресов из ответов
private-address: локальная_подсеть/маска_подсети

Вы можете добавить эти строки в ваш конфигурационный файл для исключения всего диапазона частных адресов:

private-address:  10.0.0.0/8
private-address:  172.16.0.0/12
private-address:  192.168.0.0/16
private-address:  169.254.0.0/16
private-address:  fd00::/8
private-address:  fe80::/10

Примечание: Блокирование подсети 127.0.0.0/8 может вызвать неполадки в работе приложений, например которые блокируют спам и рекламу. Блокирование подсети ::ffff:0:0/96 не позволяет правильно интерпретировать IPv4 адреса в нотации IPv6.

Стоит заметить, что блокированные с помощью параметра private-address адреса все еще можно получить в ответах от DNS сервера, если они принадлежат доменам из private-domain, либо содержаться в local-data. Поэтому для работоспособности запросов локальных доменов настройте Unbound как указано этом разделе #Используя openresolv.

Добавить локальный DNS сервер

Для использования локального DNS сервер для прямого и обратного поиска локальных адресов добавьте нужные зоны как показано ниже (выберите нужный IP адрес DNS сервера локальной сети вместо адреса 10.0.0.1 указанного ниже):

local-zone: "10.in-addr.arpa." transparent

Данные строки необходима для работы обратного поиска.

forward-zone:
name: "mynetwork.com."
forward-addr: 10.0.0.1
forward-zone:
name: "10.in-addr.arpa."
forward-addr: 10.0.0.1

Примечание: В отличии от зон переадресации (forward-zone), зоны заглушки(stub-zone) будут работать только если они указывают на авторитетный сервер напрямую. Например на BIND сервер если он настроен как авторитетный, но если вы укажите для зоны заглушки, например unbound сервер который переадресует локальные запросы на другой DNS сервер, то работать это не будет и самое главное вы не получите никаких ошибок.

Вы так же можете добавить localhost для переадресации и обратного поиска с помощью следующих строк:

local-zone: "localhost." static
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-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. 2 3600 1200 604800 10800"
local-data: "1.0.0.127.in-addr.arpa. 10800 IN PTR localhost."

Переадресация остальных запросов

Если ваш сетевой менеджер поддерживает Openresolv (Русский), вы можете настроить его для предоставления внешних DNS серверов для Unbound:

/etc/resolvconf.conf
...
# Путь к конфигурационному файлу для Unbound
unbound_conf=/etc/unbound/resolvconf.conf

Выполните resolvconf -u для внесения изменений.

include: "/etc/unbound/resolvconf.conf"
Ручное указание DNS серверов

Для использования серверов для стандартных зон переадресации, которые находятся за пределами локальной машины и сети, добавьте зону переадресации с именем . в ваш конфигурационный файл. В этом примере все запросы переадресуются на DNS сервера Google:

forward-zone:
  name: "."
  forward-addr: 8.8.8.8
  forward-addr: 8.8.4.4

Переадресация через DNS over TLS

Для использования DNS over TLS необходимо указать параметру tls-cert-bundle путь до системного корневого набора сертификатов, что позволит Unbound переадресовывать TLS запросы и использовать сервера с технологией DNS over TLS .

/etc/unbound/unbound.conf
...
server:
...
	tls-cert-bundle: /etc/ssl/certs/ca-certificates.crt
...
forward-zone:
        name: "."
        forward-tls-upstream: yes
        forward-addr: 1.1.1.1@853#cloudflare-dns.com

Вы можете указать интерфейсы, на которые будет отвечать сервер с помощью IP адреса. По умолчанию принимает запросы только от localhost.

Для прослушивания всех интерфейсов, используйте следующую строку:

interface: 0.0.0.0

Для определения доступа к серверу определенным IP адресам используйте опцию access-control:

access-control: подсеть действие
access-control: 192.168.1.0/24 allow

действие может быть одним из: deny (игнорирует запросы), refuse (отвечает ошибкой), allow (разрешает рекурсивные запросы), allow_snoop (разрешает рекурсивные и остальные запросы) По умолчанию игнорируются все запросы, кроме от localhost.

How does DNS work?

At the DNS system’s core are authoritative DNS servers and recursive DNS resolvers. Authoritative servers contain the definitive mapping of domain names to IP addresses, while recursive resolvers query these servers to obtain the required information. DNS queries, DNS messages, and responses are exchanged between the recursive resolver and the authoritative servers until the final IP address is resolved.

You can point clients to your own recursive DNS server or other DNS servers. Many will point to their own DNS server to resolve authoritative DNS server internal DNS zones that may be configured.

Windows DNS Server with local zones

Installing Unbound DNS using apt install

sudo apt install unbound

This will install Unbound and its dependencies on your system. Once the installation is complete, you can proceed with the configuration.

How does Unbound work?

Unbound can be configured as a local DNS server or a recursive DNS resolver, improving your DNS infrastructure’s performance and security. You can also use it along with other security solutions like Pi-Hole.

Запустите и включите службу unbound.service.

Удаленное управление Unbound

В составе unbound присутствует утилита unbound-control которая позволяет удаленно контролировать сервер unbound. Команды схожи с pdnsd-ctl пакета .

Перед тем, как начать, необходимо выполнить следующие шаги:

1) Для начала выполните следующую команду

# unbound-control-setup

которая сгенерирует пару самоподписанных сертификатов и ключей для сервера и клиента. Они будут находится в директории /etc/unbound.

2) После, отредактируйте /etc/unbound/unbound.conf используя следующий пример. Опция control-enable: yes обязательная, остальное можете настроить как необходимо вам.

remote-control:
    # Включает удаленный доступ с помощью unbound-control(8).
    # настройте ключи и сертификаты с помощью команды unbound-control-setup.
    control-enable: yes
   
    # Интерфейс, с которого будет происходить управление
    # задайте 0.0.0.0 и ::0 для прослушивания всех интерфейсов.
    control-interface: 127.0.0.1
   
    # номер порта для удаленного доступа.
    control-port: 8953
   
    # ключ unbound сервера.
    server-key-file: "/etc/unbound/unbound_server.key"
   
    # сертификат unbound сервера.
    server-cert-file: "/etc/unbound/unbound_server.pem"
   
    # ключ для unbound-control.
    control-key-file: "/etc/unbound/unbound_control.key"
   
    # сертификат для unbound-control.
    control-cert-file: "/etc/unbound/unbound_control.pem"

Список команд, которые вы можете использовать для unbound-control:

  • выводит статистику не сбрасывая ее
 # unbound-control stats_noreset
  • выводит кеш в стандартный вывод
 # unbound-control dump_cache
  • Очищает кеш и перезагружает настройки
 # unbound-control reload

Обратитесь к для подробностей и поддерживаемых команд.

Using Docker run command

First, create a directory on the host machine to store Unbound configuration files and logs:

mkdir -p /path/to/unbound/config

Replace /path/to/unbound/config with the desired path on your host machine.

Next, run the Unbound container using the docker run command and mount the host directory to the container’s /opt/unbound/etc/unbound directory:

docker run -d --name unbound \ -v /path/to/unbound/config:/opt/unbound/etc/unbound \ -p 53:53/tcp -p 53:53/udp \ --restart=always \ mvance/unbound

Local DNS server

Unbound can be configured as a local DNS server, providing DNS resolution services to devices on your local network. This can improve the performance and security of your DNS infrastructure, as Unbound can cache DNS responses and perform DNSSEC validation.

Tips and tricks

To blacklist a domain, use local-zone: "domainname" always_refuse.

Save the blacklist as a separate file (e.g. /etc/unbound/blacklist.conf) for ease of management and include it from /etc/unbound/unbound.conf. For example:

/etc/unbound/blacklist.conf
local-zone: "blacklisted.example" always_refuse
local-zone: "anotherblacklisted.example" always_refuse
/etc/unbound/unbound.conf
server:
...
  include: /etc/unbound/blacklist.conf
  • In order to return some OK statuses on those hosts, you can change the 127.0.0.1 redirection to a server you control and have that server respond with empty 204 replies, see this page
  • To convert a hosts file from another source to the unbound format do:
    $ grep '^0\.0\.0\.0' hostsfile | awk '{print "local-zone: \""$2"\" always_refuse"}' > /etc/unbound/blacklist.conf
  • A list of potential sources for the blacklist can be found in OpenWrt’s adblock package’s README.

Tango-inaccurate.pngThe factual accuracy of this article or section is disputed.Tango-inaccurate.png

WAN facing DNS

It is also possible to change the configuration files and interfaces on which the server is listening so that DNS queries from machines outside of the local network can access specific machines within the LAN. This is useful for web and mail servers which are accessible from anywhere, and the same techniques can be employed as has been achieved using bind for many years, in combination with suitable port forwarding on firewall machines to forward incoming requests to the right machine.

Roothints systemd timer

Here is an example systemd service and timer that update root.hints monthly using the method in #Root hints:

/etc/systemd/system/roothints.service
[Unit]
Description=Update root hints for unbound
After=network.target

[Service]
ExecStart=/usr/bin/curl -o /etc/unbound/root.hints https://www.internic.net/domain/named.cache
/etc/systemd/system/roothints.timer
[Unit]
Description=Run root.hints monthly

[Timer]
OnCalendar=monthly
Persistent=true
 
[Install]
WantedBy=timers.target

Start/enable the roothints.timer systemd timer.

Keeping DNS cache always up to date

unbound supports prefetching where cached DNS entries are automatically updated before they expire to keep the cache always up to date. To quote the man page, turning it on gives about 10 percent more traffic and load on the machine, but popular items do not expire from the cache. This is particularly useful on mobile links with high RTT.

To enable prefetching, add this under the server section:

prefetch: yes

Оцените статью
Master Hi-technology
Добавить комментарий