Lynis: auditoría, hardening y seguridad de sistemas

Siguiendo el hilo de artículos relacionados con la seguridad de sistemas Unix y GNU/Linux hoy voy a hablar sobre Lynis, una herramienta de seguridad y auditoría de sistemas open source sencilla de instalar y muy potente y personalizable que permite tener una visión clara del estado del sistema en cuanto a vulnerabilidades, hardening y seguridad en general.

Como complemento a esta herramienta, os recomiendo revisar otros artículos relacionados como por ejemplo instalación y configuración de AIDE (Advanced Intrusion Detection Environment) o el de Anti rootkit en Linux con rkhunter.

El funcionamiento de la herramienta es similar al Rkhunter. Realiza una gran cantidad de pruebas contra el sistema para determinar el estado de la seguridad del sistema, por ejemplo, la búsqueda de software instalado y sus vulnerabilidades o la revisión de configuración en busca de fallos de seguridad y software desactualizado. Todo ello queda reflejado en un informe final junto con un listado de recomendaciones para solventar todos los fallos encontrados. Así pues, esta herramienta es de utilidad para realizar auditorías de sistemas, escaneo de vulnerabilidades y hardening del sistema.

lynis

Lynis se ofrece en versión gratuita y Enterprise, vamos a ver como instalar (que no es necesario), ejecutar e interpretar la versión gratuita.

Descargamos la última versión estable de la herramienta:

$ wget http://cisofy.com/files/lynis-1.6.3.tar.gz

Descomprimimos:

$ tar -xzvf lynis-1.6.3.tar.gz

La herramienta puede ser ejecutada sin necesidad de instalación, simplemente tras descomprimir el archivo ejecutamos:

 # sh lynis

ó

 # ./lynis

Al ejecutar la herramienta sin parámetros visualizamos la ayuda y las opciones disponibles para la ejecución:

[+] Initializing program
------------------------------------
  Scan options:
    --auditor ""            : Auditor name
    --check-all (-c)              : Check system
    --no-log                      : Don't create a log file
    --pentest                     : Non-privileged scan (useful for pentest)
    --profile            : Scan the system with the given profile file
    --quick (-Q)                  : Quick mode, don't wait for user input
    --tests ""             : Run only tests defined by 
    --tests-category "" : Run only tests defined by 

  Layout options:
    --no-colors                   : Don't use colors in output
    --quiet (-q)                  : No output, except warnings
    --reverse-colors              : Optimize color display for light backgrounds

  Misc options:
    --check-update                : Check for updates
    --debug                       : Debug logging to screen
    --view-manpage (--man)        : View man page
    --version (-V)                : Display version number and quit

  Enterprise options:
    --plugin-dir "<path">         : Define path of available plugins
    --upload                      : Upload data to central node

  Error: No parameters specified!
  See man page and documentation for all available options.

