в общем защита линуха для чайникоФФ рулит =)
Защита Linux для ленивых.
Привет! Сегодня я хочу рассказать о программах определения и защиты от сканирования, а именно scanlogd и portsentry.
Я использую gentoo linux, и соответственно все настройки проводились в этом (и только в этом) дистрибутиве.
Не хочу вдаваться в подробности самого процесса скнирования портов и методах его определения, а перейду сразу к делу.
#1.scanlogd
Установка и настройка scanlogd сводится в gentoo linux к
emerge scanlogd ; rc-update add scanlogd default
Для просмотра результатов работы программы хорошо бы иметь системный логгер. Я, например, использую syslog-ng.
Scanlogd не делает ничего для защита вашей машины от атакующего(то бишь сканирующего), а просто пишет все определеннные
им попытки в /var/log/messages. Вот собственно и все. Больше ничего хорошего про него сказать не могу. Он определяет
далеко не все попытки скана. В общем я не рекомендую его использовать.
#2.portsentry
А вот это уже куда интереснее, portsentry не только определяет большинство попыток обычного скана но и позволит вам от них
защититься. Для наилучшего фунционирования хорошо бы еще заиметь iptables.
Настройка portsentry весьма просто и интуитивно понятна. Собственно перейдем к ней. Главный конфигурационный файл
portsentry /etc/portsentry/portsentry.conf, также в /etc/portsentry находятся файлы *.sample которые являются примерами
настройки. Их надо переименовать(а лучше скопировать), просто убрав расширения .sample.
Начнем с основного /etc/portsentry/portsentry.conf c моими русскоязычными комментариями под строками авторских
Код: Выделить всё
# PortSentry Configuration
# Настройка portsentry
# $Id: portsentry.conf,v 1.25 2003/05/23 16:15:39 crowland Exp crowland $
#
# IMPORTANT NOTE: You CAN NOT put spaces between your port arguments.
# ВАЖНОЕ ЗАМЕЧАНИЕ: НЕЛЬЗЯ разделять порты пробелами.
# The default ports will catch a large number of common probes
#
# All entries must be in quotes.
# Все записи должны быть в кавычках.
#######################
# Port Configurations # Настройка портов
#######################
#
#
# Some example port configs for classic and basic Stealth modes
# Несколько примеров конфигураций для классического и базово "Скрытого" режима
# I like to always keep some ports at the "low" end of the spectrum.
# This will detect a sequential port sweep really quickly and usually
# these ports are not in use (i.e. tcpmux port 1)
# Тут втор рекомендует оставлять в нижеследующем списке начальные порты (например 1)
# ** X-Windows Users **: If you are running X on your box, you need to be sure
# you are not binding PortSentry to port 6000 (or port 2000 for OpenWindows users).
# Doing so will prevent the X-client from starting properly.
# Обращение к пользователям X Window System: если вы работаете с иксами не вписывайте туда 6000-й порт или
# 2000-й если вы пользователь OpenWindows (?)
# These port bindings are *ignored* for Advanced Stealth Scan Detection Mode.
# Эти порты *игнорируются* для улучшенного "скрытого" режима
# Un-comment these if you are really anal:
# рекомендуется не раскомментировать это =)
#TCP_PORTS="1,7,9,11,15,70,79,80,109,110,111,119,138,139,143,512,513,514,515,540,635,10
80,1524,2000,2001,4000,4001,5742,6000,6001,6667,12345,12346,20034,27665,30303,32
7
71,32772,32773,32774,31337,40421,40425,49724,54320"
#UDP_PORTS="1,7,9,66,67,68,69,111,137,138,161,162,474,513,517,518,635,640,641,666,700,2
049,31335,27444,34555,32770,32771,32772,32773,32774,31337,54321"
#
# Use these if you just want to be aware:
# раскомментируйте это если хотите быть осведомлены (присоединяюсь к авторской рекомендации)
#TCP_PORTS="1,11,15,79,111,119,143,540,635,1080,1524,2000,5742,6667,12345,12346,20034,2
7665,31337,32771,32772,32773,32774,40421,49724,54320"
#UDP_PORTS="1,7,9,69,161,162,513,635,640,641,700,37444,34555,31335,32771,32772,32773,32
774,31337,54321"
#
# Use these for just bare-bones
# Это тоже лучше не использовать
#TCP_PORTS="1,11,15,110,111,143,540,635,1080,1524,2000,12345,12346,20034,32771,32772,32
773,32774,49724,54320"
#UDP_PORTS="1,7,9,69,161,162,513,640,700,32770,32771,32772,32773,32774,31337,54321"
###########################################
# Advanced Stealth Scan Detection Options # Улушенный режим определения "скрытых" сканирований
###########################################
#
# This is the number of ports you want PortSentry to monitor in Advanced mode.
# Any port *below* this number will be monitored. Right now it watches
# everything below 1024.
#
# Это число, все порты ниже которого будут проверяться в этом режиме
#
# On many Linux systems you cannot bind above port 61000. This is because
# these ports are used as part of IP masquerading. I don't recommend you
# bind over this number of ports. Realistically: I DON'T RECOMMEND YOU MONITOR
# OVER 1024 PORTS AS YOUR FALSE ALARM RATE WILL ALMOST CERTAINLY RISE. You've been
# warned! Don't write me if you have have a problem because I'll only tell
# you to RTFM and don't run above the first 1024 ports.
# АВТОР РЕКОМЕНДУЕТ НЕ ИЗМЕНЯТЬ ЭТО ЗНАЧЕНИЕ!!!
# А также говорит не писать ему, если из-за этого будут проблемы.
ADVANCED_PORTS_TCP="1024"
ADVANCED_PORTS_UDP="1024"
#
# This field tells PortSentry what ports (besides listening daemons) to
# ignore. This is helpful for services like ident that services such
# as FTP, SMTP, and wrappers look for but you may not run (and probably
# *shouldn't* IMHO).
#
# By specifying ports here PortSentry will simply not respond to
# incoming requests, in effect PortSentry treats them as if they are
# actual bound daemons. The default ports are ones reported as
# problematic false alarms and should probably be left alone for
# all but the most isolated systems/networks.
# Игнорируемые порты. portsentry не будет обращать внимание на запросы к ним.
# Рекомендую оставить как есть, так как могут быть ложные предупреждения.
# Default TCP ident and NetBIOS service
# При использовании в windows сети NetBIOS'a:
ADVANCED_EXCLUDE_TCP="113,139"
# А также при использовании bootp
# Default UDP route (RIP), NetBIOS, bootp broadcasts.
ADVANCED_EXCLUDE_UDP="520,138,137,67"
######################
# Configuration Files# Конфигурационные файлы
######################
#
# Hosts to ignore
# Игнорируемые хосты
IGNORE_FILE="/etc/portsentry/portsentry.ignore"
# Hosts that have been denied (running history)
# Запрещенные хосты(с ведением истории)
HISTORY_FILE="/etc/portsentry/portsentry.history"
# Hosts that have been denied this session only (temporary until next restart)
# Запрещенные хосты только для этой сессии(до перезапуска)
BLOCKED_FILE="/etc/portsentry/portsentry.blocked"
##############################
# Misc. Configuration Options# Дополнительные опции
##############################
# DNS Name resolution - Setting this to "1" will turn on DNS lookups
# for attacking hosts. Setting it to "0" (or any other value) will shut
# it off.
# Определять DNS-адрес атакующего (1- включено, 0 или любое другое число выключено)
RESOLVE_HOST = "1"
###################
# Response Options# Опции ответа
###################
# Options to dispose of attacker. Each is an action that will
# be run if an attack is detected. If you don't want a particular
# option then comment it out and it will be skipped.
# Здесь определяется что делать в ответ на действия атакующего
# The variable $TARGET$ will be substituted with the target attacking
# host when an attack is detected. The variable $PORT$ will be substituted
# with the port that was scanned.
# Переменная $TARGET$ означает атакующего
##################
# Ignore Options # Опции игнорирования
##################
# These options allow you to enable automatic response
# options for UDP/TCP. This is useful if you just want
# warnings for connections, but don't want to react for
# a particular protocol (i.e. you want to block TCP, but
# not UDP). To prevent a possible Denial of service attack
# against UDP and stealth scan detection for TCP, you may
# want to disable blocking, but leave the warning enabled.
# I personally would wait for this to become a problem before
# doing though as most attackers really aren't doing this.
# The third option allows you to run just the external command
# in case of a scan to have a pager script or such execute
# but not drop the route. This may be useful for some admins
# who want to block TCP, but only want pager/e-mail warnings
# on UDP, etc.
#
# Эти опции полезны если вы хотите предотвратить DOS-атаку на UDP или скрытое сканирование tcp
# А также для админов, которые хотят только получать предупреждения по e-mail или на пейджер
# 0 = Do not block UDP/TCP scans. 0 - не блокировать TCP/UDP сканирования
# 1 = Block UDP/TCP scans. 1 - блокировать UDP/TCP сканирования
# 2 = Run external command only (KILL_RUN_CMD) 2 - запускать только внешнюю команду (KILL_RUN_CMD)
# А обычному пользователю, IMHO, лучше все таки блокировать.
BLOCK_UDP="1"
BLOCK_TCP="1"
###################
# Dropping Routes:#
###################
# This command is used to drop the route or add the host into
# a local filter table.
#
# The gateway (333.444.555.666) should ideally be a dead host on
# the *local* subnet. On some hosts you can also point this at
# localhost (127.0.0.1) and get the same effect. NOTE THAT
# 333.444.555.66 WILL *NOT* WORK. YOU NEED TO CHANGE IT!!
# В идеале 3333.444.555.666 должен быть мертвым хостом в локальной сети
# Пример (333.444.555.666) НЕ БУДЕТ РАБОТАТЬ! Смените этот IP
#
# ALL KILL ROUTE OPTIONS ARE COMMENTED OUT INITIALLY. Make sure you
# uncomment the correct line for your OS. If you OS is not listed
# here and you have a route drop command that works then please
# mail it to me so I can include it. ONLY ONE KILL_ROUTE OPTION
# CAN BE USED AT A TIME SO DON'T UNCOMMENT MULTIPLE LINES.
# Можно использовать только одну строку! НЕЛЬЗЯ РАСКОММЕНТИРОВАТЬ НЕСКОЛЬКО!
# NOTE: The route commands are the least optimal way of blocking
# and do not provide complete protection against UDP attacks and
# will still generate alarms for both UDP and stealth scans. I
# always recommend you use a packet filter because they are made
# for this purpose.
# Замечание: это самый плохой способ защиты. Рекомендуется использовать вместо него пакетный фильтр(см.далее)
# Ниже приведены примеры для разных ОС
# Generic # Cтандартный
#KILL_ROUTE="/sbin/route add $TARGET$ 333.444.555.666"
# Generic Linux # Стандартный Linux
#KILL_ROUTE="/sbin/route add -host $TARGET$ gw 333.444.555.666"
# Newer versions of Linux support the reject flag now. This
# is cleaner than the above option.
# Для новых версий Linux, лучше способа сверху.
#KILL_ROUTE="/sbin/route add -host $TARGET$ reject"
# Generic BSD (BSDI, OpenBSD, NetBSD, FreeBSD) Для *BSD
#KILL_ROUTE="/sbin/route add $TARGET$ 333.444.555.666"
# Generic Sun
#KILL_ROUTE="/usr/sbin/route add $TARGET$ 333.444.555.666 1"
# NEXTSTEP
#KILL_ROUTE="/usr/etc/route add $TARGET$ 127.0.0.1 1"
# FreeBSD
#KILL_ROUTE="route add -net $TARGET$ -netmask 255.255.255.255 127.0.0.1 -blackhole"
# Digital UNIX 4.0D (OSF/1 / Compaq Tru64 UNIX)
#KILL_ROUTE="/sbin/route add -host -blackhole $TARGET$ 127.0.0.1"
# Generic HP-UX
#KILL_ROUTE="/usr/sbin/route add net $TARGET$ netmask 255.255.255.0 127.0.0.1"
# Using a packet filter is the PREFERRED. The below lines
# work well on many OS's. Remember, you can only uncomment *one*
# KILL_ROUTE option.
# использование пакетного фильтра предпочтительно. Можно раскомментировать только одну строку!
# ipfwadm support for Linux
#KILL_ROUTE="/sbin/ipfwadm -I -i deny -S $TARGET$ -o"
#
# ipfwadm support for Linux (no logging of denied packets)
#KILL_ROUTE="/sbin/ipfwadm -I -i deny -S $TARGET$"
#
# ipchain support for Linux
#KILL_ROUTE="/sbin/ipchains -I input -s $TARGET$ -j DENY -l"
#
# ipchain support for Linux (no logging of denied packets)
#KILL_ROUTE="/sbin/ipchains -I input -s $TARGET$ -j DENY"
#
# iptables support for Linux
#KILL_ROUTE="/sbin/iptables -I INPUT -s $TARGET$ -j MIRROR" # моя любимая =)
#
# For those of you running FreeBSD (and compatible) you can
# use their built in firewalling as well.
#
#KILL_ROUTE="/sbin/ipfw add 1 deny all from $TARGET$:255.255.255.255 to any"
#
#
# For those running ipfilt (OpenBSD, etc.)
# NOTE THAT YOU NEED TO CHANGE external_interface TO A VALID INTERFACE!!
# Для пользователеей ipfilt (OpenBSD и др.)
# НЕ ЗАБУДЬТЕ ПОМЕНЯТЬ external_interface на ваш РЕАЛЬНЫЙ ИНТЕРФЕЙС!!
#KILL_ROUTE="/bin/echo 'block in log on external_interface from $TARGET$/32 to any' | /sbin/ipf -f -"
###############
# TCP Wrappers#
###############
# This text will be dropped into the hosts.deny file for wrappers
# to use. There are two formats for TCP wrappers:
# Этот текст будет прописываться в файл hosts.deny
# Format One: Old Style - The default when extended host processing
# options are not enabled.
# Формат 1: старый стиль (не указывается что делать с хостом)
#KILL_HOSTS_DENY="ALL: $TARGET$"
# Format Two: New Style - The format used when extended option
# processing is enabled. You can drop in extended processing
# options, but be sure you escape all '%' symbols with a backslash
# to prevent problems writing out (i.e. \%c \%h )
# формат 2: новый стиль (указывается что делать с хостом)
#KILL_HOSTS_DENY="ALL: $TARGET$ : DENY"
###################
# External Command# Внешние команды
###################
# This is a command that is run when a host connects, it can be whatever
# you want it to be (pager, etc.). This command is executed before the
# route is dropped or after depending on the KILL_RUN_CMD_FIRST option below
#
# Это команда, которая запускается после подключения атакующего до или после
# запуска KILL_ROUTE # (в зависимости от KILL_RUN_CMD_FIRST)
# I NEVER RECOMMEND YOU PUT IN RETALIATORY ACTIONS AGAINST THE HOST SCANNING
# YOU!
# тут Автор не рекомендует делать что-нибудь плохое с хостом, сканирующим вас
#
# TCP/IP is an *unauthenticated protocol* and people can make scans appear out
# of thin air. The only time it is reasonably safe (and I *never* think it is
# reasonable) to run reverse probe scripts is when using the "classic" -tcp mode.
# This mode requires a full connect and is very hard to spoof.
#
# Тут говорится, что люди могут сканировать вас просто так, от нечего делать.
#
# The KILL_RUN_CMD_FIRST value should be set to "1" to force the command
# to run *before* the blocking occurs and should be set to "0" to make the
# command run *after* the blocking has occurred.
# 1 - запуск KILL_RUN_CMD до блокировки сканирующего 0 - после
KILL_RUN_CMD_FIRST = "1"
#
#
KILL_RUN_CMD="wall ...::: $TARGET$ SCANS YOU :::..." # к примеру вот это выводит надпись о сканировании на все терминалы
##################### #####################
# Scan trigger value#
#####################
# Enter in the number of port connects you will allow before an
# alarm is given. The default is 0 which will react immediately.
# A value of 1 or 2 will reduce false alarms. Anything higher is
# probably not necessary. This value must always be specified, but
# generally can be left at 0.
# Число подключений до появления предупреждения
# Установка в 1 или 2 снизит число ложных предупреждений
# NOTE: If you are using the advanced detection option you need to
# be careful that you don't make a hair trigger situation. Because
# Advanced mode will react for *any* host connecting to a non-used
# below your specified range, you have the opportunity to really
# break things. (i.e someone innocently tries to connect to you via
# SSL [TCP port 443] and you immediately block them). Some of you
# may even want this though. Just be careful.
# ПРИМЕЧАНИЕ: если вы используете улучшенный режим определения скрытого сканирования лучше используйте 1 или 2
# Улучшенный режим блокирует все хосты подключающиеся к неиспользованным ранее портам.
SCAN_TRIGGER="2"
######################
# Port Banner Section# БАННЕР
######################
#
# Enter text in here you want displayed to a person tripping the PortSentry.
# I *don't* recommend taunting the person as this will aggravate them.
# Leave this commented out to disable the feature
# Введите здесь текст, показываемый атакующему. Не рекомендуется раскомментировать.
# Stealth scan detection modes don't use this feature
# Режимы определения скрытого сканирования не использую это
#PORT_BANNER="** UNAUTHORIZED ACCESS PROHIBITED *** YOUR CONNECTION ATTEMPT HAS BEEN LOGGED. GO AWAY."
#
#EOF
Нет-нет, какой еще EOF!? Нам предстоит еще настроить /etc/conf.d/portsentry
# Config file for /etc/init.d/portsentry
#
# This file is read by /etc/init.d/portsentry. See the portsentry.8
# manpage for details.
#
# The options in this file refer to commandline arguments (all in lowercase)
# of portsentry. Use only one tcp and udp mode at a time.
#
#PORTSENTRY_MODES="udp tcp" #обычный режим
#PORTSENTRY_MODES="stcp sudp" #режим определения скрытых сканирований
#PORTSENTRY_MODES="atcp audp" #улучшенный режим определения скрытых скнирований
вот теперь все.
EOF