Kern.log в отдельный файл журнала для журнала iptables

Kern.log в отдельный файл журнала для журнала iptables Хостинг

главная

Статьи
Linux, FreeBSD

Теги: Linux
Iptables

Kern.log в отдельный файл журнала для журнала iptables

В CentOS и других современных Linux по-умолчанию логи iptables пишутся в /var/log/messages. Это не всегда удобно. Если логирование включено на постоянной основе, то лог iptables способен за минуты полностью задавить все остальные сведения. В такой ситуации может быть необходимым вынести лог iptables в отдельный файл, например, /var/log/iptables.log.

In my iptables rule, I have rules like:

asked Apr 28, 2016 at 15:37

Sunny's user avatar

When your /etc/rsyslog.conf
loads yours *.conf in /etc/rsyslog.d
, it reads your files alphabetically. So, you need to make sure that your rules are in a file that comes before 50-default.conf, like:

 01-myiptablesrules.conf 

This way, your rules will be read first, and discard it. You should also use this syntax:

 :msg, contains, "iptables@@" { *.* /var/log/iptables.log stop
} 

*You should use stop instead of ~

Or if you don’t have others kern.* than your iptables messages, you should modify 50-default.conf
with:

 kern.* /var/log/iptables.log 

answered May 8, 2016 at 19:16

Luiz Guilherme Littig Berger's user avatar

Is there a line in your rsyslog config files that prints the message to /var/log/kern.log
? If so, post that code. Also post your rsyslog verison number. In the meantime, this could work:

 :msg,contains,"iptables@@" /var/log/iptables.log
:msg,contains,"iptables@@" ~ 

answered May 2, 2016 at 17:35

drewyupdrew's user avatar

Is it possible log all dropped connections by IPTables and set a iptables.log file for logging in /var/log/?

asked Jan 29, 2016 at 16:17

You can do this my configuring iptables to ‘mark’ the messages e.g.

 iptables -A INPUT -s 192.0.2.0/24 -j LOG --log-prefix='[iptables] ' 

Now you can configure your rsyslog to send these messages to a particular log file by adding a suitable entry to it’s configuration e.g.

 :msg,contains,"[iptables] " /var/log/iptables.log 

answered Jan 29, 2016 at 18:09

user9517's user avatar

20 gold badges
215 silver badges
297 bronze badges

there is a way to log packets in IPTables. first you need to create new chain to logging packets.

 iptables -N LOGGING 
 iptables -A INPUT -j LOGGING
iptables -A OUTPUT -j LOGGING 

now you can log the packets to the syslogs using this.

 iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables-Dropped: " --log-level 4 

finally this command.

 iptables -A LOGGING -j DROP 

please add this new lines to bottom of your IPTables files.

answered Jan 29, 2016 at 16:43

Shyamin Ayesh's user avatar

A working solution with ulogd

a)Ensure you have this module on start

 modprobe nf_log_ipv4
cp /etc/modules /etc/modules.bak
echo nf_log_ipv4 >> /etc/modules 

b)edit the file /etc/ulogd.conf
enable those plugin(uncomment #)

 plugin="/usr/lib64/ulogd/ulogd_inppkt_NFLOG.so"
plugin="/usr/lib64/ulogd/ulogd_filter_IFINDEX.so"
plugin="/usr/lib64/ulogd/ulogd_filter_IP2STR.so"
plugin="/usr/lib64/ulogd/ulogd_filter_PRINTPKT.so"
plugin="/usr/lib64/ulogd/ulogd_output_LOGEMU.so"
plugin="/usr/lib64/ulogd/ulogd_raw2packet_BASE.so" 

add this line before the first commented # stack

 stack=firewall11:NFLOG,base1:BASE,ifi1:IFINDEX,ip2str1:IP2STR,print1:PRINTPKT,emu11:LOGEMU 

and finally at the end of file add those lines

 [firewall11]
group=11
[emu11]
file="/var/log/iptables.log"
sync=1 

c)
Now, I prefer to use old method of iptables script instead of firewalld, in my iptables script I use those lines for logging.

 # Log
iptables -N LOGGING
iptables -A INPUT -j LOGGING
iptables -A FORWARD -j NFLOG
iptables -A LOGGING -j NFLOG --nflog-prefix "[firewall-drop]:" --nflog-group 11
iptables -A LOGGING -j DROP 

d) the final parts

 touch /var/log/iptables.log
systemctl restart ulogd 

Verify if work with this command

 tail -f /var/log/iptables.log 

