«Beanstalk Protocol» и «DNS сервер BIND с локальными зонами»: разница между страницами

Материал из support.qbpro.ru
(Различия между страницами)
imported>Supportadmin
(Новая страница: « = Beanstalk Protocol = Protocol -------- The beanstalk protocol runs over TCP using ASCII encoding. Clients connect, send commands and data, wait for responses…»)
 
imported>Vix
Нет описания правки
 
Строка 1: Строка 1:
Исходные данные


= Beanstalk Protocol =
Для корректной работы DNS нем необходимо иметь настроенную сеть. DNS в текущей статье будет настроен на дистрибутиве Debian, особенности других дистрибутивов тоже будут отмечены. Конфиг сети стенда следующий:


Protocol
dns:~# cat /etc/network/interfaces
--------
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
  address 10.0.0.152
  netmask 255.255.255.0
  gateway 10.0.0.254
auto eth1
iface eth1 inet static
  address 192.168.1.1
  netmask 255.255.255.0
где 10.0.0.152/24 - внешний интерфейс (подсеть, выделенная провайдером), 192.168.1.1/24 - внутренний (Локальная сеть). Настраиваемая зона будет иметь имя example.com. В примере со slave сервером, вторичный сервер будет расположен на IP 10.0.0.191.


The beanstalk protocol runs over TCP using ASCII encoding. Clients connect,
Установка BIND9
send commands and data, wait for responses, and close the connection. For each
connection, the server processes commands serially in the order in which they
were received and sends responses in the same order. All integers in the
protocol are formatted in decimal and (unless otherwise indicated)
nonnegative.


Names, in this protocol, are ASCII strings. They may contain letters (A-Z and
Для работы DNS сервера необходимо установить пакет bind9 (в некоторых дистрибутивах - bind). Как отмечено на схеме - основным конфигурационным файлом BIND является файл named.conf (данный файл может быть размещен в каталоге /etc, иногда в /etc/bind ).
a-z), numerals (0-9), hyphen ("-"), plus ("+"), slash ("/"), semicolon (";"),
dot ("."), dollar-sign ("$"), underscore ("_"), and parentheses ("(" and ")"),
but they may not begin with a hyphen. They are terminated by white space
(either a space char or end of line). Each name must be at least one character
long.


The protocol contains two kinds of data: text lines and unstructured chunks of
Параметры (синтаксис) named.conf
data. Text lines are used for client commands and server responses. Chunks are
used to transfer job bodies and stats information. Each job body is an opaque
sequence of bytes. The server never inspects or modifies a job body and always
sends it back in its original form. It is up to the clients to agree on a
meaningful interpretation of job bodies.


The client may issue the "quit" command, or simply close the TCP connection
Синтаксис файла named.conf придерживается следующих правил:
when it no longer has use for the server. However, beanstalkd performs very
well with a large number of open connections, so it is usually better for the
client to keep its connection open and reuse it as much as possible. This also
avoids the overhead of establishing new TCP connections.


If a client violates the protocol (such as by sending a request that is not
IP-адреса - список IP должен быть разделен символом ";" , возможно указывать подсеть в формате 192.168.1.1/24 или 192.168.1.1/255.255.255.0, (для исключения IP перед ним нужно поставить знак !), возможно указывать имена "any", "none", "localhost" в двойных кавычках.
well-formed or a command that does not exist) or if the server has an error,
the server will reply with one of the following error messages:


- "OUT_OF_MEMORY\r\n" The server cannot allocate enough memory for the job.
Комментарии - строки начинающиеся на #, // и заключенные в /* и */ считаются комментариями.
  The client should try again later.


- "INTERNAL_ERROR\r\n" This indicates a bug in the server. It should never
В файлах описания зон - символ @ является "переменной" хранящей имя зоны, указанной в конфигурационном файле named.conf или в директиве @ $ORIGIN текущего описания зоны.
  happen. If it does happen, please report it at
  http://groups.google.com/group/beanstalk-talk.


- "BAD_FORMAT\r\n" The client sent a command line that was not well-formed.
Каждая завершенная строка параметров должна завершаться символом ; .
  This can happen if the line does not end with \r\n, if non-numeric
  characters occur where an integer is expected, if the wrong number of
  arguments are present, or if the command line is mal-formed in any other
  way.


- "UNKNOWN_COMMAND\r\n" The client sent a command that the server does not
Раздел Acl
  know.
Acl (access control list) - позволяет задать именованный список сетей. Формат раздела: acl "имя_сети" {ip; ip; ip; };


These error responses will not be listed in this document for individual
Раздел Options
commands in the following sections, but they are implicitly included in the
Раздел Options задает глобальные параметры конфигурационного файла, управляющие всеми зонами. Данный раздел имеет формат: options {операторы_раздела_Options};. Options может быть "вложен" в раздел Zone, при этом он переопределяет глобальные параметры. Часто используемые операторы options:
description of all commands. Clients should be prepared to receive an error
response after any command.


As a last resort, if the server has a serious error that prevents it from
allow-query {список_ip} - Разрешает ответы на запросы только из список_ip. При отсутствии - сервер отвечает на все запросы.
continuing service to the current client, the server will close the
allow-recursion {список_ip} - На запросы из список_ip будут выполняться рекурсивные запросы. Для остальных - итеративные. Если  не задан параметр, то сервер выполняет рекурсивные запросы для всех сетей.
connection.
allow-transfer {список_ip} - Указывает список серверов, которым разрешено брать зону с сервера (в основном тут указывают slave сервера)
directory /path/to/work/dir - указывает абсолютный путь к рабочему каталогу сервера. Этот оператор допустим только в разделе  options.
forwarders {ip порт, ip порт...} - указывает адреса хостов и если нужно порты, куда переадресовывать запросы (обычно тут указываются DNS провайдеров ISP).
forward ONLY или forward FIRST - параметр first указывает, DNS-серверу пытаться разрешать имена с помощью DNS-серверов, указанных в параметре forwarders, и лишь в случае, если разрешить имя с помощью данных серверов не удалось, то будет осуществлять попытки разрешения имени самостоятельно.
notify YES|NO - YES - уведомлять slave сервера об изменениях в зоне, NO - не уведомлять.
recursion YES|NO - YES - выполнять рекурсивные запросы, если просит клиент, NO - не выполнять (только итеративные запросы). Если ответ найден в кэше, то возвращается из кэша. (может использоваться только в разделе Options)
Раздел Zone
Определяет описание зон(ы). Формат раздела: zone {операторы_раздела_zone}; Операторы, которые наиболее часто используются:


Job Lifecycle
allow-update {список_ip} - указывает системы, которым разрешено динамически обновлять данную зону.
-------------
file "имя_файла" - указывает путь файла параметров зоны (должен быть расположен в каталоге, определенном в разделе options оператором directory)
masters {список_ip} -указывает список мастер-серверов. (допустим только в подчиненных зонах)
type "тип_зоны" - указывает тип зоны, описываемой в текущем разделе,тип_зоны может принимать следующие значения:
forward - указывает зону переадресации, которая переадресовывает запросы, пришедшие в эту зону.
hint - указывает вспомогательную зону (данный тип содержит информацию о корневых серверах, к которым сервер будет обращаться в случае невозможности найти ответ в кэше)
master - указывает работать в качестве мастер сервера для текущей зоны.
slave - указывает работать в качестве подчиненного сервера для текущей зоны.
Дополнительные параметры конфигурации
Значения времени в файлах зон по умолчанию указывается в секундах, если за ними не стоит одна из следующих букв: S - секунды, M - минуты, H- часы, D - дни, W - недели. Соответственно, запись 2h20m5s будет иметь значение 2 часа 20 минут 5 секунд и соответствовать 8405 секунд.


A job in beanstalk gets created by a client with the "put" command. During its
Любое имя хоста/записи, не оканчивающиеся точкой считается неFQDN именем и будет дополнено именем текущей зоны. Например, запись domen в файле зоны examle.com будет развернуто в FQDN-имя domen.examle.com. .
life it can be in one of four states: "ready", "reserved", "delayed", or
"buried". After the put command, a job typically starts out ready. It waits in
the ready queue until a worker comes along and runs the "reserve" command. If
this job is next in the queue, it will be reserved for the worker. The worker
will execute the job; when it is finished the worker will send a "delete"
command to delete the job.


Here is a picture of the typical job lifecycle:
В конфигурационных файлах BIND могут применяться следующие директивы:


$TTL - определяет TTL по-умолчанию для всех записей в текущей зоне.
$ORIGIN - изменяет имя зоны с указанного в файле named.conf. При этом, область действия данной директивы не распространяется  "выше" (то есть если файл включен директивой $INCLUDE, то область действия$ORIGN не распространяется на родительский)
$INCLUDE - включает указанный файл как часть файла зоны.
Для того чтобы локальный резолвер сервера тоже использовал локальный DNS, необходимо привести файл resolv.conf к следующему виду:


  put            reserve              delete
dns:~# cat /etc/resolv.conf
  -----> [READY] ---------> [RESERVED] --------> *poof*
nameserver 127.0.0.1
Если в имени ресурсной записи встречается символ "*", то это он означает что вместо него можно подразумевать любую разрешенную последовательность символов. Такую запись называют "wildcard запись". Однако, символ "*" не может быть использован где угодно. Это может быть только первый символ в поле Name текущего домена, отделенный от остальных символом "."


Настройка кэширующего DNS сервера


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


Here is a picture with more possibilities:
Для того, чтобы BIND работал в качестве кэширующего сервера, необходимо иметь конфигурационные файлы заполненные необходимой информацией:


named.conf;
описание серверов корневой зоны (зона типа hint);
описание зоны 127.in-addr.arpa.
dns:~# cat /etc/bind/named.conf
acl "lan" {
            192.168.1.1/24;
            127.0.0.1;
};
options {
            directory "/var/cache/bind";
          // If there is a firewall between you and nameservers you want
          // to talk to, you may need to fix the firewall to allow multiple
          // ports to talk.  See http://www.kb.cert.org/vuls/id/800113
          /*
          * Тут сказано, что если используется фаерволл, то необходимо
          *  нашему серверу создать соответствующие правила
          *  то есть открыть доступ по 53 TCP и UDP порту
          */
          forward first;              // задаем пересылку только первого запроса
          forwarders {                // указываем DNS сервера для пересылки
                      83.239.0.202;    // предоставленные провайдером
                      213.132.67.110;  // ибо до них ближе чем до корневых
          };
          listen-on { lan; };        // пусть слушает только нужные интерфейсы
          allow-query { lan; };      // разрешить запросы только из локальной сети
          allow-recursion { lan; };  // рекурсивные запросы тоже только из локальной
          allow-transfer { none; };  // трансфер зон нам не нужен
          version "unknown";        // не отображать версию DNS сервера при ответах
          auth-nxdomain no;    # для совместимости RFC1035
          listen-on-v6 { none; };    //IPv6 нам не нужен
          };