Podemos hacer un escaneo rápido o completo, definir únicamente ciertos tests, modificar la apariencia del informe, revisar actualizaciones, ejecutar en modo debug, añadir más plugins (para aumentar las funcionalidades de la herramienta o subir el informe a un sistema externo.

Los perfiles sirven para tener una plantilla en la que podemos indicar el sistema operativo sobre el que se realiza la prueba (Debian Linux, RedHat Linux, OpenBSD), el tipo de servicios que se ejecutan en el sistema (servidor web, correo, base de datos…) o el nivel de seguridad a utilizar (bajo, medio, alto…). De este modo, cada perfil puede tener unos test concretos. Si no se especifica ningún perfil se utilizará el de por defecto: default.prf

Podemos usar este perfil como base para aprender y crear nuestros propios perfiles.

# ./default.prf

Si revisáis el perfil, veréis que se definen los plugins a utilizar y las distintas pruebas a realizar a nivel de procesos, sistema, red, kernel, servicios (ntp, ldap, web, ssl…), etc. Os dejo una pequeña muestra de algunas de las secciones del perfil por defecto:

# more default.prf 
#################################################################################
#
# Lynis scan profile
#
# This is the default profile and is used as a baseline when testing systems and
# applications. Since there are generally no "best" options, Lynis will assume
# some default values.
# 
# All empty lines or with the # prefix will be skipped
#
# This is the default profile and contains default values. You are encouraged to
# copy this file and use it's base for custom audit profiles.
#
#################################################################################

[configuration]
# Profile name, will be used as title/description
config:profile_name:Default Audit Template:

# Number of seconds to pause between every test (0 is no pause)
config:pause_between_tests:0:

# Show inline tips about the tool
config:show_tool_tips:1:


#################################################################################
#
# Testing options
# ---------------
#
#################################################################################

# ** Scan type (how deep test has to be, light, normal or full) **
#
# config:test_scan_mode:light|normal|full:


# ** Skip one or more specific tests **
# (always ignores scan mode and will make sure the test is skipped)
#
# config:test_skip_always:AAAA-1234 BBBB-5678 CCCC-9012:


# ** Define the role(s) of a machine **
# Values: desktop|server (default: server)
#
#config:machine_role:server:


#################################################################################
#
# Plugins
# ---------------
# Define which plugins are enabled (nothing happens if plugin isn't available)
#
#################################################################################

plugin=compliance
plugin=control-panels
plugin=docker
plugin=file-integrity
plugin=files
plugin=filesystems
plugin=firewalls
plugin=processes
plugin=software
plugin=system-integrity

#################################################################################
#
# Sysctl options
# ---------------
# sysctl:::::
#
# Sysctl key       = name
# Expected value   = value of sysctl key
# Hardening points = Number of hardening points. For most keys 1 HP will be suitable
# Description      = Text description of key
#
#################################################################################

[processes]
#sysctl:kern.randompid:1234:1:Increase the next PID with an amount close to the given value:
sysctl:security.bsd.see_other_gids:0:1:Disable display of processes of other groups:
sysctl:security.bsd.see_other_uids:0:1:Disable display of processes of other users:

[kernel]
sysctl:kern.sugid_coredump:0:1:XXX:
sysctl:kernel.core_setuid_ok:0:1:XXX:
sysctl:kernel.core_uses_pid:1:1:XXX:
sysctl:kernel.ctrl-alt-del:0:1:XXX:
[...]

[network]
sysctl:net.inet.icmp.bmcastecho:0:1:Ignore ICMP packets directed to broadcast address:
sysctl:net.inet.icmp.rediraccept:0:1:Disable incoming ICMP redirect routing redirects:
sysctl:net.inet.ip.accept_sourceroute:0:1:Disable IP source routing: 
sysctl:net.inet.ip.redirect:0:1:Disable/Ignore ICMP routing redirects:
sysctl:net.inet.ip.sourceroute:0:1:Disable IP source routing:
[...]

[security]
#security.bsd.unprivileged_read_msgbuf: 1
#security.bsd.hardlink_check_gid: 0
#security.bsd.hardlink_check_uid: 0
[...]

#################################################################################
#
# Apache options
# columns: (1)apache : (2)option : (3)value
#
#################################################################################

apache:ServerTokens:Prod:


#################################################################################
#
# OpenLDAP options
# columns: (1)openldap : (2)file : (3)option : (4)expected value(s)
#
#################################################################################

openldap:slapd.conf:permissions:640-600:
openldap:slapd.conf:owner:ldap-root:
[...]

Como todo, es cuestión de ajustar la herramienta a nuestras necesidades y dejarla fina para varios perfiles de sistema operativo, servicios, etc. Las posibilidades son muy amplias.

Vamos a ver como sería una ejecución típica en la que usamos el perfil por defecto y hacemos un escaneo completo (–check-all) del sistema.

# ./lynis --check-all

La ejecución se realiza por módulos, tras la finalización de cada sección podemos revisar el resultado y continuar cuando lo estimemos oportuno:

[ Lynis 1.6.3 ]

################################################################################
 Lynis comes with ABSOLUTELY NO WARRANTY. This is free software, and you are
 welcome to redistribute it under the terms of the GNU General Public License.
 See the LICENSE file for details about using this software.

 Copyright 2007-2014 - Michael Boelen, http://cisofy.com
 Enterprise support and plugins available via CISOfy - http://cisofy.com
################################################################################

[+] Initializing program
------------------------------------
  - Detecting OS...                                           [ DONE ]
  - Clearing log file (/var/log/lynis.log)...                 [ DONE ]

  ---------------------------------------------------
  Program version:           1.6.3
  Operating system:          Linux
  Operating system name:     CentOS
  Operating system version:  CentOS release 6.3 (Final)
  Kernel version:            2.6.32
  Hardware platform:         i686
  Virtual machine:           Unknown
  Hostname:                  lab1
  Auditor:                   [Unknown]
  Profile:                   ./default.prf
  Log file:                  /var/log/lynis.log
  Report file:               /var/log/lynis-report.dat
  Report version:            1.0
  Plugin directory:          ./plugins
  ---------------------------------------------------

[ Press [ENTER] to continue, or [CTRL]+C to stop ]

La salida es clara, colores verde (OK | FOUND), rojo (WARNING), amarillo (DEFAULT | DISABLED | SUGGESTION) blanco (NOT FOUND | NOT ENABLED)… según severidad del resultado. Tras la primera parte en la que se detecta el tipo de sistema operativo, versión de kernel, perfil a utilizar y también se indica los logs donde se almacenarán los reportes, comienzan los chequeos de seguridad.

No pongo la salida completa de cada módulo para no alargar más el artículo, simplemente una parte de cada uno de ellos.

Chequeo de binarios:

[+] System Tools
------------------------------------
  - Scanning available tools...
  - Checking system binaries...
    - /bin                                                    [ FOUND ]
    - /sbin                                                   [ FOUND ]
    - /usr/bin                                                [ FOUND ]
    - /usr/sbin                                               [ FOUND ]
    - /usr/local/bin                                          [ FOUND ]
    - /usr/local/sbin                                         [ FOUND ]
    - /usr/local/libexec                                      [ FOUND ]
    - /usr/libexec                                            [ FOUND ]
    - /usr/sfw/bin                                            [ NOT FOUND ]
    - /usr/sfw/sbin                                           [ NOT FOUND ]
 [...]

Arranque y servicios:

+] Boot and services
------------------------------------
  - Checking boot loaders
    - Checking presence GRUB                                  [ OK ]
      - Checking for password protection                      [ WARNING ]
  - Check services at startup (chkconfig)                     [ DONE ]
        Result: found 24 services
  - Check startup files (permissions)                         [ OK ]