You should see some lines after an event: nmap portscan, or simply telnet to your machine(hope is disabled or firewalled).

Читайте также:  VPS и хостинг для интернет-магазина

This assumes your firewall already makes logs, as any sane firewall should. For some examples, it requires an identifiable message, such as «NETFILTER» in slm’s example.

make a file in rsyslog.d

 vim /etc/rsyslog.d/10-firewall.conf 
 # into separate file and stop their further processing
if ($msg contains 'IN=' and $msg contains 'OUT=') \
then { -/var/log/firewall & ~
} 

This works in CentOS 7 and checks for the message content too (replace «Shorewall» with whatever you have in your -j LOG rule’s message):

 # into separate file and stop their further processing
if ($msg contains 'Shorewall') and \ ($msg contains 'IN=' and $msg contains 'OUT=') \
then { -/var/log/firewall & ~
} 

This works in others (Ubuntu, Debian, openSUSE). And this is the best way to do it. No searching for strings in the message:

 # into separate file and stop their further processing
if ($syslogfacility-text == 'kern') and \\
($msg contains 'IN=' and $msg contains 'OUT=') \\
then -/var/log/firewall & ~ 

And here is what a default openSUSE machine has (which I think every distro should have and is missing) (difference seems to be only «stop» instead of «& ~»; not all systems support both syntaxes):

 if ($syslogfacility-text == 'kern') and \ ($msg contains 'IN=' and $msg contains 'OUT=') \
then { -/var/log/firewall stop
} 

And for all of the above, don’t forget a logrotate.d file too:

 vim /etc/logrotate.d/firewall 
 /var/log/firewall { rotate 7 size 500k postrotate # before using this, run the command yourself to make sure # it is right... the daemon name may vary /usr/bin/killall -HUP rsyslogd endscript
} 

Лог-файл IPTABLES