// описание настроек корневых серверов
zone "." {
          type hint;
          file "db.root";
};
// нижеописанные зоны определяют сервер авторитетным для петлевых
// интерфейсов, а так же для броадкаст-зон (согласно RFC 1912)
zone "localhost" {
          type master;
          file "localhost";
};
zone "127.in-addr.arpa" {
          type master;
          file "127.in-addr.arpa";
};
zone "0.in-addr.arpa" {
          type master;
          file "0.in-addr.arpa";
};
zone "255.in-addr.arpa" {
          type master;
          file "255.in-addr.arpa";
};


В данном примере приведен кэширующий DNS сервер, обрабатывающий запросы из списка сетей lan, в которую входит только одна локальная сеть 192.168.1.1/24 и петлевой интерфейс. При необходимости можно включить туда и другие сети. После определения списка сетей в директиве acl, в любом месте конфига можно будет ссылаться на этот список по имени (в нашем примере имя - lan), что, собственно и сделано в разделе options. Большинство параметров я прокомментировал, но отдельного внимания требует раздел, описывающий зону корневых серверов. В параметре file задан относительный путь к файлу описания корневых серверов (путь, относительно рабочего каталога сервера). За обновлениями данного файла необходимо следить, хотя он обновляется довольно редко (откуда брать обновленный файл я писал в теории DNS). Как вы заметили, имеется так же две записи для зоны localhost и две записи обратных зон для бродкаст доменов. Назначение этих зон состоит в том, чтобы избежать трансляции случайных запросов имен соответствующих IP-адресов на серверы, обслуживающие корневую зону.


  put with delay              release with delay
Чтобы не вносить неразбериху в куче конфигурационных файлов, в статье я привожу примеры на основе единого конфигурационного файла. На  самом деле, в последних версиях Debian (и других дистрибутивах Linux), файл named.conf выглядит следующим образом:
  ----------------> [DELAYED] <------------.
                        |                  |
                        | (time passes)     |
                        |                  |
  put                  v    reserve      |      delete
  -----------------> [READY] ---------> [RESERVED] --------> *poof*
                      ^  ^                |  |
                      |  \  release      |  |
                      |    `-------------'  |
                      |                      |
                      | kick                |
                      |                      |
                      |      bury          |
                    [BURIED] <---------------'
                      |
                      |  delete
                        `--------> *poof*


root@master:~# cat /etc/bind/named.conf
// This is the primary configuration file for the BIND DNS server named.
//
// Please read /usr/share/doc/bind9/README.Debian.gz for information on the
// structure of BIND configuration files in Debian, *BEFORE* you customize
// this configuration file.
//
// If you are just adding zones, please do that in /etc/bind/named.conf.local


The system has one or more tubes. Each tube consists of a ready queue and a
include "/etc/bind/named.conf.options";
delay queue. Each job spends its entire life in one tube. Consumers can show
include "/etc/bind/named.conf.local";
interest in tubes by sending the "watch" command; they can show disinterest by
include "/etc/bind/named.conf.default-zones";
sending the "ignore" command. This set of interesting tubes is said to be a
То есть основной файл не содержит конфигураций, а включает в себя более узко специализированные файлы, которые отвечают за свои задачи, например named.conf.options - содержит глобальные параметры конфигурации, named.conf.default-zones - содержит описание localhost и broadcast зон, а named.conf.local содержит описания зон, за которые отвечает данный сервер.
consumer's "watch list". When a client reserves a job, it may come from any of
the tubes in its watch list.


When a client connects, its watch list is initially just the tube named
"default". If it submits jobs without having sent a "use" command, they will
live in the tube named "default".


Tubes are created on demand whenever they are referenced. If a tube is empty
Далее, хочу обратить внимание на наличие файлов зон в каталоге, указанном в разделе options в параметре directory с именами, соответствующими параметрам file в разделах, описывающих зоны:
(that is, it contains no ready, delayed, or buried jobs) and no client refers
to it, it will be deleted.


Producer Commands
dns:~# ls -l /var/cache/bind/
-----------------
итого 24
-rw-r--r-- 1 root root  237 Май 28 01:28 0.in-addr.arpa
-rw-r--r-- 1 root root  271 Май 28 01:28 127.in-addr.arpa
-rw-r--r-- 1 root root  237 Май 28 01:28 255.in-addr.arpa
-rw-r--r-- 1 root root 2994 Май 28 01:28 db.root
-rw-r--r-- 1 root root  270 Май 28 01:28 localhost
dns:~# cat /var/cache/bind/127.in-addr.arpa
;
; BIND reverse data file for local loopback interface
;
$TTL    604800
@      IN      SOA    localhost. root.localhost. (
                              1        ; Serial
                              604800    ; Refresh
                              86400    ; Retry
                              2419200  ; Expire
                              604800 )  ; Negative Cache TTL
;
@      IN      NS      localhost.
1.0.0  IN      PTR    localhost.
Рассматривать файлы "петлевых" и бродкастовых зон не вижу смысла, т.к. после установки пакета bind настройки заданные по умолчанию в данных файлах вполне приемлемы. Далее, при организации мастер сервера мы рассмотрим пример описания файла зоны. Хочу обратить внимание, что мы настраиваем кэширующий сервер, а определяем мы его и как master для некоторых из зон. В нашем случае "кэширующий" говорит о том, что наш сервер не поддерживает ни одну из реально существующих зон, т.е. ему не делегировано прав на такое обслуживание.


The "put" command is for any process that wants to insert a job into the queue.
Да, чуть не забыл, демон named должен быть разрешен для запуска на необходимых уровнях выполнения ОС (команда в RedHat - /sbin/chkconfig bind9 on, в Debian - /usr/sbin/update-rc.d bind9 defaults). После изменения конфигурационных файлов можно добавить сервис в автозагрузку и запустить демон:
It comprises a command line followed by the job body:


put <pri> <delay> <ttr> <bytes>\r\n
dns:~# update-rc.d bind9 defaults
<data>\r\n
Adding system startup for /etc/init.d/bind9 ...
/etc/rc0.d/K20bind9 -> ../init.d/bind9
/etc/rc1.d/K20bind9 -> ../init.d/bind9
/etc/rc6.d/K20bind9 -> ../init.d/bind9
/etc/rc2.d/S20bind9 -> ../init.d/bind9
/etc/rc3.d/S20bind9 -> ../init.d/bind9
/etc/rc4.d/S20bind9 -> ../init.d/bind9
/etc/rc5.d/S20bind9 -> ../init.d/bind9
dns:~# /etc/init.d/bind9 start
Starting domain name service...: bind9.
На этом настройка кэширующего DNS завершена. Все запросы, которые попадают в кэш DNS сервера он хранит в оперативной памяти компьютера и при перезапуске демона эти данные обнуляются. Для проверки работы кэша можно выполнить команду nslookup mail.ru example.com., если в ответе содержится строка Non-authoritative answer, то адрес пришел из кэша, а так же если выполнить dig www.ru. (или другой домен, которого еще нет в кэше) и через некоторое время повторить команду, то время ответа должно быть гораздо меньше.


It inserts a job into the client's currently used tube (see the "use" command
Давайте рассмотрим другие варианты сервера.
below).


- <pri> is an integer < 2**32. Jobs with smaller priority values will be
Главный (master) сервер зоны
  scheduled before jobs with larger priorities. The most urgent priority is 0;
  the least urgent priority is 4,294,967,295.


- <delay> is an integer number of seconds to wait before putting the job in
Основной конфиг содержит следующие настройки:
  the ready queue. The job will be in the "delayed" state during this time.


- <ttr> -- time to run -- is an integer number of seconds to allow a worker
dns:~# cat /etc/bind/named.conf
  to run this job. This time is counted from the moment a worker reserves
acl "lan" {
  this job. If the worker does not delete, release, or bury the job within
          192.168.1.1/24;
  <ttr> seconds, the job will time out and the server will release the job.
          127.0.0.1;
  The minimum ttr is 1. If the client sends 0, the server will silently
};
  increase the ttr to 1.


- <bytes> is an integer indicating the size of the job body, not including the
options {
  trailing "\r\n". This value must be less than max-job-size (default: 2**16).
          directory "/var/cache/bind";
          allow-query { any; };      // отвечать на зпросы со всех интерфейсов
          recursion no;              // запретить рекурсивные запросы
          auth-nxdomain no;          // для совместимости RFC1035
          listen-on-v6 { none; };    // IPv6 нам не нужен
          version "unknown";          // не отображать версию DNS сервера при ответах


  - <data> is the job body -- a sequence of bytes of length <bytes> from the
          /*
  previous line.
          * Раскомментируйте строки ниже, если
          *  хотите разрешить рекрусивные запросы
          *  из локальной сети.
          *  (так же, необходимо закомментировать
          *  recursion no; )
          */
          # forwarders {                // указываем DNS сервера для пересылки
          #        83.239.0.202;        // предоставленные провайдером
          #        213.132.67.110;      // ибо до них ближе чем до корневых
          # };


After sending the command line and body, the client waits for a reply, which
          # allow-recursion { lan; };    // рекурсивные запросы тоже только из локальной
may be:


- "INSERTED <id>\r\n" to indicate success.
};


  - <id> is the integer id of the new job
// описание настроек корневых серверов
zone "." {
          type hint;
          file "db.root";
};


- "BURIED <id>\r\n" if the server ran out of memory trying to grow the
// нижеописанные зоны определяют сервер авторитетным для петлевых
  priority queue data structure.
// интерфейсов, а так же для броадкаст-зон (согласно RFC 1912)


  - <id> is the integer id of the new job
zone "localhost" {
          type master;
          file "localhost";
};


- "EXPECTED_CRLF\r\n" The job body must be followed by a CR-LF pair, that is,
zone "127.in-addr.arpa" {
  "\r\n". These two bytes are not counted in the job size given by the client
          type master;
  in the put command line.
          file "127.in-addr.arpa";
};


- "JOB_TOO_BIG\r\n" The client has requested to put a job with a body larger
zone "0.in-addr.arpa" {
  than max-job-size bytes.
          type master;
          file "0.in-addr.arpa";
};


- "DRAINING\r\n" This means that the server has been put into "drain mode"
zone "255.in-addr.arpa" {
  and is no longer accepting new jobs. The client should try another server
          type master;
  or disconnect and try again later.
          file "255.in-addr.arpa";
};


