
Старт курса по OSSEC
Ставим сервер из исходников с ресурса github
EN: Install the server manager from sources from the GitHub resource
Настраиваем уведомления OSSEC по Email на примере Gmail и его SMTP
EN: Configure OSSEC notifications by email on the example of Gmail and its SMTP
Посредством готового скрипта для Slack чата, создадим свой скрипт для Телеграм с симпатичным форматированием уведомлений
EN: Through a ready-made script for Slack chat, create your own script for teligs with pretty formatting of notifications
СКРИПТ (см ссылку на ресурс):
* НЕ забыть переименовать и поправить права chmod u+x ossec-telegram.sh
EN: Script (see reference to resource): * Do not forget to rename and correct "chmod u+x ossec-telegram.sh"
В этой лекции мы устанавливаем агентов для взаимодействия с нашим сервером OSSEC на примере одноплатника Odroid и Orange Pi
EN: In this lecture, we install agents to interact with our OSSEC server on the example of Odroid and Orange PI Single Paragraph
FOR AGENTS
apt install libz-dev -y
apt install make gcc libssl-dev libssl-dev libpcre2-dev libevent-dev build-essential -y
cd /tmp
wget https://github.com/ossec/ossec-hids/archive/refs/tags/3.6.0.tar.gz
tar xvf 3.6.0.tar.gz
cd ossec*
bash insall.sh
НА СЕРВЕРЕ
iptables -A INPUT -p tcp --dport 1515 -j ACCEPT
iptables -A INPUT -p tcp --dport 1514 -j ACCEPT
iptables -A INPUT -p udp --dport 1515 -j ACCEPT
iptables -A INPUT -p udp --dport 1514 -j ACCEPT
iptables-save
*Либо UFW
sudo ufw allow 1515/tcp && sudo ufw allow 1515/udp
sudo ufw allow 1514/tcp && sudo ufw allow 1514/udp
openssl genrsa -out /var/ossec/etc/sslmanager.key 2048
openssl req -new -x509 -key /var/ossec/etc/sslmanager.key -out /var/ossec/etc/sslmanager.cert -days 365
START DAEMON ON SERVER
/var/ossec/bin/ossec-authd -p 1515
tail /var/ossec/logs/ossec.log
CREATE authd.pass ON AGENT
echo "965b311fdb92b6865743d79usf7897s" > /var/ossec/etc/authd.pass
chmod 0660 /var/ossec/etc/authd.pass
chown root:ossec /var/ossec/etc/authd.pass
Add agent on agent
/var/ossec/bin/agent-auth -m 10.7.0.1 -p 1515 -P /var/ossec/etc/authd.pass
Start ossec on agent
/etc/init.d/ossec start
On OSSEC SERVER:
/etc/init.d/ossec restart
wait 2 minutes and run:
/var/ossec/bin/agent_control -l
В этой лекции мы рассмотрим одно из самых важных по OSSEC - его архитектуру.
На примере простых схем разберемся какой из компонентов за что отвечает.
EN: In this lecture, we consider one of the most important on OSSEC - its architecture. On the example of simple schemes we will deal some of the components for what is responsible.OSSEC анализирует и отслеживает файлы системного журнала в режиме реального времени, чтобы проверять, обнаруживать и предупреждать о подозрительных действиях.
Системный журнал это наш syslog - это стандарт отправки и регистрации сообщений о событиях в системе
EN: System journal This Our Syslog is the standard of sending and registering messages about events in the system.
OSSEC Поддерживает все дистрибутивы Linux, Windows Server 2003/2012, семейство BSD, Solaris, AIX, OSX
EN: OSSEC Supports All Linux distributions, Windows Server 2003/2012, BSD, Solaris, AIX, OSX
Типы предупреждений(алерты) / Types of warnings (Alerts):
- Когда на сервере открыт новый порт в режиме прослушивания. / When a new port is opened on the server in listening mode.
- При обнаружении и блокировке сканирования портов или идентификации протокола. / If you detect and block the scanning of ports or identification of the protocol.
- При блокировании атак методом перебора. / If you detect and block the scanning of ports or identification of the protocol.
- Проверка целостности предупреждает об изменении файла. / Checking integrity warns about changing the file.
- Обнаружение троянов или руткитов. /Detection of Trojans or rootkits.
- Оповещение случае сбоя службы. / Notification of the case of service failure.
- Установка и удаление пакетов. / Installing and deleting packages.
Проверка целостности работает в OSSEC, сохраняя уникальный хэш MD5/SHA1 файлов и при повторном сканировании проверет системные двоичные файлы и файлы конфигураций каждые 6 часов (это по умолчанию, но можно изменить), и если что-то изменилось, то предупреждает уведомлениями.
АРХИТЕКТУРА OSSEC / OSSEC architecture::
1) Связь между агентом и сервером / Communication between agent and server
Сервер OSSEC прослушивает 1514/udp через ossec-remote. Агенты отправляют сообщения на сервер через ossec-agentd.
Связь двусторонняя, но инициируется агентом.
2) Пользователи для ossec
User Process
root ossec-syscheckd, ossec-execd, ossec-logcollector
ossec ossec-analysisd, ossec-monitord, ossec-agentlessd
ossecr ossec-remoted
ossecm ossec-maild, ossec-csyslogd
3) Список процессов
Процесс Описание Тип установки
ossec-analysisd Основная программа. Анализирует данные из журналов, syscheck, Сервер/Standalone
rootcheck и т. Д. Запускается от непривилегированного (Автономная)
пользователь ossec под chroot.
ossec-execd Выполняет активные ответы, вызывая настроенные сценарии(скрипты). Везде
Работает под root.
ossec-maild Отправляет оповещения по электронной почте. Запускается от имени Сервер/Автономная
непривилегированного пользователя (ossecm) под chroot.
ossec-remoted Серверный сокет для связи между сервером и агентом. Запускается от Сервер
имени непривилегированного пользователя (ossecr) под chroot.
ossec-agentd Сокет на стороне агента для связи между сервером и агентом. Запускается Агент
от имени непривилегированного пользователя (ossec) под chroot.
ossec-logcollector Мониторит файлы журналов и журналы событий Windows. Везде
ossec-syscheckd Выполняет проверку целостности и обнаружение руткитов Везде
(rootcheck является его модулем).
ossec-csyslogd Утилита для системного журнала syslog для пересылки Сервер/Standalone
алертов OSSEC на удаленные серверы syslog.
ossec-monitord Отслеживайте подключение агента и сжимайте файлы ежедневного журнала. Сервер/Standalone
Создание Декодеров и Правил / Creating decoders and rules:
У многих популярных сервисов(приложений) есть журналы и декодеры для них, но есть сотни, на которые они не распространяются. Пользовательское ПО также не будут покрываться Ossec.
EN: Many popular services (applications) have magazines and decoders for them, but there are hundreds of which they do not apply. Custom software will also not be covered by OSSEC.
Но как правило, добавлять декодеры и правила для сервисов очень просто.
Все правила находятся в директории /var/ossec/rules/
EN: But as a rule, add decoders and rules for services are very simple. All rules are located in the directory /var/ossec/rules/
ДОБАВИМ ЛОГ НЕКСТКЛАУД ДЛЯ МОНИТОРИНГА / Add the log NextCloud for monitoring
В главный ossec.conf пропишем это
<localfile>
<log_format>syslog</log_format>
<location>/var/www/nextcloud/data/nextcloud.log</location>
</localfile>
Также в раздел <rules> добавим В КОНЕЦ строчку
EN :Also in the <rules> section add a line to the end
<include>owncloud_rules.xml</include>
И создаем ниже active response с БАНОМ по не верному логину
EN: And create below Active Response with a ban for not correct login
<active-response>
<command>firewall-drop</command>
<location>local</location>
<rules_id>2501</rules_id>
<timeout>1296000</timeout> // 15 суток
</active-response>
Перезапускаем OSSEC / Restarting OSSEC
/var/ossec/bin/ossec-control restart
Для тестирования логов можем запустить ossec-logtest / For test logs
run app /var/ossec/bin/ossec-logtest
/var/www/nextcloud/data/nextcloud.log
И вставляем туда строку из лога некстклауда (К ПРИМЕРУ):
EN: End paste here line from log nextcloud (example):
{"reqId":"CT52FYJFgVoAsSq1jgh3","level":2,"time":"2021-07-14T08:17:58+00:00","remoteAddr":"14.268.65.191","user":"--","app":"core","method":"GET","url":"/ocs/v2.php/cloud/capabilities","message":"Login failed: 'test2' (Remote IP: '14.268.65.191')","userAgent":"Mozilla/5.0 (Android) Nextcloud-Talk v8.2.0","version":"21.0.1.1"}
ЕСЛИ ЖЕ ЛОГ НЕ РАСПОЗНАЕТСЯ, ТО СНАЧАЛА ИЩЕМ В ИНТЕРНЕТЕ, ВДРУГ КТО-ТО УЖЕ НАПИСАЛ ДЛЯ ВАС DECODER,
ЕСЛИ НЕ НАХОДИМ, ТО СОЗДАЕМ СОБСТВЕННЫЙ ДЕКОДЕР
EN: If the log is not recognized, first we are looking for on the Internet, suddenly someone already wrote for you Decoder, If you do not find, then create your own decoder
В файле /var/ossec/etc/decoder.xml смотрим к примеру owncloud и создаем подобный декодер
МАТЧАСТЬ ПО ДЕКОДЕРАМ ТУТ / MAIN INFO ABOUT DECODERS:
https://www.ossec.net/docs/docs/manual/rules-decoders/create-custom.html
ДОП ИНФА / Additional INFO:
Иногда правила слишком строги или недостаточно строги. Возможно, вы захотите что-то изменить или добавить что-то сами. Это можно сделать в файле local_rules.xml. Предлагаем увеличить количество неудачных попыток входа в систему по http-аутентификации для apache2. Если мы посмотрим на apache_rules.xml, мы увидим ряд правил. Интересный:
EN: Sometimes the rules are too strict or not sufficiently strict. Perhaps you want to change something or add something yourself. This can be done in the local_rules.xml file. We propose to increase the number of unsuccessful login attempts on HTTP authentication for Apache2. If we look at apache_rules.xml, we will see a number of rules. Interesting:
<rule id="30119" level="12" frequency="6" timeframe="120">
<if_matched_sid>30118</if_matched_sid>
<same_source_ip />
<description>Multiple attempts blocked by Mod Security.</description>
<group>access_denied,</group>
</rule>
Чтобы изменить частоту с 6 на 10, нам нужно скопировать правило и вставить его в local_rules.xml. Затем мы добавляем параметр overwrite = ”yes”, чтобы сообщить OSSEC, что необходимо перезаписать правило, определенное в apache_rules.xml, и вместо этого использовать правило, определенное в local_rules.xml. Правило могло бы выглядеть так:
EN: To change the frequency from 6 to 10, we need to copy the rule and paste it into Local_rules.xml. Then we add the Overwrite = "Yes" parameter to inform OSSEC that you need to overwrite the rule defined in Apache_rules.xml, and instead use the rule defined in Local_Rules.xml. The rule could look like this:
<rule id="30119" level="12" frequency="10" timeframe="120" overwrite="yes">
<if_matched_sid>30118</if_matched_sid>
<same_source_ip />
<description>Multiple attempts blocked by Mod Security.</description>
<group>access_denied,</group>
</rule>
Если мы хотим полностью игнорировать это правило, поскольку оно нам не актуально, мы просто меняем уровень на 0:
EN: If we want to fully ignore this rule, since it is not relevant to us, we simply change the level of 0:
<rule id="30119" level="0" frequency="10" timeframe="120" overwrite="yes">
<if_matched_sid>30118</if_matched_sid>
<same_source_ip />
<description>Multiple attempts blocked by Mod Security.</description>
<group>access_denied,</group>
</rule>
Подсказка с копированием ssh ключа / Help for copying SSH key
ssh-copy-id -i ~/.ssh/id_rsa.pub root@example.com
Github Issue Open and Closed
https://github.com/ossec/ossec-hids/issues
Открываем документацию / Open Documentation
https://www.ossec.net/docs/
1) Uninstall:
via source:
/var/ossec/bin/ossec-control stop
rm -rf /var/ossec
rm /etc/init.d/*ossec*
rm /etc/ossec-init.conf
via apt:
apt purge ossec-hids-server -y
apt purge ossec-hids-agent -y
rm -rf /var/ossec
rm /etc/init.d/*ossec*
rm /etc/ossec-init.conf
2) Решение если агент не может подключиться (куда смотреть) - ответ: логи и открыть 1514 порт udp/tcp / а также проверить в ossec.conf к какому серверу идет основное подключение
EN: Decision If the agent cannot connect (where to watch) - Answer: Logs and open 1514 UDP / TCP port / and also check in OSSEC.conf to which server is the main connection
3) Уменьшить таймаут по сканированию файлов на изменения
EN: Reduce the timeout on scanning files for changes 10 minutes
syscheck 600 #(10 минут)
4) Если не стартуют некоторые компоненты (not running...), то смотрим конфиг на ошибки
EN: If some components do not start (not running ...), then watch the config on errors
Syscheck/Rootcheck /var/ossec/bin/ossec-syscheckd -t
local files /var/ossec/bin/ossec-logcollector -t
global/rules/decoders (manager only) /var/ossec/bin/ossec-analysisd -t
Client (agent only) /var/ossec/bin/ossec-agentd -t
/var/ossec/bin/ossec-logtest -d -c /var/ossec/etc/ossec.conf
Также смотрим лог tail /var/ossec/log/ossec.log
5) Фиксим права / Fixing permissions
chown -R ossec:ossec /var/ossec
6) Если проблемы при установке через компиляцию - отсутствуют нужные библиотеки ( apt install some_library)
Смотреть лог ошибки и искать необходимую библиотеку, если лень - использовать Docker-версию либо добавить репозиторий и установить через apt install ossec-hids-server/ossec-hids-agent (ссылку на репозиторий можно взять из урока ansible)
EN: If the problems when installing through a compilation - there are no necessary libraries (apt install some_library)
Watch the log error and search for the necessary library if it is too lazy to use a docker version or add repository and install via apt install ossec-hids-server/ossec-hids-agent (link to repository can be taken from the AnSible lesson)
7) Уменьшить время реконнекта агентов (править ossec.conf на агенте )
EN: Decrase times for recconnects agents (change ossec.conf on agent)
<ossec_config>
<client>
<server-ip>10.7.0.1</server-ip>
<notify_time>20</notify_time> <-ТУТ (секунды)
<config-profile></config-profile>
</client>
8) Добавить наш локальный IP в whitelist в ossec.conf, чтобы не прилетало активных ответов по нашему IP (блокировки и тд)
EN: Add our local IP to Whitelist in Ossec.conf, so as not to arrive active responses on our IP (blocking and so on)
9) Удалить IP из блокировки / Remove IP from blocks:
/var/ossec/active-response/bin/host-deny.sh delete - 150.150.150.150
/var/ossec/active-response/bin/firewall-drop.sh delete - 150.150.150.150
Задаем вопросы в личку телеграм / My telegram for questions
@worldranger
Работа с агентами и получение отчетов / Work with agents and receiving reports
/var/ossec/bin/agent_control –l
Получения списка всех агентов: / Getting a list of all agents:
/var/ossec/bin/agent_control –i id_агента
Получение информации о агенте, интересна здесь контрольная сумма файла конфигурации. Ее можно сравнить с конфигурацией на сервере:
EN: Getting information about the agent is interesting here the control sum of the configuration file. It can be compared with the configuration on the server:
md5sum /var/ossec/etc/shared/agent.conf
Если контрольные суммы не совпадают, значит агент не подхватил конфиг с сервера.
EN: If the checksums do not coincide, then the agent did not catch the config from the server.
/var/ossec/bin/agent_control –R id_агента
Перезапуск агента, обычно необходимо для применения изменений в конфиге для агентов.
EN: Restarting the agent is usually necessary to apply changes in the config for agents.
/var/ossec/bin/agent_control -r –a
Принудительный запуск проверки целостности и поиска руткитов на всех агентах:
EN: Forced launch of the integrity check and search for rootkits on all agents:
/var/ossec/bin/agent_control -r –u id_агента
Тоже самое, но только для определенного агента: / The same, but only for a certain agent:
/var/ossec/bin/syscheck_update -h
Обнуление счетчиков контрольных сумм файлов: / Zeroing counter checks:
/var/ossec/bin/syscheck_update -h
-l List available agents.
-a Update (clear) syscheck database for all agents.
-u <id> Update (clear) syscheck database for a specific agent.
-u local Update (clear) syscheck database locally.
Для получения отчетов в консоли можно пользоваться этим: / To obtain reports in the console, you can use this:
/var/ossec/bin/ossec-reportd
Примеры / Examples:
Вывод всех алертов за сегодняшнего дня / Show all Alerts for today
cat /var/ossec/logs/alerts/alerts.log | /var/ossec/bin/ossec-reportd -s
Вывод всех алертов за определенный день / Show all Alerts for a certain day
cat /var/ossec/logs/alerts/2014/Dec/ossec-alerts-29.log.gz | /var/ossec/bin/ossec-reportd -s
Вывод всех алертов о смене конторльных сумм за день / Show all Alerts about changing checksum per day
cat /var/ossec/logs/alerts/alerts.log | /var/ossec/bin/ossec-reportd -s -f group syscheck
Вывод всех неудачных попыток авторизации за день / Show all unsuccessful attempts by authorization per day
cat /var/ossec/logs/alerts/alerts.log | /var/ossec/bin/ossec-reportd -s -f rule 5503
Вывод всех неудачных попыток авторизации по ssh за день / Show all unsuccessful attempts to authorize SSH per day
cat /var/ossec/logs/alerts/alerts.log | /var/ossec/bin/ossec-reportd -s -f rule 5716
Вывод всех установленных пакетов за день / The output of all installed packages per day
cat /var/ossec/logs/alerts/alerts.log | /var/ossec/bin/ossec-reportd -s -f rule 2902
Вывод всех удаленных пакетов за день / Show all remote packages per day
cat /var/ossec/logs/alerts/alerts.log | /var/ossec/bin/ossec-reportd -s -f rule 2903
Вывод попыток брутфорса ssh за день / Show Brutfors SSH per day
cat /var/ossec/logs/alerts/alerts.log | /var/ossec/bin/ossec-reportd -s -f rule 5712
Вывод данных за месяц / Show all data per month
cat /var/ossec/logs/alerts/2021/Jul/*.gz | /var/ossec/bin/ossec-reportd -s
Можно получать отчеты о смене контрольных сумм файлов определенного агента или какого либо файла.
EN: You can receive reports on changing the checksum of files of a specific agent or any file.
/var/ossec/bin/syscheck_control
Несколько месяцев назад я пытался найти доступную информацию по OSSEC на русском языке, ее было не так много, но вся она была разбросана по всему интернету по кусочкам. Пришлось приложить много усилий, чтобы собрать это все воедино, и еще больше сил для того чтобы подробно разобраться в этом и создать курс.
Эти лекции для тех кто хочет научиться первым важным азам кибербезопасности сразу на практике, уметь быстро реагировать на важные события и быть уверенным администритором в своей ИТ-инфраструктуре.
Вы научитесь мониторить cybersecurity серверов с помощью Email уведомлений/Телеграм/Диаграмм, а также правильно использовать систему обнаружения вторжений OSSEC для наблюдения за безопасностью сетевых узлов на платформах Linux и Windows.
- Познакомитесь с несколькими способами установки OSSEC сервера и агентов (Включая Docker, Ansible)
- Изучим архитектуру OSSEC и разберемся как оно работает
- Узнаем из чего состоят активные ответы и какая связь между правилами
- Как создать свои правила для OSSEC на примере приложения NextCloud (облачного файлового хранилища)
- Установим простой веб-интерфейс для отображения наших событий OSSEC
- Разберемся с продвинутым анализом событий в стеке ELK (Elastic seach / Logstash / Kibana) с красивым выводом всей информации в диаграммах и удобном дашборде
- Затронем основные проблемы с установкой и настройкой OSSEC и быстрым поиском и решением
- А также инструкция по работе с отчетами OSSEC через его компоненты с интерфейсом cli
Это уникальный курс, так как затрагивает все аспекты приложения OSSEC на русском языке и с подробным разъяснением каждого из компонентов
EN: A few months ago, I tried to find available information on OSSEC, quality information was not so much, and the whole it was scattered throughout the Internet. I had to make a lot of effort to collect it all together, and even more forces in order to figure it out in detail and create a course.
These lectures for those who want to learn the first important steps of cybersecurity immediately in practice, be able to quickly respond to important events and be a confident administrator in their IT infrastructure.
You will learn to monitor the cybersecurity of servers using email notifications / Telegram /Charts, and correctly use the OSSEC intrusion detection system to monitor network nodes on Linux and Windows platforms.
- Get acquainted with several ways to install OSSEC servers and agents (including Docker, Ansible)
- We study the OSSEC architecture and will figure it out how it works
- We learn from what consists are active response and what communication between the rules
- How to create your own rules for OSSEC on the example of the NEXTCLOUD application (cloud files storage)
- Install a simple web interface to display our OSSEC events.
- We will deal with advanced analysis of events in the ELK stack (Elastic Seach / Logstash / Kibana) with a beautiful output of all information in diagrams and convenient dashboard
- We will touch on the main problems with installing and configuring OSSEC and quick search and solution
- as well as instructions for working with OSSEC reports through its components with the CLI interface
This is a unique course, as it affects all aspects of the OSSEC application and with a detailed explanation of each of the components.