среда, 16 мая 2018 г.

Redis Sentinel: Make your dataset highly available

Source.

At this point the Sentinel jumps in. So what is this Sentinel stuff? The Sentinel process is a Redis Instance which was started with the –sentinel Option (or redis-sentinel binary). It needs a configuration file that tells the Sentinel which Redis master it should monitor.
In short, these are the benefits of using Sentinel:
  • Monitoring: Sentinel constantly checks if the Redis master and its slave instances are working.
  • Notifications: It can notify the system administrators or other tools via an API if something happens to your Redis instances.
  • Automatic Failover: When Sentinel detects a failure of the master node it will start a failover where a slave is promoted to master. The additional slaves will be reconfigured automatically to use the new master. The application/clients that are using the Redis setup will be informed about the new address to use for the connection.
  • Configuration provider: Sentinel can be used for service discovery. That means clients can connect to the Sentinel in order to ask for the current address of your Redis master. After a failover Sentinel will provide the new address.

Configuration and example setup with three nodes

The Sentinel processes are a part of a distributed system. That means your Sentinel processes are working together. For a high availability setup we suggest using more than one Sentinel, as Sentinel itself should not be a single point of failure. It also improves the proper failure detection via quorum.
Before you deploy Sentinel, consider the following facts. More in-depth information on the most important points can be found below:
  • At least Three Sentinel instances are needed for a robust deployment.
  • Separate your Sentinel instances with different VMs or servers.
  • Due to the asynchronous replication of Redis the distributed setup does not guarantee that acknowledged writes are retained during failures.
  • Your client-library needs to support Sentinel.
  • Test your high availability setup from time to time in your test environment and even in production systems.
  • Sentinel, Docker or other NAT/Port Mapping technologies should only be mixed with care.
A three node setup is a good start, so run your Redis Master and two Slaves before setting up the Sentinel processes. On each of your Redis Hosts you create the same Sentinel config (/etc/redis-sentinel.conf, depending on your Linux distribution), like so:
Let’s dig deeper and see what these options do:
  1. This line tells Sentinel which master to monitor (myHAsetup). The Sentinel will find the host at 192.168.1.3:6379. The quorum for this setup is 2. The quorum is only used to detect failures: This number of Sentinels must agree about the fact that the master is not reachable. When a failure is detected, one Sentinel is elected as the leader who authorizes the failover. This happens when the majority of Sentinel processes vote for the leader.
  2. The time in milliseconds an instance is allowed be unreachable for a Sentinel (not answering to PINGs or replies with an error). After this time, the master is considered to be down.
  3. The timeout in milliseconds that Sentinel will wait after a failover before initiating a new failover.
  4. The number of slaves that can sync with the new master at the same time after a failover. The lower the number the longer the failover will need to complete. Using the slaves to serve old data to clients, you maybe don’t want to re-synchronize all slaves with the new master at the same time as there is a very short timeframe in which the slave stops while loading the bulk data from the master. In this case set it to 1.If this does not matter set it to the maximum of slaves that might be connected to the master.
  5. Listen IP, limited to one interface.
After you set up the Sentinel configuration for your instances, start it via init script, systemd unit or simply via its binary (redis-server /path/to/sentinel.conf –sentinel). The Sentinel processes will discover the master, slaves and other connected sentinels and the system is complete. Let’s see now what the setup looks like and what happens during a failover.
redis-sentinel
We have three Redis instances and three Sentinel instances:
M1 = Master
R1 = Replica 1 / Slave 1
R2 = Replica 2 / Slave 2
S1 = Sentinel 1
S2 = Sentinel 2
S3 = Sentinel 3
Let’s check the status of the Sentinel: Via the option -p 26379 you connect directly to the Sentinel API.
As you see the Sentinels are monitoring one master “myHAsetup”, their status is OK and you can see how many slaves and other Sentinels are discovered.
So far so good, everything looks fine. Now let’s see what happens when the master is unresponsive: We can simulate an outage by issuing the following command.
This produces the following log file:
Here a short summary of what happens
  1. Failure is detected
  2. Config-Version Epoch is increased by +1
  3. Leader is elected
  4. Quorum check. 3 Sentinels see the master down
  5. Delay for the next possible failover, after the current one
  6. – 10. Failover to the new master, reconfiguration of the slave nodes (old master 192.168.1.29 is already marked as slave and down at the moment)
  7. Old master comes back to the setup (after hanging in DEBUG for 30 seconds)
  8. Old master is converted to slave and synchronizes to the new master.