The "use" command is for producers. Subsequent put commands will put jobs into
// описание основной зоны
the tube specified by this command. If no use command has been issued, jobs
zone "example.com" {
will be put into the tube named "default".
          type master;
          file "example.com";
          allow-transfer { 10.0.0.191; };
};


use <tube>\r\n
//описание обратных зон
zone "0.0.10.in-addr.arpa" {
          type master;
          file "0.0.10.in-addr.arpa";
          allow-transfer { 10.0.0.191; };
};


- <tube> is a name at most 200 bytes. It specifies the tube to use. If the
zone "1.168.192.in-addr.arpa" {
  tube does not exist, it will be created.
          type master;
          file "1.168.192.in-addr.arpa";
#        allow-transfer { 10.0.0.191; };  // зона описывает локальную сеть поэтому ее не передаем
};


The only reply is:
// настройки логирования
logging {
          channel "misc" {
                    file "/var/log/bind/misc.log" versions 4 size 4m;
                    print-time yes;
                    print-severity yes;
                    print-category yes;
          };


USING <tube>\r\n
          channel "query" {
                    file "/var/log/bind/query.log" versions 4 size 4m;
                    print-time yes;
                    print-severity no;
                    print-category no;
          };


- <tube> is the name of the tube now being used.
          category default {
                    "misc";
          };


Worker Commands
          category queries {
---------------
                    "query";
          };
};
Давайте кратко разберем конфигурационный файл и настройки master сервера: мы настраиваем мастер сервер для зоны example.com. . Согласно конфига, наш BIND имеет рабочий каталог /var/cache/bind, сервер отвечает на запросы со всех интерфейсов (allow-query {any ;};), рекурсивные запросы обрабатывает как итеративные (recursion no), является мастер-сервером для зоны example.com и локальных служебных зон (type master). При этом, если необходимо разрешить кэширование (то есть рекурсивные запросы) для локальной сети, то необходимо раскомментировать параметры forwarders и allow-recursion и закомментировать recursion no;.


A process that wants to consume jobs from the queue uses "reserve", "delete",
Так же, для примера, я привел возможности BIND логировать все происходящее при работе сервера (можно для этой цели использовать syslog). В разделе logging задаются 2 параметра channel (можно и больше двух - на ваше усмотрение), эти параметры дословно можно назвать "канал" записи. Каждый канал определяет имя канала и настройки параметров записи (что записывать, а что - нет и куда писать). Директива category задает какую категорию сообщений в какой канал отправлять. Исходя из этого, мы имеем: запись стандартной информации в канал misc, а приходящие запросы посылаются в канал query. При этом, если файлы журнала достигают 4Мб (size 4m), он переименовывается добавлением к имени .1 и начинается запись в новый журнал, числа в конце других журналов увеличиваются. Журналы с номером, более указанного в version (в нашем случае 4) удаляются (Управлять ротацией логов можно так же с помощью logrotate). Параметры print* определяют заносить ли в журнал время появления, важность и категорию информации. Более подробно про настройки раздела logging можно почитать в man (5) named.conf.
"release", and "bury". The first worker command, "reserve", looks like this:


reserve\r\n
Отдельно хочется описать параметр  allow-transfer { 10.0.0.191; };. Данный параметр описывает серверы, которым разрешено скачивать копию зоны - т.н. slave серверА. В следующем примере мы разберем настройку slave DNS.


Alternatively, you can specify a timeout as follows:
Для корректной работы логирования необходимо создать соответствующий каталог и присвоить необходимые права:


reserve-with-timeout <seconds>\r\n
dns:~# mkdir /var/log/bind/
dns:~# chmod 744 /var/log/bind/
dns:~# ps aux | grep named
bind      4298  0.0  3.4  46792 13272 ?        Ssl  Jul05  0:00 /usr/sbin/named -u bind
root      4815  0.0  0.1  3304  772 pts/4    S+  18:19  0:00 grep named
dns:~# chown bind /var/log/bind/
dns:~# ls -ld /var/log/bind/
drwxr--r-- 2 bind root 4096 Июл  6 18:18 /var/log/bind/
Давайте далее рассмотрим наш файл описания зоны example.com.:


This will return a newly-reserved job. If no job is available to be reserved,
dns:~# cat /var/cache/bind/example.com
beanstalkd will wait to send a response until one becomes available. Once a
$TTL 3D
job is reserved for the client, the client has limited time to run (TTR) the
@      IN      SOA    ns.example.com. root.example.com. (
job before the job times out. When the job times out, the server will put the
                                        2011070601      ; serial
job back into the ready queue. Both the TTR and the actual time left can be
                                        8H              ; refresh
found in response to the stats-job command.
                                        2H              ; retry
                                        2W              ; expire
                                        1D)            ; minimum


If more than one job is ready, beanstalkd will choose the one with the
@      IN      NS      ns.example.com.
smallest priority value. Within each priority, it will choose the one that
@      IN      NS      ns2.example.com.
was received first.
@      IN      A      10.0.0.152
@      IN      MX      5 mx.example.com.
ns      IN      A      10.0.0.152
ns2    IN      A      10.0.0.191
mx      IN      A      10.0.0.152
www    IN      CNAME  @
а так же в домене in-addr.arpa.


A timeout value of 0 will cause the server to immediately return either a
dns:~# cat /var/cache/bind/0.0.10.in-addr.arpa
response or TIMED_OUTA positive value of timeout will limit the amount of
$TTL 3600
time the client will block on the reserve request until a job becomes
@      IN      SOA    ns.examle.comroot.example.com. (
available.
            2007042001 ; Serial
            3600      ; Refresh
            900        ; Retry
            3600000    ; Expire
            3600 )    ; Minimum
        IN      NS      ns.examle.com.
        IN      NS      ns2.example.com.
152    IN      PTR    examle.com.
191    IN      PTR    ns.example.com.
*      IN      PTR    examle.com.


During the TTR of a reserved job, the last second is kept by the server as a
dns:~# cat /var/cache/bind/1.168.192.in-addr.arpa
safety margin, during which the client will not be made to wait for another
$TTL 3600
job. If the client issues a reserve command during the safety margin, or if
@      IN      SOA    ns.examle.com.  root.example.com. (
the safety margin arrives while the client is waiting on a reserve command,
            2007042001 ; Serial
the server will respond with:
            3600      ; Refresh
            900        ; Retry
            3600000    ; Expire
            3600 )    ; Minimum
        IN      NS      ns.examle.com.
        IN      NS      ns2.example.com.
*      IN      PTR    examle.com.
Наша сеть небольшая, предполагается, что в сети совсем мало машин. Все сервисы сети размещены на одном хосте example.com., поэтому и master DNS (ns.example.com.) и почтовый сервер (mx.example.com.) указывает на одну машину (10.0.0.152).


DEADLINE_SOON\r\n
Вторичный (secondary, slave) авторитетный сервер зоны


This gives the client a chance to delete or release its reserved job before
Основная функция slave сервера - автоматическая синхронизация описания зоны с master сервером. Данная задача регламентируется документом RFC 1034 в разделе 4.3.5. Согласно данному документу обмен данными между серверами рекомендовано производить по протоколу TCP, посредством запроса AXFR. По этому запросу за одно TCP соединение должна передаваться вся зона целиком (RFC 1035).
the server automatically releases it.


TIMED_OUT\r\n
Так же, slave DNS-сервер делит нагрузку с master сервером или принимает на себя всю нагрузку в случае аварии па первом сервере.


If a non-negative timeout was specified and the timeout exceeded before a job
Прежде чем приступить к настройке slave DNS сервера, необходимо проверить возможность получения зоны вручную со вторичного сервера с помощью следующей команды:
became available, or if the client's connection is half-closed, the server
will respond with TIMED_OUT.


Otherwise, the only other response to this command is a successful reservation
root@debian:~# dig @10.0.0.152 example.com. axfr
in the form of a text line followed by the job body:


RESERVED <id> <bytes>\r\n
; <<>> DiG 9.7.3 <<>> @10.0.0.152 example.com. axfr
<data>\r\n
; (1 server found)
;; global options: +cmd
example.com.            259200  IN      SOA    ns.example.com. root.example.com. 2011070801 28800 7200 1209600 86400
example.com.            259200  IN      NS      ns.example.com.
example.com.            259200  IN      NS      ns2.example.com.
example.com.            259200  IN      A      10.0.0.152
example.com.            259200  IN      MX      5 mx.example.com.
mx.example.com.        259200  IN      A      10.0.0.152
ns.example.com.        259200  IN      A      10.0.0.152
ns2.example.com.        259200  IN      A      10.0.0.191
www.example.com.        259200  IN      CNAME  example.com.
example.com.            259200  IN      SOA    ns.example.com. root.example.com. 2011070801 28800 7200 1209600 86400
;; Query time: 14 msec
;; SERVER: 10.0.0.152#53(10.0.0.152)
;; WHEN: Fri Jul  8 15:33:54 2011
;; XFR size: 11 records (messages 1, bytes 258)
Получение зоны прошло успешно. Далее, для настройки подчиненного сервера, алгоритм следующий:


  - <id> is the job id -- an integer unique to this job in this instance of
Скопировать конфигурационный файл named.conf с master сервера;
  beanstalkd.
Заменить параметр type master на type slave в тех зонах, для которых он будет вторичным;
Параметр allow-transfer { 10.0.0.191; }; заменить на masters { 10.0.0.152;}; в тех зонах, для которых он будет вторичным;
Удалить зоны, которые не будет обслуживать текущий сервер, в том числе и корневую, если slave не будет отвечать на рекурсивные запросы;
Создать каталоги для логов, как в предыдущем примере.
Итого, мы получаем конфиг slave сервера:


- <bytes> is an integer indicating the size of the job body, not including
root@debian:~# cat /etc/bind/named.conf
   the trailing "\r\n".
options {
          directory "/var/cache/bind";
          allow-query { any; };      // отвечать на запросы со всех интерфейсов
          recursion no;              // запретить рекурсивные запросы
          auth-nxdomain no;          // для совместимости RFC1035
          listen-on-v6 { none; };   // IPv6 нам не нужен
          version "unknown";        // не отображать версию DNS сервера при ответах
};


- <data> is the job body -- a sequence of bytes of length <bytes> from the
// нижеописанные зоны определяют сервер авторитетным для петлевых
  previous line. This is a verbatim copy of the bytes that were originally
// интерфейсов, а так же для броадкаст-зон (согласно RFC 1912)
  sent to the server in the put command for this job.


