AIDE

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page AIDE and the translation is 38% complete.
Outdated translations are marked like this.


AIDE (Advanced Intrusion Detection Environment) is a host-based intrusion detection system. AIDE scans files and other resources and stores information about these files in a database. Stored information includes key file attributes such as file hash output, file size, ownership, modification time, creation time, and more. After the initial database has been created, AIDE then rescans the system and compares new scan results with previously stored values. If values differ then the file has been changed and the change will be reported. The idea behind using AIDE is to create a snapshot of a system then compare the snapshot to another created snapshot to find compromised files.

USE-флаги

It is easy to install app-forensics/aide after setting the USE flags accordingly.

USE flags for app-forensics/aide AIDE (Advanced Intrusion Detection Environment) is a file integrity checker

acl Add support for Access Control Lists
audit Enable support for Linux audit subsystem using sys-process/audit
curl Use curl for http,https and ftp backends
e2fs Enable support for checking file attributes on ext2/ext3/ext4 filesystems
mhash Add support for the mhash library
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
xattr Add support for extended attributes (filesystem-stored metadata)

USE flag changes specific to a certain package should be defined in the /etc/portage/package.use file, or a text file inside a directory called /etc/portage/package.use. For example, when using a /etc/portage/package.use file:

ФАЙЛ /etc/portage/package.useВключение поддержки zlib в пакете AIDE
app-forensics/aide zlib

Emerge

После настройки USE-флагов установите приложение:

root #emerge --ask app-forensics/aide

Конфигурация

Общий обзор

Файл настроек app-forensics/aide не настолько устрашающий, как это может показаться с первого взгляда. Файл по умолчанию хранится в /etc/aide/aide.conf, но если это необходимо, администраторы легко могут создать множественные отдельные файлы настроек. Кроме нескольких переменных, файл настроек содержит несколько кратких обозначений для того, какие аспекты файлов нужно сканировать (только хэш-суммы, или также информацию об индексных дескрипторах (inodes), и т.д.) и затем, какие файлы нужно сканировать.

Давайте сначала рассмотрим переменные.

ФАЙЛ aide.confПеременные конфигурации базы данных AIDE
database=file:/var/lib/aide/aide.db
database_out=file:/var/lib/aide/aide.db.new

Эти параметры определяют где хранить базу данных, которая содержит уже известные значения (database), и где хранить новую базу данных при ее создании (database_out). В основном, рекомендуется, чтобы эти переменные не указывали на одно и то же. Вместо этого рекомендуется ручное копирование сгенерированной базы данных из одного места в другое.

root #cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db

А сейчас, оставьте эти переменные как есть, мы вернемся к ним позже.

Next, consider the variables which are short-hand notations for what information to record in the database.

ФАЙЛ aide.confCокращенные обозначения используемые в настройке AIDE
Binlib = p+i+n+u+g+s+b+m+c+md5+sha1
Logs = p+i+n+u+g+S
...
Заметка
It should be obvious that md5 and sha1 mean that MD5 and SHA-1 checksums are taken (respectively).

Это краткие обозначения того, что нужно измерять. Эти буквы описаны в файле aide.conf по умолчанию, но в следующей таблице дан обзор самых частоиспользуемых из них.

Short Description
p Permissions
i inode number
n Number of (hard)links
u User information
g Group information
s Size
S Size (only report when the size is suddenly smaller - growing is allowed)
b Block count
m Modification time

Next is an overview of which directories to scan, and what to scan for. In three line example to follow, AIDE is instructed to scan the /bin and /sbin directories via the measures identified in the Binlib short-hand notation variable. The /var/log file will display the scan measures defined in the Logs variable defined above.

ФАЙЛ aide.confПараметры задачи сканирования
/bin Binlib
/sbin Binlib
/var/log Logs
...

AIDE поддерживает регулярные выражения и пользователям разрешено удалять совпадения. Например, чтобы просканировать /var/log, но не /var/log/portage, включите набор исключений вроде такого:

ФАЙЛ aide.confДругие задачи сканирования
/var/log Logs
!/var/log/portage

Detailed options

The configuration file is based on regular expressions, macros and rules for files and directories. Users experienced with the tripwire solution will have no difficulties dealing with AIDE's configuration file. The following macros are available:

Macro Description Syntax
ifdef If defined @@ifdef "name"
ifndef If not defined @@ifndef "name"
define Define a variable @@define "name" "value"
undef Undefine a variable @@undef "name"
ifhost if "hostname" @@ifhost "hostname"
ifnhost if not "hostname" @@ifnhost "hostname"
endif Endif must be used after any of the above macros except define and undef @@endif

These macros become very handy when dealing with multiple Gentoo boxes, while using the same configuration on all. Not all machines run the same services or even have the same users.

Next we have a set of flags which identify the permissions, file properties, checksums, cryptographic hashes, ... to validate on files and directories.

Flag Description
p permissions
i inode
n number of links
u user
g group
s size
b block count
m mtime
a atime
c ctime
S check for growing size
md5 md5 checksum
sha1 sha1 checksum
rmd160 rmd160 checksum
tiger tiger checksum
R p+i+n+u+g+s+m+c+md5
L p+i+n+u+g
E Empty group
> Growing logfile p+u+g+i+n+S