Another check with the Sentinel API confirms the new master:
At the end downtime sums up to around 7-8 seconds (6 to detect the failure + 1-2 seconds to fulfill the failover). With a stable network setup without flapping you might be able to reduce the failure detection from 6 seconds to 3 seconds, thus minimizing the downtime, during which no writes are accepted.

Maintainance

So how do you maintain such a setup? In general the procedure is similar to other high availability setups: Before you start, take a backup of your keyspace with an RDB snapshot and copy it to save place, e.g. by updating the redis.conf and increasing the ‚maxmemory‘ parameter or modifying the save parameter for the RDB snapshot engine.
  • stop Redis at one slave node
  • update the config file
  • start Redis
  • wait until the node is synchronized properly
  • repeat for the second slave
  • repeat for the master node (causing a failover)
  • change complete
Another example, where you want to update the redis-package:
  • check the change-log from the new Redis version, if there was no harmful change you can go on
  • backup your keyspace, best would be a RDB snapshot
  • stop Redis and Sentinel
  • copy both config files to a save place on the server
  • update the Redis package
  • copy both configs from save place to the config-dir (/etc/)
  • start Sentinel
  • check whether the updated Sentinel starts and is considered active by the other Sentinels
  • if not, check the logfile for the cause of the issue
  • if yes, start Redis and check the startup and logfile if everything looks fine
  • repeat for the other slave, and then for the master.
  • update complete
After these two examples we inspect the Sentinel with its API:
This is very simple – but shows that the Sentinel works properly. To bring this article to a close, let’s take a look at some advanced commands. They all follow roughly the same pattern:
CommandDescription
sentinel mastersShow a list of all monitored masters + state
sentinel master <master name>Show the state of a specified master
sentinel slaves <master name>Show the slaves of the master + state
sentinel sentinels <master name>Show the Sentinel instances for this master + state
sentinel get-master-addr-by-name <master name>Return ip and port of the master. While a failover is in progress the ip and port of the promoted slave are returned
sentinel reset <pattern>Reset the masters with a matching name. Clears previous state for the master, removes every slave and sentinel discovered. A fresh discovery is started.
sentinel failover <master name>Force a failover, as if the master was not reachable
sentinel ckquorum <master name>Check if the current Sentinel configuration is able to reach quorum and majority
sentinel flushconfigForce Sentinel to rewrite it’s configuration on disk
sentinel monitor <name> <ip> <port> <quorum>During runtime, tell Sentinel to start monitoring a new master
sentinel remove <name>Remove a specified master from monitoring
sentinel set <name>  <option> <value>Similar to config set with Redis, you can change Sentinel options. All options at the Sentinel configuration file can also be set here

пятница, 4 мая 2018 г.

PostgreSQL: How to reload config settings without restarting database

Source

If you are making modifications to the Postgres configuration file postgresql.conf (or similar), and you want to new settings to take effect without needing to restart the entire database, there are two ways to accomplish this.

Option 1: From the command-line shell

su - postgres
/usr/bin/pg_ctl reload

Option 2: Using SQL

SELECT pg_reload_conf();
Using either option will not interrupt any active queries or connections to the database, thus applying these changes seemlessly.

пятница, 20 апреля 2018 г.

Change VmWare SCSI controller type in VM Centos 7 VM

Source