The delete command removes a job from the server entirely. It is normally used
zone "localhost" {
by the client when the job has successfully run to completion. A client can
          type master;
delete jobs that it has reserved, ready jobs, delayed jobs, and jobs that are
          file "localhost";
buried. The delete command looks like this:
};


delete <id>\r\n
zone "127.in-addr.arpa" {
          type master;
          file "127.in-addr.arpa";
};


- <id> is the job id to delete.
zone "0.in-addr.arpa" {
          type master;
          file "0.in-addr.arpa";
};


The client then waits for one line of response, which may be:
zone "255.in-addr.arpa" {
          type master;
          file "255.in-addr.arpa";
};


- "DELETED\r\n" to indicate success.
// описание основной зоны
zone "example.com" {
          type slave;
          file "example.com";
          masters { 10.0.0.152; };
};


- "NOT_FOUND\r\n" if the job does not exist or is not either reserved by the
//описание обратной зоны
  client, ready, or buried. This could happen if the job timed out before the
zone "0.0.10.in-addr.arpa" {
  client sent the delete command.
          type slave;
          file "0.0.10.in-addr.arpa";
          masters { 10.0.0.152; };
};


The release command puts a reserved job back into the ready queue (and marks
// настройки логирования
its state as "ready") to be run by any client. It is normally used when the job
logging {
fails because of a transitory error. It looks like this:
          channel "misc" {
                    file "/var/log/bind/misc.log" versions 4 size 4m;
                    print-time YES;
                    print-severity YES;
                    print-category YES;
          };


release <id> <pri> <delay>\r\n
          channel "query" {
                    file "/var/log/bind/query.log" versions 4 size 4m;
                    print-time YES;
                    print-severity NO;
                    print-category NO;
          };


- <id> is the job id to release.
          category default {
                    "misc";
          };


  - <pri> is a new priority to assign to the job.
          category queries {
                    "query";
          };
};
после перезапуска наш slave сервер благополучно скопирует необходимую ему информацию с главного сервера, о чем будет говорить наличие файлов в каталоге:


  - <delay> is an integer number of seconds to wait before putting the job in
root@debian:~# ls -la /var/cache/bind/
  the ready queue. The job will be in the "delayed" state during this time.