[...]

Kernel:

[+] Kernel
------------------------------------
  - Checking default run level                                [ 3 ]
  - Checking CPU support (NX/PAE)
    CPU support: PAE and/or NoeXecute supported               [ FOUND ]
  - Checking kernel version and release                       [ DONE ]
  - Checking kernel type                                      [ DONE ]
[...]

Memoria y procesos:

[+] Memory and processes
------------------------------------
  - Checking /proc/meminfo                                    [ FOUND ]
  - Searching for dead/zombie processes                       [ OK ]
  - Searching for IO waiting processes                        [ OK ]
[...]

Usuarios, grupos y autenticación:

[+] Users, Groups and Authentication
------------------------------------
  - Search administrator accounts                             [ OK ]
  - Checking for non-unique UIDs                              [ OK ]
  - Checking consistency of group files (grpck)               [ OK ]
  - Checking non unique group ID's                            [ OK ]
  - Checking non unique group names                           [ OK ]
  - Checking password file consistency                        [ OK ]
  - Query system users (non daemons)                          [ DONE ]
  - Checking NIS+ authentication support                      [ NOT ENABLED ]
[...]

Mirad que interesante la parte de Shells. Revisa vulnerabilidades, exploits y bugs que podrían afectar a nuestras versiones, por ejemplo el reciente bug de Shellshock:

[+] Shells
------------------------------------
  - Checking shells from /etc/shells
    Result: found 3 shells (valid shells: 3).
    - Session timeout settings/tools                          [ NONE ]
  - Testing for Shellshock vulnerability
    - CVE-2014-6271 (original shellshocker)                   [ OK ]
    - CVE-2014-6277 (segfault, lcamtuf bug #1)                [ WARNING ]
    - CVE-2014-6278 (Florian's patch, lcamtuf bug #2)         [ OK ]
    - CVE-2014-7169 (taviso bug)                              [ OK ]
[...]

Sistemas de ficheros:

[+] File systems
------------------------------------
  - Checking mount points
    - Checking /home mount point                              [ SUGGESTION ]
    - Checking /tmp mount point                               [ SUGGESTION ]
  - Checking LVM volume groups                                [ NONE ]
  - Querying FFS/UFS mount points (fstab)                     [ NONE ]
  - Query swap partitions (fstab)                             [ OK ]
  - Testing swap partitions                                   [ WARNING ]
[...]

Y así hasta que terminaran los tests, no sigo poniendo pues simplemente quería que vierais el formato del informe y algunos de los chequeos que realiza. Otras pruebas que realiza son:

  • Storage
  • NFS
  • Software DNS
  • Ports and packages (revisión completa de RPMs, DEBs…)
  • Networking
  • Printers and Spools
  • Software: e-mail and messaging
  • Software: firewalls
  • Software: webserver
  • SSH support
  • SNMP support
  • Databases
  • LDAP Services
  • Software PHP
  • Squid Support
  • Logging and files
  • Insecure services
  • Banners and identification
  • Scheduled tasks
  • Accounting
  • Time and Synchronization
  • Cryptography
  • Virtualization
  • Security frameworks
  • Software: file integrity
  • Software: System tooling
  • Software: Malware scanners
  • File Permissions
  • Home directories
  • Kernel Hardening
  • Hardening
  • Custom tests

Al final de la auditoría, recibimos un informe muy completo en el que se indican los problemas encontrados y las sugerencias para corregirlos. Os dejo un extracto del informe de pruebas que he realizado:

  -[ Lynis 1.6.3 Results ]-

  Warnings:
  ----------------------------
  - No password set for single mode [AUTH-9308]
      http://cisofy.com/controls/AUTH-9308/

  - System vulnerable to Shellshock (bash) [SHLL-6290]
      http://cisofy.com/controls/SHLL-6290/

  - Couldn't find 2 responsive nameservers [NETW-2705]
      http://cisofy.com/controls/NETW-2705/

  - No MySQL root password set [DBS-1816]
      http://cisofy.com/controls/DBS-1816/

  - PHP option expose_php is possibly turned on, which can reveal useful information for attackers. [PHP-2372]
      http://cisofy.com/controls/PHP-2372/

  - One or more SSL certificates expired [CRYP-7902]
      http://cisofy.com/controls/CRYP-7902/

  Suggestions:
  ----------------------------
  - Set a password on GRUB bootloader to prevent altering boot configuration (e.g. boot in single user mode without password) [BOOT-5122]
      http://cisofy.com/controls/BOOT-5122/
  - Run chkconfig --list to see all services and disable unneeded services
      http://cisofy.com/controls/[09:55:02 Suggestion: Run chkconfig --list to see all services and disable unneeded services/
  - Configure password aging limits to enforce password changing on a regular base [AUTH-9286]
      http://cisofy.com/controls/AUTH-9286/
  - Set password for single user mode to minimize physical access attack surface [AUTH-9308]
      http://cisofy.com/controls/AUTH-9308/
  - Default umask in /etc/profile could be more strict like 027 [AUTH-9328]
      http://cisofy.com/controls/AUTH-9328/
  - To decrease the impact of a full /home file system, place /home on a separated partition [FILE-6310]
      http://cisofy.com/controls/FILE-6310/
  - To decrease the impact of a full /tmp file system, place /tmp on a separated partition [FILE-6310]
      http://cisofy.com/controls/FILE-6310/
  - Check your /etc/fstab file for swap partition mount options [FILE-6336]
 
[...]

  Follow-up:
  ----------------------------
  - Check the logfile (less /var/log/lynis.log)
  - Read security controls texts (http://cisofy.com)
  - Use --upload to upload data (Lynis Enterprise users)

================================================================================
  Lynis Scanner (details):

  Hardening index : 50 [##########          ]
  Tests performed : 191
  Plugins enabled : 0

  Lynis Modules:
  - Heuristics Check [NA] - Security Audit [V] - Vulnerability Scan [V]

  Compliance Checks:
  - HIPAA [NA] - PCI [NA] - SOx [NA] 

  Files:
  - Test and debug information      : /var/log/lynis.log
  - Report data                     : /var/log/lynis-report.dat

7 comentarios en “Lynis: auditoría, hardening y seguridad de sistemas

  1. Estimado,
    Una consulta. ¿Existe algo parecido Open Source que incluya Windows?

    Gracias

    • Hola,

      con «Windows», ¿te refieres a gráfico? Por favor, llamemos a las cosas por su nombre para evitar malentendidos.

      Un saludo.

      • Yo creo que a lo que se refiere Martín, es al escaneo para SO Windows, no tanto si es gráfico o no, es lo que menos importa.

Comments are closed.