Ir al contenido principal

Cómo automatizar auditorías de seguridad con Lynis y Ansible

Representación abstracta de informes de auditoría. Buenas prácticas y seguridad.
Fecha de publicación: marzo 24, 2023 (Actualizado en: julio 27, 2026)

Para garantizar una postura de seguridad sólida en servidores y estaciones de trabajo, la ejecución de evaluaciones periódicas es fundamental. En este escenario, Lynis destaca como una de las mejores herramientas de código abierto para el hardening (endurecimiento) de sistemas y la auditoría de cumplimiento de normativas internacionales, como CIS Benchmarks y GDPR.

Por su parte, Ansible permite automatizar tareas de configuración y orquestación IT. Al integrar ambas tecnologías, los administradores de sistemas pueden ejecutar auditorías de seguridad de Lynis de forma remota, recurrente y sin intervención manual.

Esta automatización de la seguridad aporta beneficios como:

  • Eliminación de errores humanos derivados de procesos manuales.
  • Centralización de la gestión de vulnerabilidades en infraestructuras IT grandes o entornos híbridos.
  • Monitoreo continuo del estado de los servidores.

En este artículo, exploraremos paso a paso cómo funciona la integración de Lynis y Ansible para evaluar la seguridad de tus sistemas operativos. Además, aprenderás a generar informes HTML visualmente atractivos, facilitando la presentación de los resultados de las auditorías de una manera clara, profesional y fácil de interpretar para la toma de decisiones.

1. Qué es Lynis, cómo se instala y comandos básicos

Lynis es una herramienta de código abierto especializada en auditorías de seguridad para sistemas operativos tipo Unix, abarcando distribuciones de Linux (Ubuntu, Debian, CentOS, RHEL) y macOS. A diferencia de un antivirus tradicional, Lynis se enfoca exclusivamente en el hardening (endurecimiento) del sistema y en detectar desviaciones frente a las mejores prácticas de ciberseguridad dictadas por estándares globales como CIS, NSA o PCI DSS.

Su principal ventaja es que se ejecuta directamente sobre el sistema objetivo, eliminando la necesidad de instalar agentes remotos.

¿Qué escanea Lynis durante su análisis?

  • Vulnerabilidades conocidas en servicios y aplicaciones instaladas.
  • Configuraciones inseguras en archivos críticos (por ejemplo, /etc/ssh/sshd_config) o en las reglas del firewall.
  • Brechas de control de acceso, como permisos incorrectos en directorios clave, retención de paquetes obsoletos o existencia de usuarios sin contraseña.

Al concluir el escaneo, la herramienta emite un informe detallado que incluye un índice de endurecimiento (hardening index) y una lista de recomendaciones priorizadas para mitigar los hallazgos.

Instalación y uso básico de Lynis

Para comenzar a utilizar Lynis, puedes descargarlo desde su repositorio oficial o instalarlo mediante los gestores de paquetes nativos de tu distribución (apt o yum). Una vez descargado y descomprimido (si aplica), se ejecuta desde la terminal.

El comando principal para realizar un escaneo completo del sistema es: lynis audit system

Nota: Este comando generará el informe detallado de resultados en la ruta /var/log/lynis.log.

Otros comandos útiles de personalización:

  • lynis audit system –quick : Ejecuta un análisis rápido del sistema.
  • lynis show settings : Muestra la configuración actual de la herramienta.

El proceso de auditoría es altamente personalizable: puedes omitir pruebas específicas, establecer umbrales de alerta e integrar Lynis de forma nativa con herramientas de orquestación IT como Ansible, SaltStack o Puppet.

Este tutorial técnico ha sido elaborado por Alfredo Prats, Director Técnico en Chakray Consulting, aplicando la experiencia y buenas prácticas del sector empresarial.

1.1 Instalación de Lynis desde la web

Para instalar Lynis en un sistema Linux desde la web, sigue estos pasos:

vagrant@master:~$ wget https://downloads.cisofy.com/lynis/lynis-2.7.5.tar.gz

Descomprime el archivo de Lynis con el comando tar:

vagrant@master:~$ tar zxpvf lynis-2.7.5.tar.gz

1.2 Instalación desde repositorio

La segunda opción es descargar desde el repositorio oficial. Descarga el código fuente de Lynis desde el repositorio de Git con el siguiente comando:

vagrant@master:~/repo$ git clone https://github.com/CISOfy/lynis
Cloning into 'lynis'...
remote: Enumerating objects: 14638, done.
remote: Counting objects: 100% (44/44), done.
remote: Compressing objects: 100% (31/31), done.
remote: Total 14638 (delta 21), reused 30 (delta 13), pack-reused 14594
Receiving objects: 100% (14638/14638), 7.77 MiB | 16.85 MiB/s, done.
Resolving deltas: 100% (10787/10787), done.

Navega al directorio descomprimido de Lynis:

vagrant@master:~/repo$ ls
lynis

vagrant@master:~/repo$ cd lynis/

2. Auditar

Una vez instalado, ya podemos realizar nuestra primera auditoría del sistema. La prueba que vamos a realizar a continuación es una instalación limpia de Ubuntu, esto afectará a nuestro análisis y el informe que nos generará. Es recomendable realizar una auditoría antes y después para comparar resultados. Para realizar nuestra primera auditoría tenemos que realizar los siguientes pasos:

Paso 1. Nos dirigimos al directorio que ha generado y ejecutamos el siguiente script y nos saldrá todas las opciones disponibles.

vagrant@master:~/lynis$ ./lynis 

[ Lynis 2.7.5 ]

################################################################################
  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.

  2007-2019, CISOfy - https://cisofy.com/lynis/
  Enterprise support available (compliance, plugins, interface and tools)
################################################################################


[+] Initializing program
------------------------------------


  Usage: lynis command [options]


  Command:

    audit
        audit system                  : Perform local security scan
        audit system remote <host>    : Remote security scan
        audit dockerfile <file>       : Analyze Dockerfile

    show
        show                          : Show all commands
        show version                  : Show Lynis version
        show help                     : Show help

    update
        update info                   : Show update details


  Options:

    --no-log                          : Don't create a log file
    --pentest                         : Non-privileged scan (useful for pentest)
    --profile <profile>               : Scan the system with the given profile file
    --quick (-Q)                      : Quick mode, don't wait for user input

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

    Misc options
    --debug                           : Debug logging to screen
    --view-manpage (--man)            : View man page
    --verbose                         : Show more details on screen
    --version (-V)                    : Display version number and quit

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

    More options available. Run './lynis show options', or use the man page.

  No command provided. Exiting..

Paso 2. Para escanear todo el sistema pondremos las siguientes opciones.

vagrant@master:~/lynis$ ./lynis audit system

Paso 3: Inicializando el programa