итого 28
drwxrwxr-x  2 root bind 4096 Июл 8 18:47 .
drwxr-xr-x 10 root root 4096 Июл  8 15:17 ..
-rw-r--r--  1 bind bind  416 Июл  8 18:32 0.0.10.in-addr.arpa
......
-rw-r--r--  1 bind bind  455 Июл  8 18:32 example.com
........
В принципе,/stroallow-transfer {pngp slave сервер может не хранить копию зоны у себя в файловой системе. Эта копия нужна только в момент старта DNS. Наличие копии зоны в файловой системе может избавить от сбоя при недоступности master сервера во время запуска slave DNS. Если не указать опцию file в разделе zone, то копия не создается.


The client expects one line of response, which may be:
Настройка netfilter (iptables) для DNS BIND


- "RELEASED\r\n" to indicate success.
Собственно, настроив работу сервера, неплохо было бы его защитить. Мы знаем, что сервер работает на 53/udp порту. Почитав статью о том, что такое netfilter и правила iptables и ознакомившись с практическими примерами iptables, можно создать правила фильтрации сетевого трафика:


- "BURIED\r\n" if the server ran out of memory trying to grow the priority
dns ~ # iptables-save
  queue data structure.
# типовые правила iptables для DNS
*filter
:INPUT DROP [7511:662704]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -m conntrack --ctstate INVALID -j DROP
# разрешить доступ локальной сети к DNS серверу:
-A INPUT -s 192.168.1.1/24 -d 192.168.1.1/32 -p udp -m udp --dport 53 -m conntrack --ctstate NEW -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
-A OUTPUT -p icmp -j ACCEPT
-A OUTPUT -p udp -m udp --sport 32768:61000 -j ACCEPT
-A OUTPUT -p tcp -m tcp --sport 32768:61000 -j ACCEPT
-A OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
# разрешить доступ DNS серверу совершать исходящие запросы
-A OUTPUT -p udp -m udp --dport 53 -m conntrack --ctstate NEW -j ACCEPT
COMMIT
Это типовой пример! Для задания правил iptables под Ваши задачи и конфигурацию сети, необходимо понимать принцип работы netfilter в Linux, почитав вышеуказанные статьи.


- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.
Устранение неполадок


The bury command puts a job into the "buried" state. Buried jobs are put into a
Основным источником для выявления проблем с DNS является системный лог. Вот пример ошибок при запуске, когда я ошибся с путем к файлу зоны коревых серверов:
FIFO linked list and will not be touched by the server again until a client
kicks them with the "kick" command.


The bury command looks like this:
Jul  5 18:12:43 dns-server named[4224]: starting BIND 9.7.3 -u bind
Jul  5 18:12:43 dns-server named[4224]: built with '--prefix=/usr' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--sysconfdir=/etc/bind' '--localstatedir=/var' '--enable-threads' '--enable-largefile' '--with-libtool' '--enable-shared' '--enable-static' '--with-openssl=/usr' '--with-gssapi=/usr' '--with-gnu-ld' '--with-dlz-postgres=no' '--with-dlz-mysql=no' '--with-dlz-bdb=yes' '--with-dlz-filesystem=yes' '--with-dlz-ldap=yes' '--with-dlz-stub=yes' '--with-geoip=/usr' '--enable-ipv6' 'CFLAGS=-fno-strict-aliasing -DDIG_SIGCHASE -O2' 'LDFLAGS=' 'CPPFLAGS='
Jul  5 18:12:43 dns-server named[4224]: adjusted limit on open files from 1024 to 1048576
Jul  5 18:12:43 dns-server named[4224]: found 1 CPU, using 1 worker thread
Jul  5 18:12:43 dns-server named[4224]: using up to 4096 sockets
Jul  5 18:12:43 dns-server named[4224]: loading configuration from '/etc/bind/named.conf'
Jul  5 18:12:43 dns-server named[4224]: reading built-in trusted keys from file '/etc/bind/bind.keys'
Jul  5 18:12:43 dns-server named[4224]: using default UDP/IPv4 port range: [1024, 65535]
Jul  5 18:12:43 dns-server named[4224]: using default UDP/IPv6 port range: [1024, 65535]
Jul  5 18:12:43 dns-server named[4224]: listening on IPv4 interface lo, 127.0.0.1#53
Jul  5 18:12:43 dns-server named[4224]: listening on IPv4 interface eth1, 192.168.1.1#53
Jul  5 18:12:43 dns-server named[4224]: generating session key for dynamic DNS
Jul  5 18:12:43 dns-server named[4224]: could not configure root hints from '/etc/bind/db.root': file not found
Jul  5 18:12:43 dns-server named[4224]: loading configuration: file not found            # файл не найден
Jul  5 18:12:43 dns-server named[4224]: exiting (due to fatal error)
Jul  5 18:15:05 dns-server named[4298]: starting BIND 9.7.3 -u bind
Jul  5 18:15:05 dns-server named[4298]: built with '--prefix=/usr' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--sysconfdir=/etc/bind' '--localstatedir=/var' '--enable-threads' '--enable-largefile' '--with-libtool' '--enable-shared' '--enable-static' '--with-openssl=/usr' '--with-gssapi=/usr' '--with-gnu-ld' '--with-dlz-postgres=no' '--with-dlz-mysql=no' '--with-dlz-bdb=yes' '--with-dlz-filesystem=yes' '--with-dlz-ldap=yes' '--with-dlz-stub=yes' '--with-geoip=/usr' '--enable-ipv6' 'CFLAGS=-fno-strict-aliasing -DDIG_SIGCHASE -O2' 'LDFLAGS=' 'CPPFLAGS='
Jul  5 18:15:05 dns-server named[4298]: adjusted limit on open files from 1024 to 1048576
Jul  5 18:15:05 dns-server named[4298]: found 1 CPU, using 1 worker thread
Jul  5 18:15:05 dns-server named[4298]: using up to 4096 sockets
Jul  5 18:15:05 dns-server named[4298]: loading configuration from '/etc/bind/named.conf'
Jul  5 18:15:05 dns-server named[4298]: using default UDP/IPv4 port range: [1024, 65535]
Jul  5 18:15:05 dns-server named[4298]: using default UDP/IPv6 port range: [1024, 65535]
Jul  5 18:15:05 dns-server named[4298]: listening on IPv4 interface lo, 127.0.0.1#53
Jul  5 18:15:05 dns-server named[4298]: listening on IPv4 interface eth1, 192.168.1.1#53
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: 254.169.IN-ADDR.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: 2.0.192.IN-ADDR.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: 100.51.198.IN-ADDR.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: 113.0.203.IN-ADDR.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: 255.255.255.255.IN-ADDR.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: 0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: D.F.IP6.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: 8.E.F.IP6.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: 9.E.F.IP6.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: A.E.F.IP6.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: B.E.F.IP6.ARPA
Jul  5 18:15:05 dns-server named[4298]: automatic empty zone: 8.B.D.0.1.0.0.2.IP6.ARPA
Jul  5 18:15:05 dns-server named[4298]: zone 0.in-addr.arpa/IN: loaded serial 1
Jul  5 18:15:05 dns-server named[4298]: zone 127.in-addr.arpa/IN: loaded serial 1
Jul  5 18:15:05 dns-server named[4298]: zone 255.in-addr.arpa/IN: loaded serial 1
Jul  5 18:15:05 dns-server named[4298]: zone localhost/IN: loaded serial 2
Jul  5 18:15:05 dns-server named[4298]: running                                  # запуск прошел удачно
Отличным инструментом для диагностики являются команды диагностики DNS.


bury <id> <pri>\r\n
* [http://www.k-max.name/linux/howto-dns-server-bind/ HOWTO DNS сервер BIND (практика)]
 
- <id> is the job id to release.
 
- <pri> is a new priority to assign to the job.
 
There are two possible responses:
 
- "BURIED\r\n" to indicate success.
 
- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.
 
The "touch" command allows a worker to request more time to work on a job.
This is useful for jobs that potentially take a long time, but you still want
the benefits of a TTR pulling a job away from an unresponsive worker.  A worker
may periodically tell the server that it's still alive and processing a job
(e.g. it may do this on DEADLINE_SOON). The command postpones the auto
release of a reserved job until TTR seconds from when the command is issued.
 
The touch command looks like this:
 
touch <id>\r\n
 
- <id> is the ID of a job reserved by the current connection.
 
There are two possible responses:
 
- "TOUCHED\r\n" to indicate success.
 
- "NOT_FOUND\r\n" if the job does not exist or is not reserved by the client.
 
The "watch" command adds the named tube to the watch list for the current
connection. A reserve command will take a job from any of the tubes in the
watch list. For each new connection, the watch list initially consists of one
tube, named "default".
 
watch <tube>\r\n
 
- <tube> is a name at most 200 bytes. It specifies a tube to add to the watch
  list. If the tube doesn't exist, it will be created.
 
The reply is:
 
WATCHING <count>\r\n
 
- <count> is the integer number of tubes currently in the watch list.
 
The "ignore" command is for consumers. It removes the named tube from the
watch list for the current connection.
 
ignore <tube>\r\n
 
The reply is one of:
 
- "WATCHING <count>\r\n" to indicate success.
 
  - <count> is the integer number of tubes currently in the watch list.
 
- "NOT_IGNORED\r\n" if the client attempts to ignore the only tube in its
  watch list.
 
Other Commands
--------------
 
The peek commands let the client inspect a job in the system. There are four
variations. All but the first operate only on the currently used tube.
 
- "peek <id>\r\n" - return job <id>.
 
- "peek-ready\r\n" - return the next ready job.
 
- "peek-delayed\r\n" - return the delayed job with the shortest delay left.
 
- "peek-buried\r\n" - return the next job in the list of buried jobs.
 
There are two possible responses, either a single line:
 
- "NOT_FOUND\r\n" if the requested job doesn't exist or there are no jobs in
  the requested state.
 
Or a line followed by a chunk of data, if the command was successful:
 
FOUND <id> <bytes>\r\n
<data>\r\n
 
- <id> is the job id.
 
- <bytes> is an integer indicating the size of the job body, not including
  the trailing "\r\n".
 
- <data> is the job body -- a sequence of bytes of length <bytes> from the
  previous line.
 
The kick command applies only to the currently used tube. It moves jobs into
the ready queue. If there are any buried jobs, it will only kick buried jobs.
Otherwise it will kick delayed jobs. It looks like:
 
kick <bound>\r\n
 
- <bound> is an integer upper bound on the number of jobs to kick. The server
  will kick no more than <bound> jobs.
 
The response is of the form:
 
KICKED <count>\r\n
 
- <count> is an integer indicating the number of jobs actually kicked.
 
The kick-job command is a variant of kick that operates with a single job
identified by its job id. If the given job id exists and is in a buried or
delayed state, it will be moved to the ready queue of the the same tube where it
currently belongs. The syntax is:
 
kick-job <id>\r\n
 
- <id> is the job id to kick.
 
The response is one of:
 
- "NOT_FOUND\r\n" if the job does not exist or is not in a kickable state. This
  can also happen upon internal errors.
 
- "KICKED\r\n" when the operation succeeded.
 
The stats-job command gives statistical information about the specified job if
it exists. Its form is:
 
stats-job <id>\r\n
 
- <id> is a job id.
 
The response is one of:
 
- "NOT_FOUND\r\n" if the job does not exist.
 
- "OK <bytes>\r\n<data>\r\n"
 
  - <bytes> is the size of the following data section in bytes.
 
  - <data> is a sequence of bytes of length <bytes> from the previous line. It
    is a YAML file with statistical information represented a dictionary.
 
The stats-job data is a YAML file representing a single dictionary of strings
to scalars. It contains these keys:
 
- "id" is the job id
 
- "tube" is the name of the tube that contains this job
 
- "state" is "ready" or "delayed" or "reserved" or "buried"
 
- "pri" is the priority value set by the put, release, or bury commands.
 
- "age" is the time in seconds since the put command that created this job.
 
- "time-left" is the number of seconds left until the server puts this job
  into the ready queue. This number is only meaningful if the job is
  reserved or delayed. If the job is reserved and this amount of time
  elapses before its state changes, it is considered to have timed out.
 
- "file" is the number of the earliest binlog file containing this job.
  If -b wasn't used, this will be 0.
 
- "reserves" is the number of times this job has been reserved.
 
- "timeouts" is the number of times this job has timed out during a
  reservation.
 
- "releases" is the number of times a client has released this job from a
  reservation.
 
- "buries" is the number of times this job has been buried.
 
- "kicks" is the number of times this job has been kicked.
 
The stats-tube command gives statistical information about the specified tube
if it exists. Its form is:
 
stats-tube <tube>\r\n
 
- <tube> is a name at most 200 bytes. Stats will be returned for this tube.
 
The response is one of:
 
- "NOT_FOUND\r\n" if the tube does not exist.
 
- "OK <bytes>\r\n<data>\r\n"
 
  - <bytes> is the size of the following data section in bytes.
 
  - <data> is a sequence of bytes of length <bytes> from the previous line. It
    is a YAML file with statistical information represented a dictionary.
 
The stats-tube data is a YAML file representing a single dictionary of strings
to scalars. It contains these keys:
 
- "name" is the tube's name.
 
- "current-jobs-urgent" is the number of ready jobs with priority < 1024 in
  this tube.
 
- "current-jobs-ready" is the number of jobs in the ready queue in this tube.
 
- "current-jobs-reserved" is the number of jobs reserved by all clients in
  this tube.
 
- "current-jobs-delayed" is the number of delayed jobs in this tube.
 
- "current-jobs-buried" is the number of buried jobs in this tube.
 
- "total-jobs" is the cumulative count of jobs created in this tube in
  the current beanstalkd process.
 
- "current-using" is the number of open connections that are currently
  using this tube.
 
- "current-waiting" is the number of open connections that have issued a
  reserve command while watching this tube but not yet received a response.
 
- "current-watching" is the number of open connections that are currently
  watching this tube.
 
- "pause" is the number of seconds the tube has been paused for.
 
- "cmd-delete" is the cumulative number of delete commands for this tube
 
- "cmd-pause-tube" is the cumulative number of pause-tube commands for this
  tube.
 
- "pause-time-left" is the number of seconds until the tube is un-paused.
 
The stats command gives statistical information about the system as a whole.
Its form is:
 
stats\r\n
 
The server will respond:
 
OK <bytes>\r\n
<data>\r\n
 
- <bytes> is the size of the following data section in bytes.
 
- <data> is a sequence of bytes of length <bytes> from the previous line. It
  is a YAML file with statistical information represented a dictionary.
 
The stats data for the system is a YAML file representing a single dictionary
of strings to scalars. Entries described as "cumulative" are reset when the
beanstalkd process starts; they are not stored on disk with the -b flag.
 
- "current-jobs-urgent" is the number of ready jobs with priority < 1024.
 
- "current-jobs-ready" is the number of jobs in the ready queue.
 
- "current-jobs-reserved" is the number of jobs reserved by all clients.
 
- "current-jobs-delayed" is the number of delayed jobs.
 
- "current-jobs-buried" is the number of buried jobs.
 
- "cmd-put" is the cumulative number of put commands.
 
- "cmd-peek" is the cumulative number of peek commands.
 
- "cmd-peek-ready" is the cumulative number of peek-ready commands.
 
- "cmd-peek-delayed" is the cumulative number of peek-delayed commands.
 
- "cmd-peek-buried" is the cumulative number of peek-buried commands.
 
- "cmd-reserve" is the cumulative number of reserve commands.
 
- "cmd-use" is the cumulative number of use commands.
 
- "cmd-watch" is the cumulative number of watch commands.
 
- "cmd-ignore" is the cumulative number of ignore commands.
 
- "cmd-delete" is the cumulative number of delete commands.
 
- "cmd-release" is the cumulative number of release commands.
 
- "cmd-bury" is the cumulative number of bury commands.
 
- "cmd-kick" is the cumulative number of kick commands.
 
- "cmd-stats" is the cumulative number of stats commands.
 
- "cmd-stats-job" is the cumulative number of stats-job commands.
 
- "cmd-stats-tube" is the cumulative number of stats-tube commands.
 
- "cmd-list-tubes" is the cumulative number of list-tubes commands.
 
- "cmd-list-tube-used" is the cumulative number of list-tube-used commands.
 
- "cmd-list-tubes-watched" is the cumulative number of list-tubes-watched
  commands.
 
- "cmd-pause-tube" is the cumulative number of pause-tube commands.
 
- "job-timeouts" is the cumulative count of times a job has timed out.
 
- "total-jobs" is the cumulative count of jobs created.
 
- "max-job-size" is the maximum number of bytes in a job.
 
- "current-tubes" is the number of currently-existing tubes.
 
- "current-connections" is the number of currently open connections.
 
- "current-producers" is the number of open connections that have each
  issued at least one put command.
 
- "current-workers" is the number of open connections that have each issued
  at least one reserve command.
 
- "current-waiting" is the number of open connections that have issued a
  reserve command but not yet received a response.
 
- "total-connections" is the cumulative count of connections.
 
- "pid" is the process id of the server.
 
- "version" is the version string of the server.
 
- "rusage-utime" is the cumulative user CPU time of this process in seconds
  and microseconds.
 
- "rusage-stime" is the cumulative system CPU time of this process in
  seconds and microseconds.
 
- "uptime" is the number of seconds since this server process started running.
 
- "binlog-oldest-index" is the index of the oldest binlog file needed to
  store the current jobs.
 
- "binlog-current-index" is the index of the current binlog file being
  written to. If binlog is not active this value will be 0.
 
- "binlog-max-size" is the maximum size in bytes a binlog file is allowed
  to get before a new binlog file is opened.
 
- "binlog-records-written" is the cumulative number of records written
  to the binlog.
 
- "binlog-records-migrated" is the cumulative number of records written
  as part of compaction.
 
- "id" is a random id string for this server process, generated when each
  beanstalkd process starts.
 
- "hostname" the hostname of the machine as determined by uname.
 
The list-tubes command returns a list of all existing tubes. Its form is:
 
list-tubes\r\n
 
The response is:
 
OK <bytes>\r\n
<data>\r\n
 
- <bytes> is the size of the following data section in bytes.
 
- <data> is a sequence of bytes of length <bytes> from the previous line. It
  is a YAML file containing all tube names as a list of strings.
 
The list-tube-used command returns the tube currently being used by the
client. Its form is:
 
list-tube-used\r\n
 
The response is:
 
USING <tube>\r\n
 
- <tube> is the name of the tube being used.
 
The list-tubes-watched command returns a list tubes currently being watched by
the client. Its form is:
 
list-tubes-watched\r\n
 
The response is:
 
OK <bytes>\r\n
<data>\r\n
 
- <bytes> is the size of the following data section in bytes.
 
- <data> is a sequence of bytes of length <bytes> from the previous line. It
  is a YAML file containing watched tube names as a list of strings.
 
The quit command simply closes the connection. Its form is:
 
quit\r\n
 
The pause-tube command can delay any new job being reserved for a given time. Its form is:
 
pause-tube <tube-name> <delay>\r\n
 
- <tube> is the tube to pause
 
- <delay> is an integer number of seconds to wait before reserving any more
  jobs from the queue
 
There are two possible responses:
 
- "PAUSED\r\n" to indicate success.
 
- "NOT_FOUND\r\n" if the tube does not exist.

Версия от 16:26, 16 октября 2016

Исходные данные

Для корректной работы DNS нем необходимо иметь настроенную сеть. DNS в текущей статье будет настроен на дистрибутиве Debian, особенности других дистрибутивов тоже будут отмечены. Конфиг сети стенда следующий:

dns:~# cat /etc/network/interfaces
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
 address 10.0.0.152
 netmask 255.255.255.0
 gateway 10.0.0.254

auto eth1
iface eth1 inet static
 address 192.168.1.1
 netmask 255.255.255.0

где 10.0.0.152/24 - внешний интерфейс (подсеть, выделенная провайдером), 192.168.1.1/24 - внутренний (Локальная сеть). Настраиваемая зона будет иметь имя example.com. В примере со slave сервером, вторичный сервер будет расположен на IP 10.0.0.191.

Установка BIND9

Для работы DNS сервера необходимо установить пакет bind9 (в некоторых дистрибутивах - bind). Как отмечено на схеме - основным конфигурационным файлом BIND является файл named.conf (данный файл может быть размещен в каталоге /etc, иногда в /etc/bind ).

Параметры (синтаксис) named.conf

Синтаксис файла named.conf придерживается следующих правил:

IP-адреса - список IP должен быть разделен символом ";" , возможно указывать подсеть в формате 192.168.1.1/24 или 192.168.1.1/255.255.255.0, (для исключения IP перед ним нужно поставить знак !), возможно указывать имена "any", "none", "localhost" в двойных кавычках.

Комментарии - строки начинающиеся на #, // и заключенные в /* и */ считаются комментариями.

В файлах описания зон - символ @ является "переменной" хранящей имя зоны, указанной в конфигурационном файле named.conf или в директиве @ $ORIGIN текущего описания зоны.

Каждая завершенная строка параметров должна завершаться символом ; .

Раздел Acl Acl (access control list) - позволяет задать именованный список сетей. Формат раздела: acl "имя_сети" {ip; ip; ip; };

Раздел Options Раздел Options задает глобальные параметры конфигурационного файла, управляющие всеми зонами. Данный раздел имеет формат: options {операторы_раздела_Options};. Options может быть "вложен" в раздел Zone, при этом он переопределяет глобальные параметры. Часто используемые операторы options:

allow-query {список_ip} - Разрешает ответы на запросы только из список_ip. При отсутствии - сервер отвечает на все запросы.
allow-recursion {список_ip} - На запросы из список_ip будут выполняться рекурсивные запросы. Для остальных - итеративные. Если  не задан параметр, то сервер выполняет рекурсивные запросы для всех сетей.
allow-transfer {список_ip} - Указывает список серверов, которым разрешено брать зону с сервера (в основном тут указывают slave сервера)
directory /path/to/work/dir - указывает абсолютный путь к рабочему каталогу сервера. Этот оператор допустим только в разделе  options.
forwarders {ip порт, ip порт...} - указывает адреса хостов и если нужно порты, куда переадресовывать запросы (обычно тут указываются DNS провайдеров ISP).
forward ONLY или forward FIRST - параметр first указывает, DNS-серверу пытаться разрешать имена с помощью DNS-серверов, указанных в параметре forwarders, и лишь в случае, если разрешить имя с помощью данных серверов не удалось, то будет осуществлять попытки разрешения имени самостоятельно.
notify YES|NO - YES - уведомлять slave сервера об изменениях в зоне, NO - не уведомлять.
recursion YES|NO - YES - выполнять рекурсивные запросы, если просит клиент, NO - не выполнять (только итеративные запросы). Если ответ найден в кэше, то возвращается из кэша. (может использоваться только в разделе Options)

Раздел Zone Определяет описание зон(ы). Формат раздела: zone {операторы_раздела_zone}; Операторы, которые наиболее часто используются:

allow-update {список_ip} - указывает системы, которым разрешено динамически обновлять данную зону.
file "имя_файла" - указывает путь файла параметров зоны (должен быть расположен в каталоге, определенном в разделе options оператором directory)
masters {список_ip} -указывает список мастер-серверов. (допустим только в подчиненных зонах)
type "тип_зоны" - указывает тип зоны, описываемой в текущем разделе,тип_зоны может принимать следующие значения:
forward - указывает зону переадресации, которая переадресовывает запросы, пришедшие в эту зону.
hint - указывает вспомогательную зону (данный тип содержит информацию о корневых серверах, к которым сервер будет обращаться в случае невозможности найти ответ в кэше)
master - указывает работать в качестве мастер сервера для текущей зоны.
slave - указывает работать в качестве подчиненного сервера для текущей зоны.

Дополнительные параметры конфигурации Значения времени в файлах зон по умолчанию указывается в секундах, если за ними не стоит одна из следующих букв: S - секунды, M - минуты, H- часы, D - дни, W - недели. Соответственно, запись 2h20m5s будет иметь значение 2 часа 20 минут 5 секунд и соответствовать 8405 секунд.

Любое имя хоста/записи, не оканчивающиеся точкой считается неFQDN именем и будет дополнено именем текущей зоны. Например, запись domen в файле зоны examle.com будет развернуто в FQDN-имя domen.examle.com. .

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

$TTL - определяет TTL по-умолчанию для всех записей в текущей зоне.
$ORIGIN - изменяет имя зоны с указанного в файле named.conf. При этом, область действия данной директивы не распространяется  "выше" (то есть если файл включен директивой $INCLUDE, то область действия$ORIGN не распространяется на родительский)
$INCLUDE - включает указанный файл как часть файла зоны.

Для того чтобы локальный резолвер сервера тоже использовал локальный DNS, необходимо привести файл resolv.conf к следующему виду:

dns:~# cat /etc/resolv.conf
nameserver 127.0.0.1

Если в имени ресурсной записи встречается символ "*", то это он означает что вместо него можно подразумевать любую разрешенную последовательность символов. Такую запись называют "wildcard запись". Однако, символ "*" не может быть использован где угодно. Это может быть только первый символ в поле Name текущего домена, отделенный от остальных символом "."

Настройка кэширующего DNS сервера

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

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

named.conf;
описание серверов корневой зоны (зона типа hint);
описание зоны 127.in-addr.arpa.
dns:~# cat /etc/bind/named.conf
acl "lan" {
           192.168.1.1/24;
           127.0.0.1;
};

options {
           directory "/var/cache/bind";

          // If there is a firewall between you and nameservers you want
          // to talk to, you may need to fix the firewall to allow multiple
          // ports to talk.  See http://www.kb.cert.org/vuls/id/800113
          /*
          * Тут сказано, что если используется фаерволл, то необходимо
          *  нашему серверу создать соответствующие правила
          *  то есть открыть доступ по 53 TCP и UDP порту
          */

          forward first;              // задаем пересылку только первого запроса

          forwarders {                // указываем DNS сервера для пересылки
                     83.239.0.202;    // предоставленные провайдером
                     213.132.67.110;  // ибо до них ближе чем до корневых
          };

         listen-on { lan; };        // пусть слушает только нужные интерфейсы
         allow-query { lan; };      // разрешить запросы только из локальной сети
         allow-recursion { lan; };  // рекурсивные запросы тоже только из локальной
         allow-transfer { none; };  // трансфер зон нам не нужен

         version "unknown";         // не отображать версию DNS сервера при ответах

         auth-nxdomain no;    # для совместимости RFC1035
         listen-on-v6 { none; };    //IPv6 нам не нужен
         };

// описание настроек корневых серверов
zone "." {
         type hint;
         file "db.root";
};

// нижеописанные зоны определяют сервер авторитетным для петлевых
// интерфейсов, а так же для броадкаст-зон (согласно RFC 1912)

zone "localhost" {
         type master;
         file "localhost";
};

zone "127.in-addr.arpa" {
         type master;
          file "127.in-addr.arpa";
};

zone "0.in-addr.arpa" {
         type master;
         file "0.in-addr.arpa";
};

zone "255.in-addr.arpa" {
         type master;
         file "255.in-addr.arpa";
};

В данном примере приведен кэширующий DNS сервер, обрабатывающий запросы из списка сетей lan, в которую входит только одна локальная сеть 192.168.1.1/24 и петлевой интерфейс. При необходимости можно включить туда и другие сети. После определения списка сетей в директиве acl, в любом месте конфига можно будет ссылаться на этот список по имени (в нашем примере имя - lan), что, собственно и сделано в разделе options. Большинство параметров я прокомментировал, но отдельного внимания требует раздел, описывающий зону корневых серверов. В параметре file задан относительный путь к файлу описания корневых серверов (путь, относительно рабочего каталога сервера). За обновлениями данного файла необходимо следить, хотя он обновляется довольно редко (откуда брать обновленный файл я писал в теории DNS). Как вы заметили, имеется так же две записи для зоны localhost и две записи обратных зон для бродкаст доменов. Назначение этих зон состоит в том, чтобы избежать трансляции случайных запросов имен соответствующих IP-адресов на серверы, обслуживающие корневую зону.

Чтобы не вносить неразбериху в куче конфигурационных файлов, в статье я привожу примеры на основе единого конфигурационного файла. На самом деле, в последних версиях Debian (и других дистрибутивах Linux), файл named.conf выглядит следующим образом:

root@master:~# cat /etc/bind/named.conf // This is the primary configuration file for the BIND DNS server named. // // Please read /usr/share/doc/bind9/README.Debian.gz for information on the // structure of BIND configuration files in Debian, *BEFORE* you customize // this configuration file. // // If you are just adding zones, please do that in /etc/bind/named.conf.local

include "/etc/bind/named.conf.options"; include "/etc/bind/named.conf.local"; include "/etc/bind/named.conf.default-zones"; То есть основной файл не содержит конфигураций, а включает в себя более узко специализированные файлы, которые отвечают за свои задачи, например named.conf.options - содержит глобальные параметры конфигурации, named.conf.default-zones - содержит описание localhost и broadcast зон, а named.conf.local содержит описания зон, за которые отвечает данный сервер.


Далее, хочу обратить внимание на наличие файлов зон в каталоге, указанном в разделе options в параметре directory с именами, соответствующими параметрам file в разделах, описывающих зоны:

dns:~# ls -l /var/cache/bind/ итого 24 -rw-r--r-- 1 root root 237 Май 28 01:28 0.in-addr.arpa -rw-r--r-- 1 root root 271 Май 28 01:28 127.in-addr.arpa -rw-r--r-- 1 root root 237 Май 28 01:28 255.in-addr.arpa -rw-r--r-- 1 root root 2994 Май 28 01:28 db.root -rw-r--r-- 1 root root 270 Май 28 01:28 localhost dns:~# cat /var/cache/bind/127.in-addr.arpa

BIND reverse data file for local loopback interface

$TTL 604800 @ IN SOA localhost. root.localhost. (

                             1         ; Serial
                             604800    ; Refresh
                             86400     ; Retry
                             2419200   ; Expire
                             604800 )  ; Negative Cache TTL

@ IN NS localhost. 1.0.0 IN PTR localhost. Рассматривать файлы "петлевых" и бродкастовых зон не вижу смысла, т.к. после установки пакета bind настройки заданные по умолчанию в данных файлах вполне приемлемы. Далее, при организации мастер сервера мы рассмотрим пример описания файла зоны. Хочу обратить внимание, что мы настраиваем кэширующий сервер, а определяем мы его и как master для некоторых из зон. В нашем случае "кэширующий" говорит о том, что наш сервер не поддерживает ни одну из реально существующих зон, т.е. ему не делегировано прав на такое обслуживание.

Да, чуть не забыл, демон named должен быть разрешен для запуска на необходимых уровнях выполнения ОС (команда в RedHat - /sbin/chkconfig bind9 on, в Debian - /usr/sbin/update-rc.d bind9 defaults). После изменения конфигурационных файлов можно добавить сервис в автозагрузку и запустить демон:

dns:~# update-rc.d bind9 defaults Adding system startup for /etc/init.d/bind9 ... /etc/rc0.d/K20bind9 -> ../init.d/bind9 /etc/rc1.d/K20bind9 -> ../init.d/bind9 /etc/rc6.d/K20bind9 -> ../init.d/bind9 /etc/rc2.d/S20bind9 -> ../init.d/bind9 /etc/rc3.d/S20bind9 -> ../init.d/bind9 /etc/rc4.d/S20bind9 -> ../init.d/bind9 /etc/rc5.d/S20bind9 -> ../init.d/bind9 dns:~# /etc/init.d/bind9 start Starting domain name service...: bind9. На этом настройка кэширующего DNS завершена. Все запросы, которые попадают в кэш DNS сервера он хранит в оперативной памяти компьютера и при перезапуске демона эти данные обнуляются. Для проверки работы кэша можно выполнить команду nslookup mail.ru example.com., если в ответе содержится строка Non-authoritative answer, то адрес пришел из кэша, а так же если выполнить dig www.ru. (или другой домен, которого еще нет в кэше) и через некоторое время повторить команду, то время ответа должно быть гораздо меньше.

Давайте рассмотрим другие варианты сервера.

Главный (master) сервер зоны

Основной конфиг содержит следующие настройки:

dns:~# cat /etc/bind/named.conf acl "lan" {

         192.168.1.1/24;
         127.0.0.1;

};

options {

         directory "/var/cache/bind";
         allow-query { any; };       // отвечать на зпросы со всех интерфейсов
         recursion no;               // запретить рекурсивные запросы
         auth-nxdomain no;           // для совместимости RFC1035
         listen-on-v6 { none; };     // IPv6 нам не нужен
         version "unknown";          // не отображать версию DNS сервера при ответах
         /*
         *  Раскомментируйте строки ниже, если
         *  хотите разрешить рекрусивные запросы
         *  из локальной сети.
         *  (так же, необходимо закомментировать
         *  recursion no; )
         */
         # forwarders {                 // указываем DNS сервера для пересылки
         #         83.239.0.202;        // предоставленные провайдером
         #         213.132.67.110;      // ибо до них ближе чем до корневых
         # };
         # allow-recursion { lan; };    // рекурсивные запросы тоже только из локальной

};

// описание настроек корневых серверов zone "." {

         type hint;
         file "db.root";

};