В CentOS 7 логи управляются с помощью rsyslog (конфиги /etc/rsyslog.conf, /etc/rsyslog.d/*.conf).

Предположим, мы хотим логировать в файл /var/log/iptables.log попытки соединения с портом 1234/tcp и 53/udp.

Читайте также:  Исправление ошибки: отсутствуют подписанные драйверы устройств — пошаговое руководство

Для этого среди прочих наших правил iptables должны быть правила с действием LOG, например, такие:

—A INPUT -i eth0 -p tcp -m tcp —dport 1234 -j LOG —log-prefix —1234—LOG—

—A INPUT -i eth0 -p udp -m udp —dport 53 -j LOG —log-prefix —UDP—LOG—

Правила LOG должны быть ДО принятия решения (ACCEPT, DROP, REJECT, FORWARD). Иначе нужный нам пакет просто не дойдет до правила с LOG.

В директории /etc/rsyslog.d/ создадим отдельный файл конфига с фильтрами, которые будут понимать, какие именно пакеты от ядра надо сохранить в лог-файл iptables.log:

 # touch /etc/rsyslog.d/iptables.conf
# nano /etc/rsyslog.d/iptables.conf
:msg, contains, "--1234--LOG--" -/var/log/iptables.log
& stop
:msg, contains, "--UDP--LOG--" -/var/log/iptables.log
& stop
# systemctl restart rsyslog.service 

Проверяем, должно работать.

Use a Fixed Priority for iptables

The traditional UNIX syslog service only has two ways to categorize, and consequently route, messages: facility and priority. Facilities include kernel, mail, daemon, etc. Priorities include emergency, alert, warning, debug, etc. The Linux iptables
firewall runs in the kernel and therefore always has the facility set to kern. Using traditional syslog software, the only way you can separate iptables messages from other kernel messages is to set the priority on all iptables messages to something specific that hopefully isn’t used for other kernel logging.

 kern.=debug -/var/log/iptables.log 

and specifically remove the kernel debugging messages from all other logs like so:

 kern.*;kern.!=debug -/var/log/kern.log 

and in each iptables logging rule use the command line option --log-level debug
.

There are two distinct disadvantages to this approach. First, there’s no guarantee that other kernel components won’t use the priority you’ve set iptables to log at. There’s a real possibility that useful messages will be lost in the deluge of firewall logging. Second, this approach prevents you from actually setting meaningful priorities in your firewall logs. You might not care about random machines hammering Windows networking ports, but you definitely want to know about malformed packets reaching your server.

Logrotate

Чтобы лог-файл /var/log/iptables.log не рос бесконечно в размере, необходимо настроить его ротацию, по аналогии с другими лог-файлами.

Logrotate выполняется ежедневно по расписанию cron (/etc/cron.daily/logrotate) используя конфиг /etc/logrotate.conf и конфиги из директории /etc/logrotate.d, если они есть.

Создадим файл /etc/logrotate.d/iptables:

 /var/log/iptables.log
{ missingok notifempty rotate 5 size 300k create 0600 root root postrotate /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true endscript
} 

Проверить работу можно принудительно, не дожидаясь увеличения размера лога:

 # logrotate -v /etc/logrotate.d/iptables
reading config file /etc/logrotate.d/iptables
Allocating hash table for state file, size 15360 B
Handling 1 logs
rotating pattern: /var/log/iptables.log 307200 bytes (5 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/iptables.log log does not need rotating (log size is below the 'size' threshold) 

Если перевести, то «судя по настройкам из /etc/logrotate.d/iptables, ротацию надо делать логу /var/log/iptables.log при достижении размера 307200 байт, держать 5 ротаций лога, пустой файл не ротировать, а старые удалять. Конкретно сейчас лог /var/log/iptables.log не нуждается в ротации, поскольку его размер меньше порога size».

Читайте также:  Инвестируйте в кошелек Webmoney: безопасно управляйте своими онлайн-средствами

В man logrotate предлагается пример:

 /var/log/messages { rotate 5 weekly postrotate /usr/bin/killall -HUP syslogd endscript
} 

Выбирайте на здоровье! Все.

Авторизуйтесь для добавления комментариев!

Фильтр на основе содержимого сообщения с помощью rsyslog

rsyslog
в основном является заменой традиционного демона системного журнала — klogd и sysklogd в Linux. Фактически, в Debian и Ubuntu вы можете просто:

$ sudo apt-get install rsyslog

и если вы не настроили /etc/syslog.conf
, ведение журнала должно продолжать работать точно так же. rsyslog был системным журналом по умолчанию в системах на базе Red Hat/Fedora для ряда версий, но если он не установлен:

$ sudo yum install rsyslog

Настройка iptables для использования уникального префикса

Мы настроим rsyslog для фильтрации на основе начала сообщения от iptables. Таким образом, для каждого правила ведения журнала в сценарии брандмауэра добавьте --log-prefix "iptables: "
. Большинство приложений для построения брандмауэров можно легко настроить для добавления префикса к каждому правилу ведения журнала. Например, если вы используете firehol
как и я, вы могли бы добавить:

 FIREHOL_LOG_PREFIX="firehol: " 

Настройка rsyslog для фильтрации по префиксу

 :msg,startwith,"iptables:" -/var/log/iptables.log
& ~ 

Первая строка означает отправку всех сообщений, начинающихся с «iptables:», на /var/log/iptables.log
. Вторая строка означает отбрасывание сообщений, которые совпали в предыдущей строке. Вторая строка, конечно, необязательна, но она избавляет от необходимости явно отфильтровывать журналы брандмауэра из последующих правил системного журнала.

Когда я настраивал это на своих машинах, я заметил одну проблему, которая может быть особенностью firehol, но, вероятно, в любом случае стоит упомянуть. Кажется, что firehol добавляет дополнительную одинарную кавычку в начале сообщений журнала, которая должна соответствовать правилу rsyslog. Например, вот сообщение журнала от firehol:

 17 апр 12:41:07 отметьте ядро: 'firehol: 'IN-internet':'IN=eth0 OUT= MAC=fe:fd:cf:c0:47:b5:00:0e:39:6f :48:00:08:00 SRC=189.137.225.191 DST=207.192.75.74 LEN=64 TOS=0x00 PREC=0x00 TTL=32 ID=5671 DF PROTO=TCP SPT=3549 DPT=5555 WINDOW=65535 RES=0x00 SYN УРГП=0 

Обратите внимание на дополнительные кавычки после «kernel: » и перед «firehol: «. Итак, на моей машине я настроил фильтр rsyslog следующим образом:

 :msg,startwith,"'firehol: " -/var/log/iptables.log
& ~ 

Настройка ротации журналов iptables

 /var/log/iptables.log
{
повернуть 7
ежедневно
отсутствует
непустой
задержка сжатия
компресс
постротировать
invoke-rc.d rsyslog rotate > /dev/null
эндскрипт
} 

Предыдущий сценарий указывает logrotate ежедневно менять журнал брандмауэра и сохранять журналы за последние семь дней.

Оцените статью
Хостинги