If AIDE is compiled with mhash support, then the following flags can be used as well:

Flag Description
haval haval checksum
gost gost checksum
crc32 crc32 checksum

Инициализация и частое сканирование

Сначала нам нужно инициализировать базу данных один раз.

root #aide --init --config=/etc/aide/aide.conf
AIDE, version 0.14.2
  
### AIDE database at /var/lib/aide/aide.db.new initialized.

Как только база данных инициализирована, мы можем скопировать файл базы данных.

root #cd /var/lib/aide; cp aide.db.new aide.db

Теперь, с доступной базой данных, мы можем просканировать записи снова для обнаружения потенциальных изменений:

root #aide --check --config=/etc/aide/aide.conf
AIDE, version 0.14.2
  
### All files match AIDE database. Looks okay!

Если произошло изменение файла(ов), будет послано уведомление:

This is not a real error and is simply aide stating it cannot find a database so it must create one, this may take several minutes.

root #aide --check --config=/etc/aide/aide.conf
AIDE found differences between database and filesystem!!
Start timestamp: 2013-04-11 15:31:02
  
Summary:
  Total number of files:        318
  Added files:                  0
  Removed files:                0
  Changed files:                2
  
  
---------------------------------------------------
Changed files:
---------------------------------------------------
  
changed: /etc/pam.d
changed: /etc/pam.d/run_init
  
---------------------------------------------------
Detailed information about changes:
---------------------------------------------------
  
  
Directory: /etc/pam.d
  Mtime    : 2013-04-09 22:11:18              , 2013-04-11 15:31:01
  Ctime    : 2013-04-09 22:11:18              , 2013-04-11 15:31:01
  
File: /etc/pam.d/run_init
  Size     : 205                              , 208
  Mtime    : 2013-04-09 22:11:18              , 2013-04-11 15:31:00
  Ctime    : 2013-04-09 22:11:18              , 2013-04-11 15:31:01
  Inode    : 394203                           , 394053
  MD5      : Mm0KPzpPt63eqGClTJ/KaQ==         , eLUrP2BsIq25f3AZX+dlBA==
  SHA1     : NrQtsUeOsXS4RHUq+ejYBne5V6E=     , 5A6ef6VJCcMiqEjKQ7e9xkBNZB8=

Лучшие Практики

Ясно определите что нужно сканировать

Файл конфигурации AIDE по умолчанию полезен, но требуется его тонкая настройка для соответствия требованиям пользователей. Важно знать какие файлы нужно сканировать и почему.

Например, для сканирования всех файлов, связанных с аутентификацией, и никаких других файлов, используйте следующие настройки:

ФАЙЛ aide.confЗадачи сканирования, связанные с аутентификацией
# Политики SELinux и настройки
/etc/selinux ConfFiles
# Базы данных аутентификации
/etc/passwd ConfFiles
/etc/shadow ConfFiles
/etc/nsswitch.conf ConfFiles
# Конфигурация аутентификации
/etc/pam.d ConfFiles
/etc/securetty ConfFiles
/etc/security ConfFiles
# Библиотеки PAM
/lib(64)?/security Binlib

Храните базу данных на внешнем носителе и в режиме только для чтения

Вторым важным аспектом является то, что полученную в результате базу данных нужно хранить на внешнем носителе, когда она Вам не нужна, и использовать режим только для чтения, когда эта база данных понадобилась. Это дает некоторую защиту от злоумышленника, который уже мог скомпрометировать компьютер, чтобы модифицировать базу данных с результатами сканирования. Например, храните конечную базу данных на смонтированном каталоге NFS в режиме только для чтения (для серверов), или на носителе данных с доступом только для чтения (если возможен физический доступ к компьютеру), таком как CD/DVD или USB-флеш-накопитель с переключателем в режим "только чтение".

После размещения базы данных в месторасположении только для чтения, обновите файл aide.conf, чтобы database= указывал на это новое место.

Делайте автономное сканирование

Если необходимо, попытайтесь использовать автономные методы сканирования системы. В случае с виртуальными платформами, возможно сделать снимок системы, смонтировать этот снимок (с доступом только на чтение) и затем запустить aide сканирование на примонтированной файловой системе.

root #losetup /dev/loop0 /srv/virt/gentoo.img
root #vgscan
root #vgchange -ay
root #mount -o ro /dev/volgrpX/volumeY /mnt/image
root #chroot /mnt/image
root #aide --check --config=/path/to/aide.conf
root #exit
root #umount /mnt/image
root #vgchange -an /dev/volgrpX
root #losetup -d /dev/loop0

Подход, представленный выше, использует chroot. Это требуется только тогда, когда исходная файловая система сканируется с работающей системы, и администратор хочет выполнить автономную проверку. Если первоначальное сканирование проводилось в автономном режиме, то файл aide.conf уже будет указывать на точку монтирования и база данных сразу же будет пользоваться этими путями, поэтому в данном случае не требуется использование chroot.

Смотрите также

  • Integrity/Concepts повествует об идеях связанных с целостностью системы

Ссылки