// нижеописанные зоны определяют сервер авторитетным для петлевых // интерфейсов, а так же для броадкаст-зон (согласно RFC 1912)

zone "localhost" {

         type master;
         file "localhost";

};

zone "127.in-addr.arpa" {

         type master;
         file "127.in-addr.arpa";

};

zone "0.in-addr.arpa" {

         type master;
         file "0.in-addr.arpa";

};

zone "255.in-addr.arpa" {

         type master;
         file "255.in-addr.arpa";

};

// описание основной зоны zone "example.com" {

         type master;
         file "example.com";
         allow-transfer { 10.0.0.191; };

};

//описание обратных зон zone "0.0.10.in-addr.arpa" {

         type master;
         file "0.0.10.in-addr.arpa";
         allow-transfer { 10.0.0.191; };

};

zone "1.168.192.in-addr.arpa" {

         type master;
         file "1.168.192.in-addr.arpa";
  1. allow-transfer { 10.0.0.191; }; // зона описывает локальную сеть поэтому ее не передаем

};

// настройки логирования logging {

         channel "misc" {
                   file "/var/log/bind/misc.log" versions 4 size 4m;
                   print-time yes;
                   print-severity yes;
                   print-category yes;
         };
         channel "query" {
                   file "/var/log/bind/query.log" versions 4 size 4m;
                   print-time yes;
                   print-severity no;
                   print-category no;
         };
         category default {
                   "misc";
         };
         category queries {
                   "query";
         };

}; Давайте кратко разберем конфигурационный файл и настройки master сервера: мы настраиваем мастер сервер для зоны example.com. . Согласно конфига, наш BIND имеет рабочий каталог /var/cache/bind, сервер отвечает на запросы со всех интерфейсов (allow-query {any ;};), рекурсивные запросы обрабатывает как итеративные (recursion no), является мастер-сервером для зоны example.com и локальных служебных зон (type master). При этом, если необходимо разрешить кэширование (то есть рекурсивные запросы) для локальной сети, то необходимо раскомментировать параметры forwarders и allow-recursion и закомментировать recursion no;.