[+] Initializing program
------------------------------------

  ###################################################################
  #                                                                 #
  #   NON-PRIVILEGED SCAN MODE                                      #
  #                                                                 #
  ###################################################################

  NOTES:
  --------------
  * Some tests will be skipped (as they require root permissions)
  * Some tests might fail silently or give different results

  - Detecting OS...                                           [ DONE ]
  - Checking profiles...                                      [ DONE ]

  ---------------------------------------------------
  Program version:           2.7.5
  Operating system:          Linux
  Operating system name:     Ubuntu Linux
  Operating system version:  20.04
  Kernel version:            5.4.0
  Hardware platform:         x86_64
  Hostname:                  master
  ---------------------------------------------------
  Profiles:                  /home/vagrant/lynis/default.prf
  Log file:                  /tmp/lynis.log
  Report file:               /tmp/lynis-report.dat
  Report version:            1.0
  Plugin directory:          ./plugins
  ---------------------------------------------------
  Auditor:                   [Not Specified]
  Language:                  en
  Test category:             all
  Test group:                all
  ---------------------------------------------------
  - Program update status...                                  [ WARNING ]

      ===============================================================================
        Lynis update available
      ===============================================================================

        Current version is more than 4 months old

        Current version : 275   Latest version : 308

*Nota (julio de 2026): Este tutorial fue elaborado utilizando una versión anterior de Lynis. Actualmente la versión estable es la 3.1.5. Antes de implementar el procedimiento en producción, consulta siempre la documentación oficial y verifica los pasos correspondientes a la versión vigente.
Please update to the latest version.
  New releases include additional features, bug fixes, tests, and baselines.

  Download the latest version:

  Packages (DEB/RPM) -  https://packages.cisofy.com
  Website (TAR)      -  https://cisofy.com/downloads/
  GitHub (source)    -  https://github.com/CISOfy/lynis

===============================================================================

Análisis del sistema, plugins, kernel y servicios

¿Qué evalúa Lynis durante una auditoría de seguridad?

Durante su ejecución, Lynis realiza un escaneo exhaustivo de los siguientes componentes críticos para garantizar que el entorno operativo esté protegido:

  • Sistema y servicios: Evalúa que el sistema operativo y los demonios (servicios) en ejecución estén optimizados y bajo parámetros estrictos de seguridad.
  • Reglas del Firewall: Verifica que el cortafuegos esté correctamente configurado y activo para filtrar el tráfico y proteger la infraestructura de conexiones no autorizadas.
  • Políticas de contraseñas: Comprueba los esquemas de autenticación para detectar políticas deficientes y prevenir el uso de contraseñas débiles.
  • Gestión de cuentas de usuario: Analiza los perfiles del sistema para garantizar el principio de privilegios mínimos, detectando cuentas con accesos de administrador innecesarios.
  • Permisos de archivos y directorios: Inspecciona el sistema de archivos para evitar que usuarios no autorizados tengan permisos de lectura, escritura o ejecución excesivos.
  • Paquetes y software instalado: Identifica dependencias inseguras, software obsoleto o la presencia de paquetes innecesarios que puedan representar una vulnerabilidad.
  • Configuración de red: Examina las interfaces y protocolos de red para evitar la exposición de información sensible y cerrar posibles vectores de ataque externos.

Y muchas más comprobaciones del sistema.

[+] System Tools
------------------------------------
- Scanning available tools...
  - Checking system binaries...

[+] Plugins (phase 1)
------------------------------------
 Note: plugins have more extensive tests and may take several minutes to complete
  
  - Plugins enabled                                           [ NONE ]

[+] Boot and services
------------------------------------
  - Service Manager                                           [ systemd ]
  - Checking presence GRUB2                                   [ FOUND ]
    - Checking for password protection                        [ NONE ]
  - Check running services (systemctl)                        [ DONE ]
        Result: found 22 running services
  - Check enabled services at boot (systemctl)                [ DONE ]
        Result: found 58 enabled services
  - Check startup files (permissions)                         [ OK ]

[+] Kernel
------------------------------------
  - Checking default run level                                [ RUNLEVEL 5 ]
  - Checking CPU support (NX/PAE)
    CPU support: PAE and/or NoeXecute supported               [ FOUND ]
  - Checking kernel version and release                       [ DONE ]
  - Checking kernel type                                      [ DONE ]
  - Checking loaded kernel modules                            [ DONE ]
      Found 57 active modules
  - Checking Linux kernel configuration file                  [ FOUND ]
  - Checking default I/O kernel scheduler                     [ NOT FOUND ]
  - Checking for available kernel update                      [ OK ]
  - Checking core dumps configuration                         [ DISABLED ]
    - Checking setuid core dumps configuration                [ PROTECTED ]
  - Check if reboot is needed                                 [ YES ]

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

