Некоторые по ошибке называют Unbound DNS Resolver ДНС сервером. Разница между DNS Resolver и DNS Server в том, что Resolver является посредником между приложением, которое запрашивает ДНС записи и ДНС сервером, второй же (держатель/сервер зоны, он же и резолвер в одной проге) служит для полноценного обслуживания доменных имен/зон с поддержкой всех типов ДНС записей (A, TXT, SOA, PTR etc).
ДНС сервера провайдера или других поставщиков могут быть ненадёжны, а поэтому лучше использовать так называемые корневые ДНС сервера ака «Root Servers» от первоисточника IANA (Администрация адресного пространства Интернет — Internet Assigned Numbers Authority) с которого по идее должны обновляться и ДНС сервера нашего провайдера. Более того, все ДНС запросы регистрируются у нашего Интернет провайдера, а лучше будет если они будут регистрироваться где-то в другом месте/стране.
Unbound это кэширующий DNS ресолвер (не ДНС сервер!) который служит для обслуживания рекурсивных запросов. Во процессе своей работы свой кэш он целиком хранит в оперативной памяти, лимит которой ограничивается директивой «key-cache-size: 4m«. Unbound поддерживает расширение DNSSEC и способен работать как «validator».
К плюсам Unbound ресолвера, в сравнении с ДНС серверами типа BIND, можно отнести скорость работы и малый размер. На официальном сайте есть сравнительная информация популярных DNS серверов по количеству обработанных запросов:
Server Queries/sec (10 clients) Unbound 8 276 MaraDNS 3 068 BIND 3 003 dnscache 2 928 PowerDNS Recursor 2 074
Установка и настройка unbound под Windows XP
Загрузить unbound-ххх.zip, распаковать, переименовать каталог unbound-ххх в Unbound и передвинуть в C:\Program Files\Unbound (именно в этот каталог программа смотрит по умолчанию), добавить в конец файла service.conf строку «do-ip6: no» для отключения протокола ip6 (пока не на всех ОС установлен/поддерживается).
Загрузить named.root, переименовать его в named.cache и переместить его в C:\Program Files\Unbound. Открыть консоль и перейти в cd /d "c:\Program Files\Unbound\", после чего установить Unbound как службу выполнив unbound-service-install.exe
Теперь, если мы хотим использовать DNSSEC, то из каталога cd /d "c:\Program Files\Unbound\" нам нужно выполнить файл unbound-anchor.exe, который проверит наличие/доступность root.key и обновит/создаст его примерно с таким содержимым:
; autotrust trust anchor file ;;id: . 1 ;;last_queried: 1364027536 ;;Sat Mar 21 11:01:27 2013 ;;last_success: 1364027536 ;;Sat Mar 21 11:01:27 2013 ;;next_probe_time: 1364071854 ;;Sat Mar 22 22:50:54 2013 ;;query_failed: 0 ;;query_interval: 43200 ;;retry_time: 8640 . 172800 IN DNSKEY 257 3 8 AwEAAagAIKlVZrpC6Ia7gEzahOR+9WPOJKD098y489hfsk\ sd'f-4gcCjFFVQUTf6v58fLjwBd0YI0\ EzrAcQqBGCzh/RKJFD)S*FYER(HSDJFDKDOPFJIODSHFERFGIDSHFDIBV78egf8w/VHL496M/\ QZxkjf5/Efucp2gaDX6RS6CXpoY68LsvPVjR0ZSwzz1apAzvN9dlzEheX7ICJBBtuA6G3LQpzW\ 5hOA2hzCTMjJPJ8LbqF6dsV6DoBQzgul0sGIcGOYl7OyQdXfZ57relSQageu+ipAdTTJ25AsRT\ Aoub8ONGcLmqrAmRLKBP1dfwhYB4N7knNnulqQxA+Uk1ihz0= ;{id = 19036 (ksk), size\ = 2048b} ;;state=2 [ VALID ] ;;count=0 ;;lastchange=1364027536 ;;Sat Mar \ 21 11:01:27 2013
Теперь в service.conf нужно явно указать строку «auto-trust-anchor-file: «C:\Program Files\Unbound\root.key»» или «trust-anchor: «. IN DS 19036 8 2 49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5«», запустить сервис «Unbound DNS validator«, а иначе лыжи не поедут и DNSSEC не будет работать! Проверить можно выполнив команду dig com. SOA +dnssec, в результате мы должны видеть наличие флага AD в строке «;; flags: qr rd ra ad;«:
>dig com. SOA +dnssec ; <<>> DiG 9.3.2 <<>> com. SOA +dnssec ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 230 ;; flags: qr rd ra ad; QUERY: 1, ANSWER: 2, AUTHORITY: 14, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags: do; udp: 4096 ;; QUESTION SECTION: ;com. IN SOA ;; ANSWER SECTION: com. 900 IN SOA a.gtld-servers.net. nstld.verisi gn-grs.com. 1364032049 1800 900 604800 86400 com. 900 IN RRSIG SOA 8 1 900 20130330094729 20130 323083729 23975 com. EBxeTAIHI4Gooj8J+k5L8WRo6GKMFvj8B/nygRxduUc/pihyXYy9XWUa aj xdiy1cr+NktjVZFWKQDFVZGstsmm1Vc/WbajggY9qyV2eJXg0Kd4BF 2S/rEW/kjdYU3qeaurDH8SKpj GhyR00haELra6Ed57k/ke8DN6MyxZ4/ 3WQ= ;; AUTHORITY SECTION: com. 172800 IN NS e.gtld-servers.net. com. 172800 IN NS m.gtld-servers.net. com. 172800 IN NS i.gtld-servers.net. com. 172800 IN NS k.gtld-servers.net. com. 172800 IN NS l.gtld-servers.net. com. 172800 IN NS c.gtld-servers.net. com. 172800 IN NS h.gtld-servers.net. com. 172800 IN NS b.gtld-servers.net. com. 172800 IN NS f.gtld-servers.net. com. 172800 IN NS j.gtld-servers.net. com. 172800 IN NS g.gtld-servers.net. com. 172800 IN NS d.gtld-servers.net. com. 172800 IN NS a.gtld-servers.net. com. 172800 IN RRSIG NS 8 1 172800 20130327041900 201 30320030900 23975 com. pzdn+HfS1clWqjvnbGgg0Yesi/4MjV7sdiNsfS1tAmMIaxpCAAM37WeE 8UXc3umlh3McIYywFPIxBEqI9dBw2iUAhrdFUQ8kS2M3BA1p/s5By5He 3gx7u6xFu6rLfRXKpxwfvqW 77FCqMkdeo3bOtsxBES6RDvuJxJUmOZ2P 6JU= ;; Query time: 609 msec ;; SERVER: 127.0.0.1#53(127.0.0.1) ;; WHEN: Sat Mar 23 11:47:46 2013 ;; MSG SIZE rcvd: 637
dig есть и для Windows. Более наглядно проверить используем ли мы DNSSEC можно вот по этой ссыле, если нет, то мы увидим надпись «No, you are not using DNSSEC«, а под нею мужичка в печали взявшегося за репу:)
А если да, то видим мессагу «Yes, you are using DNSSEC«, а под ней радостного чувачка:)
Полный конфиг, работающей па моём ПК конфигурации Unbound DNS Resolver ака DNSSEC, представлен ниже:
unbound.exe вешает CPU (процессор)
По умолчанию unbound работает ака «module-config: «validator iterator»» и при запросе доменного имени пытается выстроить из имеющихся в списке «Root Servers» так называемую цепочку доверия «chain of trust» для запрошенного домена, в ходе построения которой unbound.exe может отнимать много времени центрального процессора, а если в service.conf мы установили «val-log-level: 2» повышенный уровень для сообщений, то в сисьлоге мы увидим: [unbound:0] info: validation failure <s20.rimg.info. A IN>: No DNSKEY record for key info. while building chain of trust
Тобишь если заметили, что unbound.exe вешает CPU, то значит в данный момент происходит «while building chain of trust» — смотрим на время в которое unbound.exe подвесил CPU, потом заглядываем в сисьлог. После облома «while building chain of trust» запрос будет закэширован и проц. больше вешаться не должен.
Это может происходить из-за того, что фаервол блокирует исходящие запросы по протоколу TCP на 53 порт (проверьте логи фаервола!) и если нет возможности разрешить TCP на 53 порт, то в service.conf нужно добавить «do-tcp: no» — т.е. отключить TCP для unbound.
Проблему с большой загрузкой ещё можно урегулировать директивами «outgoing-range: ..» (количество портов выделяемых на поток) и «target-fetch-policy: …» (глубина запросов).
unbound.exe не отвечает на запросы
Может быть так, что unbound.exe перестал отвечать на запросы, а в ответ на whois в консоль можем получить «Затребованное имя допустимо и оно найдено в базе данных, но для имени отсутствуют связанные с ним данные, которые были разрешены для него.«.
unbound.exe работает нормально, слушает 53 порт, но на запросы не отвечает. Перезапуск сервиса не помогает, перезагрузка ОС тоже не помогает и мы продолжаем получать «Затребованное имя допустимо и оно найдено в базе данных, но для имени отсутствуют связанные с ним данные, которые были разрешены для него.«.
Причиной сего бага может быть глюк брандмауэра или какого-то Интернет-секюрити (если установлен). В моём случае смена режимов брандмауэра с «Пользовательский» на «Неактивен» и обратно решило проблему.
Блокируем скрытые «сервисы» в \etc\hosts
Теперь не помешает заглушить так называемые вредные скрытые сервисы *.onion и *.i2p (i2p — Invisible Internet Project) добавив в c:\WINDOWS\system32\drivers\etc\hosts такие строки:
127.0.0.2 idnxcnkne4qt76tg.onion 127.0.0.2 j6im4v42ur6dpic3.onion 127.0.0.2 p3igkncehackjtib.onion 127.0.0.2 vwp5zrdfwmw4avcq.onion 127.0.0.2 p4fsi4ockecnea7l.onion 127.0.0.2 37lnq2veifl4kar7.onion 127.0.0.2 3g2upl4pq6kufc4m.onion 127.0.0.3 i2p2.i2p 127.0.0.3 i2p-projekt.i2p 127.0.0.3 plugins.i2p 127.0.0.3 echelon.i2p 127.0.0.3 postman.i2p 127.0.0.3 freshcoffee.i2p 127.0.0.3 mail.i2p 127.0.0.3 zzz.i2p 127.0.0.3 killyourtv.i2p 127.0.0.3 eepsites.i2p 127.0.0.3 i2pbote.i2p 127.0.0.3 false.i2p 127.0.0.3 forum.i2p 127.0.0.3 pastethis.i2p 127.0.0.3 ugha.i2p 127.0.0.3 planet.i2p 127.0.0.3 stats.i2p 127.0.0.3 inr.i2p
Итоги
Unbound DNS Resolver хорошее решение для обеспечения целостности ДНС запросов и на мой взгляд является лучшим из существующих фрии DNS Resolver. На Unbound я наткнулся, когда искал пути перенаправления ДНС запросов через прокси, а соксификаторы и прочие геморройные утилы меня как-то не особо привлекали.
В браузерах Mozilla Firefox можно использовать родное решение для использования ДНС через socks прокси, в настройках about:config нужно установить network.proxy.socks_remote_dns = true. В браузере Google Chrome якобы есть предположение (маловероятное), что для этого же эффекта нужно отключить DNS prefetching (упреждающее чтение DNS) в расширенных настройках Google Chrome или добавить флаг «-dns-prefetch-disable» при запуске из командной строки.
Сслки по теме DNSSEC
- doc/DnsResolver – Tor Bug Tracker & Wiki
- Unbound: Howto enable DNSSEC
- DNSSEC — Википедия
- Features/DNSSEC — FedoraProject
- I2P — Википедия
- I2P Anonymous Network — I2P
- .onion — Википедия
Олег Головский
How to Install Unbound on Windows 10
Unbound is a free, open-source Domain Name System (DNS) server which is designed to be fast and secure. It can be used to improve performance and privacy of DNS queries on your Windows 10 computer.
Here’s how to install Unbound on Windows 10:
Step 1: Download Unbound
To begin, download the latest version of Unbound for Windows from the official website http://unbound.net/download.html.
Step 2: Extract the Zip File
Once the download is complete, extract the contents of the zip file to a folder of your choice.
Step 3: Set Up Configuration File
Next, open the unbound.conf file located in the unbound-x.x.x\etc folder. This file contains the configuration settings for Unbound.
You can use the default configuration or modify it according to your preferences. Once you are done with the configuration, save the document.
Step 4: Start Unbound
To start Unbound, go to the extracted folder location and click on the unbound.exe file. This will start the DNS server and it will begin listening to DNS queries.
Step 5: Test Unbound
To make sure that Unbound is working properly, open a command prompt and type:
nslookup <your domain>
If you see the IP address of the domain you entered, this means that Unbound is working properly.
Conclusion
This concludes the installation of Unbound on Windows 10. You can now enjoy faster and more secure DNS queries on your computer.
If you want to self-host in an easy, hands free way, need an external IP address, or simply want your data in your own hands, give IPv6.rs a try!
Alternatively, for the best virtual desktop, try Shells!
unbound — Unbound DNS
This is a transcript (and/or step-by-step guide) how to setup up an Unbound DNS server for a home or small business environment.
Pre-checks
Ubuntu or Debian Server
Setup a standard installation of a Ubuntu 22.04 Server (LTS) or Debain 10/11 Server and make sure to do apt update
and apt upgrade
. Of course you can use other Linux distros,but the file location mentioned in this document might be different.
DNS Stub Listener
Ubuntu and maybe also other Linux distro use a local DNS Stub Listener which per default listens on port 53. If this is the case a DNS server can’t be setup as it needs to listen on the default DNS port 53. So the DNS Stub Listener needs to be disabled on this system.
Disable DNS Stub Listener in systemd-resolve daemon:
— Check if systemd-resolve is running by doing lsof -i -N -P
and check port 53
— Disable systemd-resolve by editing /etc/systemd/resolved.conf
and setting DNSStubListener=no
— Restart systemd-resovle with: systemctl restart systemd-resolved.service
Timezone
This is optional but it’s recommended to set your timezone correct so when reading logfiles the timestamps match up with the real local time.
— Check timezone with: timedatectl status
— Set with: timedatectl set-timezone Europe/Berlin
System settings
This should be adjusted according to the settings in unbound.conf.
File: /etc/sysctl.d/unbound.conf
:
# Adjust this to what you set in unbound.conf
# This is for setting so-rcvbuf and so-sndbuf: 8m (8 x 1024 x 1024) in bytes
net.core.rmem_max=8388608
net.core.wmem_max=8388608
Install
- Install:
sudo apt install unbound
- Setup primary root DNS Servers (root.hints)
- Unbound has a list in it’s code but it’s good to update every six months
- Get latest root-hints:
curl -Lo /var/lib/unbound/root.hints https://www.internic.net/domain/named.cache
- Change owner:
chown unbound:unbound /var/lib/unbound/root.hints
- Setup certificate for DNSSEC (root.key) (Note: might have be done by installer already)
- Get auto-trust-anchor for DNSSEC:
unbound-anchor -a /var/lib/unbound/root.key chown unbound:unbound /var/lib/unbound/root.key chmod 500 /var/lib/unbound/root.key
- Check with:
unbound-anchor -l
- Optional: start unbound control:
unbound-control start
Regular updates
The root.hints file doesn’t change very often but it’s a good idea to pull a regular update.
To do this edit cron with crontab -e
:
# m h dom mon dow command
0 0 * * * /usr/local/bin/update-unbound.sh
This will run the command daily at midnight.
/usr/local/bin/update-unbound.sh
curl https://www.internic.net/domain/named.cache -o /var/lib/unbound/root.hints
chown unbound:unbound /var/lib/unbound/root.hints
Check crontab configuration with crontab -l
.
Configuration
The main unbound configuration file is /etc/unbound.conf
. This file will source all configuration files from /etc/unbound/unbound.conf.d/
. It’s best practice to add a separate file with you specific configuration to the unbound.conf.d directory.
The complete configuration file can be found in the code section here: aschmid-it.conf
Here are a couple important sections:
Interface and protocol
It’s important you to choose the correct interface address to listen on. In below 0.0.0.0
is select which means it will listen on all network interface. You can specify a specific interface but be careful not to use 127.0.0.0
because then unbound will only listen to requests from localhost and will not be reachable by other systems.
# specify the interfaces to answer queries from by ip-address. The default
# is to listen to localhost (127.0.0.1 and ::1). specify 0.0.0.0 and ::0 to
# bind to all available interfaces. specify every interface[@port] on a new
# 'interface:' labeled line. The listen interfaces are not changed on
# reload, only on restart.
interface: 0.0.0.0
interface: ::0
# port to answer queries from
port: 53
# Enable IPv4, "yes" or "no".
do-ip4: yes
# Enable IPv6, "yes" or "no".
do-ip6: yes
# Enable UDP, "yes" or "no".
do-udp: yes
# Enable TCP, "yes" or "no". If TCP is not needed, Unbound is actually
# quicker to resolve as the functions related to TCP checks are not done.i
# NOTE: you may need tcp enabled to get the DNSSEC results from *.edu domains
# due to their size.
do-tcp: yes
Access control
Make sure that this section enables the networks from which you want to access your unbound server. If the correct networks are not enabled unbound will block requests and hence you not get you DNS server to answer requests.
# control which client ips are allowed to make (recursive) queries to this
# server. Specify classless netblocks with /size and action. By default
# everything is refused, except for localhost. Choose deny (drop message),
# refuse (polite error reply), allow (recursive ok), allow_snoop (recursive
# and nonrecursive ok)
access-control: 127.0.0.0/8 allow
access-control: 10.0.0.0/8 allow
access-control: 192.168.0.0/16 allow
access-control: fe80::/8 allow
access-control: fd00:192:168:10::/64 allow
access-control: 2003:db::/16 allow
Local network
private-domain: "home.lan"
domain-insecure: "home.lan" # stop DNSSEC validation for this zone
domain-insecure: "168.192.in-addr.arpa."
local-zone: "168.192.in-addr.arpa." nodefault
stub-zone:
name: "home.lan"
stub-addr: 192.168.1.1
stub-tls-upstream: no
stub-zone:
name: "168.192.in-addr.arpa."
stub-addr: 192.168.1.1
stub-tls-upstream: no
stub-zone:
name: "8.6.1.0.2.9.1.0.0.0.d.f.ip6.arpa."
stub-addr: fd00:192:168:1:1111:2222:3333:4444
stub-tls-upstream: no
stub-zone:
name: "b.d.0.0.3.0.0.2.ip6.arpa."
stub-addr: fd00:192:168:1:1111:2222:3333:4444
stub-tls-upstream: no
DNS-over-TLS (DOT) Configuration
First enable DOT:
# Enable DoT in Unbound
tls-upstream: no # enabling here will enable for all, use forward-tls-upstream and stub-tls-upstream instead per zone
tls-cert-bundle: "/etc/ssl/certs/ca-certificates.crt"
Then configure DOT:
# If you do not want to use the root DNS servers you can use the following
# forward-zone to forward all queries to Google DNS, OpenDNS.com or your
# local ISP's dns servers for example. If use use forward-zone you must make
# sure to comment out the auto-trust-anchor-file directive above or else all
# DNS queries will fail. We highly suggest using Google DNS as it is
# extremely fast.
#
forward-zone:
name: "."
# forward-addr: 8.8.8.8 # Google Public DNS
# forward-addr: 4.2.2.4 # Level3 Verizon
# forward-addr: 74.207.247.4 # OpenNIC DNS
# forward-addr: 1.1.1.1 # Cloudflare
#
# DoT Resolvers - General
forward-tls-upstream: yes
forward-addr: 1.1.1.2@853#security.cloudflare-dns.com
forward-addr: 1.0.0.2@853#security.cloudflare-dns.com
forward-addr: 2606:4700:4700::1112@853#security.cloudflare-dns.com
forward-addr: 2606:4700:4700::1002@853#security.cloudflare-dns.com
forward-addr: 208.67.220.220@853#dns.opendns.com
forward-addr: 208.67.222.222@853#dns.opendns.com
forward-addr: 2620:119:53::53@853#dns.opendns.com
forward-addr: 2620:119:35::35@853#dns.opendsn.com
Log settings
# log verbosity
verbosity: 1
# Logging
use-syslog: no # if set to yes logfile is overwritten, default is yes
logfile: /var/log/unbound/unbound.log
log-time-ascii: yes # Logs time in ascii instead of epoch, default is no
log-queries: no
log-replies: yes
log-tag-queryreply: yes # Adds tags query and reply to log files, default is no
log-local-actions: yes # Logs lines to inform about local action, e.g. local-zone
# log-servfail: no # logs why queries failed
Monitoring
If you want to remotely monitor your unbound server with something like Prometheus make sure to include:
remote-control:
control-enable: yes
Check configuration
To validate the configuration file you can use unbound-checkconf
.
This will validate that the syntax of the configuration file is correct and prevent any errors when starting or re-starting unbound.
Logging DNS requests
To get some insight and keep DNS information you can enable logging on the unbound server.
Logfile
- If using a logfile first create:
mkdir /var/log/unbound chown unbound:unbound /var/log/unbound/ touch /var/log/unbound/unbound.log chown unbound:unbound /var/log/unbound/unbound.log
- Then fix appamor (Ubuntu only):
/etc/apparmor.d/local/usr.sbin.unbound
# Site-specific additions and overrides for usr.sbin.unbound. # For more details, please see /etc/apparmor.d/local/README. /var/log/unbound/unbound.log rw,
- Parse new config:
apparmor_parser -r /etc/apparmor.d/usr.sbin.unbound
- Restart:
systemctl restart unbound
Logfile rotation
- Make sure the config file contains:
logfile: /var/log/unbound.log
log-queries: yes
- Rotate logs via logrotate
- Create file:
/etc/logrotate.d/unbound
# A Schmid IT - Rotate unbound logs
/var/log/unbound/unbound.log {
daily
rotate 90
misingok
notifempty
# compress
# delaycompress
sharedscripts
create 644 unbound unbound
postrotate
/usr/sbin/unbound-control log_reopen
endscript
}
- Check:
logrotate /etc/logrotate.conf --debug
Logfile Syntax
<!-- queries -->
<rule id="unbound-query" class='system' provider='syslog-ng'>
<patterns>
<pattern>@ESTRING:PID: @@ESTRING:SEVERITY: @@ESTRING:CLIENTIP: @@ESTRING:NAME: @@ESTRING:TYPE: @@ESTRING:CLASS: @@ESTRING:RETURN_CODE: @@FLOAT:TIME_TO_RESOLVE:@ @NUMBER:FROM_CACHE:@ @NUMBER:RESPONSE_SIZE:@</pattern>
</patterns>
<tags><tag>query</tag></tags>
</rule>
(...)
<!-- redirect queries (AD Blocklists) -->
<rule id="unbound-redirect" class='system' provider='syslog-ng'>
<patterns>
<pattern>@ESTRING:PID: @@ESTRING:SEVERITY: @@ESTRING:NAME: @redirect @IPvANY:CLIENTIP:@@@@NUMBER:PORT:@ @ESTRING:NAME: @@ESTRING:TYPE: @@STRING:CLASS:@</pattern>
</patterns>
<tags><tag>redirect</tag></tags>
</rule>
Acknowledgement
This was put together by using the helpful information from several sources:
- DNSWATCH: (https://dnswatch.com/dns-docs/UNBOUND/)
- Calomel: (https://calomel.org/unbound_dns.html)
- Blocklists: (https://github.com/hagezi/dns-blocklists)
Минимальная настройка DNS-сервера unbound.
Небольшая заметка для себя, чтобы не забыть. Информацию брал опять же по инструкциями из интернета и из руководства самой программы.
Почему unbound? Ну просто захотел unbound и всё тут.
Цель поднятия сервера — кэширующий сервер для VPN. Т.е. нужна какая-то служба, которая будет работать на том же хосте и заниматься разрешением имён. Никакими зонами сервер заведовать не будет, но при этом наружу он торчать тоже не должен.
Установка сервера:
sudo apt install unbound
Теперь надо дописать конфигурационный файл для реализации заданных условий. У меня получилось примерно так «/etc/unbound/unbound.conf.d/00-conf.conf«:
# Параметры сервера server: # Писать в лог только ошибки verbosity: 0 # Стандартный порт для DNS port: 53 # Интерфейсы, на которых будет открыт порт interface: 127.0.0.1 interface: 10.118.0.1 interface: 10.128.0.1 # Интерфейс, через который будут передаваться запросы # на другие DNS-серверы outgoing-interface: 0.0.0.0 # Список доступа access-control: 10.128.0.0/24 allow access-control: 10.118.0.0/24 allow access-control: 127.0.0.0/8 allow # Явное разрешение работать на всех протоколах do-ip4: yes do-ip6: yes do-udp: yes do-tcp: yes # Настройка удалённого управления remote-control: # включение функции удалённого управления control-enable: yes control-interface: 127.0.0.1
Ключи шифрования будут сохранены со стандартными именами, поэтому в секции «remote-control» они не указываются.
Для функционирования управления unbound с помощью команды «unbound-control» необходимо сгенерировать ключи шифрования командой «unbound-control-setup«.
После всех манипуляций надо перезапустить сервер:
sudo systemctl restart unbound
Теперь необходимо проверить работоспособность сервера.
Сначала разрешение имён через него:
$ nslookup ya.ru 127.0.0.1 Server: 127.0.0.1 Address: 127.0.0.1#53 Non-authoritative answer: Name: ya.ru Address: 87.250.250.242 Name: ya.ru Address: 2a02:6b8::2:242
Потом работоспособность удалённого управления:
$ sudo unbound-control status version: 1.9.0 verbosity: 1 threads: 1 modules: 3 [ subnet validator iterator ] uptime: 1156 seconds options: reuseport control(ssl) unbound (pid 23488) is running...
—>
DNS Filtering with Unbound (and general DNS stuff)
We want to serve DNS for LAN clients, but block or redirect results for certain domains (advertisements, maleware, etc.).
(See how to do something similar in a slightly lighter-weight way with dnsmasq.)
Refresher on DNS Basics
A DNS server can be either authoritative or recursive.
An authoritative DNS server returns DNS records for its domain of authority (its zone). Authoritative DNS servers are hierarchical. The ICANN root DNS servers sit at the top of the hierarchy, followed by the TLD nameservers (e.g. “.com”), followed by authoritative nameservers for second-level domains (“example.com”), etc.
A recursive DNS server queries other nameservers (moving as far through the hierarchy of authoritative nameservers as necessary) on behalf of clients. It caches results, only hitting other nameservers for new lookups or when the TTL of a cached record expires.
Installing and Activating Unbound
On Debian, we install Unbound as a package:
# apt-get install unbound
…and edit /etc/unbound/unbound.conf
.
On FreeBSD 10.1 and later, Unbound is installed by default.
% uname -sr
FreeBSD 10.3-RELEASE-p7
% whereis unbound
unbound: /usr/sbin/unbound /usr/share/man/man8/unbound.8.gz /usr/ports/dns/unbound
# sysrc local_unbound_enable=YES
local_unbound_enable: NO -> YES
# service local_unbound start
Performing initial setup.
Extracting forwarders from /etc/resolv.conf.
/var/unbound/forward.conf created
/var/unbound/lan-zones.conf created
/var/unbound/control.conf created
/var/unbound/unbound.conf created
/etc/resolvconf.conf created
original /etc/resolv.conf saved as /etc/resolv.conf.20160826.095904
Starting local_unbound.
FreeBSD has the shell script local-unbound-setup
that does magic things to auto generate unbound.conf
.
Double-check its output, especially since it sets up any nameservers found in /etc/resolv.conf
as forwarders, which is often not what we want; it may be necessary to edit any nameservers apart from 127.0.0.1
out of /etc/resolv.conf
, delete /var/unbound/forwarders.conf
, and re-run /usr/sbin/local-unbound-setup
.
Because we want to provide name service to our LAN(s), create /var/unbound/conf.d/lan-allow.conf
:
server:
interface: 10.0.1.1
interface: 10.0.2.1
access-control: 10.0.1.0/24 allow
access-control: 10.0.2.0/24 allow
If the box gets its address via DHCP, resolvconf
might overwrite /etc/resolv.conf
. In this case, override the DHCP nameservers in /etc/dhcpclient.conf
:
interface "em0" {
supersede domain-name-servers 127.0.0.1
}
On FreeBSD the service is called local_unbound
, so:
# service local_unbound restart
If we’re handing out DHCP leases from FreeBSD, we may want to edit /usr/local/etc/dhcpd.conf
to hand out our new nameserver:
option domain-name-servers 10.0.1.1;
and restart the daemon:
# service isc-dhcpd restart
Blocking
In unbound.conf
:
include: /etc/unbound/blacklist.conf
The format of the blacklist file:
local-zone: "example.com" refuse
The first line of the blacklist.conf
file should be:
server:
To periodically update our blacklist, we can have cron run something like this script:
#!/bin/sh
curl --silent --user username:*********** --output /tmp/dg-ads.tar.gz http://www.squidblacklist.org/downloads/squidblacklists/dg/dg-ads.tar.gz
curl --silent --user username:*********** --output /tmp/dg-malicious.tar.gz http://www.squidblacklist.org/downloads/squidblacklists/dg/dg-malicious.tar.gz
touch /var/unbound/whitelist
if [ -s /tmp/dg-ads.tar.gz ]
then
cd /tmp
tar -xvf /tmp/dg-ads.tar.gz
fi
if [ -s /tmp/dg-malicious.tar.gz ]
then
cd /tmp
tar -xvf /tmp/dg-malicious.tar.gz
fi
if [ -s /tmp/dg-ads.acl -a -s /tmp/dg-malicious.acl -a -e /var/unbound/whitelist ]
then
cat /tmp/dg-ads.acl /tmp/dg-malicious.acl | sort | uniq \
| cat - /var/unbound/whitelist /var/unbound/whitelist | sort | uniq -u \
| sed '/^#.*/d' `# Delete comments` \
| sed 's/
//g' `# Delete Windows newlines` \
| sed -n -E '/^[a-z0-9\-\.]+/p' `# Strip any chars not valid in a domain name` \
| sed 's/^\.//' `# Strip starting dots (e.g. ".example.com")` \
| awk '{print "local-zone: \""$1"\" refuse"}' \
| sed '1 i\
server:
' > /var/unbound/conf.d/blacklist.conf
if unbound-checkconf /var/unbound/conf.d/blacklist.conf ; then
unbound-control reload
fi
fi
If we want to redirect to 127.0.0.1 rather than returning REFUSED:
cat /tmp/dg-ads.acl /tmp/dg-malicious.acl /tmp/dg-porn.acl | sort | uniq \
| cat - /var/unbound/whitelist /var/unbound/whitelist | sort | uniq -u \
| sed '/^#.*/d' `# Delete comments` \
| sed 's/
//g' `# Delete Windows newlines` \
| sed -n -E '/^[a-z0-9\-\.]+/p' `# Strip any chars not valid in a domain name` \
| sed 's/^\.//' `# Strip starting dots (e.g. ".example.com")` \
| awk '{print "local-zone: \""$1"\" redirect\nlocal-data: \""$1" A 127.0.0.1\""}' \
| sed '1 i\
server:
' > /var/unbound/conf.d/blacklist.conf
unbound-control
See unbound-control(8)
.
If not using the default config file location, it may be necessary to tell unbound-control
the location of the config file (-c /var/unbound/unbound.conf
).
# unbound-control status
version: 1.5.9
verbosity: 1
threads: 1
modules: 2 [ validator iterator ]
uptime: 419 seconds
options: control(ssl)
unbound (pid 22087) is running...
# unbound-control stats_noreset
thread0.num.queries=5
thread0.num.cachehits=1
thread0.num.cachemiss=4
thread0.num.prefetch=0
thread0.num.recursivereplies=4
thread0.requestlist.avg=0
thread0.requestlist.max=0
thread0.requestlist.overwritten=0
thread0.requestlist.exceeded=0
thread0.requestlist.current.all=0
thread0.requestlist.current.user=0
thread0.recursion.time.avg=0.293604
thread0.recursion.time.median=0.349525
thread0.tcpusage=0
total.num.queries=5
total.num.cachehits=1
total.num.cachemiss=4
total.num.prefetch=0
total.num.recursivereplies=4
total.requestlist.avg=0
total.requestlist.max=0
total.requestlist.overwritten=0
total.requestlist.exceeded=0
total.requestlist.current.all=0
total.requestlist.current.user=0
total.recursion.time.avg=0.293604
total.recursion.time.median=0.349525
total.tcpusage=0
time.now=1472176370.069576
time.up=235.308012
time.elapsed=235.308012
DNS Spoofing (a.k.a. DNS cache poisoning)
A recursive DNS server can in some cases be tricked into caching bad records, thereby diverting clients to incorrect and potentially harmful destinations.
DNSSEC prevents many cache poisoning exploits.
Configure Windows DNS Server to Use Unbound
We might need Windows DNS servers. We can configure them to use our Unbound DNS server as a forwarder.
In the Windows DNS Manager, view the Properties of the DNS server. Go to the Forwarders tab, and enter the IP address of our Unbound DNS server.
https://technet.microsoft.com/en-us/library/cc754941%28v=ws.11%29.aspx
https://technet.microsoft.com/en-us/library/cc730756%28v=ws.11%29.aspx
If anything on the LAN will be querying our Unbound server directly, we may want to include this in our unbound.conf
:
forward-zone:
name: "mylan.example.com"
forward-addr: 10.0.0.2
forward-addr: 10.0.0.3
Playing with dig (or drill)
Note that FreeBSD has drill
instead of dig
. On Debian, drill is available in the ldnsutils
package.
Just the IP:
% dig +short example.com
93.184.216.34
Find nameservers for a domain:
% dig ns +short example.com
b.iana-servers.net.
a.iana-servers.net.
Query a particular nameserver:
% dig +noall +answer example.com @8.8.8.8
example.com. 20817 IN A 93.184.216.34
See the TTL for a record:
% dig +noall +answer example.com
example.com. 15313 IN A 93.184.216.34
Reverse lookup (PTR):
% dig +short -x 8.8.8.8
google-public-dns-a.google.com.
Compare the TTL for a cached record at different recursive nameservers:
% dig @10.0.0.1 +noall +answer example.com
example.com. 86400 IN A 93.184.216.34
% dig @8.8.8.8 +noall +answer example.com
example.com. 15277 IN A 93.184.216.34
Look at any record type for a domain:
% dig +noall +answer any example.com
example.com. 15423 IN A 93.184.216.34
example.com. 19191 IN NS b.iana-servers.net.
example.com. 19191 IN NS a.iana-servers.net.
example.com. 1191 IN SOA sns.dns.icann.org. noc.dns.icann.org. 2015082641 7200 3600 1209600 3600
example.com. 17 IN TXT "v=spf1 -all"
example.com. 17 IN TXT "$Id: example.com 4415 2015-08-24 20:12:23Z davids $"
example.com. 19191 IN AAAA 2606:2800:220:1:248:1893:25c8:1946
One of the points of interest in the above is the Start Of Authority record, which we see more clearly with dig’s multiline
switch:
% dig +noall +answer +multiline soa example.com
example.com. 1326 IN SOA sns.dns.icann.org. noc.dns.icann.org. (
2015082641 ; serial
7200 ; refresh (2 hours)
3600 ; retry (1 hour)
1209600 ; expire (2 weeks)
3600 ; minimum (1 hour)
)
The SOA record includes:
— the primary nameserver for the domain (sns.dns.icann.org)
— the party responsible for the domain (noc.dns.icann.org)
— the timestamp when the record was last modified (2015082641 ; serial)
— seconds till the zone refresh (7200 ; refresh)
— seconds to wait until retrying a failed zone refresh (3600 ; retry)
— seconds until a zone result should not be considered authoritative (1209600 ; expire)
— seconds a resolver should consider a negative result valid before requerying (3600 ; minimum)
Find which nameservers in a zone have synchronized which version of the name record (all servers are synced in this case):
% dig google.com +nssearch | awk '{ print $2, $4 }'
ns2.google.com. 131206105
ns3.google.com. 131206105
ns1.google.com. 131206105
ns2.google.com. 131206105
Bypass the resolver’s cache to see a worst-case full query path (results abridged):
% dig +trace example.com
; <<>> DiG 9.10.3-P4-Debian <<>> +trace example.com
;; global options: +cmd
. 3600 IN NS k.root-servers.net.
. 3600 IN NS e.root-servers.net.
;; Received 768 bytes from 10.0.0.2#53(10.0.0.2) in 1 ms
com. 172800 IN NS f.gtld-servers.net.
com. 172800 IN NS d.gtld-servers.net.
;; Received 735 bytes from 198.41.0.4#53(a.root-servers.net) in 27 ms
example.com. 172800 IN NS a.iana-servers.net.
example.com. 172800 IN NS b.iana-servers.net.
;; Received 591 bytes from 192.35.51.30#53(f.gtld-servers.net) in 51 ms
example.com. 86400 IN A 93.184.216.34
example.com. 86400 IN NS a.iana-servers.net.
example.com. 86400 IN NS b.iana-servers.net.
;; Received 452 bytes from 199.43.135.53#53(a.iana-servers.net) in 24 ms
Look for TXT records:
% dig +noall +answer txt google.com
google.com. 3598 IN TXT "v=spf1 include:_spf.google.com ~all"
(An spf record indicates which servers are allowed to send mail for the domain.)
What DNS queries are happening now?
What if we want to log queries for debugging purposes?
# unbound-control -c /var/unbound/unbound.conf set_option verbosity: 1
ok
# unbound-control -c /var/unbound/unbound.conf set_option log-queries: yes
ok
This logs a lot of stuff, so when we’re done looking for a specific thing, turn down logging:
# unbound-control -c /var/unbound/unbound.conf set_option log-queries: no
ok
# unbound-control -c /var/unbound/unbound.conf set_option verbosity: 0
ok
By default, it logs to syslog.
Links
- https://forums.freebsd.org/threads/49131/
- http://serverfault.com/questions/18748/overriding-some-dns-entries-in-bind-for-internal-networks
- https://wiki.archlinux.org/index.php/Unbound#Block_advertising
- https://www.vultr.com/docs/running-nsd-and-unbound-on-openbsd-5-6
- http://man.openbsd.org/unbound.8
- http://man.openbsd.org/unbound.conf
- http://man.openbsd.org/nsd.8
- https://en.wikipedia.org/wiki/Alternative_DNS_root
- https://en.wikipedia.org/wiki/DNS_spoofing
- https://en.wikipedia.org/wiki/TXT_record
- http://pid1.com/posts/post13.html
- https://blog.des.no/2013/09/local-caching-resolver-in-freebsd-10/
- https://wiki.alpinelinux.org/wiki/Setting_up_unbound_DNS_server#root-hints