Так же, для примера, я привел возможности BIND логировать все происходящее при работе сервера (можно для этой цели использовать syslog). В разделе logging задаются 2 параметра channel (можно и больше двух - на ваше усмотрение), эти параметры дословно можно назвать "канал" записи. Каждый канал определяет имя канала и настройки параметров записи (что записывать, а что - нет и куда писать). Директива category задает какую категорию сообщений в какой канал отправлять. Исходя из этого, мы имеем: запись стандартной информации в канал misc, а приходящие запросы посылаются в канал query. При этом, если файлы журнала достигают 4Мб (size 4m), он переименовывается добавлением к имени .1 и начинается запись в новый журнал, числа в конце других журналов увеличиваются. Журналы с номером, более указанного в version (в нашем случае 4) удаляются (Управлять ротацией логов можно так же с помощью logrotate). Параметры print* определяют заносить ли в журнал время появления, важность и категорию информации. Более подробно про настройки раздела logging можно почитать в man (5) named.conf.

Отдельно хочется описать параметр allow-transfer { 10.0.0.191; };. Данный параметр описывает серверы, которым разрешено скачивать копию зоны - т.н. slave серверА. В следующем примере мы разберем настройку slave DNS.

Для корректной работы логирования необходимо создать соответствующий каталог и присвоить необходимые права:

dns:~# mkdir /var/log/bind/ dns:~# chmod 744 /var/log/bind/ dns:~# ps aux | grep named bind 4298 0.0 3.4 46792 13272 ? Ssl Jul05 0:00 /usr/sbin/named -u bind root 4815 0.0 0.1 3304 772 pts/4 S+ 18:19 0:00 grep named dns:~# chown bind /var/log/bind/ dns:~# ls -ld /var/log/bind/ drwxr--r-- 2 bind root 4096 Июл 6 18:18 /var/log/bind/ Давайте далее рассмотрим наш файл описания зоны example.com.:

dns:~# cat /var/cache/bind/example.com $TTL 3D @ IN SOA ns.example.com. root.example.com. (

                                       2011070601      ; serial
                                       8H              ; refresh
                                       2H              ; retry
                                       2W              ; expire
                                       1D)             ; minimum

@ IN NS ns.example.com. @ IN NS ns2.example.com. @ IN A 10.0.0.152 @ IN MX 5 mx.example.com. ns IN A 10.0.0.152 ns2 IN A 10.0.0.191 mx IN A 10.0.0.152 www IN CNAME @ а так же в домене in-addr.arpa.

dns:~# cat /var/cache/bind/0.0.10.in-addr.arpa $TTL 3600 @ IN SOA ns.examle.com. root.example.com. (

            2007042001 ; Serial
            3600       ; Refresh
            900        ; Retry
            3600000    ; Expire
            3600 )     ; Minimum
       IN      NS      ns.examle.com.
       IN      NS      ns2.example.com.

152 IN PTR examle.com. 191 IN PTR ns.example.com.

  • IN PTR examle.com.

dns:~# cat /var/cache/bind/1.168.192.in-addr.arpa $TTL 3600 @ IN SOA ns.examle.com. root.example.com. (

            2007042001 ; Serial
            3600       ; Refresh
            900        ; Retry
            3600000    ; Expire
            3600 )     ; Minimum
       IN      NS      ns.examle.com.
       IN      NS      ns2.example.com.
  • IN PTR examle.com.

Наша сеть небольшая, предполагается, что в сети совсем мало машин. Все сервисы сети размещены на одном хосте example.com., поэтому и master DNS (ns.example.com.) и почтовый сервер (mx.example.com.) указывает на одну машину (10.0.0.152).

Вторичный (secondary, slave) авторитетный сервер зоны

Основная функция slave сервера - автоматическая синхронизация описания зоны с master сервером. Данная задача регламентируется документом RFC 1034 в разделе 4.3.5. Согласно данному документу обмен данными между серверами рекомендовано производить по протоколу TCP, посредством запроса AXFR. По этому запросу за одно TCP соединение должна передаваться вся зона целиком (RFC 1035).

Так же, slave DNS-сервер делит нагрузку с master сервером или принимает на себя всю нагрузку в случае аварии па первом сервере.

Прежде чем приступить к настройке slave DNS сервера, необходимо проверить возможность получения зоны вручную со вторичного сервера с помощью следующей команды:

root@debian:~# dig @10.0.0.152 example.com. axfr

<<>> DiG 9.7.3 <<>> @10.0.0.152 example.com. axfr
(1 server found)
global options
+cmd

