En este artículo, exploraremos cómo funciona Lynis y Ansible y cómo se puede utilizar para evaluar la seguridad de un sistema. También, proporcionaremos algunos consejos para aumentar la seguridad. Además, veremos como se puede automatizar la ejecución utilizando Ansible.
Finalmente, veremos cómo se pueden generar informes HTML más estéticos para presentar los resultados de las auditorías de Lynis de una manera más clara y fácil de entender.
Seguiremos el siguiente índice:
|
1. Instalación de Lynis
Lynis es una herramienta de código abierto utilizada para realizar auditorías de seguridad en sistemas operativos basados en Unix, como Linux y macOS. Lynis se ejecuta en el sistema objetivo y escanea el sistema en busca de vulnerabilidades y configuraciones inseguras. Al final del escaneo, Lynis proporciona un informe detallado con recomendaciones para mejorar la seguridad del sistema.
Para utilizar Lynis, primero debes descargarlo y descomprimirlo en tu sistema. Luego, puedes ejecutarlo utilizando el comando “lynis” seguido de cualquier opción de parámetro que desees utilizar. Por ejemplo, para escanear el sistema completo y generar un informe, puedes usar el comando “lynis audit system”. Lynis también tiene muchas otras opciones de parámetros que puedes utilizar para realizar escaneos más específicos o para personalizar el proceso de auditoría.
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
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 ===============================================================================
2.1 Análisis del sistema, plugins, kernel, servicios…
Algunas de las comprobaciones que realiza Lynis incluyen:
- Revisión de la configuración del sistema: Lynis revisa la configuración del sistema y de los servicios para asegurarse de que estén configurados de manera segura y optimizada.
- Revisión de la configuración del firewall: Lynis revisa la configuración del firewall para asegurarse de que esté configurado de manera adecuada y que esté protegiendo el sistema.
- Revisión de la configuración de contraseñas: Lynis revisa la configuración de contraseñas para asegurarse de que estén configuradas de manera segura y que no se estén utilizando contraseñas débiles.
- Revisión de la configuración de cuentas: Lynis revisa la configuración de cuentas para asegurarse de que estén configuradas de manera segura y que no se estén utilizando cuentas con permisos de administrador innecesarios.
- Revisión de la configuración de archivos: Lynis revisa la configuración de archivos para asegurarse de que estén configurados de manera segura y que no se estén utilizando permisos de archivo innecesarios.
- Revisión de la configuración de paquetes: Lynis revisa la configuración de paquetes para asegurarse de que estén configurados de manera segura y que no se estén utilizando paquetes innecesarios o vulnerables.
- Revisión de la configuración de la red: Lynis revisa la configuración de la red para asegurarse de que esté configurada de manera segura y que no se esté exponiendo información sensible a través de la red.
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 (/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)
3.1 Recomendaciones para mejorar la puntuación de Lynis
El propio software de Lynis nos proporciona un listado con los puntos a cubrir para mejorarlo, muchas de ellas son fáciles de solucionar, otras dependen de si necesitas el cambio o no. Aquí hay algunas recomendaciones generales para mejorar la puntuación de Lynis y aumentar la seguridad del sistema:
- Cambiar puerto ssh. Un sencillo paso que protege un poco nuestro sistema.
- Configura y utiliza un firewall para limitar el acceso no autorizado a tu sistema.
- Editar cabeceras por defecto.
- Utiliza contraseñas seguras y únicas para cada cuenta de usuario y servicio.
- Configura la autenticación de dos factores para proteger tus cuentas de usuario y servicio.
- Desactiva los servicios y demonios innecesarios para minimizar los puntos de ataque.
- Configura y utiliza herramientas de monitoreo de seguridad para vigilar el sistema y recibir alertas en caso de actividad sospechosa.
- Utiliza contraseñas de administrador o root fuertes y evita utilizar estos usuarios a menos que sea absolutamente necesario.
Es importante tener en cuenta que estas recomendaciones son solo una guía general y que la configuración de seguridad de tu sistema dependerá de tus requisitos específicos y de tu entorno de red. Se recomienda encarecidamente seguir las recomendaciones específicas que proporcione Lynis en su informe de salida y considerar la contratación de un profesional de seguridad informática para ayudar a implementar medidas adicionales de seguridad en tu sistema.
Una vez realizado los cambios, volver a realizar el análisis para ver la mejora de puntuación.
4. Cómo utilizar Ansible para ejecutar Lynis y automatizar el proceso
Desde Chakray hacemos este proceso de una manera automática y totalmente personalizada, en caso de tener una gran cantidad de máquinas o servidores se hace todo este proceso de una forma más cómoda y rápida mediante Ansible.
4.1 ¿Qué herramientas necesitamos para automatizar la tarea y generar informes en Lynis?
La principal herramienta que necesitamos es Ansible.
Ansible es una una herramienta de automatización que permite a los administradores de sistemas automatizar tareas repetitivas y configurar sistemas de forma segura y rápida. Mediante el archivo hosts podremos definir todos y cada uno de los servidores donde queremos lanzar la auditoría. Para la generación de informes personalizados, en este caso html, será necesario tener python3 para poder generarlos.
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 (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'compliance' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'configuration' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'control-panels' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'crypto' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'dns' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'docker' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'file-integrity' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'file-systems' enabled according profile
(/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'firewalls' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'forensics' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'hardware' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'intrusion-detection' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'intrusion-prevention' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'kernel' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'malware' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'memory' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'nginx' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'pam' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'processes' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'security-modules' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'software' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'system-integrity' enabled according profile (/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'systemd' enabled according profile
(/home/vagrant/ansible-playbooks/chakray-lynis/lynis/default.prf) 2023-02-11 13:22:06 Plugin 'users' enabled according profile (/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 (/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.
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 mejorar la seguridad, tenemos que encontrar un equilibrio entre comodidad y seguridad. El informe nos ofrece una gran cantidad de sugerencias para mejorar, entre ellas, cambiar puerto de acceso al sistema, cambiar cabeceras, protocolos…
Este proceso se le llama bastionado, es el proceso de fortalecer la seguridad del sistema eliminando o desactivando cualquier componente o servicio no esencial y configurando medidas de seguridad adicionales. Esto se hace para minimizar el riesgo de que el sistema sea atacado o comprometido por un atacante. Este proceso se puede hacer mediante un script de bastionado del sistema, este es un conjunto de instrucciones que se ejecutan automáticamente para implementar medidas de seguridad en un sistema Linux.
Una vez ejecutado el script de bastionado volvemos a generar los informes para verificar de nuevo la seguridad y podemos ver que la puntuación ha mejorado.
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.
6. Conclusión
En resumen, utilizar Ansible para generar informes con Lynis es una forma eficiente y sencilla de automatizar la auditoría y la evaluación de la seguridad de los sistemas. Con una simple configuración puedes utilizar Ansible para ejecutar Lynis de forma automática en varios servidores y recopilar informes de forma centralizada y sin esfuerzo. Esto te permite ahorrar tiempo y esfuerzo al evaluar la seguridad de tus sistemas, y te ayuda a mantener una visión clara y actualizada de su estado de seguridad.
De la mano de Chakray se puede realizar de una manera automatizada en caso de tener un grupo de servidores y cómoda gracias a los informes personalizados, si quieres más información puede contactar con nosotros.