Las distribuciones GNU/Linux son ampliamente por su seguridad. Pero, ¿alguna vez te has puesto a pensar en como comprobar si tu sistema esta realmente protegido?.
Existen numerosas distribuciones basadas en el núcleo Linux, a día de hoy se cuentan más de 600. Cada una de ellas con su propia configuración, paquetes y servicios ejecutandose en segundo plano, sin olvidar las diferentes versiones de cada uno. Todo esto hace que la seguridad no dependa solo del propio kernel Linux y su arquitectura, sino que puede abrir muchas brechas de seguridad en nuestros sistemas.
Es por esto que debemos apoyarnos en herramientas que nos ayuden en la tarea de auditar nuestros sistemas, para así encontrar nuestras posibles vulnerabilidades y hacer algo al respecto.
¿Que es Lynis?
Lynis es una herramienta opensource de seguridad ampliamente conocida y utilizada en el mundo GNU/Linux. Esta herramienta nos ayuda a realizar un exhaustivo análisis/auditoria de seguridad en profundidad en nuestro sistema. Al final nos entrega un informe bastante completo sobre el estado de cada fragmento.
Lynis es comúnmente utilizado por administradores de sistemas, auditores y desarrolladores para evaluar la seguridad de sus sistemas.
Instalar Lynis
Aunque es posible y fácil, no es necesario instalar Lynis para utilizarlo, es posible simplemente descargarlo y utilizarlo para que pueda mantener sus sistemas limpios. De cualquier forma, aquí te dejamos las opciones disponibles:
Clonarlo desde GitHub
$ git clone https://github.com/CISOfy/lynis Cloning into 'lynis'... remote: Counting objects: 1733, done. remote: Compressing objects: 100% (8/8), done. remote: Total 1733 (delta 3), reused 0 (delta 0), pack-reused 1725 Receiving objects: 100% (1733/1733), 886.18 KiB | 378.00 KiB/s, done. Resolving deltas: 100% (1204/1204), done. Checking connectivity... done.
$ cd lynis
Instalación via administrador de paquetes:
La instalación via package manager es otra opción para usar Lynis, solo hay que añadir el repositorio adecuado e instalar:
Red Hat y CentOS
$ sudo vi /etc/yum.repos.d/cisofy-lynis.repo [lynis] name=CISOfy Software - Lynis package baseurl=https://packages.cisofy.com/community/lynis/rpm/ enabled=1 gpgkey=https://packages.cisofy.com/keys/cisofy-software-rpms-public.key gpgcheck=1 priority=2
$ yum install lynis
Debian y Ubuntu
$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C80E383C3DE9F082E01391A0366C67DE91CA5D5F
$ sudo apt install apt-transport-https
$ echo "deb https://packages.cisofy.com/community/lynis/deb/ stable main" | sudo tee /etc/apt/sources.list.d/cisofy-lynis.list
$ sudo apt update
$ sudo apt-get install lynis
openSUSE
$ sudo rpm --import https://packages.cisofy.com/keys/cisofy-software-rpms-public.key
$ sudo zypper addrepo --gpgcheck --name "CISOfy Lynis repository" --priority 1 --refresh --type rpm-md https://packages.cisofy.com/community/lynis/rpm/ lynis
$ sudo zypper refresh
$ sudo zypper install lynis
Fedora
Crear archivo de repositorio:
$ sudo vi /etc/yum.repos.d/cisofy-lynis.repo
Agrega el siguiente contenido al archivo y guarda:
[lynis] name=CISOfy Software - Lynis package baseurl=https://packages.cisofy.com/community/lynis/rpm/ enabled=1 gpgkey=https://packages.cisofy.com/keys/cisofy-software-rpms-public.key gpgcheck=1 priority=2
Actualiza el repositorio e instala:
$ sudo dnf update lynis
$ sudo dnf install lynis
Instalación via Homebrew
Para usuarios de macOS, Homebrew puede ser usado para instalar lynis
$ brew install lynis
Ejecutar Lynis
Lynis no necesita una configuración previa para ser ejecutado, es posible hacerlo pero no es necesario.
Si Lynis fue instalado via Homebrew o administrador de paquetes, entonces puedes ejecutarlo desde cualquier directorio:
$ lynis audit system
pero en los casos de descarga directa o por medio de GitHub, primero hay que entrar al directorio y despues ejecutarlo de esta manera:
$ ./lynis audit system --quick
Reporte
El comando anterior devolverá un informe detallado, dependiendo de los servicios que tengas instalados puede durar un poco más. Al principio puede parecer algo engorroso en intimidante, pero no es nada fuera de este mundo.
Cabe aclarar primero, que veremos avisos y sugerencias, las cuales vendrán explicadas en la parte final del reporte.
Veamos un ejemplo:
Inicializando
Lo primero que hace Lynis como parte de la inicialización es encontrar información completa sobre el sistema operativo que se ejecuta en la máquina:
[ Lynis 3.0.0 ] ################################################################################ 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-2020, CISOfy - https://cisofy.com/lynis/ Enterprise support available (compliance, plugins, interface and tools) ################################################################################ [+] Initializing program ------------------------------------ - Detecting OS... [ DONE ] - Checking profiles... [ DONE ] --------------------------------------------------- Program version: 3.0.0 Operating system: Linux Operating system name: Ubuntu Operating system version: 18.04 Kernel version: 5.3.0 Hardware platform: x86_64 Hostname: ip-11-0-0-70 --------------------------------------------------- Profiles: /etc/lynis/default.prf Log file: /var/log/lynis.log Report file: /var/log/lynis-report.dat Report version: 1.0 Plugin directory: /usr/share/lynis/plugins --------------------------------------------------- Auditor: [Not Specified] Language: en Test category: all Test group: all --------------------------------------------------- - Program update status... [ NO UPDATE ]
Herramientas y Complementos
Enseguida vienen verificaciones para ver qué herramientas y complementos del sistema están instalados:
[+] 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 ]
Arranque y Servicios
Ahora vemos las opciones de arranque y servicios donde vemos que nos advierte sobre la protección de contraseña.
[+] Boot and services ------------------------------------ - Service Manager [ systemd ] - Checking UEFI boot [ DISABLED ] - Checking presence GRUB [ OK ] - Checking presence GRUB2 [ FOUND ] - Checking for password protection [ NONE ] - Check running services (systemctl) [ DONE ] Result: found 25 running services - Check enabled services at boot (systemctl) [ DONE ] Result: found 51 enabled services - Check startup files (permissions) [ OK ]
Kernel y Memoria
Aquí podemos notar que hay un reinicio necesario:
[+] 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 68 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 - configuration in systemd conf files [ DEFAULT ] - configuration in etc/profile [ DEFAULT ] - 'hard' configuration in security/limits.conf [ DEFAULT ] - 'soft' configuration in security/limits.conf [ DEFAULT ] - Checking setuid core dumps configuration [ PROTECTED ] - Check if reboot is needed [ YES ] [+] Memory and Processes ------------------------------------ - Checking /proc/meminfo [ FOUND ] - Searching for dead/zombie processes [ NOT FOUND ] - Searching for IO waiting processes [ NOT FOUND ] - Search prelink tooling [ NOT FOUND ]
Usuarios, Grupos y Autenticación
En esta sección vemos que nos dice que hay algunas sugerencias:
[+] Users, Groups and Authentication ------------------------------------ - Administrator accounts [ OK ] - Unique UIDs [ OK ] - Consistency of group files (grpck) [ OK ] - Unique group IDs [ OK ] - Unique group names [ OK ] - Password file consistency [ OK ] - Password hashing methods [ OK ] - Checking minimum group password hashing rounds [ DISABLED ] - Checking maximum group password hashing rounds [ DISABLED ] - Query system users (non daemons) [ DONE ] - NIS+ authentication support [ NOT ENABLED ] - NIS authentication support [ NOT ENABLED ] - Sudoers file(s) [ FOUND ] - Permissions for directory: /etc/sudoers.d [ OK ] - Permissions for: /etc/sudoers [ OK ] - Permissions for: /etc/sudoers.d/99-snapd.conf [ OK ] - Permissions for: /etc/sudoers.d/README [ OK ] - Permissions for: /etc/sudoers.d/90-cloud-init-users [ OK ] - 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 expired passwords [ OK ] - 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 ]
Sistema de archivos
Tenemos algunas sugerencias más para nuestro sistema de archivos:
[+] 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 ] - ACL support root file system [ ENABLED ] - Mount options of / [ NON DEFAULT ] - Mount options of /dev [ PARTIALLY HARDENED ] - Mount options of /dev/shm [ PARTIALLY HARDENED ] - Mount options of /run [ PARTIALLY HARDENED ] - Total without nodev:27 noexec:33 nosuid:29 ro or noexec (W^X): 28 of total 62 - Checking Locate database [ FOUND ] - Disable kernel support of some filesystems - Discovered kernel modules: udf
DNS
Vemos que no tenemos un nombre de dominio y un archivo hosts configurado:
[+] Name services ------------------------------------ - Checking search domains [ FOUND ] - Checking /etc/resolv.conf options [ FOUND ] - Searching DNS domain name [ UNKNOWN ] - Checking /etc/hosts - Duplicate entries in hosts file [ NONE ] - Presence of configured hostname in /etc/hosts [ NOT FOUND ] - Hostname mapped to localhost [ NOT FOUND ] - Localhost mapping to IP address [ OK ]
Puertos y Paquetes
Encontramos el primer problema mayor, al notificarnos que tenemos paquetes vulnerables:
[+] Ports and packages ------------------------------------ - Searching package managers - Searching dpkg package manager [ FOUND ] - Querying package manager - Query unpurged packages [ FOUND ] - Checking security repository in sources.list file [ OK ] - Checking APT package database [ OK ] - Checking vulnerable packages [ WARNING ] - Checking upgradeable packages [ SKIPPED ] - Checking package audit tool [ INSTALLED ] Found: apt-get - Toolkit for automatic upgrades (unattended-upgrade) [ FOUND ]
Redes
Tenemos una advertencia al no contar con un monitor ARP:
[+] Networking ------------------------------------ - Checking IPv6 configuration [ ENABLED ] Configuration method [ AUTO ] IPv6 only [ NO ] - Checking configured nameservers - Testing nameservers Nameserver: 127.0.0.53 [ OK ] - DNSSEC supported (systemd-resolved) [ NO ] - Checking default gateway [ DONE ] - Getting listening ports (TCP/UDP) [ DONE ] - Checking promiscuous interfaces [ OK ] - Checking waiting connections [ OK ] - Checking status DHCP client [ NOT ACTIVE ] - Checking for ARP monitoring software [ NOT FOUND ] - Uncommon network protocols [ 0 ]
Impresoras y correo
No tenemos impresoras conectadas ni servicios de correo:
[+] Printers and Spools ------------------------------------ - Checking cups daemon [ NOT FOUND ] - Checking lp daemon [ NOT RUNNING ] [+] Software: e-mail and messaging ------------------------------------
Cortafuegos y Servidor web
Tenemos algunas reglas del cortafuegos sin utilizar, sin embargo no tenemos servidores web instalados:
[+] Software: firewalls -------------------------º----------- - Checking iptables kernel module [ FOUND ] - Checking iptables policies of chains [ FOUND ] - Checking for empty ruleset [ OK ] - Checking for unused rules [ FOUND ] - Checking host based firewall [ ACTIVE ] [+] Software: webserver ------------------------------------ - Checking Apache [ NOT FOUND ] - Checking nginx [ NOT FOUND ]
SSH
Esta sección es una de las más criticas y vemos que tenemos varias advertencias de Lynis:
[+] SSH Support ------------------------------------ - Checking running SSH daemon [ FOUND ] - Searching SSH configuration [ FOUND ] - OpenSSH option: AllowTcpForwarding [ SUGGESTION ] - OpenSSH option: ClientAliveCountMax [ SUGGESTION ] - OpenSSH option: ClientAliveInterval [ OK ] - OpenSSH option: Compression [ SUGGESTION ] - OpenSSH option: FingerprintHash [ OK ] - OpenSSH option: GatewayPorts [ OK ] - OpenSSH option: IgnoreRhosts [ OK ] - OpenSSH option: LoginGraceTime [ OK ] - OpenSSH option: LogLevel [ SUGGESTION ] - OpenSSH option: MaxAuthTries [ SUGGESTION ] - OpenSSH option: MaxSessions [ SUGGESTION ] - OpenSSH option: PermitRootLogin [ OK ] - OpenSSH option: PermitUserEnvironment [ OK ] - OpenSSH option: PermitTunnel [ OK ] - OpenSSH option: Port [ SUGGESTION ] - OpenSSH option: PrintLastLog [ OK ] - OpenSSH option: StrictModes [ OK ] - OpenSSH option: TCPKeepAlive [ SUGGESTION ] - OpenSSH option: UseDNS [ OK ] - OpenSSH option: X11Forwarding [ SUGGESTION ] - OpenSSH option: AllowAgentForwarding [ SUGGESTION ] - OpenSSH option: AllowUsers [ NOT FOUND ] - OpenSSH option: AllowGroups [ NOT FOUND ]
SNMP, DB, LDAP, PHP y Squid
No tenemos ninguna sugerencia por aquí:
[+] SNMP Support ------------------------------------ - Checking running SNMP daemon [ NOT FOUND ] [+] Databases ------------------------------------ - MySQL process status [ FOUND ] - MongoDB status [ FOUND ] [+] LDAP Services ------------------------------------ - Checking OpenLDAP instance [ NOT FOUND ] [+] PHP ------------------------------------ - Checking PHP [ FOUND ] - Checking PHP disabled functions [ FOUND ] - Checking expose_php option [ OFF ] - Checking enable_dl option [ OFF ] - Checking allow_url_fopen option [ ON ] - Checking allow_url_include option [ OFF ] - Checking listen option [ OK ] [+] Squid Support ------------------------------------ - Checking running Squid daemon [ NOT FOUND ]
Logs
Nos avisa que no tenemos habilitados los logs remotos:
[+] 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 remote logging [ NOT ENABLED ] - Checking log directories (static list) [ DONE ] - Checking open log files [ DONE ] - Checking deleted files in use [ FILES FOUND ]
Permisos en archivos importantes
Como vemos, tenemos sugerencias sobre los permisos de algunos archivos y una advertencia en home:
[+] File Permissions ------------------------------------ - Starting file permissions check File: /boot/grub/grub.cfg [ OK ] File: /etc/at.deny [ SUGGESTION ] File: /etc/crontab [ SUGGESTION ] File: /etc/group [ OK ] File: /etc/group- [ OK ] File: /etc/hosts.allow [ OK ] File: /etc/hosts.deny [ OK ] File: /etc/issue [ OK ] File: /etc/issue.net [ OK ] File: /etc/passwd [ OK ] File: /etc/passwd- [ OK ] File: /etc/ssh/sshd_config [ SUGGESTION ] Directory: /root/.ssh [ OK ] Directory: /etc/cron.d [ SUGGESTION ] Directory: /etc/cron.daily [ SUGGESTION ] Directory: /etc/cron.hourly [ SUGGESTION ] Directory: /etc/cron.weekly [ SUGGESTION ] Directory: /etc/cron.monthly [ SUGGESTION ] [+] Home directories ------------------------------------ - Permissions of home directories [ WARNING ] - Ownership of home directories [ OK ] - Checking shell history files [ OK ]
Hardening
Esta parte es una de las más importantes, aquí vemos recomendaciones sobre las configuraciones de seguridad de nuestro núcleo. Es posible cambiar su valor en función de tu postura de seguridad:
[+] Kernel Hardening ------------------------------------ - Comparing sysctl key pairs with scan profile - fs.protected_hardlinks (exp: 1) [ OK ] - fs.protected_symlinks (exp: 1) [ OK ] - 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) [ OK ] - 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) [ DIFFERENT ] - 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) [ OK ] - 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 ]
Sugerencias
Hacia el final, Lynis nos explica cada punto señalado en el reporte. Cada sugerencia viene con un TEST-ID al final, debemos tenerlo a mano para utilizarlo más adelante.
Pondremos solo una parte ya que esta sección es algo extensa:
-[ Lynis 3.0.0 Results ]- Warnings (1): ---------------------------- ! Reboot of system is most likely needed [KRNL-5830] - Solution : reboot https://cisofy.com/lynis/controls/KRNL-5830/ Suggestions (60): ---------------------------- * Set a password on GRUB boot loader to prevent altering boot configuration (e.g. boot in single user mode without password) [BOOT-5122] https://cisofy.com/lynis/controls/BOOT-5122/ * If not required, consider explicit disabling of core dump in /etc/security/limits.conf file [KRNL-5820] https://cisofy.com/lynis/controls/KRNL-5820/ * Check PAM configuration, add rounds if applicable and expire passwords to encrypt with new values [AUTH-9229] https://cisofy.com/lynis/controls/AUTH-9229/ * Configure minimum encryption algorithm rounds in /etc/login.defs [AUTH-9230] https://cisofy.com/lynis/controls/AUTH-9230/ * Configure maximum encryption algorithm rounds in /etc/login.defs [AUTH-9230] https://cisofy.com/lynis/controls/AUTH-9230/ * Install a PAM module for password strength testing like pam_cracklib or pam_passwdqc [AUTH-9262] https://cisofy.com/lynis/controls/AUTH-9262/ * When possible set expire dates for all password protected accounts [AUTH-9282] https://cisofy.com/lynis/controls/AUTH-9282/
Resumen
Por último, Lynis nos da un resumen de todo el reporte y nos muestra la ruta donde se guarda el reporte:
Lynis security scan details: Hardening index : 65 [############# ] Tests performed : 267 Plugins enabled : 0 Components: - Firewall [V] - Malware scanner [X] Scan mode: Normal [V] Forensics [ ] Integration [ ] Pentest [ ] Lynis modules: - Compliance status [?] - Security audit [V] - Vulnerability scan [V] Files: - Test and debug information : /var/log/lynis.log - Report data : /var/log/lynis-report.dat
Detalles
Lynis nos ofrece una opción para encontrar información más detallada sobre cada sugerencia, a la que se puede acceder utilizando el comando show details seguido del número TEST_ID:
$ lynis show details KRNL-5830
2020-07-08 17:08:50 Performing test ID KRNL-5830 (Checking if system is running on the latest installed kernel) 2020-07-08 17:08:50 Test: Checking presence /var/run/reboot-required.pkgs 2020-07-08 17:08:50 Result: file /var/run/reboot-required.pkgs exists 2020-07-08 17:08:50 Result: reboot is needed, related to 40 packages 2020-07-08 17:08:50 Package: 40 2020-07-08 17:08:50 Result: /boot exists, performing more tests from here 2020-07-08 17:08:50 Result: found /boot/vmlinuz-4.4.0-185-generic 2020-07-08 17:08:50 Test: checking kernel version on disk 2020-07-08 17:08:50 Result: found version 4.4.0-185-generic 2020-07-08 17:08:50 Result: active kernel version 4.4.0-135-generic 2020-07-08 17:08:50 Result: reboot needed, as there is a difference between active kernel and the one on disk 2020-07-08 17:08:50 Result: /var/cache/apt/archives/ does not exist 2020-07-08 17:08:50 Warning: Reboot of system is most likely needed [test:KRNL-5830] [details:] [solution:text:reboot] 2020-07-08 17:08:50 Hardening: assigned partial number of hardening points (0 of 5). Currently having 5 points (out of 16) 2020-07-08 17:08:50 Security check: file is normal 2020-07-08 17:08:50 Checking permissions of /usr/share/lynis/include/tests_memory_processes 2020-07-08 17:08:50 File permissions are OK 2020-07-08 17:08:50 ====
Pruebalo
Como podemos ver, Lynis es una excelente herramienta para fortificar nuestros sistemas Linux. La profunda revision que hace de nuestro sistema, lo convierte en un gran aliado para protegernos frente a cualquier vulnerabilidad.
Recuerda que actualmente, la información es el bien más preciado y debemos protegerla a toda costa.