example.com. 259200 IN SOA ns.example.com. root.example.com. 2011070801 28800 7200 1209600 86400 example.com. 259200 IN NS ns.example.com. example.com. 259200 IN NS ns2.example.com. example.com. 259200 IN A 10.0.0.152 example.com. 259200 IN MX 5 mx.example.com. mx.example.com. 259200 IN A 10.0.0.152 ns.example.com. 259200 IN A 10.0.0.152 ns2.example.com. 259200 IN A 10.0.0.191 www.example.com. 259200 IN CNAME example.com. example.com. 259200 IN SOA ns.example.com. root.example.com. 2011070801 28800 7200 1209600 86400

Query time
14 msec
SERVER
10.0.0.152#53(10.0.0.152)
WHEN
Fri Jul 8 15:33:54 2011
XFR size
11 records (messages 1, bytes 258)

Получение зоны прошло успешно. Далее, для настройки подчиненного сервера, алгоритм следующий:

Скопировать конфигурационный файл named.conf с master сервера; Заменить параметр type master на type slave в тех зонах, для которых он будет вторичным; Параметр allow-transfer { 10.0.0.191; }; заменить на masters { 10.0.0.152;}; в тех зонах, для которых он будет вторичным; Удалить зоны, которые не будет обслуживать текущий сервер, в том числе и корневую, если slave не будет отвечать на рекурсивные запросы; Создать каталоги для логов, как в предыдущем примере. Итого, мы получаем конфиг slave сервера:

root@debian:~# cat /etc/bind/named.conf options {

         directory "/var/cache/bind";
         allow-query { any; };      // отвечать на запросы со всех интерфейсов
         recursion no;              // запретить рекурсивные запросы
         auth-nxdomain no;          // для совместимости RFC1035
         listen-on-v6 { none; };    // IPv6 нам не нужен
         version "unknown";         // не отображать версию DNS сервера при ответах

};

// нижеописанные зоны определяют сервер авторитетным для петлевых // интерфейсов, а так же для броадкаст-зон (согласно RFC 1912)

zone "localhost" {

         type master;
         file "localhost";

};

zone "127.in-addr.arpa" {

         type master;
         file "127.in-addr.arpa";

};

zone "0.in-addr.arpa" {

         type master;
         file "0.in-addr.arpa";

};

zone "255.in-addr.arpa" {

         type master;
         file "255.in-addr.arpa";

};

// описание основной зоны zone "example.com" {

         type slave;
         file "example.com";
         masters { 10.0.0.152; };

};

//описание обратной зоны zone "0.0.10.in-addr.arpa" {

         type slave;
         file "0.0.10.in-addr.arpa";
         masters { 10.0.0.152; };

};

// настройки логирования logging {

         channel "misc" {
                   file "/var/log/bind/misc.log" versions 4 size 4m;
                   print-time YES;
                   print-severity YES;
                   print-category YES;
         };
         channel "query" {
                   file "/var/log/bind/query.log" versions 4 size 4m;
                   print-time YES;
                   print-severity NO;
                   print-category NO;
         };
         category default {
                   "misc";
         };
         category queries {
                   "query";
         };

}; после перезапуска наш slave сервер благополучно скопирует необходимую ему информацию с главного сервера, о чем будет говорить наличие файлов в каталоге:

root@debian:~# ls -la /var/cache/bind/ итого 28 drwxrwxr-x 2 root bind 4096 Июл 8 18:47 . drwxr-xr-x 10 root root 4096 Июл 8 15:17 .. -rw-r--r-- 1 bind bind 416 Июл 8 18:32 0.0.10.in-addr.arpa ...... -rw-r--r-- 1 bind bind 455 Июл 8 18:32 example.com ........ В принципе,/stroallow-transfer {pngp slave сервер может не хранить копию зоны у себя в файловой системе. Эта копия нужна только в момент старта DNS. Наличие копии зоны в файловой системе может избавить от сбоя при недоступности master сервера во время запуска slave DNS. Если не указать опцию file в разделе zone, то копия не создается.

Настройка netfilter (iptables) для DNS BIND

Собственно, настроив работу сервера, неплохо было бы его защитить. Мы знаем, что сервер работает на 53/udp порту. Почитав статью о том, что такое netfilter и правила iptables и ознакомившись с практическими примерами iptables, можно создать правила фильтрации сетевого трафика:

dns ~ # iptables-save

  1. типовые правила iptables для DNS
  • filter
INPUT DROP [7511:662704]
FORWARD DROP [0:0]
OUTPUT DROP [0:0]

-A INPUT -i lo -j ACCEPT -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A INPUT -m conntrack --ctstate INVALID -j DROP

  1. разрешить доступ локальной сети к DNS серверу:

-A INPUT -s 192.168.1.1/24 -d 192.168.1.1/32 -p udp -m udp --dport 53 -m conntrack --ctstate NEW -j ACCEPT -A OUTPUT -o lo -j ACCEPT -A OUTPUT -p icmp -j ACCEPT -A OUTPUT -p udp -m udp --sport 32768:61000 -j ACCEPT -A OUTPUT -p tcp -m tcp --sport 32768:61000 -j ACCEPT -A OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

  1. разрешить доступ DNS серверу совершать исходящие запросы

-A OUTPUT -p udp -m udp --dport 53 -m conntrack --ctstate NEW -j ACCEPT COMMIT Это типовой пример! Для задания правил iptables под Ваши задачи и конфигурацию сети, необходимо понимать принцип работы netfilter в Linux, почитав вышеуказанные статьи.

Устранение неполадок

Основным источником для выявления проблем с DNS является системный лог. Вот пример ошибок при запуске, когда я ошибся с путем к файлу зоны коревых серверов:

Jul 5 18:12:43 dns-server named[4224]: starting BIND 9.7.3 -u bind Jul 5 18:12:43 dns-server named[4224]: built with '--prefix=/usr' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--sysconfdir=/etc/bind' '--localstatedir=/var' '--enable-threads' '--enable-largefile' '--with-libtool' '--enable-shared' '--enable-static' '--with-openssl=/usr' '--with-gssapi=/usr' '--with-gnu-ld' '--with-dlz-postgres=no' '--with-dlz-mysql=no' '--with-dlz-bdb=yes' '--with-dlz-filesystem=yes' '--with-dlz-ldap=yes' '--with-dlz-stub=yes' '--with-geoip=/usr' '--enable-ipv6' 'CFLAGS=-fno-strict-aliasing -DDIG_SIGCHASE -O2' 'LDFLAGS=' 'CPPFLAGS=' Jul 5 18:12:43 dns-server named[4224]: adjusted limit on open files from 1024 to 1048576 Jul 5 18:12:43 dns-server named[4224]: found 1 CPU, using 1 worker thread Jul 5 18:12:43 dns-server named[4224]: using up to 4096 sockets Jul 5 18:12:43 dns-server named[4224]: loading configuration from '/etc/bind/named.conf' Jul 5 18:12:43 dns-server named[4224]: reading built-in trusted keys from file '/etc/bind/bind.keys' Jul 5 18:12:43 dns-server named[4224]: using default UDP/IPv4 port range: [1024, 65535] Jul 5 18:12:43 dns-server named[4224]: using default UDP/IPv6 port range: [1024, 65535] Jul 5 18:12:43 dns-server named[4224]: listening on IPv4 interface lo, 127.0.0.1#53 Jul 5 18:12:43 dns-server named[4224]: listening on IPv4 interface eth1, 192.168.1.1#53 Jul 5 18:12:43 dns-server named[4224]: generating session key for dynamic DNS Jul 5 18:12:43 dns-server named[4224]: could not configure root hints from '/etc/bind/db.root': file not found Jul 5 18:12:43 dns-server named[4224]: loading configuration: file not found # файл не найден Jul 5 18:12:43 dns-server named[4224]: exiting (due to fatal error) Jul 5 18:15:05 dns-server named[4298]: starting BIND 9.7.3 -u bind Jul 5 18:15:05 dns-server named[4298]: built with '--prefix=/usr' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--sysconfdir=/etc/bind' '--localstatedir=/var' '--enable-threads' '--enable-largefile' '--with-libtool' '--enable-shared' '--enable-static' '--with-openssl=/usr' '--with-gssapi=/usr' '--with-gnu-ld' '--with-dlz-postgres=no' '--with-dlz-mysql=no' '--with-dlz-bdb=yes' '--with-dlz-filesystem=yes' '--with-dlz-ldap=yes' '--with-dlz-stub=yes' '--with-geoip=/usr' '--enable-ipv6' 'CFLAGS=-fno-strict-aliasing -DDIG_SIGCHASE -O2' 'LDFLAGS=' 'CPPFLAGS=' Jul 5 18:15:05 dns-server named[4298]: adjusted limit on open files from 1024 to 1048576 Jul 5 18:15:05 dns-server named[4298]: found 1 CPU, using 1 worker thread Jul 5 18:15:05 dns-server named[4298]: using up to 4096 sockets Jul 5 18:15:05 dns-server named[4298]: loading configuration from '/etc/bind/named.conf' Jul 5 18:15:05 dns-server named[4298]: using default UDP/IPv4 port range: [1024, 65535] Jul 5 18:15:05 dns-server named[4298]: using default UDP/IPv6 port range: [1024, 65535] Jul 5 18:15:05 dns-server named[4298]: listening on IPv4 interface lo, 127.0.0.1#53 Jul 5 18:15:05 dns-server named[4298]: listening on IPv4 interface eth1, 192.168.1.1#53 Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: 254.169.IN-ADDR.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: 2.0.192.IN-ADDR.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: 100.51.198.IN-ADDR.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: 113.0.203.IN-ADDR.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: 255.255.255.255.IN-ADDR.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: 0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: D.F.IP6.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: 8.E.F.IP6.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: 9.E.F.IP6.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: A.E.F.IP6.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: B.E.F.IP6.ARPA Jul 5 18:15:05 dns-server named[4298]: automatic empty zone: 8.B.D.0.1.0.0.2.IP6.ARPA Jul 5 18:15:05 dns-server named[4298]: zone 0.in-addr.arpa/IN: loaded serial 1 Jul 5 18:15:05 dns-server named[4298]: zone 127.in-addr.arpa/IN: loaded serial 1 Jul 5 18:15:05 dns-server named[4298]: zone 255.in-addr.arpa/IN: loaded serial 1 Jul 5 18:15:05 dns-server named[4298]: zone localhost/IN: loaded serial 2 Jul 5 18:15:05 dns-server named[4298]: running # запуск прошел удачно Отличным инструментом для диагностики являются команды диагностики DNS.