Что такое name-серверы (ns)
Содержание:
Configuring the Secondary DNS Server
In most environments, it is a good idea to set up a secondary DNS server that will respond to requests if the primary becomes unavailable. Luckily, the secondary DNS server is much easier to configure.
On ns2, edit the file:
At the top of the file, add the ACL with the private IP addresses of all of your trusted servers:
/etc/bind/named.conf.options — updated 1 of 2 (secondary)
Below the directive, add the following lines:
/etc/bind/named.conf.options — updated 2 of 2 (secondary)
Save and close the file. This file should look exactly like ns1’s file except it should be configured to listen on ns2’s private IP address.
Now edit the file:
Define slave zones that correspond to the master zones on the primary DNS server. Note that the type is “slave”, the file does not contain a path, and there is a directive which should be set to the primary DNS server’s private IP address. If you defined multiple reverse zones in the primary DNS server, make sure to add them all here:
/etc/bind/named.conf.local — updated (secondary)
Now save and close the file.
Run the following command to check the validity of your configuration files:
Once that checks out, restart BIND:
Allow DNS connections to the server by altering the UFW firewall rules:
Now you have primary and secondary DNS servers for private network name and IP address resolution. Now you must configure your client servers to use your private DNS servers.
Configuring DNS Clients
Before all of your servers in the “trusted” ACL can query your DNS servers, you must configure each of them to use ns1 and ns2 as name servers. This process varies depending on OS, but for most Linux distributions it involves adding your name servers to the file.
Ubuntu 18.04 Clients
On Ubuntu 18.04, networking is configured with Netplan, an abstraction that allows you to write standardized network configuration and apply it to incompatible backend networking software. To configure DNS, we need to write a Netplan configuration file.
First, find the device associated with your private network by querying the private subnet with the command:
In this example, the private interface is .
Next, create a new file in called :
Inside, paste the following contents. You will need to modify the interface of the private network, the addresses of your ns1 and ns2 DNS servers, and the DNS zone:
Note: Netplan uses the YAML data serialization format for its configuration files. Because YAML uses indentation and whitespace to define its data structure, make sure that your definition uses consistent indentation to avoid errors.
/etc/netplan 00-private-nameservers.yaml
Save and close the file when you are finished.
Next, tell Netplan to attempt to use the new configuration file by using . If there are problems that cause a loss of networking, Netplan will automatically roll back the changes after a timeout:
If the countdown is updating correctly at the bottom, the new configuration is at least functional enough to not break your SSH connection. Press ENTER to accept the new configuration.
Now, check that the system’s DNS resolver to determine if your DNS configuration has been applied:
Scroll down until you see the section for your private network interface. You should see the private IP addresses for your DNS servers listed first, followed by some fallback values. Your domain should should be in the “DNS Domain”:
Your client should now be configured to use your internal DNS servers.
Ubuntu 16.04 and Debian Clients
On Ubuntu 16.04 and Debian Linux servers, you can edit the file:
Inside, find the line. If it is attached to the interface, move it to your networking interface ( or for example). Next, prepend your own name servers in front of the list that is currently there. Below that line, add a option pointed to the base domain of your infrastructure. In our case, this would be “nyc3.example.com”:
/etc/network/interfaces
Save and close the file when you are finished.
Make sure that the package is installed on your system:
Now, restart your networking services, applying the new changes with the following commands. Make sure you replace with the name of your networking interface:
This should restart your network without dropping your current connection. If it worked correctly, you should see something like this:
Double check that your settings were applied by typing:
You should see your name servers in the file, as well as your search domain:
Your client is now configured to use your DNS servers.
CentOS Clients
On CentOS, RedHat, and Fedora Linux, edit the file. You may have to substitute with the name of your primary network interface:
Search for the and options and set them to the private IP addresses of your primary and secondary name servers. Add a parameter that with your infrastructure’s base domain. In this guide, that would be “nyc3.example.com”:
/etc/sysconfig/network-scripts/ifcfg-eth0
Save and close the file when you are finished.
Now, restart the networking service by typing:
The command may hang for a few seconds, but should return you to the prompt shortly.
Check that your changes were applied by typing:
You should see your name servers and search domain in the list:
/etc/resolv.conf
Your client should now be able to connect to and use your DNS servers.
Как выполнить перезапуск сети
Выше я везде предлагал перезагрузить сервер, чтобы проверить новые сетевые настройки. Не всегда это обязательно делать. Иногда достаточно просто перечитать сетевую конфигурацию. Для перезапуска сети в Debian можно воспользоваться командой:
Она выполняется не мгновенно, обычно несколько секунд. Выполнить перезагрузку сети можно так же командой:
Она делает то же самое, но есть некая обратная связь о том, как все прошло. Если у вас все в порядке на сервере и нет сетевых ошибок, то рестарт сети можно спокойно делать удаленно по ssh. Вас даже не отключит от текущей сессии. Но на всякий случай я не рекомендую это делать, если у вас нет доступа к консоли сервера. Всякое может случиться, я бы не рисковал лишний раз. Настройку сети, как и фаервола, лучше не делать, не имея прямого доступа к консоли сервера.
Установка шлюза по-умолчанию (default gateway)
Теперь разберемся со шлюзом по-умолчанию. В предыдущих примерах со статическим ip адресом и настройками по dhcp у нас не было необходимости указывать отдельно default gateway. Мы его устанавливали вместе с остальными настройками. Чтобы посмотреть установленный по-умолчанию шлюз в debian, можно воспользоваться следующей командой в консоли:
Это шлюз по-умолчанию (default gateway). Можно воспользоваться другими, более популярными и привычными командами:
Если получите ошибки:
Значит у вас не установлен пакет net-tools. Установить его можно следующей командой.
Сетевые инструменты из пакета net-tools объявлены устаревшими и не включены в состав базовой системы. Я ими продолжаю пользоваться, потому что мне нравится их вывод больше, чем у команды ip. Netstat мне видится более информативным, хотя по сути, они все показывают одно и то же. Отказ в пользу утилиты ip идет по той причине, что она объединяет в себе все основные сетевые инструменты. Удобнее пользоваться только ей одной для настройки сети, нежели разными утилитами для разных целей.
Если нам нужно сменить default gateway, то сначала надо удалить текущий шлюз, а потом назначить новый.
То же самое, только с помощью ip:
Проверяем, что получилось:
Все получилось. Эта настройка будет действовать до перезагрузки. Чтобы ее сохранить, либо меняйте конфигурационный файл interfaces, либо, при необходимости, придумывайте что-то еще.
Настройка DNS-клиентов
Прежде чем все ваши серверы в доверенном ACL смогут отправлять запросы на ваши DNS-серверы, вы должны настроить для каждого из них использование ns1 и ns2 в качестве сервера имен. Этот процесс варьируется в зависимости от операционной системы, но для большинства дистрибутивов Linux он подразумевает добавление ваших серверов доменных имен в файл .
Клиенты Ubuntu 18.04
На Ubuntu 18.04 настройка сетевого взаимодействия выполняется с помощью Netplan, абстракции, которая позволяет вам записывать стандартную конфигурацию сети и применять ее к несовместимому сетевому ПО, отвечающему за бекэнд. Для настройки DNS нам потребуется записать файл конфигурации Netplan.
Во-первых, найдите устройство, связанное с вашей частной сетью, отправив частной подсети команду :
В этом примере используется частный интерфейс .
Далее необходимо создать новый файл в с именем :
Вставьте в файл следующее содержимое. Вам потребуется изменить интерфейс частной сети, адреса ваших DNS-серверов ns1 и ns2, а также зону DNS:
Примечание: Netplan использует формат сериализации данных YAML для своих файлов конфигурации. Поскольку YAML использует структурирование текста и пробелы для определения структуры данных, убедитесь, что ваше определение имеет равномерное структурирование текста во избежание ошибок.
/etc/netplan 00-private-nameservers.yaml
Сохраните файл и закройте его после завершения.
Затем вы должны сообщить Netplan о необходимости использования нового файла конфигурации с помощью команды . При наличии проблем, которые приводят к потере подключения к сети, Netplan будет автоматически перезапускать изменения по истечении определенного периода времени:
Если счетчик в нижней части обновляется корректно, это значит, что новой конфигурации удалось по крайней мере не повредить ваше соединение SSH. Нажмите ENTER, чтобы принять изменения в конфигурации.
Теперь проверьте DNS-преобразователь системы, чтобы определить, применены ли изменения в конфигурацию DNS:
Прокрутите вниз, пока не увидите раздел для вашего интерфейса частной сети. Вы должны увидеть частные IP-адреса ваших DNS-серверов, которые будут перечислены в первую очередь, а за ними идут резервные значения. Ваш домен должен находиться в строке DNS Domain:
Ваш клиент должен быть настроен на использование ваших внутренних DNS-серверов.
Клиенты Ubuntu 16.04 и Debian
В серверах Ubuntu 16.04 и Debian вы можете изменить файл :
Внутри найдите строку и добавьте ваши серверы доменных имен в начало списка, который уже добавлен в файл. Под этой строкой добавьте опцию , указывающую на базовый домен вашей инфраструктуры. В нашем случае это будет “nyc3.example.com”:
/etc/network/interfaces
Сохраните файл и закройте его после завершения.
Перезапустите ваши сетевые службы, применив изменения с помощью следующих команд. Убедитесь, что вы заменили на имя вашего сетевого интерфейса:
В результате будет выполнен перезапуск вашей сети без отключения текущего подключения. Если все работает корректно, вы должны увидеть примерно следующее:
Еще раз проверьте, что ваши настройки были применены, введя следующую команду:
Вы должны увидеть ваши серверы доменных имен в файле , а также ваш домен поиска:
Ваш клиент настроен для использования ваших DNS-серверов.
Клиенты CentOS
В CentOS, RedHat и Fedora Linux отредактируйте файл . Возможно, вам придется заменить на имя вашего основного сетевого интерфейса:
Найдите опции и и задайте для них частные IP-адреса ваших основного и дополнительного серверов доменных имен. Добавьте параметр , используя базовый домен вашей инфраструктуры. В этом руководстве это будет “nyc3.example.com”:
/etc/sysconfig/network-scripts/ifcfg-eth0
Сохраните файл и закройте его после завершения.
Перезапустите сетевую службу с помощью следующей команды:
Команда может зависнуть на несколько секунд, но через короткое время вы должны вернуться в командную строку.
Убедитесь, что изменения вступили в силу, введя следующую команду:
Вы должны увидеть ваши серверы доменных имен и домена поиска в списке:
/etc/resolv.conf
Ваш клиент теперь может подключиться и использовать ваши DNS-серверы.
Советы и рекомендации
Интеграция сетевого интерфейса и рабочего стола
Systemd-networkd не имеет встроенной функциональности для интерактивного управления сетевыми интерфейсами, ни через графическое приложение, ни через командную оболочку. Тем не менее, существует ряд утилит для отображения состояния сети, изменения настроек или получения уведомлений.
- Утилита командной строки networkctl позволяет вывести информацию о сетевых интерфейсах.
- Когда networkd настраивается с помощью WPA supplicant, утилитами wpa_cli и wpa_gui можно динамически настраивать WLAN-интерфейсы.
- Плагин AUR выводит уведомления при изменениях в работе интерфейса (например, при установлении соединения или его завершении).
- Демон AUR позволяет выполнять сценарии при изменении состояния интерфейса. Работает схожим образом с NetworkManager-dispatcher.
- Отобразить информацию о DNS-сервере для systemd-resolved можно командой .
Назначение IP-адреса на основании SSID
Может возникнуть ситуация, когда дома вы используете беспроводную сеть с DHCP, а на работе — беспроводную же сеть, но со статическим IP-адресом. Пример смешанных настроек приведён ниже.
Примечание: Номер в начале имени файла определяет порядок, в котором они будут обрабатываться. В разделе можно использовать параметры SSID, BSSID или оба одновременно.
/etc/systemd/network/24-wireless-office.network
# отдельные настройки для сети WiFi на работе Name=wlp2s0 SSID=название_точки_доступа #BSSID=aa:bb:cc:dd:ee:ff Address=10.1.10.9/24 Gateway=10.1.10.1 DNS=10.1.10.1 #DNS=8.8.8.8
/etc/systemd/network/25-wireless-dhcp.network
# для остальных сетей используется DHCP Name=wlp2s0 DHCP=ipv4
Объединение проводного и беспроводного интерфейсов
См. также Wireless bonding.
Объединение интерфейсов (bonding) позволяет использовать для одного Интернет-соединения несколько сетевых интерфейсов. Если затем, например, проводной сетевой интерфейс по какой-то причине отключится, соединение будет перенаправлено на беспроводной.
Создайте объединённый интерфейс. В качестве режима работы необходимо указать active-backup, чтобы пакеты направлялись на запасной сетевой интерфейс, если основной будет отключён.
/etc/systemd/network/bond0.netdev
Name=bond0 Kind=bond Mode=active-backup PrimaryReselectPolicy=always MIIMonitorSec=1s
Укажите проводной интерфейс в качестве основного:
/etc/systemd/network/20-ethernet-bond.network
Name=enp0s25 Bond=bond0 PrimarySlave=true
Беспроводной интерфейс будет запасным:
/etc/systemd/network/30-wifi-bond.network
Name=wlan0 Bond=bond0
Объединённый интрефейс необходимо настроить так же, как настраивается обычный сетевой интерфейс:
/etc/systemd/network/10-bond0.network
Name=bond0 DHCP=ipv4
Теперь, если Ethernet-интерфейс будет отключён, соединение сохранится по беспроводной сети:
$ networkctl
IDX LINK TYPE OPERATIONAL SETUP 1 lo loopback carrier unmanaged 2 enp0s25 ether no-carrier configured 3 bond0 bond degraded-carrier configured 5 wlan0 wlan enslaved configured 4 links listed.
Resource Records (RR)
DNS is made up of several registrations, RR or Resource Records, defining the various domain information. The first is dedicated to name resolution, in our case, it is the file db.example.com. The second will be used for reverse name resolution, it is the file db.example.com.inv.
Files in var/cache/bind/
RR for name reso (db.example.com file)
$TTL 3600
@ IN SOA sid.example.com. root.example.com. (
2007010401 ; Serial
3600 ; Refresh
600 ; Retry
86400 ; Expire
600 ) ; Negative Cache TTL
;
@ IN NS sid.example.com.
@ IN MX 10 sid.example.com.
sid IN A 192.168.0.1
etch IN A 192.168.0.2
pop IN CNAME sid
www IN CNAME sid
mail IN CNAME sid
RR for inverse name resol ( db.example.com.inv file)
@ IN SOA sid.example.com. root.example.com. (
2007010401 ; Serial
3600 ; Refresh
600 ; Retry
86400 ; Expire
600 ) ; Negative Cache TTL
;
@ IN NS sid.example.com.
1 IN PTR sid.example.com.
2 IN PTR etch.example.com.
Some Explanations :
$TTL : (Time To Live) expresses the duration (in seconds) validity, by default, of the information contained in the RRs. Once this time expires, it is necessary to recheck the data. Types :
SOA : Show romanization
-
1. Serial : is the whole non-signed 32 bits. This is the serial number to increment with each change of file. It allows the secondary server to reload the information they have. The general purpose is to format it this way YYYYMMDDXX, either for the first amendment 01/04/2007 -> 2007040101, for the second 2007040102.
-
2. Refresh : defines the data refresh period.
-
3. Retry : if an error occurs during the last refresh, it will be repeated at the end of time Retry.
-
4. Expires’: the server is considered unavailable after the time expires.
-
5. Negative cache TTL’: set the lifetime of a NXDOMAIN response from us.
-
‘NS: information on behalf of nameservers for the domain.
-
‘A: associates a host name to an IPv4 address (32 bits)
-
‘YYYY: associates a host name to an IPv6 address (128 bits)
-
‘CNAME: identifies the canonical name of an alias (a name that points to another name)
-
‘PTR: This is simply the inverse resolution (the opposite of type A).
The classes in the association determines the Internet class. Other classes are available (CH and HS). For more information please consult the rfc1035
Notes
Red Hat SELinux BIND Security Profile:
- By default, Red Hat ships BIND with the most secure SELinux policy that will not prevent normal BIND operation and will prevent exploitation of all known
BIND security vulnerabilities . See the selinux(8) man page for information about SElinux.
It is not necessary to run named in a chroot environment if the Red Hat SELinux policy for named is enabled. When enabled, this policy is far more secure
than a chroot environment. Users are recommended to enable SELinux and remove the bind-chroot package.
With this extra security comes some restrictions:
By default, the SELinux policy does not allow named to write any master zone database files. Only the root user may create files in the $ROOTDIR/var/named
zone database file directory (the options { «directory» } option), where $ROOTDIR is set in /etc/sysconfig/named.
The «named» group must be granted read privelege to these files in order for named to be enabled to read them.
Any file created in the zone database file directory is automatically assigned the SELinux file context named_zone_t .
By default, SELinux prevents any role from modifying named_zone_t files; this means that files in the zone database directory cannot be modified by dynamic
DNS (DDNS) updates or zone transfers.
The Red Hat BIND distribution and SELinux policy creates three directories where named is allowed to create and modify files: /var/named/slaves,
/var/named/dynamic /var/named/data. By placing files you want named to modify, such as slave or DDNS updateable zone files and database / statistics dump files
in these directories, named will work normally and no further operator action is required. Files in these directories are automatically assigned the
‘named_cache_t’ file context, which SELinux allows named to write.
Red Hat BIND SDB support:
Red Hat ships named with compiled in Simplified Database Backend modules that ISC provides in the «contrib/sdb» directory. Install bind-sdb package if you
want use them
The SDB modules for LDAP, PostGreSQL, DirDB and SQLite are compiled into named-sdb.
See the documentation for the various SDB modules in /usr/share/doc/bind-sdb-*/ .