[+] Users, Groups and Authentication
------------------------------------
  - Administrator accounts                                    [ OK ]
  - Unique UIDs                                               [ OK ]
  - Unique group IDs                                          [ OK ]
  - Unique group names                                        [ OK ]
  - Password file consistency                                 [ SUGGESTION ]
  - Query system users (non daemons)                          [ DONE ]
  - NIS+ authentication support                               [ NOT ENABLED ]
  - NIS authentication support                                [ NOT ENABLED ]
 - sudoers file                                              [ FOUND ]
  - PAM password strength tools                               [ SUGGESTION ]
  - PAM configuration files (pam.conf)                        [ FOUND ]
  - PAM configuration files (pam.d)                           [ FOUND ]
  - PAM modules                                               [ FOUND ]
  - LDAP module in PAM                                        [ NOT FOUND ]
  - Accounts without expire date                              [ OK ]
  - Accounts without password                                 [ OK ]
  - Checking user password aging (minimum)                    [ DISABLED ]
  - User password aging (maximum)                             [ DISABLED ]
  - Checking Linux single user mode authentication            [ OK ]
  - Determining default umask
    - umask (/etc/profile)                                    [ NOT FOUND ]
    - umask (https://cdn.chakray.com/etc/login.defs)                                 [ SUGGESTION ]
  - LDAP authentication support                               [ NOT ENABLED ]
  - Logging failed login attempts                             [ ENABLED ]

[+] Shells
------------------------------------
  - Checking shells from /etc/shells
    Result: found 9 shells (valid shells: 9).
    - Session timeout settings/tools                          [ NONE ]
  - Checking default umask values
    - Checking default umask in /etc/bash.bashrc              [ NONE ]
    - Checking default umask in /etc/profile                  [ NONE ]

[+] File systems
------------------------------------
  - Checking mount points
    - Checking /home mount point                              [ SUGGESTION ]
    - Checking /tmp mount point                               [ SUGGESTION ]
    - Checking /var mount point                               [ SUGGESTION ]
  - Query swap partitions (fstab)                             [ NONE ]
  - Testing swap partitions                                   [ OK ]
  - Testing /proc mount (hidepid)                             [ SUGGESTION ]
  - Checking for old files in /tmp                            [ OK ]
  - Checking /tmp sticky bit                                  [ OK ]
  - Checking /var/tmp sticky bit                              [ OK ]
  - Mount options of /                                        [ OK ]
  - Disable kernel support of some filesystems
    - Discovered kernel modules: udf 

[+] USB Devices
------------------------------------
  - Checking usb-storage driver (modprobe config)             [ NOT DISABLED ]
  - Checking USB devices authorization                        [ DISABLED ]
  - Checking USBGuard                                         [ NOT FOUND 
]

[+] Storage
------------------------------------
  - Checking firewire ohci driver (modprobe config)           [ DISABLED ]

[+] NFS
------------------------------------
  - Check running NFS daemon                                  [ NOT FOUND ]

[+] Name services
------------------------------------
  - Checking search domains                                   [ FOUND ]
  - Checking /etc/resolv.conf options                         [ FOUND ]
  - Searching DNS domain name                                 [ FOUND ]
      Domain name: local
  - Checking /etc/hosts
    - Checking /etc/hosts (duplicates)                        [ OK ]
    - Checking /etc/hosts (hostname)                          [ OK ]
    - Checking /etc/hosts (localhost)                         [ OK ]
    - Checking /etc/hosts (localhost to IP)                   [ OK ]

[+] Ports and packages
------------------------------------
  - Searching package managers
    - Searching dpkg package manager                          [ FOUND ]
      - Querying package manager
    - Query unpurged packages                                 [ NONE ]
  - Checking security repository in sources.list file         [ OK ]
  - Checking upgradeable packages                             [ SKIPPED ]
  - Checking package audit tool                               [ NONE ]
  - Toolkit for automatic upgrades (unattended-upgrade)       [ FOUND ]

[+] Networking
------------------------------------
  - Checking IPv6 configuration                               [ ENABLED ]
      Configuration method                                    [ AUTO ]
      IPv6 only                                               [ NO ]
  - Checking configured nameservers
    - Testing nameservers
        Nameserver: 127.0.0.53                                [ OK ]
  - Getting listening ports (TCP/UDP)                         [ DONE ]
  - Checking promiscuous interfaces                           [ OK ]
  - Checking status DHCP client                               [ NOT ACTIVE ]
  - Checking for ARP monitoring software                      [ NOT FOUND ]

[+] Printers and Spools
------------------------------------
  - Checking cups daemon                                      [ NOT FOUND ]
  - Checking lp daemon                                        [ NOT RUNNING ]

[+] Software: e-mail and messaging
------------------------------------
[+] Software: firewalls
------------------------------------
  - Checking iptables kernel module                           [ FOUND ]
  - Checking host based firewall                              [ ACTIVE ]

[+] Software: webserver
------------------------------------
  - Checking Apache                                           [ NOT FOUND ]
  - Checking nginx                                            [ NOT FOUND ]

[+] SSH Support
------------------------------------
  - Checking running SSH daemon                               [ FOUND ]
    - Searching SSH configuration                             [ FOUND ]
    - SSH option: AllowTcpForwarding                          [ NOT FOUND ]
    - SSH option: ClientAliveCountMax                         [ NOT FOUND ]
    - SSH option: ClientAliveInterval                         [ NOT FOUND ]
    - SSH option: Compression                                 [ NOT FOUND ]
    - SSH option: FingerprintHash                             [ NOT FOUND ]
    - SSH option: GatewayPorts                                [ NOT FOUND ]
    - SSH option: IgnoreRhosts                                [ NOT FOUND ]
    - SSH option: LoginGraceTime                              [ NOT FOUND ]
    - SSH option: LogLevel                                    [ NOT FOUND ]
    - SSH option: MaxAuthTries                                [ NOT FOUND ]
    - SSH option: MaxSessions                                 [ NOT FOUND ]
    - SSH option: PermitRootLogin                             [ NOT FOUND ]
    - SSH option: PermitUserEnvironment                       [ NOT FOUND ]
    - SSH option: PermitTunnel                                [ NOT FOUND ]
    - SSH option: Port                                        [ NOT FOUND ]
    - SSH option: PrintLastLog                                [ NOT FOUND ]
    - SSH option: StrictModes                                 [ NOT FOUND ]
    - SSH option: TCPKeepAlive                                [ NOT FOUND ]
    - SSH option: UseDNS                                      [ NOT FOUND ]
    - SSH option: VerifyReverseMapping                        [ NOT FOUND ]
    - SSH option: X11Forwarding                               [ NOT FOUND ]
    - SSH option: AllowAgentForwarding                        [ NOT FOUND ]
   - SSH option: AllowUsers                                  [ NOT FOUND ]
    - SSH option: AllowGroups                                 [ NOT FOUND ]

[+] SNMP Support
------------------------------------
  - Checking running SNMP daemon                              [ NOT FOUND ]

[+] Databases
------------------------------------
    No database engines found

[+] LDAP Services
------------------------------------
  - Checking OpenLDAP instance                                [ NOT FOUND ]

[+] PHP
------------------------------------
  - Checking PHP                                              [ NOT FOUND ]

[+] Squid Support
------------------------------------
  - Checking running Squid daemon                             [ NOT FOUND ]

[+] Logging and files
------------------------------------
  - Checking for a running log daemon                         [ OK ]
    - Checking Syslog-NG status                               [ NOT FOUND ]
    - Checking systemd journal status                         [ FOUND ]
    - Checking Metalog status                                 [ NOT FOUND ]
    - Checking RSyslog status                                 [ FOUND ]
    - Checking RFC 3195 daemon status                         [ NOT FOUND ]
    - Checking minilogd instances                             [ NOT FOUND ]
  - Checking logrotate presence                               [ OK ]
  - Checking log directories (static list)                    [ DONE ]
  - Checking open log files                                   [ DONE ]
  - Checking deleted files in use                             [ DONE ]

[+] Insecure services
------------------------------------
  - Installed inetd package                                   [ NOT FOUND ]
  - Installed xinetd package                                  [ OK ]
    - xinetd status                                           [ NOT ACTIVE ]
  - Installed rsh client package                              [ OK ]
  - Installed rsh server package                              [ OK ]
  - Installed telnet client package                           [ OK ]
  - Installed telnet server package                           [ NOT FOUND ]
[+] Banners and identification
------------------------------------
  - /etc/issue                                                [ FOUND ]
    - /etc/issue contents                                     [ WEAK ]
  - /etc/issue.net                                            [ FOUND ]
    - /etc/issue.net contents                                 [ WEAK ]

[+] Scheduled tasks
------------------------------------
  - Checking crontab and cronjob files                        [ DONE ]
  - Checking atd status                                       [ RUNNING ]
    - Checking at users                                       [ DONE ]
    - Checking at jobs                                        [ NONE ]

[+] Accounting
------------------------------------
  - Checking accounting information                           [ NOT FOUND ]
  - Checking sysstat accounting data                          [ NOT FOUND ]
  - Checking auditd                                           [ NOT FOUND ]

[+] Time and Synchronization
------------------------------------

[+] Cryptography
------------------------------------
  - Checking for expired SSL certificates [0/3]               [ NONE ]

[+] Virtualization
------------------------------------

[+] Containers
------------------------------------

[+] Security frameworks
------------------------------------
  - Checking presence AppArmor                                [ FOUND ]
    - Checking AppArmor status                                [ UNKNOWN ]
  - Checking presence SELinux                                 [ NOT FOUND ]
  - Checking presence TOMOYO Linux                            [ NOT FOUND ]
  - Checking presence grsecurity                              [ NOT FOUND ]
  - Checking for implemented MAC framework                    [ NONE ]

[+] Software: file integrity
------------------------------------
  - Checking file integrity tools
  - Checking presence integrity tool                          [ NOT FOUND ]

[+] Software: System tooling
------------------------------------
  - Checking automation tooling
    - Ansible artifact                                        [ FOUND ]
  - Automation tooling                                        [ FOUND ]
  - Checking for IDS/IPS tooling                              [ NONE ]
[+] Software: Malware
------------------------------------

[+] File Permissions
------------------------------------
  - Starting file permissions check

[+] Home directories
------------------------------------
  - Checking shell history files                              [ OK ]

[+] Kernel Hardening
------------------------------------
  - Comparing sysctl key pairs with scan profile
    - fs.suid_dumpable (exp: 0)                               [ DIFFERENT ]
    - kernel.core_uses_pid (exp: 1)                           [ DIFFERENT ]
    - kernel.ctrl-alt-del (exp: 0)                            [ OK ]
    - kernel.dmesg_restrict (exp: 1)                          [ DIFFERENT ]
    - kernel.kptr_restrict (exp: 2)                           [ DIFFERENT ]
    - kernel.randomize_va_space (exp: 2)                      [ OK ]
    - kernel.sysrq (exp: 0)                                   [ DIFFERENT ]
    - kernel.yama.ptrace_scope (exp: 1 2 3)                   [ OK ]
    - net.ipv4.conf.all.accept_redirects (exp: 0)             [ DIFFERENT ]
    - net.ipv4.conf.all.accept_source_route (exp: 0)          [ OK ]
    - net.ipv4.conf.all.bootp_relay (exp: 0)                  [ OK ]
    - net.ipv4.conf.all.forwarding (exp: 0)                   [ OK ]
    - net.ipv4.conf.all.log_martians (exp: 1)                 [ DIFFERENT ]
    - net.ipv4.conf.all.mc_forwarding (exp: 0)                [ OK ]
    - net.ipv4.conf.all.proxy_arp (exp: 0)                    [ OK ]
    - net.ipv4.conf.all.rp_filter (exp: 1)                    [ DIFFERENT ]
    - net.ipv4.conf.all.send_redirects (exp: 0)               [ DIFFERENT ]
    - net.ipv4.conf.default.accept_redirects (exp: 0)         [ DIFFERENT ]
    - net.ipv4.conf.default.accept_source_route (exp: 0)      [ DIFFERENT ]
    - net.ipv4.conf.default.log_martians (exp: 1)             [ DIFFERENT ]
    - net.ipv4.icmp_echo_ignore_broadcasts (exp: 1)           [ OK ]
    - net.ipv4.icmp_ignore_bogus_error_responses (exp: 1)     [ OK ]
    - net.ipv4.tcp_syncookies (exp: 1)                        [ OK ]
    - net.ipv4.tcp_timestamps (exp: 0 1)                      [ OK ]
    - net.ipv6.conf.all.accept_redirects (exp: 0)             [ DIFFERENT ]
    - net.ipv6.conf.all.accept_source_route (exp: 0)          [ OK ]
    - net.ipv6.conf.default.accept_redirects (exp: 0)         [ DIFFERENT ]
    - net.ipv6.conf.default.accept_source_route (exp: 0)      [ OK ]

[+] Hardening
------------------------------------
 - Installed compiler(s)                                   [ FOUND ]
    - Installed malware scanner                               [ NOT FOUND ]

[+] Custom Tests
------------------------------------
  - Running custom tests...                                   [ NONE ]

[+] Plugins (phase 2)
------------------------------------

================================================================================

  -[ Lynis 2.7.5 Results ]-

  Warnings (2):
  ----------------------------
  ! Version of Lynis is very old and should be updated [LYNIS] 
      https://cisofy.com/lynis/controls/LYNIS/

  ! Reboot of system is most likely needed [KRNL-5830] 
    - Solution : reboot
      https://cisofy.com/lynis/controls/KRNL-5830/

  Suggestions (24):
  ----------------------------
  * Set a password on GRUB bootloader to prevent altering boot configuration (e.g. boot in single user mode without password) [BOOT-5122] 
      https://cisofy.com/lynis/controls/BOOT-5122/

  * Run pwck manually and correct any errors in the password file [AUTH-9228] 
      https://cisofy.com/lynis/controls/AUTH-9228/

  * Install a PAM module for password strength testing like pam_cracklib or pam_passwdqc [AUTH-9262] 
      https://cisofy.com/lynis/controls/AUTH-9262/

  * Configure minimum password age in /etc/login.defs [AUTH-9286] 
      https://cisofy.com/lynis/controls/AUTH-9286/

  * Configure maximum password age in /etc/login.defs [AUTH-9286] 
      https://cisofy.com/lynis/controls/AUTH-9286/

  * Default umask in /etc/login.defs could be more strict like 027 [AUTH-9328] 
      https://cisofy.com/lynis/controls/AUTH-9328/

  * To decrease the impact of a full /home file system, place /home on a separate partition [FILE-6310] 
      https://cisofy.com/lynis/controls/FILE-6310/

  * To decrease the impact of a full /tmp file system, place /tmp on a separate partition [FILE-6310] 
      https://cisofy.com/lynis/controls/FILE-6310/

  * To decrease the impact of a full /var file system, place /var on a separate partition [FILE-6310] 
https://cisofy.com/lynis/controls/FILE-6310/

* Disable drivers like USB storage when not used, to prevent unauthorized storage or data theft [STRG-1840] 
    https://cisofy.com/lynis/controls/STRG-1840/

* Install debsums utility for the verification of packages with known good database. [PKGS-7370] 
    https://cisofy.com/lynis/controls/PKGS-7370/

* Install package apt-show-versions for patch management purposes [PKGS-7394] 
    https://cisofy.com/lynis/controls/PKGS-7394/

* Install a package audit tool to determine vulnerable packages [PKGS-7398] 
    https://cisofy.com/lynis/controls/PKGS-7398/

* Consider running ARP monitoring software (arpwatch,arpon) [NETW-3032] 
    https://cisofy.com/lynis/controls/NETW-3032/

* Add a legal banner to /etc/issue, to warn unauthorized users [BANN-7126] 
    https://cisofy.com/lynis/controls/BANN-7126/

* Add legal banner to /etc/issue.net, to warn unauthorized users [BANN-7130] 
    https://cisofy.com/lynis/controls/BANN-7130/

* Enable process accounting [ACCT-9622] 
    https://cisofy.com/lynis/controls/ACCT-9622/

* Enable sysstat to collect accounting (no results) [ACCT-9626] 
    https://cisofy.com/lynis/controls/ACCT-9626/

* Enable auditd to collect audit information [ACCT-9628] 
    https://cisofy.com/lynis/controls/ACCT-9628/

* Check output of aa-status [MACF-6208] 
  - Details  : /sys/kernel/security/apparmor/profiles
  - Solution : Run aa-status
    https://cisofy.com/lynis/controls/MACF-6208/

* Install a file integrity tool to monitor changes to critical and sensitive files [FINT-4350] 
    https://cisofy.com/lynis/controls/FINT-4350/

* One or more sysctl values differ from the scan profile and could be tweaked [KRNL-6000] 
  - Solution : Change sysctl value or disable test (skip-test=KRNL-6000:<sysctl-key>)
    https://cisofy.com/lynis/controls/KRNL-6000/

* Harden compilers like restricting access to root user only [HRDN-7222] 
    https://cisofy.com/lynis/controls/HRDN-7222/

* Harden the system by installing at least one malware scanner, to perform periodic file system scans [HRDN-7230] 
  - Solution : Install a tool like rkhunter, chkrootkit, OSSEC
   https://cisofy.com/lynis/controls/HRDN-7230/

  Follow-up:
  ----------------------------
  - Show details of a test (lynis show details TEST-ID)
  - Check the logfile for all details (less /tmp/lynis.log)
  - Read security controls texts (https://cisofy.com)
  - Use --upload to upload data to central system (Lynis Enterprise users)

================================================================================

2.2 Puntuación

Después del escaneo del sistema nos da una puntuación del 62%, junto a la información de las pruebas realizadas.

Lynis security scan details:

  Hardening index : 62 [############        ]
  Tests performed : 205
  Plugins enabled : 0

  Components:
  - Firewall               [V]
  - Malware scanner        [X]

  Lynis modules:
  - Compliance status      [?]
  - Security audit         [V]
  - Vulnerability scan     [V]

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

================================================================================
  Notice: Lynis update available
  Current version : 275    Latest version : 308
================================================================================

3. Auditoría por grupos en Lynis 

Una de las características de Lynis es la capacidad de dividir los resultados de la auditoría en grupos para facilitar la revisión y el análisis. Estos grupos incluyen:

vagrant@master:~/lynis$ ./lynis show groups
accounting
authentication
banners
boot_services
containers
crypto
databases
dns
file_integrity
file_permissions
filesystems
firewalls
hardening
homedirs
insecure_services
kernel
kernel_hardening
ldap
logging
mac_frameworks
mail_messaging
malware
memory_processes
nameservices
networking
php
ports_packages
printers_spools
scheduling
shells
snmp
squid
ssh
storage
storage_nfs
system_integrity
time
tooling
usb
virtualization
webservers

La opción “–tests-from-group” en Lynis permite ejecutar solo las pruebas de auditoría específicas asignadas a un grupo determinado. Por ejemplo, si queremos ejecutar solo las pruebas de seguridad del kernel y de firewalls, podríamos utilizar el siguiente comando:

vagrant@master:~lynis$ ./lynis --tests-from-group "kernel firewallks"

[Lynis 2.7.5]

################################################################################
  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.

  2007-2019, CISOfy - https://cisofy.com/lynis/
  Enterprise support available (compliance, plugins, interface and tools)
################################################################################


[+] Initializing program
------------------------------------
  - Detecting OS...                                           [ DONE ]
  - Checking profiles...                                      [ DONE ]

  ---------------------------------------------------
  Program version:           2.7.5
  Operating system:          Linux
  Operating system name:     Ubuntu Linux
  Operating system version:  20.04
  Kernel version:            5.4.0
  Hardware platform:         x86_64
  Hostname:                  master
  ---------------------------------------------------
  Profiles:                  /home/vagrant/lynis/default.prf
  Log file:                  /tmp/lynis.log
  Report file:               /tmp/lynis-report.dat
  Report version:            1.0
  Plugin directory:          ./plugins
  ---------------------------------------------------
  Auditor:                   [Not Specified]
  Language:                  en
  Test category:             all
  Test group:                kernel firewalls
  ---------------------------------------------------
  - Program update status...                                  [ WARNING ]

      ===============================================================================
        Lynis update available
      ===============================================================================

        Current version is more than 4 months old

        Current version : 275   Latest version : 308

        Please update to the latest version.
        New releases include additional features, bug fixes, tests, and baselines.

        Download the latest version:
Packages (DEB/RPM) -  https://packages.cisofy.com
        Website (TAR)      -  https://cisofy.com/downloads/
        GitHub (source)    -  https://github.com/CISOfy/lynis

      ===============================================================================


[+] System Tools
------------------------------------
  - Scanning available tools...
  - Checking system binaries...

[+] Plugins (phase 1)
------------------------------------
 Note: plugins have more extensive tests and may take several minutes to complete
  
  - Plugins enabled                                           [ NONE ]

[+] Kernel
------------------------------------
  - Checking default run level                                [ RUNLEVEL 5 ]
  - Checking CPU support (NX/PAE)
    CPU support: PAE and/or NoeXecute supported               [ FOUND ]
  - Checking kernel version and release                       [ DONE ]
  - Checking kernel type                                      [ DONE ]
  - Checking loaded kernel modules                            [ DONE ]
      Found 57 active modules
  - Checking Linux kernel configuration file                  [ FOUND ]
  - Checking default I/O kernel scheduler                     [ NOT FOUND ]
  - Checking for available kernel update                      [ OK ]
  - Checking core dumps configuration                         [ DISABLED ]
    - Checking setuid core dumps configuration                [ PROTECTED ]
  - Check if reboot is needed                                 [ YES ]

[+] Software: firewalls
------------------------------------
  - Checking iptables kernel module                           [ FOUND ]
  - Checking host based firewall                              [ ACTIVE ]

[+] Custom Tests
------------------------------------
  - Running custom tests...                                   [ NONE ]

[+] Plugins (phase 2)
------------------------------------

================================================================================

  -[ Lynis 2.7.5 Results ]-

  Warnings (2):
  ----------------------------
 ! Version of Lynis is very old and should be updated [LYNIS] 
      https://cisofy.com/lynis/controls/LYNIS/

  ! Reboot of system is most likely needed [KRNL-5830] 
    - Solution : reboot
      https://cisofy.com/lynis/controls/KRNL-5830/

  No suggestions

  Follow-up:
  ----------------------------
  - Show details of a test (lynis show details TEST-ID)
  - Check the logfile for all details (less /tmp/lynis.log)
  - Read security controls texts (https://cisofy.com)
  - Use --upload to upload data to central system (Lynis Enterprise users)

================================================================================

  Lynis security scan details:

  Hardening index : 64 [############        ]
  Tests performed : 15
  Plugins enabled : 0

  Components:
  - Firewall               [V]
  - Malware scanner        [X]

  Lynis modules:
  - Compliance status      [?]
  - Security audit         [V]
  - Vulnerability scan     [V]

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

================================================================================
  Notice: Lynis update available
  Current version : 275    Latest version : 308
================================================================================

  Skipped tests due to non-privileged mode
    FIRE-4508 - Check used policies of iptables chains
    FIRE-4512 - Check iptables for empty ruleset
    FIRE-4513 - Check iptables for unused rules
    FIRE-4586 - Check firewall logging

================================================================================

  Lynis 2.7.5

  Auditing, system hardening, and compliance for UNIX-based systems
  (Linux, macOS, BSD, and others)

 2007-2019, CISOfy - https://cisofy.com/lynis/
  Enterprise support available (compliance, plugins, interface and tools)

================================================================================

  [TIP]: Enhance Lynis audits by adding your settings to custom.prf (see /home/vagrant/lynis/default.prf for all settings)

Cómo mejorar la puntuación de Lynis tras la auditoría 

Al finalizar el escaneo, el propio software de Lynis genera un informe con sugerencias específicas (suggestions) para corregir los puntos débiles. Aunque aplicar cada cambio dependerá de las necesidades operativas de tu entorno, seguir estas recomendaciones generales de hardening aumentará significativamente la seguridad de tu sistema y tu puntuación final:

Autenticación y Control de Acceso:

  • Cambiar el puerto SSH: Modificar el puerto 22 predeterminado es un paso sencillo que mitiga en gran medida los ataques automatizados de fuerza bruta.
  • Fortalecer las credenciales: Utiliza contraseñas seguras, largas y únicas para cada cuenta de usuario y servicio.
  • Restringir el uso de root: Evita usar la cuenta de administrador global. Emplea cuentas con privilegios estándar y utiliza sudo solo cuando sea estrictamente necesario.
  • Habilitar Autenticación de Dos Factores (2FA): Añade una capa extra de protección indispensable para salvaguardar las cuentas críticas.

Red, Servicios y Sistema:

  • Configurar un Firewall estricto: Define reglas claras para limitar el tráfico y bloquear accesos no autorizados a tu infraestructura.
  • Reducir la superficie de ataque: Desactiva los servicios, demonios y módulos innecesarios. Si no lo usas, no debe estar en ejecución.
  • Ocultar información del sistema: Edita los banners y cabeceras por defecto (como las de SSH o servidores web) para no revelar las versiones del software a posibles atacantes.

Monitoreo Continuo:

  • Implementar herramientas de monitorización: Configura sistemas que vigilen la integridad del sistema y generen alertas inmediatas ante cualquier actividad sospechosa.

⚠️ Nota de seguridad: Estas directrices son una base de referencia. La configuración óptima dependerá siempre de tu arquitectura de red. Te recomendamos priorizar el reporte de salida de Lynis y, para entornos de producción críticos, considerar el apoyo de profesionales en ciberseguridad.

Siguiente paso: Una vez que hayas aplicado estos ajustes, vuelve a ejecutar el análisis de Lynis. Esto te permitirá validar que las vulnerabilidades se han cerrado y visualizar la mejora en tu índice de endurecimiento (Hardening Index).

4. Cómo automatizar las auditorías de Lynis utilizando Ansible

En Chakray, gestionamos este procedimiento de manera totalmente automatizada y adaptada a cada entorno. Cuando se administra una gran infraestructura con múltiples servidores o máquinas virtuales, ejecutar evaluaciones manuales resulta ineficiente. El uso de Ansible nos permite escalar este proceso, ejecutando auditorías de forma simultánea, cómoda y ultrarrápida en toda la red.

¿Qué herramientas necesitamos para automatizar Lynis y generar informes?

Para configurar este flujo de trabajo automatizado, requerimos los siguientes componentes base:

    • Ansible: Es la herramienta de automatización principal. Permite a los administradores de sistemas eliminar tareas repetitivas, orquestar la infraestructura y configurar sistemas de manera ágil y segura.
  • Archivo de inventario (hosts): Es el archivo de configuración donde definiremos y agruparemos todos y cada uno de los servidores (nodos) sobre los cuales queremos lanzar la auditoría de seguridad remota.
  • Python 3: Es un requisito indispensable para la etapa final del proceso. Se encargará de procesar los datos resultantes de la auditoría para generar informes HTML personalizados, facilitando la visualización e interpretación de las métricas.

Para utilizar Ansible para generar informes con Lynis, primero deberás tenerlo instalado y configurado en tu equipo. Luego, necesitarás crear un archivo de playbook de Ansible que contenga las instrucciones para ejecutar Lynis y generar el informe.

vagrant@master:~/ansible-playbooks/chakray-lynis$ ls
ansible.sh  hosts  playbook.yml  reports

Para ejecutar el playbook, simplemente ejecuta el comando Ansible-playbook seguido del nombre del archivo del playbook:

vagrant@master:~/ansible-playbooks/chakray-lynis$ sudo ansible-playbook -uroot --become-user=root playbook.yml

Esto ejecutará Lynis en el servidor y generará un informe en el archivo especificado. Si necesitamos agregar más de un servidor lo primero que tendremos que hacer es agregar un grupo en el archivo hosts y éste nos generará una auditoría para cada una de ellas.

Una vez terminado el proceso, vemos que nos ha generado una carpeta con los archivos logs para el nodo.

vagrant@master:~/ansible-playbooks/chakray-lynis/reports/localhost/var/log$ ls
lynis-report.dat  lynis.log

El archivo de registro de Lynis se encuentra en el directorio “/var/log/lynis.log” y contiene información detallada sobre el proceso de escaneo y los resultados del mismo. Este archivo de registro es útil para revisar los resultados del escaneo y realizar seguimiento de las mejoras realizadas en la configuración de seguridad del sistema. También puede ser útil para diagnósticos y solución de problemas relacionados con la seguridad del sistema.

vagrant@master:~/ansible-playbooks/chakray-lynis/reports/localhost/var/lo
g$ cat lynis.log 
2023-02-11 13:22:06 Starting Lynis 3.0.8 with PID 64012, build date 2022-05-17
2023-02-11 13:22:06 ====
2023-02-11 13:22:06 ### 2007-2021, CISOfy - https://cisofy.com/lynis/ ###
2023-02-11 13:22:06 Checking permissions of /home/vagrant/ansible-playbooks/chakray-lynis/lynis/include/profiles
2023-02-11 13:22:06 File permissions are OK
2023-02-11 13:22:06 Reading profile/configuration /home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf
2023-02-11 13:22:06 Action: created temporary file /tmp/lynis.Mt4I3rhuK9
2023-02-11 13:22:06 Language set via profile to ''
2023-02-11 13:22:06 Plugin 'authentication' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'compliance' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'configuration' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'control-panels' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'crypto' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'dns' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'docker' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'file-integrity' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'file-systems' enabled according profile 
(https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'firewalls' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'forensics' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'hardware' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'intrusion-detection' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'intrusion-prevention' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'kernel' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'malware' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'memory' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'nginx' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'pam' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'processes' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'security-modules' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'software' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'system-integrity' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'systemd' enabled according profile 
(https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:06 Plugin 'users' enabled according profile (https://cdn.chakray.com/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf)
2023-02-11 13:22:07 Set option to default value: NTPD_ROLE --> client
2023-02-11 13:22:07 ====
2023-02-11 13:22:07 EOL check: 0
2023-02-11 13:22:07 Program version:           3.0.8
2023-02-11 13:22:07 Operating system:          Linux
2023-02-11 13:22:07 Operating system name:     Ubuntu
2023-02-11 13:22:07 Operating system version:  20.04
2023-02-11 13:22:07 Kernel version:            5.4.0
2023-02-11 13:22:07 Kernel version (full):     5.4.0-62-generic
2023-02-11 13:22:07 Hardware platform:         x86_64
2023-02-11 13:22:07 -----------------------------------------------------
2023-02-11 13:22:07 Hostname:                  master
2023-02-11 13:22:07 Auditor:                   [Not Specified]
2023-02-11 13:22:07 Profiles:                  /home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf
2023-02-11 13:22:07 Work directory:            /home/vagrant/ansible-playbooks/chakray-lynis/lynis
2023-02-11 13:22:07 Include directory:         /home/vagrant/ansible-playbooks/chakray-lynis/lynis/include
2023-02-11 13:22:07 Plugin directory:          ./plugins
2023-02-11 13:22:07 -----------------------------------------------------
2023-02-11 13:22:07 Log file:                  /var/log/lynis.log
2023-02-11 13:22:07 Report file:               /var/log/lynis-report.dat
2023-02-11 13:22:07 Report version:            1.0
2023-02-11 13:22:07 -----------------------------------------------------
2023-02-11 13:22:07 Test category:             all
2023-02-11 13:22:07 Test group:                all
2023-02-11 13:22:07 BusyBox used:              0
2023-02-11 13:22:07 ====
2023-02-11 13:22:07 Test: Checking for program update...
2023-02-11 13:22:07 Current installed version  : 308
2023-02-11 13:22:07 Latest stable version      : 308
2023-02-11 13:22:07 No Lynis update available.
2023-02-11 13:22:07 Suggestion: This release is more than 4 months old. Check the website or GitHub to see if there is an update available. [test:LYNIS] [details:-] [solution:-]
2023-02-11 13:22:07 ====
2023-02-11 13:22:07 Checking permissions of /home/vagrant/ansible-playbooks/chakray-lynis/lynis/include/binaries
2023-02-11 13:22:07 File permissions are OK
2023-02-11 13:22:07 ====
2023-02-11 13:22:07 Action: Performing tests from category: System tools
2023-02-11 13:22:07 Start scanning for available audit binaries and tools...
2023-02-11 13:22:07 ====

...
2023-02-11 13:22:50 ====
2023-02-11 13:22:50 Action: Performing tests from category: Custom tests
2023-02-11 13:22:50 Test: Checking for tests_custom file
2023-02-11 13:22:50 ====
2023-02-11 13:22:50 Action: Performing plugin tests
2023-02-11 13:22:50 Result: Found 2 plugins of which 2 are enabled
2023-02-11 13:22:50 Result: Plugins phase 2 finished
2023-02-11 13:22:50 Checking permissions of /home/vagrant/ansible-playbooks/chakray-lynis/lynis/include/report
2023-02-11 13:22:50 File permissions are OK
2023-02-11 13:22:50 Hardening index : [60] [############        ]
2023-02-11 13:22:50 Hardening strength: System has been hardened, but could use additional hardening
2023-02-11 13:22:50 ====
2023-02-11 13:22:51 Checking permissions of /home/vagrant/ansible-playbooks/chakray-lynis/lynis/include/tool_tips
2023-02-11 13:22:51 File permissions are OK
2023-02-11 13:22:51 Tool tips: enabled
2023-02-11 13:22:51 ================================================================================
2023-02-11 13:22:51 Tests performed:     263
2023-02-11 13:22:51 Total tests:         463
2023-02-11 13:22:51 Active plugins:      2
2023-02-11 13:22:51 Total plugins:       2
2023-02-11 13:22:51 ================================================================================
2023-02-11 13:22:51 Lynis 3.0.8
2023-02-11 13:22:51 2007-2021, CISOfy - https://cisofy.com/lynis/
2023-02-11 13:22:51 Enterprise support available (compliance, plugins, interface and tools)
2023-02-11 13:22:51 Program ended successfully
2023-02-11 13:22:51 ================================================================================
2023-02-11 13:22:51 PID file removed (https://cdn.chakray.com/var/run/lynis.pid)
2023-02-11 13:22:51 Temporary files:  /tmp/lynis.Mt4I3rhuK9 /tmp/lynis.QH6PlRW8MR /tmp/lynis.2PJaxXJl4f /tmp/lynis.Kk63v57XeV
2023-02-11 13:22:51 Action: removing temporary file /tmp/lynis.Mt4I3rhuK9
2023-02-11 13:22:51 Info: temporary file /tmp/lynis.QH6PlRW8MR was already removed
2023-02-11 13:22:51 Info: temporary file /tmp/lynis.2PJaxXJl4f was already removed
2023-02-11 13:22:51 Action: removing temporary file /tmp/lynis.Kk63v57XeV
2023-02-11 13:22:51 Lynis ended successfully.

Podemos destacar todos los cambios, aplicaciones, paquetes… que tenemos en nuestro servidor, información sobre el kernel y los cambios que tenemos que hacer para mejorar la seguridad.

Por último, también podemos ver que el software nos ofrece una puntuación sobre nuestra seguridad del sistema. En este caso es una máquina de ejemplo totalmente vacía y la puntuación que nos ofrece es de 60.

2023-02-11 13:22:50 Hardening index : [60] [############        ]

Todo este archivo es difícil de observar en este formato, desde Chakray realizamos un informe totalmente personalizado para cada una de los servidores mediante un script en python.

vagrant@master:~/ansible-playbooks/chakray-lynis/reports$ python3 prepare_data.py 
Reportes generados, ver index.html

Este también genera automáticamente un informe, en este caso con formato html.

Informe de Auditoría de Chakray

Figura 1. Informe de Auditoría de Chakray

Una vez creados, los informes HTML se pueden visualizar en un navegador web. Los informes HTML son útiles porque permiten presentar información de manera clara y atractiva, y también son fácilmente accesibles y pueden ser compartidos a través de Internet de forma versátil. De esta manera podemos ver todas las sugerencias que nos proporciona para mejorar la seguridad y así mejorar la puntuación que nos ofrece el informe.

5. ¿Cómo podemos mejorar la seguridad de los informes Lynis?

Para elevar la puntuación de hardening de Lynis y obtener informes más limpios, es necesario encontrar un equilibrio entre usabilidad (comodidad) y seguridad. No todas las sugerencias del informe serán aplicables en todos los entornos; por ejemplo, en un servidor de desarrollo se podrá tolerar cierto nivel de riesgo que no sería aceptable en producción.

El informe de Lynis suele proponer mejoras como:

  • Cambiar el puerto por defecto de servicios como SSH (del 22 a uno no estándar).

  • Modificar cabeceras HTTP de servidores web (NginxApache) para no revelar versiones.

  • Deshabilitar protocolos obsoletos o inseguros (por ejemplo, TLS 1.0SSLv3SMBv1).

Proceso de bastionado (hardening) del sistema

A este conjunto de acciones se le denomina bastionado (o hardening en inglés). Consiste en fortalecer la seguridad del sistema eliminando o desactivando cualquier componente, servicio o puerto no esencial, y aplicando configuraciones adicionales de defensa en profundidad. El objetivo es minimizar la superficie de ataque y reducir el riesgo de que un atacante comprometa el servidor.

El bastionado se puede automatizar mediante un script de bastionado: un conjunto de instrucciones (por ejemplo, en BashPython o mediante un playbook de Ansible) que ejecutan de forma automática medidas como cerrar puertos innecesarios, aplicar parches de seguridad, configurar fail2ban, reforzar políticas de contraseñas o activar auditorías con auditd.

Verificación de resultados tras el bastionado

Una vez ejecutado el script de bastionado, vuelves a generar los informes de Lynis para verificar de nuevo el estado de seguridad. En esta segunda ejecución, podrás comprobar que muchas de las advertencias anteriores han desaparecido y que la puntuación de hardening (hardening index) ha mejorado notablemente. Este ciclo de auditar → bastionar → re-auditar es la base de una mejora continua de la seguridad en entornos Linux y Unix.

Host findings

Figura 2. Host findings

Hemos mejorado la seguridad al 79%, este nos volverá a ofrecer una lista de las sugerencias y podemos valorar si son necesarias. Estos cambios se podrían realizar de manera manual.

FAQ sobre auditorías de seguridad con Lynis y Ansible

¿Lynis modifica la configuración de mi sistema?

No. Lynis es una herramienta de solo lectura, diseñada para auditar el sistema sin realizar ningún cambio en él. Su función es analizar la configuración actual e informar sobre vulnerabilidades y configuraciones inseguras, pero nunca aplicará cambios o arreglos por sí misma. Eres tú, el administrador, quien debe implementar manualmente las mejoras sugeridas o a través de un playbook de Ansible para fortalecer el sistema de manera controlada.

¿Cómo puedo conservar los colores de la salida de Lynis al generar un informe?

Al exportar la salida de Lynis a un archivo de texto plano, los códigos de color se pierden y se convierten en caracteres extraños. Para conservar el formato con colores, una solución común es canalizar la salida de Lynis a la herramienta ansi2html. Por ejemplo, el comando ./lynis audit system | ansi2html > /var/log/{{ inventory_hostname }}-lynis.html genera un informe en HTML que conserva los colores originales (verde para los elementos [ DONE ], etc.), siendo mucho más legible.

¿Puedo ejecutar Lynis en sistemas Windows?

No directamente. Lynis está diseñado específicamente para sistemas basados en Unix, como LinuxmacOSBSD y Solaris. Aunque no existe una versión nativa para Windows, es posible auditar la seguridad de una máquina Windows desde un nodo de control Linux utilizando herramientas complementarias. Sin embargo, la propia herramienta no se ejecuta en el núcleo de Windows, ya que su arquitectura está orientada a entornos tipo UNIX.

¿Qué tipos de comprobaciones realiza Lynis en un sistema?

Lynis lleva a cabo más de 300 comprobaciones en diversas áreas críticas del sistema, entre las que se incluyen la autenticación de usuarios, los permisos del sistema de archivos, el endurecimiento del kernel, la configuración de servicios de red, la detección de vulnerabilidades en el software instalado y los controles de cumplimiento normativo. Adicionalmente, puede verificar la conformidad del sistema con estándares de seguridad como CIS BenchmarksISO 27001PCI DSS e HIPAA.

El valor de automatizar tu seguridad con Ansible y Lynis

En resumen, utilizar Ansible para orquestar la ejecución de Lynis representa una estrategia eficiente, escalable y sencilla para automatizar la auditoría y la evaluación continua de la seguridad en tu infraestructura IT.

Con una configuración mínima basada en un archivo inventory y un playbook  de Ansible bien estructurado, puedes ejecutar auditorías de forma simultánea sobre múltiples entornos (ya sean servidores físicos, máquinas virtuales o contenedores) y recopilar los resultados de manera centralizada y sin intervención manual.

Implementar esta integración te permitirá:

  • Ahorrar tiempo y recursos operativos al eliminar las tareas de auditoría repetitivas.
  • Tener una visión global y actualizada sobre la postura de seguridad de toda tu arquitectura técnica.
  • Detectar desviaciones de forma temprana y aplicar correcciones inmediatas aprovechando el mismo flujo de automatización.

¿Necesitas escalar la seguridad de tu infraestructura? De la mano de Chakray, podemos ayudarte a implementar este flujo de trabajo de manera 100% automatizada para grandes grupos de servidores, facilitando la toma de decisiones gracias a la generación de informes HTML personalizados. Si deseas optimizar tus auditorías o necesitas apoyo especializado, contacta con nosotros.