Cómo enviar alertas AVC de SELinux por email (setroubleshoot-server)

Nadie nos impide hacer troubleshooting/debug de SELinux a través del log de audit (/var/log/audit/audit.log), el problema es que en dicho log la información se vuelca en bruto y puede ser complejo analizarla si nuestros conocimientos de SELinux no son avanzados o si no tenemos buena vista. Para evitar esto existe un paquete que nos solucionará este problema, setroubleshoot-server.

# yum info setroubleshoot-server

Available Packages
Name        : setroubleshoot-server
Arch        : i686
Version     : 3.0.47
Release     : 3.el6_3
Size        : 1.3 M
Repo        : updates
Summary     : SELinux troubleshoot server
URL         : https://fedorahosted.org/setroubleshoot
License     : GPLv2+
Description : Provides tools to help diagnose SELinux problems. When AVC messages
            : are generated an alert can be generated that will give information
            : about the problem and help track its resolution. Alerts can be configured
            : to user preference. The same tools can be run on existing log files.

Básicamente, setroubleshoot-server es una herramienta que diagnostica los problemas de SELinux a partir de las alertas AVC generadas en el log de audit y las parsea para volcar información legible en /var/log/messages que posteriormente, a través de un identificador único podemos consultar con sealert, ejemplo:

Contenido de /var/log/messages:

setroubleshoot: SELinux is preventing /usr/sbin/httpd from getattr access on the file /var/www/html/index.html. For complete SELinux messages. run sealert -l 66719ae7-cd7f-474e-a7c5-b70e0739ab91

Ejecución de sealert:

# sealert -l 66719ae7-cd7f-474e-a7c5-b70e0739ab91
SELinux is preventing /usr/sbin/httpd from getattr access on the file /var/www/html/index2.html.

*****  Plugin restorecon (99.5 confidence) suggests  *************************

If you want to fix the label. 
/var/www/html/index2.html default label should be httpd_sys_content_t.
Then you can run restorecon.
Do
# /sbin/restorecon -v /var/www/html/index2.html

*****  Plugin catchall (1.49 confidence) suggests  ***************************

If you believe that httpd should be allowed getattr access on the index2.html file by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# grep httpd /var/log/audit/audit.log | audit2allow -M mypol
# semodule -i mypol.pp

Additional Information:
Source Context                unconfined_u:system_r:httpd_t:s0
Target Context                system_u:object_r:admin_home_t:s0
Target Objects                /var/www/html/index2.html [ file ]
Source                        httpd
Source Path                   /usr/sbin/httpd
Port                          
Host                          lab1
....
....
....
....

Bien, la idea de esta entrada es enviar estas alertas por correo electrónico, de modo que si somos realmente paranoicos podamos estar al tanto de todas las alertas de tipo AVC que tenemos en un sistema. Para ello existe una sección [email] en el fichero de configuración de setroubleshoot: /etc/setroubleshoot/setroubleshoot.conf:

[email]
# recipients_filepath: Path name of file with email recipients. One address
# per line, optionally followed by enable flag. Comment character is #.
recipients_filepath = /var/lib/setroubleshoot/email_alert_recipients

# smtp_port: The SMTP server port
smtp_port = 25

# smtp_host: The SMTP server address
smtp_host = localhost

# from_address: The From: email header
from_address = SELinux_Troubleshoot

# subject: The Subject: email header
subject = SELinux AVC Alert

Simplemente indicamos los parámetros del servidor SMTP que queramos usar y posteriormente, una en cada línea las direcciones de correo electrónico a las que enviar las alertas en el fichero /var/lib/setroubleshoot/email_alert_recipients.

Una vez configurado todo e instalado setroubleshoot-server reiniciamos auditd para releer los cambios:

# /etc/init.d/auditd restart
Stopping auditd:                                           [  OK  ]
Starting auditd:                                           [  OK  ]

También tenemos que reiniciar (o iniciar) messagebus ya que sino recibiremos estos mensajes en el log messages:

Dec  4 09:44:54 lab1 sedispatch: Connection Error (Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory): AVC Will be dropped
Dec  4 09:44:54 lab1 sedispatch: Connection Error (Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory): AVC Will be dropped
# /etc/init.d/messagebus restart
Stopping system message bus:                               [FAILED]
Starting system message bus:                               [  OK  ]

Si forzamos entonces una alerta de SELinux recibiremos un correo con toda la información, ejemplo:

Received: from [127.0.0.1] (localhost [IPv6:::1])
	by lab1.localdomain (Postfix) with ESMTP id BBAA148D9
	for ; Tue,  4 Dec 2012 10:04:13 +0100 (CET)
Content-Type: multipart/alternative; boundary="===============0185241993=="
MIME-Version: 1.0
Subject: [SELinux AVC Alert] SELinux is preventing /usr/sbin/httpd from
	getattr access on the file /var/www/html/index2.html.
From: SELinux_Troubleshoot@lab1.localdomain
To: root@lab1.localdomain
Date: Tue, 04 Dec 2012 09:04:12 -0000
Message-Id: 

--===============0185241993==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

SELinux is preventing /usr/sbin/httpd from getattr access on the file /var/www/html/index2.html.

*****  Plugin restorecon (99.5 confidence) suggests  *************************

If you want to fix the label. 
/var/www/html/index2.html default label should be httpd_sys_content_t.
Then you can run restorecon.
Do
# /sbin/restorecon -v /var/www/html/index2.html

*****  Plugin catchall (1.49 confidence) suggests  ***************************

If you believe that httpd should be allowed getattr access on the index2.html file by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# grep httpd /var/log/audit/audit.log | audit2allow -M mypol
# semodule -i mypol.pp

Additional Information:
Source Context                unconfined_u:system_r:httpd_t:s0
Target Context                system_u:object_r:admin_home_t:s0
Target Objects                /var/www/html/index2.html [ file ]
Source                        httpd
Source Path                   /usr/sbin/httpd
Port                          
Host                          lab1
Source RPM Packages           
Target RPM Packages           
Policy RPM                    
Selinux Enabled               True
Policy Type                   targeted
Enforcing Mode                Enforcing
Host Name                     lab1
Platform                      Linux lab1 2.6.32-220.el6.i686 #1 SMP Tue Dec 6
                              16:15:40 GMT 2011 i686 i686
Alert Count                   11
First Seen                    Tue Dec  4 09:49:49 2012
Last Seen                     Tue Dec  4 10:03:53 2012
Local ID                      66719ae7-cd7f-474e-a7c5-b70e0739ab91

Raw Audit Messages
type=AVC msg=audit(1354611833.269:24): avc:  denied  { getattr } for  pid=1429 comm="httpd" path="/var/www/html/index2.html" dev=dm-0 ino=42 scontext=unconfined_u:system_r:httpd_t:s0 tcontext=system_u:object_r:admin_home_t:s0 tclass=file

type=SYSCALL msg=audit(1354611833.269:24): arch=i386 syscall=stat64 success=no exit=EACCES a0=16f78d8 a1=bfc9d120 a2=4c6ff4 a3=8170 items=0 ppid=1425 pid=1429 auid=0 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=1 comm=httpd exe=/usr/sbin/httpd subj=unconfined_u:system_r:httpd_t:s0 key=(null)

Hash: httpd,httpd_t,admin_home_t,file,getattr

audit2allow

#============= httpd_t ==============
allow httpd_t admin_home_t:file getattr;

audit2allow -R

#============= httpd_t ==============
allow httpd_t admin_home_t:file getattr;

--===============0185241993==--