В этом руководстве вы узнаете, как установить и настроить Snort 3 на Rocky Linux.
Snort – это легкая система обнаружения сетевых вторжений.
Она поддерживает ведение журнала на основе правил и может выполнять поиск/сопоставление содержимого в дополнение к обнаружению множества других атак и зондов, таких как переполнение буфера, скрытое сканирование портов, CGI-атаки, SMB-зонды и многое другое.
Snort имеет возможность оповещения в реальном времени, причем оповещения отправляются в syslog, отдельный файл “alert” или даже на компьютер Windows через Samba.
🌐 Обзор решений IDS и IPS для улучшения сетевой аналитики и безопасности
Сборка и установка Snort 3 на Rocky Linux из исходного кода
Для успешной сборки и установки Snort 3 на Rocky Linux существует ряд инструментов сборки и зависимостей, которые необходимо установить до начала процесса сборки.
Установите EPEL и включите Powertools репо;
dnf install epel-release
dnf config-manager --set-enabled powertools
Затем установите необходимые инструменты сборки и библиотеки;
dnf -y install bison flex libtool nghttp2 libnghttp2-devel \
libpcap-devel pcre-devel openssl-devel libdnet-devel \
libtirpc-devel git gcc-c++ libunwind-devel cmake hwloc-devel \
luajit-devel xz-devel libnfnetlink-devel libmnl-devel \
libnetfilter_queue-devel uuid-devel libsafec-devel
Загрузите и установите последнюю версию библиотеки Snort DAQ (библиотека сбора данных).
DAQ недоступен в репозиториях по умолчанию, поэтому вам необходимо собрать и установить его из исходного кода;
mkdir snort-source-files && cd snort-source-files
git clone https://github.com/snort3/libdaq.git cd libdaq ./bootstrap ./configure make make install
Скачайте и установите кэширующий потоки malloc от google, Tcmalloc, распределитель памяти, оптимизированный для ситуаций с высоким параллелизмом, который обеспечит лучшую скорость в обмен на более высокое использование памяти.
Это необязательная зависимость, но настоятельно рекомендуемая.
cd ../ wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.9.1/gperftools-2.9.1.tar.gz tar xzf gperftools-2.9.1.tar.gz cd gperftools-2.9.1/ ./configure make make install
Установка Snort 3 на Rocky Linux из исходного кода
Теперь, когда у нас есть все необходимые зависимости, загрузите и установите Snort 3 на Rocky Linux;
На странице релизов найдите тарбол с последней версией Snort и загрузите его.
Команда ниже загружает Snort 3.1.28.0, который является последней версией на момент написания этой статьи.
cd ../
wget https://github.com/snort3/snort3/archive/refs/tags/3.1.28.0.tar.gz
Распакуйте и перейдите в каталог исходников Snort 3, скомпилируйте и установите его;
tar xzf 3.1.28.0.tar.gz
cd snort3-3.1.28.0
./configure_cmake.sh --prefix=/usr/local --enable-tcmalloc
Пример вывода сборки:
... ------------------------------------------------------- snort version 3.1.28.0 Install options: prefix: /usr/local includes: /usr/local/include/snort plugins: /usr/local/lib64/snort Compiler options: CC: /usr/bin/cc CXX: /usr/bin/c++ CFLAGS: -fvisibility=hidden -DNDEBUG -g -ggdb -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-free -O2 -g -DNDEBUG CXXFLAGS: -fvisibility=hidden -DNDEBUG -g -ggdb -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-free -O2 -g -DNDEBUG EXE_LDFLAGS: MODULE_LDFLAGS: Feature options: DAQ Modules: Static () libatomic: System-provided Flatbuffers: OFF Hyperscan: OFF ICONV: ON Libunwind: ON LZMA: ON RPC DB: Built-in SafeC: OFF TCMalloc: ON JEMalloc: OFF UUID: OFF ------------------------------------------------------- -- Configuring done -- Generating done -- Build files have been written to: /root/snort-source-files/snort3-3.1.28.0/build
Перейдите в каталог сборки, скомпилируйте и установите Snort 3 на Rocky Linux;
cd build
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib64/pkgconfig:/usr/local/lib/pkgconfig
make
make install
После завершения установки обновите общие библиотеки;
ln -s /usr/local/lib/libtcmalloc.so.4 /lib/
ln -s /usr/local/lib/libdaq.so.3 /lib/
ldconfig
Проверьте установку Snort 3, проверив версию;
snort -V
,,_ -*> Snort++ <*- o" )~ Version 3.1.28.0 '''' By Martin Roesch & The Snort Team http://snort.org/contact#team Copyright (C) 2014-2022 Cisco and/or its affiliates. All rights reserved. Copyright (C) 1998-2013 Sourcefire, Inc., et al. Using DAQ version 3.0.7 Using LuaJIT version 2.1.0-beta3 Using OpenSSL 1.1.1k FIPS 25 Mar 2021 Using libpcap version 1.9.1 (with TPACKET_V3) Using PCRE version 8.42 2018-03-20 Using ZLIB version 1.2.11 Using LZMA version 5.2.4
Получение справки Snort
Чтобы получить справку командной строки Snort, просто выполните любую из приведенных ниже команд и проверьте разницу
snort --help
snort -?
Snort has several options to get more help: -? list command line options (same as --help) --help this overview of help --help-commands [<module prefix>] output matching commands --help-config [<module prefix>] output matching config options --help-counts [<module prefix>] output matching peg counts --help-limits print the int upper bounds denoted by max* --help-module <module> output description of given module --help-modules list all available modules with brief help --help-modules-json dump description of all available modules in JSON format --help-plugins list all available plugins with brief help --help-options [<option prefix>] output matching command line options --help-signals dump available control signals --list-buffers output available inspection buffers --list-builtin [<module prefix>] output matching builtin rules --list-gids [<module prefix>] output matching generators --list-modules [<module type>] list all known modules --list-plugins list all known modules --show-plugins list module and plugin versions --help* and --list* options preempt other processing so should be last on the command line since any following options are ignored. To ensure options like --markup and --plugin-path take effect, place them ahead of the help or list options. Options that filter output based on a matching prefix, such as --help-config won't output anything if there is no match. If no prefix is given, everything matches. Report bugs to bugs@snort.org.
Настройка Snort 3 на Rocky Linux
Настройка сетевых интерфейсов
Прежде всего, переведите интерфейс, на котором Snort прослушивает сетевой трафик, в режим promiscuous, чтобы он мог видеть весь сетевой трафик, отправляемый на него, а не только трафик, исходящий только от сервера Snort 3.
ip link set dev enp0s8 promisc on
Проверим:
ip add sh enp0s8
3: enp0s8: <BROADCAST,MULTICAST,PROMISC,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 08:00:27:84:be:8b brd ff:ff:ff:ff:ff:ff
inet 192.168.60.22/24 metric 100 brd 192.168.56.255 scope global dynamic enp0s8
valid_lft 377sec preferred_lft 377sec
inet6 fe80::a00:27ff:fe84:be8b/64 scope link
valid_lft forever preferred_lft forever
Отключите разгрузку интерфейса, чтобы Snort не обрезал большие пакеты размером более 1518 байт. Вы можете проверить, включена ли эта функция;
ethtool -k enp0s8 | grep receive-offload
generic-receive-offload: on
large-receive-offload: off [fixed]
GRO включен, в то время как LRO фиксирован и, следовательно, не может быть изменен.
Затем отключите;
ethtool -K enp0s8 gro off lro off
Изменения двух сетевых карт являются временными. Чтобы изменения сохранялись при перезагрузке системы, создайте и включите блок обслуживания systemd для реализации изменений;
cat > /etc/systemd/system/snort3-nic.service << 'EOL' [Unit] Description=Set Snort 3 NIC in promiscuous mode and Disable GRO, LRO on boot After=network.target [Service] Type=oneshot ExecStart=/usr/sbin/ip link set dev enp0s8 promisc on ExecStart=/usr/sbin/ethtool -K enp0s8 gro off lro off TimeoutStartSec=0 RemainAfterExit=yes [Install] WantedBy=default.target EOL
Запустите и включите службу при загрузке;
systemctl enable --now snort3-nic.service
Установка правил Snort 3 на Rocky Linux
Правила – это основной момент для механизма обнаружения вторжений Snorts. Существует три типа правил Snort:
Правила сообщества
Зарегистрированные правила
Правила подписчика
В этом руководстве мы установим правила Snortсообщества;
Создайте каталог Snort Rules. В конфигурационном файле /usr/local/etc/snort/snort_defaults.lua путь к правилам по умолчанию (RULE_PATH) определен как /usr/local/etc/rules.
mkdir /usr/local/etc/rules
Скачайте правила сообщества Snort 3 со страницы загрузки Snort 3;
wget -qO- \
https://www.snort.org/downloads/community/snort3-community-rules.tar.gz \
| tar xz -C /usr/local/etc/rules/
ls -1 /usr/local/etc/rules/snort3-community-rules/
AUTHORS
LICENSE
sid-msg.map
snort3-community.rules
VRT-License.txt
Теперь, когда у нас есть правила для начала работы, необходимо настроить Snort 3.
Откройте главный файл конфигурации для редактирования;
vim /usr/local/etc/snort/snort.lua
Задайте сети для защиты от атак в качестве значения для переменной HOME_NET. Это может быть один IP-адрес, подсети… Для простоты я просто установил это значение на подсеть интерфейса Snort 3. EXTERNAL_NET – это любая другая сеть, кроме нашей HOME_NET;
... -- HOME_NET and EXTERNAL_NET must be set now -- setup the network addresses you are protecting HOME_NET = '192.168.60.22/32' -- set up the external network addresses. -- (leave as "any" in most situations) -- EXTERNAL_NET = 'any' EXTERNAL_NET = '!$HOME_NET' ...
Сохраните изменения и выйдите из файла.
Далее обновите пути к вашим правилам в конфигурационном файле /usr/local/etc/snort/snort.lua.
ips = { -- use this to enable decoder and inspector alerts --enable_builtin_rules = true, -- use include for rules files; be sure to set your path -- note that rules files can include other rules files -- (see also related path vars at the top of snort_defaults.lua) variables = default_variables, rules = [[ include $RULE_PATH/snort3-community-rules/snort3-community.rules ]] }
Сохраните и выйдите из файла конфигурации.
Установка Snort OpenAppID
OpenAppID – это плагин уровня приложений, который позволяет Snort обнаруживать различные приложения, Facebook, Netflix, Twitter и Reddit, используемые в сети. Выполните приведенные ниже команды, загруженные со страницы загрузки Snort 3, и установите Snort OpenAppID;
wget https://www.snort.org/downloads/openappid/23020 -O OpenAppId-23020.tgz
tar -xzvf OpenAppId-23020.tgz
cp -R odp /usr/local/lib/
Далее отредактируйте конфигурационный файл Snort 3 и определите расположение библиотек OpenAppID;
vim /usr/local/etc/snort/snort.lua
appid =
{
-- appid requires this to use appids in rules
--app_detector_dir = 'directory to load appid detectors from'
app_detector_dir = '/usr/local/lib',
log_stats = true,
}
mkdir /var/log/snort
Затем запустите проверку синтаксиса;
snort -c /usr/local/etc/snort/snort.lua
-------------------------------------------------- o")~ Snort++ 3.1.28.0 -------------------------------------------------- Loading /usr/local/etc/snort/snort.lua: Loading snort_defaults.lua: Finished snort_defaults.lua: Loading file_magic.lua: Finished file_magic.lua: ssh host_cache pop so_proxy stream_tcp mms smtp gtp_inspect packets dce_http_proxy stream_icmp normalizer ips binder wizard appid file_id stream_udp http2_inspect http_inspect ftp_data search_engine ftp_server port_scan dce_http_server dce_smb dce_tcp netflow iec104 cip telnet ssl sip rpc_decode modbus host_tracker stream_user stream_ip back_orifice trace classifications dnp3 active process ftp_client decode daq alerts stream network references arp_spoof output hosts dns dce_udp imap file_policy s7commplus stream_file Finished /usr/local/etc/snort/snort.lua: -------------------------------------------------- pcap DAQ configured to passive. Snort successfully validated the configuration (with 0 warnings). o")~ Snort exiting
Создайте пользовательские локальные правила для целей тестирования нашей установки Snort.
vim /usr/local/etc/rules/local.rules
Создайте правило для обнаружения тестов ping;
alert icmp any any -> $HOME_NET any (msg:"ICMP connection test"; sid:1000001; rev:1;)
Сохраните и выйдите из файла локальных правил. Проверьте синтаксис;
snort -c /usr/local/etc/snort/snort.lua -R /usr/local/etc/rules/local.rules
Затем запустите тест, выполнив приведенную ниже команду;
snort -c /usr/local/etc/snort/snort.lua -R /usr/local/etc/rules/local.rules -i enp0s8 -A alert_fast -s 65535 -k none
На другом терминале выполните ping вашего сервера Snort.
Во время выполнения ping вы должны увидеть строки предупреждений, записанные в стандартный вывод;
... 05/03-11:24:01.979485 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:03.006407 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:04.026118 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:05.053991 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:06.074083 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:07.097995 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:08.122173 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:09.145955 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:10.169989 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:11.194106 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:12.218152 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:13.241983 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:14.266063 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:15.289931 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:16.314112 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:17.337879 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:18.362716 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:19.364461 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:20.365276 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:21.370316 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:22.371367 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:23.386220 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:24.410267 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:25.410309 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:26.426397 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:27.427366 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:28.442598 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 05/03-11:24:29.443398 [**] [1:1000001:1] "ICMP connection test" [**] [Priority: 0] [AppID: ICMP] {ICMP} 192.168.56.1 -> 192.168.56.124 ...