In RHEL 7.x this is a bit different as modprobe.conf doesn't exist.
In my case I needed to change the controller for the root disk from Paravirtual to LSI Logic SAS. As the previous posts suggest, this needs to be done in two places, the regular disk and the RamDisk as both will need to boot with the new driver.
First, if possible, clone your machine, don't snapshot it. Whenever you are working with disks, it's best not to involve snapshots. You may not need to do this second step, I did it in the theory that the disk controller would initialize itself if introduced to the system through an additional disk, just like you'd do for Windows: Second step - Shut down your VM, Attach a 1 GB disk using the SCSI controller type you'd like to change your root disk to and bring the system back up to modprobe discover it. (You might be able to do this hot) Third step - run the following command to add the correct driver to the RamDisk (Remember in my case I was moving from the VMWare Paravirtual to the LSI Logic SAS driver. It's likely you are going the opposite way, but you just need to change the driver type: dracut -f -v --add-drivers mptsas
Other options for drivers are: mptspi mptscsih mptbase
After doing this, shut down and remove the 1 GB temporary disk. Change the controller for the root disk to whatever driver you just added to the ramdisk, and boot up the system.

вторник, 3 апреля 2018 г.

Creating Kerberos Keytab Files Compatible with Active Directory

Source

How to create a keytab file for a Kerberos user logging into Active Directory.  What's a keytab file?  It's basically a file that contains a table of user accounts, with an encrypted hash of the user's password.  Why have a keytab file?  Well, when you want a server process to automatically logon to Active Directory on startup, you have two options:  type the password (in clear text) into a config file somewhere, or store an encrypted hash of the password in a keytab file.  Which is safer?  Well, you can decide.  In any case, you'd better do a good job of protecting the file (be it a config file or a keytab).

Anyway, the accepted way to store a hashed password in Kerberos is to use a keytab file.  Now the file can be created using a number of utilities.  On a Windows machine, you can use ktpass.exe.  On Ubuntu Linux, you can use ktutil.



Before I demonstrate how to create the keytab, a word about encryption.  There are a number of encryption types used for hashing a password.  These include DES-CBC-CRC, DES-CBC-MD5, RC4-HMAC and a few others.  Active Directory uses RC4-HMAC by default.  Back in Windows 2000, you could also use the DES types without any trouble, but since Windows 2003, only RC4-HMAC is supported, unless you make a registry change (to all of your domain controllers).  If you need to use DES for some reason, then refer to the Technet article at the bottom of the page.

Before attempting to create a keytab file, you'll need to know the user's kerberos principal name, in the form of username@MYDOMAIN.COM, and the user's password.

Creating a KeyTab on Windows (tested on Windows Server 2008 R2)
Open a command prompt and type the following command:


ktpass /princ username@MYDOMAIN.COM /pass password /ptype KRB5_NT_PRINCIPAL /out username.keytab
Creating a KeyTab on Ubuntu Linux (tested on Ubuntu 10.10 - Maverick Meerkat)
Open a terminal window and type the following commands:

ktutil
addent -password -p username@MYDOMAIN.COM -k 1 -e RC4-HMAC
- enter password for username -
wkt username.keytab
q

Testing the Keytab File
Now in order to test the keytab, you'll need a copy of kinit.  You can use the version that's on Ubuntu, or if on Windows, you can install the latest Java runtime from Sun (JRE).  In either case, you'll need to setup your /etc/krb5.conf file (on Linux) or c:\windows\krb5.ini (on Windows).  Either file should look something like this:

[libdefaults]
default_realm = MYDOMAIN.COM
krb4_config = /etc/krb.conf
krb4_realms = /etc/krb.realms
kdc_timesync = 1
ccache_type = 4
forwardable = true
proxiable = true

[realms]
MYDOMAIN.COM = {
kdc = mydomain.com:88
admin_server = mydomain.com
default_domain = mydomain.com
}

[domain_realm]
.mydomain.com = MYDOMAIN.COM
mydomain.com = MYDOMAIN.COM

[login]
krb4_convert = true
krb4_get_tickets = false

Once you've got your Kerberos file setup, you can use kinit to test the keytab.  First, try to logon with your user account without using the keytab:

kinit username@MYDOMAIN.COM
- enter the password -

If that doesn't work, your krb5 file is wrong.  If it does work, now try the keytab file:

kinit username@MYDOMAIN.COM -k -t username.keytab

Now you should successfully authenticate without being prompted for a password.  Success!

More Information
If you need to use any other encryption Type than RC4-HMAC, then you'll need to tweak your AD domain controllers.  Please refer to the following TechNet article.

четверг, 14 декабря 2017 г.

How to unlock an user account in Linux?

Source

How to unlock a user account in Linux?

Some times on Linux boxes the user account will be locked due to issues such as wrong password entry, account expiry etc. In this post we will see how to unlock user account with different commands.
Example1: Check if the password is disabled by viewing /etc/shadow file for user entry.
grep ‘username’ /etc/shadow
if you are able to see ! in the second field starting that indicates that password is disabled, you have to enable it back by using passwd with -u option
passwd -u username
Example:
passwd -u surendra
Unlocking password for user temp.
passwd: Success
Example2: Check if the user expiry date is reached or not by using chage command
chage -l username
Example
chage -l surendra
Last password change : Jan 05, 2012
Password expires : never
Password inactive : never
Account expires : Jan 01, 2012
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7


If you see that the account expires use usermod or chage command to extend the user expiry time.
usermod -e yyyy-mm-dd username
usermod -e 2012-05-10 surendra
or
chage -E yyyy-mm-dd username
chage -E 2012-05-10 surendra
this will extend user expiry time to 5 more months.
Example3: Check if the user shell is set to a valid shell or not, if it’s not set it to a valid one.
grep ‘username’ /etc/passwd
Example:
grep ‘surendra’ /etc/passwd
If the user shell in seventh feild is set to /sbin/nologin or /bin/false set it back to /bin/bash or /bin/ksh
usermod -s /bin/bash usrename
usermod -s /bin/bash surendra
Share your thoughts on this and let us know if you have other ideas to unlock user accounts in Linux.

воскресенье, 20 августа 2017 г.

Force unmount of NFS-mounted directory

source


If the NFS server disappeared and you can't get it back online, one trick that I use is to add an alias to the interface with the IP of the NFS server (in this example, 192.0.2.55).

Linux

The command for that is something roughly like:
ifconfig eth0:fakenfs 192.0.2.55 netmask 255.255.255.255
Where 192.0.2.55 is the IP of the NFS server that went away. You should then be able to ping the address, and you should also be able to unmount the filesystem (use unmount -f). You should then destroy the aliased interface so you no longer route traffic to the old NFS server to yourself with:
ifconfig eth0:fakenfs down 
 
 umount -f -l /my/mount/dir

понедельник, 14 августа 2017 г.

Установка Bind 9 (named) в CentOS 7

Источник

Устанавливаем Bind 9 (named) в CentOS 7

Первым делом проверим, установлен ли у нас днс сервер в системе:
# rpm -qa bind*
 bind-libs-lite-9.9.4-14.el7.x86_64
 bind-license-9.9.4-14.el7.noarch
У меня не установлен, так как во время инсталляции centos выбрал минимальный пакет программ. Сервер имен у нас будет работать в chroot окружении, так что устанавливаем соответствующие пакеты:
# yum -y install bind bind-utils bind-chroot
Установка bind в CentOS 7
Еще раз обращаю внимание, что мы будем использовать bind в chroot среде для увеличения безопасности. Это накладывает определенные особенности в настройке и управлении сервером. Нужно быть внимательным в этих мелочах. Итак, запускаем bind:
# systemctl start named-chroot
# systemctl enable named-chroot
ln -s '/usr/lib/systemd/system/named-chroot.service' '/etc/systemd/system/multi-user.target.wants/named-chroot.service'
Проверяем содержимое chroot каталога:
# ls -l /var/named/chroot/etc
Настройка bind в chroot
Все в порядке, сервер запустился, необходимые файлы созданы, все готово для настройки. Займемся ей.

Настраиваем DNS сервер в CentOS 7

Файл конфигурации нашего сервера располагается по адресу /var/named/chroot/etc/named.conf. Открываем его и приводим к следующему виду:
# mcedit /var/named/chroot/etc/named.conf
options {
listen-on port 53 { any; };
listen-on-v6 port 53 { none; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
allow-query { 127.0.0.1; 192.168.7.0/24; };
recursion yes;
allow-recursion { 127.0.0.1; 192.168.7.0/24; };
forwarders { 8.8.8.8; };
version "DNS Server";
managed-keys-directory "/var/named/dynamic";
pid-file "/run/named/named.pid";
session-keyfile "/run/named/session.key";
};

zone "." IN {
type hint;
file "named.ca";
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

logging {
channel default_file {
file "/var/log/named/default.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};
category default { default_file; };
};
Эта конфигурация обеспечит работу обычного кэширующего сервера в локальной сети. Комментарии к некоторым параметрам:
listen-on-v6 port 53 { none; }; Отключили работу на интерфейсе ipv6.
allow-query { 127.0.0.1; 192.168.7.0/24; }; Разрешаем обычные запросы только из локальной сети.
allow-recursion { 127.0.0.1; 192.168.7.0/24; }; Разрешаем рекурсивные запросы только из локальной сети.
forwarders { 8.8.8.8; }; Перенаправляем запросы, которые сами не резолвим, на днс сервер гугла. У меня указан он просто для примера. Тут лучше всего указать сначала ДНС серверы провайдера.
version «DNS Server»; Скрываем версию бинда, вместо этого выводим указанную строку.
Не забудьте отредактировать правила фаервола для корректной работы DNS сервера — открыть 53 порт UDP для работы кэширующего сервера, который мы сейчас настроили, и 53 порт TCP для пересылки зон, о которых речь пойдет дальше

Поддержка собственной зоны

Допустим, нам необходимо в нашем named разместить собственную зону site1.ru. Первым делом создаем файл зоны, которую будет обслуживать dns сервер:
# mcedit /var/named/chroot/var/named/site1.ru.zone
$TTL 86400
@        IN     SOA     site1.ru. site1.ru.local. (
                        2015092502
                        43200
                        3600
                        3600000
                        2592000 )

        IN NS ns1.site1.ru.
        IN NS ns2.site1.ru.
        IN A 192.168.7.254
        IN MX 10 mx.site1.ru.

gate    IN A 192.168.7.254
mx      IN A 192.168.7.250
ns1     IN A 192.168.7.235
ns2     IN A 192.168.7.231
Описание синтаксиса файлов зон достаточно хорошо освещено в интернете, не хочется подробно на этом останавливаться. При желание каждый сам сможет посмотреть, если у него возникнет необходимость настроить поддержку собственной зоны.
Выставляем необходимые права:
# chown root:named /var/named/chroot/var/named/site1.ru.zone
# chmod 0640 /var/named/chroot/var/named/site1.ru.zone
Дальше подключаем файл зоны в конфигурационном файле bind — /var/named/chroot/etc/named.conf:
zone "site1.ru" {
 type master;
 file "site1.ru.zone";
};
Перечитываем конфигурацию named с помощью rndc:
# rndc reconfig

Настройка логов в bind (named)

Гораздо интереснее и полезнее разобраться с подробным логированием работы сервера. Я долгое время поверхностно хватался за всякие рекомендации и куски примерных конфигов в интернете, пока в не решил разобраться сам с этой темой и не полез в оригинальный мануал.
Bind дает широкие возможности для ведения логов. Можно фиксировать практически все, что связано с работой сервера. Я сейчас на простых примерах покажу, как это работает.
Первым делом в конфигурации мы задаем канал, куда будут складываться логи по тем или иным событиям. Вот пример подобного канала:
channel general {
file "/var/log/named/general.log" versions 3 size 5m;
severity dynamic;
print-time yes;
Здесь указано название канала, которые мы придумываем сами — general, указан путь до файла, сказано, что хранить будем 3 версии лога размером не более 5 мегабайт. Параметр severity может принимать следующие значения:
Описание параметров severity
critical Только критические ошибки.
error Обычные ошибки и все что выше.
warning Предупреждения и все, что выше.
notice Уведомления и все, что выше.
info Информационные сообщения и все что выше.
debug Сообщения уровня debug и все, что выше. Уровни debug  регулируются значениями 0, 1, 2, 3.
dynamic То же, что и debug, только его уровень регулируется глобальной настройкой сервера.
Параметр print-time указывает на то, что в лог необходимо записывать время события. Помимо указанных мной настроек, в конфигурации канала могут быть добавлены следующие параметры:
  • print-severity yes | no — указывает, писать или нет параметр severity в лог
  • print-category yes | no — указывает писать или нет название категории логов
Я эти параметры не указал, так как по-умолчанию устанавливается значение no, которое лично меня устраивает.
Дальше необходимо указать категорию логов и в какой канал мы будем ее записывать:
category general { general; };
Категорий у днс сервера bind достаточно много. Вот мой перевод полного списка с описаниями:
Описание категорий логов в bind (named)
default Сюда будут попадать события всех категорий из этой таблицы, если они не определены отдельно, за исключением категории queries, которую нужно включать специально. То есть если обозначить только категорию default, то в нее будут сыпаться события всех категорий.
general Эта категория для всех логов, которые не включены ни в одну из перечисленных категорий.
database Сообщения, относящиеся к хранению зон и кэшированию.
security Подтверждение и отказ в выполнении запросов.
config Все, что относится к чтению и выполнению файла конфигурация.
resolver Разрешение имен, включая информацию о рекурсивных запросах, выполняемых от имени клиента кэширующим сервером.
xfer-in Информация о получении зон.
xfer-out Информация о передаче зон.
notify Логирование операций протокола NOTIFY.
client Выполнение клиентских запросов.
unmatched Сообщения, которые named не смог отнести ни к одному классу или для которых не определено отображение.
network Логирование сетевых операций.
update Динамические апдейты.
update-security Подтверждение или отклонение запросов на апдейт.
queries Логирование запросов к ДНС серверу. Для включения этой категории необходимо отдельно задать параметр в конфигурации сервера. Это связано с тем, что эта категория генерирует очень много записей в лог файл, что может сказаться на производительности сервера.
query-errors Ошибки запросов к серверу.
dispatch Перенаправление входящих пакетов модулям сервера на обработку.
dnssec Работа протоколов DNSSEC и TSIG.
lame-servers Фиксируются ошибки, которые получает bind при обращении к удаленным серверам в попытке выполнить запрос на разрешение имени.
delegation-only Логирование запросов, вернувших NXDOMAIN.
edns-disabled Запросы, которые вынуждены использовать plain DNS из-за превышения timeouts.
RPZ  Все операции, связанные с выполнение Response Policy Zone (RPZ).
rate-limit  Операции связанные с одним или несколькими rate-limit statements в options или view.
Таким образом, чтобы вывести все категории логов в отдельные файлы, необходимо в конфиг named добавить следующую конструкцию:
logging {

channel default {
file "/var/log/named/default.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel general {
file "/var/log/named/general.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel database {
file "/var/log/named/database.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel security {
file "/var/log/named/security.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel config {
file "/var/log/named/config.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel resolver {
file "/var/log/named/resolver.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel xfer-in {
file "/var/log/named/xfer-in.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel xfer-out {
file "/var/log/named/xfer-out.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel notify {
file "/var/log/named/notify.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel client {
file "/var/log/named/client.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel unmatched {
file "/var/log/named/unmatched.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel network {
file "/var/log/named/network.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel update {
file "/var/log/named/update.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel update-security {
file "/var/log/named/update-security.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel queries {
file "/var/log/named/queries.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel query-errors {
file "/var/log/named/query-errors.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel dispatch {
file "/var/log/named/dispatch.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel dnssec {
file "/var/log/named/dnssec.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel lame-servers {
file "/var/log/named/lame-servers.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel delegation-only {
file "/var/log/named/delegation-only.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel edns-disabled {
file "/var/log/named/edns-disabled.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel rpz {
file "/var/log/named/rpz.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel rate-limit {
file "/var/log/named/rate-limit.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

channel cname {
file "/var/log/named/cname.log" versions 3 size 5m;
severity dynamic;
print-time yes;
};

category default { default; };
category general { general; };
category database { database; };
category security { security; };
category config { config; };
category resolver { resolver; };
category xfer-in { xfer-in; };
category xfer-out { xfer-out; };
category notify { notify; };
category client { client; };
category unmatched { unmatched; };
category network { network; };
category update { update; };
category update-security { update-security; };
category queries { queries; };
category query-errors { query-errors; };
category dispatch { dispatch; };
category dnssec { dnssec; };
category lame-servers { lame-servers; };
category delegation-only { delegation-only; };
category edns-disabled { edns-disabled; };
category rpz { rpz; };
category rate-limit { rate-limit; };
category cname { cname; };
};
Теперь создадим папку для логов. Не забываем, что мы работаем в chroot окружении:
# cd /var/named/chroot/var/log && mkdir named && chown named. named
Если мы хотим собирать все логи запросов из категории queries, то в раздел options файла конфигурации необходимо добавить параметр, который это разрешает:
querylog yes;
Перезапускаем bind:
# systemctl reload named-chroot.service

Проверка работы DNS Server

Первым делом пойдем в каталог с логами и проверим, что там у нас:
# cd /var/named/chroot/var/log/named
# ls -l
Настройка логов в bind (named)
Все файлы журнала созданы и начали наполняться. Можно проверить один из них. Например, посмотрим, как наш сервер centos (192.168.7.246) логирует запросы пользователей. Попробуем с компьютера 192.168.7.254 (windows) выполнить nslookup yandex.ru и посмотрим как это отразится в лог файле:
26-Sep-2015 19:25:30.923 client 192.168.7.254#56374 (yandex.ru): query: yandex.ru IN A + (192.168.7.246)
26-Sep-2015 19:25:31.013 client 192.168.7.254#56375 (yandex.ru): query: yandex.ru IN AAAA + (192.168.7.246)
Теперь выполним ping site1.ru, чтобы проверить, как сервер поддерживает нашу зону:
centos dns
Смотрим, что в логах:
26-Sep-2015 19:28:01.660 client 192.168.7.254#49816 (site1.ru): query: site1.ru IN A + (192.168.7.246)
Таким образом очень удобно отследить, куда лезет компьютер. Например, можно поднять временно dns сервер, включить лог запросов. В клиенте указать единственный днс сервер, который мы настроили. Дальше можно отслеживать, к примеру, куда лезет винда после загрузки без нашего ведома. Или откуда грузится реклама в скайпе.