Bienvenidos a un nuevo post en byte-mind, en este caso vamos a tratar una herramienta para la detección de rootkits en nuestro sistema Linux, se trata de rkhunter.
Vamos a ver en qué consiste esta herramienta, aunque para aquellos que no lo sepan vamos a explicar primero que es un rootkit.
¿Qué es un rootkit?
Un rootkit es un programa que permite un acceso de privilegio continuo a un sistema pero que mantiene su presencia activamente.
Se oculta del control de los administradores al corromper el funcionamiento normal del sistema operativo o de otras aplicaciones. El término proviene de una concatenación de la palabra inglesa “root” que significa raíz (nombre tradicional de la cuenta privilegiada en los sistemas operativos Unix) y de la palabra inglesa “kit” que significa conjunto de herramientas (en referencia a los componentes de software que implementan este programa). El término “rootkit” tiene connotaciones negativas ya que se le asocia al malware.
En otras palabras, usualmente se le asocia con malware, que se esconde a sí mismo y a otros programas, procesos, archivos, directorios, claves de registro, y puertos que permiten al intruso mantener el acceso a una amplia variedad de sistemas operativos como pueden ser GNU/Linux, Solaris o Microsoft Windows para remotamente ejecutar acciones o extraer información sensible.
Vista la explicación en este post no vamos a explicar a como protegernos sino que vamos a enseñar una herramienta que nos ayude a detertarlos, esa es la función de la tool rkhunter.
Instalación de rkhunter
Para la instalación del paquete podemos hacerlo desde el repositorio de la distribución utilizada o mediante la descarga e instalación del paquete desde su página oficial, vamos a explicar como hacerlo de las dos formas.
Para la instalación en sistemas basados en Debian:
1 |
sudo apt-get install rkhunter -y |
O desde aptitude:
1 |
sudo aptitude install rkhunter |
Instalaciónn en centos:
1 |
sudo yum install rkhunter |
O, si disponemos de dnf:
1 |
sudo dnf install rkhunter |
La otra opción es la descarga del paquete desde sourceforge. Descargaremos el mismo:
1 |
wget http://downloads.sourceforge.net/project/rkhunter/rkhunter/1.4.6/rkhunter-1.4.6.tar.gz -O rkhunter-1.4.6.tar.gz |
Extracción del mismo:
1 |
tar xzvf rkhunter-1.4.6.tar.gz |
E instalación:
1 |
sudo ./installer.sh --install |
Ayuda de la herramienta
Como siempre dispone de un comando de ayuda para observar las posibilidades del mismo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
$ rkhunter --help Usage: rkhunter {--check | --unlock | --update | --versioncheck | --propupd [{filename | directory | package name},...] | --list [{tests | {lang | languages} | rootkits | perl | propfiles}] | --config-check | --version | --help} [options] Current options are: --append-log Append to the logfile, do not overwrite --bindir <directory>... Use the specified command directories -c, --check Check the local system -C, --config-check Check the configuration file(s), then exit --cs2, --color-set2 Use the second color set for output --configfile <file> Use the specified configuration file --cronjob Run as a cron job (implies -c, --sk and --nocolors options) --dbdir <directory> Use the specified database directory --debug Debug mode (Do not use unless asked to do so) --disable <test>[,<test>...] Disable specific tests (Default is to disable no tests) --display-logfile Display the logfile at the end --enable <test>[,<test>...] Enable specific tests (Default is to enable all tests) --hash {MD5 | SHA1 | SHA224 | SHA256 | SHA384 | SHA512 | NONE | <command>} Use the specified file hash function (Default is SHA256) -h, --help Display this help menu, then exit --lang, --language <language> Specify the language to use (Default is English) --list [tests | languages | List the available test names, languages, rootkits | perl | rootkit names, perl module status propfiles] or file properties database, then exit -l, --logfile [file] Write to a logfile (Default is /var/log/rkhunter.log) --noappend-log Do not append to the logfile, overwrite it --nocf Do not use the configuration file entries for disabled tests (only valid with --disable) --nocolors Use black and white output --nolog Do not write to a logfile --nomow, --no-mail-on-warning Do not send a message if warnings occur --ns, --nosummary Do not show the summary of check results --novl, --no-verbose-logging No verbose logging --pkgmgr {RPM | DPKG | BSD | Use the specified package manager to obtain BSDng | SOLARIS | or verify file property values. NONE} (Default is NONE) --propupd [file | directory | Update the entire file properties database, package]... or just for the specified entries -q, --quiet Quiet mode (no output at all) --rwo, --report-warnings-only Show only warning messages --sk, --skip-keypress Don't wait for a keypress after each test --summary Show the summary of system check results (This is the default) --syslog [facility.priority] Log the check start and finish times to syslog (Default level is authpriv.notice) --tmpdir <directory> Use the specified temporary directory --unlock Unlock (remove) the lock file --update Check for updates to database files --vl, --verbose-logging Use verbose logging (on by default) -V, --version Display the version number, then exit --versioncheck Check for latest version of program -x, --autox Automatically detect if X is in use -X, --no-autox Do not automatically detect if X is in use |
Configuración de rkhunter
Una vez instalado rkhunter es necesario configurar el mismo antes de realizar la primera revisión del sistema, para ello deberemos editar el fichero de configuración situado en /etc/rkhunter.conf
Opciones para la actualización de la base de datos
La variable UPDATE_MIRRORS se encargará de verificar los archivos en busca de actualizaciones cuando se buscan actualizaciones de rkhunter con la opción –update, el valor a 1 permitirá estas actualizaciones.
La variable MIRRORS_MODE indicará que repositorios utilzar cuando se proporcionen las opciones de –update o –versioncheck, en este caso hay 3 posibles opciones:
- 0 -> utiliza cualquier repo
- 1 -> utiliza sólo repos locales
- 2 -> utiliza sólo repos remotos
La variable WEB_CMD nos permite establecer el comando a utilizar cuando rkhunter se descarga datos de internet para la actualización de su base de datos, por defecto su valor está vacío.
Opciones para el escaneo y programación de tareas con cron
Por defecto, rkhunter generará un fichero en el directorio cron.daily para el análisis del sistema y búsqueda de actualizaciones, por lo tanto este script se ejecutará todos los días, pero es posible realizar algunos cambios para evitar cuando y como se hacen estos chequeos.
La variable CRON_DAILY_RUN (booleano) nos permite establecer si debe de ejecutarse diariamente, sólo deberemos de indicar con “true” o “false” si queremos que se ejecute.
La variable CRON_DB_UPDATE (booleano) permite especificar si queremos habilitar las actualizaciones semanales de la base de datos.
La variable APT_AUTOGEN (booleano) permite activar las actualizaciones automáticas de la base de datos.
Permitir ficheros y directorios ocultos
Podemos añadir en la configuración ficheros o directorios ocultos conocidos para evitar las alertas al realizar un chequeo con rkhunter, podemos hacerlo con la siguiente variable:
1 2 |
ALLOWHIDDENDIR=/path/.file ALLOWHIDDENDIR=/path/.dir |
Chequear la configuración aplicada
Para verificar que no tenemos errores en los cambios aplicados, podemos ejecutar la opción –config-check o -C en su versión corta:
1 |
$ rkhunter --config-check |
Si existe algún error mostraría el mismo para su corrección, en caso de no haber nada, el comando anterior no devolverá ninguna salida por consola.
Actualización de la base de datos de rkhunter
Una vez aplicada nuestra configuración podemos forzar la actualización de los datos de rkhunter mediante la opción –update, esta opción es vital ya que son los archivos que utilizará la herramienta para determinar si hay actividades sospechosas en el sistema, por lo que es necesario que estén actualizados.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$ rkhunter --update [ Rootkit Hunter version 1.4.6 ] Checking rkhunter data files... Checking file mirrors.dat [ No update ] Checking file programs_bad.dat [ No update ] Checking file backdoorports.dat [ No update ] Checking file suspscan.dat [ No update ] Checking file i18n/cn [ No update ] Checking file i18n/de [ No update ] Checking file i18n/en [ No update ] Checking file i18n/tr [ No update ] Checking file i18n/tr.utf8 [ No update ] Checking file i18n/zh [ No update ] Checking file i18n/zh.utf8 [ No update ] Checking file i18n/ja [ No update ] |
Los ficheros i18/* son sólo para fines de localización por lo que no son esenciales para la funcionalidad del programa.
También podemos comprobar sólo la versión con el comando:
1 2 3 4 5 6 |
$ rkhunter --versioncheck [ Rootkit Hunter version 1.4.6 ] Checking rkhunter version... This version : 1.4.6 Latest version: 1.4.6 |
Establecer una línea base para los chequeos
Rkhunter comparará varias propiedades de los archivos existentes con lo obtenido anteriormente. Para actualizar el estado actual en el archivo de datos de rkhunter podemos realizar con la opción –propupd:
1 2 3 |
$ rkhunter --propupd [ Rootkit Hunter version 1.4.6 ] File created: searched for 175 files, found 127 |
Chequear el sistema
Ahora que ya está configurado y actualizado el estado del sistema podemos realizar un chequeo del mismo con la opción –check.
Como lo he montado en una máquina virtual simplemente para la demostración, adjunto a continuación la salida completa del chequeo realizado:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 |
$ rkhunter --check [ Rootkit Hunter version 1.4.6 ] Checking system commands... Performing 'strings' command checks Checking 'strings' command [ OK ] Performing 'shared libraries' checks Checking for preloading variables [ None found ] Checking for preloaded libraries [ None found ] Checking LD_LIBRARY_PATH variable [ Not found ] Performing file properties checks Checking for prerequisites [ OK ] /usr/sbin/adduser [ OK ] /usr/sbin/chkconfig [ OK ] /usr/sbin/chroot [ OK ] /usr/sbin/depmod [ OK ] /usr/sbin/fsck [ OK ] /usr/sbin/groupadd [ OK ] /usr/sbin/groupdel [ OK ] /usr/sbin/groupmod [ OK ] /usr/sbin/grpck [ OK ] /usr/sbin/ifconfig [ OK ] /usr/sbin/ifdown [ OK ] /usr/sbin/ifup [ OK ] /usr/sbin/init [ OK ] /usr/sbin/insmod [ OK ] /usr/sbin/ip [ OK ] /usr/sbin/lsmod [ OK ] /usr/sbin/lsof [ OK ] /usr/sbin/modinfo [ OK ] /usr/sbin/modprobe [ OK ] /usr/sbin/nologin [ OK ] /usr/sbin/pwck [ OK ] /usr/sbin/rmmod [ OK ] /usr/sbin/route [ OK ] /usr/sbin/rsyslogd [ OK ] /usr/sbin/runlevel [ OK ] /usr/sbin/sestatus [ OK ] /usr/sbin/sshd [ OK ] /usr/sbin/sulogin [ OK ] /usr/sbin/sysctl [ OK ] /usr/sbin/useradd [ OK ] /usr/sbin/userdel [ OK ] /usr/sbin/usermod [ OK ] /usr/sbin/vipw [ OK ] /usr/bin/awk [ OK ] /usr/bin/basename [ OK ] /usr/bin/bash [ OK ] /usr/bin/cat [ OK ] /usr/bin/chattr [ OK ] /usr/bin/chmod [ OK ] /usr/bin/chown [ OK ] /usr/bin/cp [ OK ] /usr/bin/curl [ OK ] /usr/bin/cut [ OK ] /usr/bin/date [ OK ] /usr/bin/df [ OK ] /usr/bin/diff [ OK ] /usr/bin/dirname [ OK ] /usr/bin/dmesg [ OK ] /usr/bin/du [ OK ] /usr/bin/echo [ OK ] /usr/bin/egrep [ OK ] /usr/bin/env [ OK ] /usr/bin/fgrep [ OK ] /usr/bin/file [ OK ] /usr/bin/find [ OK ] /usr/bin/grep [ OK ] /usr/bin/groups [ OK ] /usr/bin/head [ OK ] /usr/bin/id [ OK ] /usr/bin/ipcs [ OK ] /usr/bin/kill [ OK ] /usr/bin/last [ OK ] /usr/bin/lastlog [ OK ] /usr/bin/ldd [ OK ] /usr/bin/less [ OK ] /usr/bin/logger [ OK ] /usr/bin/login [ OK ] /usr/bin/ls [ OK ] /usr/bin/lsattr [ OK ] /usr/bin/mail [ OK ] /usr/bin/md5sum [ OK ] /usr/bin/mktemp [ OK ] /usr/bin/more [ OK ] /usr/bin/mount [ OK ] /usr/bin/mv [ OK ] /usr/bin/netstat [ OK ] /usr/bin/newgrp [ OK ] /usr/bin/passwd [ OK ] /usr/bin/perl [ OK ] /usr/bin/pgrep [ OK ] /usr/bin/ping [ OK ] /usr/bin/pkill [ OK ] /usr/bin/ps [ OK ] /usr/bin/pwd [ OK ] /usr/bin/readlink [ OK ] /usr/bin/rkhunter [ OK ] /usr/bin/rpm [ OK ] /usr/bin/runcon [ OK ] /usr/bin/sed [ OK ] /usr/bin/sh [ OK ] /usr/bin/sha1sum [ OK ] /usr/bin/sha224sum [ OK ] /usr/bin/sha256sum [ OK ] /usr/bin/sha384sum [ OK ] /usr/bin/sha512sum [ OK ] /usr/bin/size [ OK ] /usr/bin/sort [ OK ] /usr/bin/ssh [ OK ] /usr/bin/stat [ OK ] /usr/bin/strings [ OK ] /usr/bin/su [ OK ] /usr/bin/sudo [ OK ] /usr/bin/tail [ OK ] /usr/bin/telnet [ OK ] /usr/bin/test [ OK ] /usr/bin/top [ OK ] /usr/bin/touch [ OK ] /usr/bin/tr [ OK ] /usr/bin/uname [ OK ] /usr/bin/uniq [ OK ] /usr/bin/users [ OK ] /usr/bin/vmstat [ OK ] /usr/bin/w [ OK ] /usr/bin/watch [ OK ] /usr/bin/wc [ OK ] /usr/bin/wget [ OK ] /usr/bin/whatis [ OK ] /usr/bin/whereis [ OK ] /usr/bin/which [ OK ] /usr/bin/who [ OK ] /usr/bin/whoami [ OK ] /usr/bin/numfmt [ OK ] /usr/bin/kmod [ OK ] /usr/bin/systemctl [ OK ] /usr/bin/gawk [ OK ] /usr/bin/mailx [ OK ] /usr/lib/systemd/systemd [ OK ] [Press <ENTER> to continue] Checking for rootkits... Performing check of known rootkit files and directories 55808 Trojan - Variant A [ Not found ] ADM Worm [ Not found ] AjaKit Rootkit [ Not found ] Adore Rootkit [ Not found ] aPa Kit [ Not found ] Apache Worm [ Not found ] Ambient (ark) Rootkit [ Not found ] Balaur Rootkit [ Not found ] BeastKit Rootkit [ Not found ] beX2 Rootkit [ Not found ] BOBKit Rootkit [ Not found ] cb Rootkit [ Not found ] CiNIK Worm (Slapper.B variant) [ Not found ] Danny-Boy's Abuse Kit [ Not found ] Devil RootKit [ Not found ] Diamorphine LKM [ Not found ] Dica-Kit Rootkit [ Not found ] Dreams Rootkit [ Not found ] Duarawkz Rootkit [ Not found ] Ebury backdoor [ Not found ] Enye LKM [ Not found ] Flea Linux Rootkit [ Not found ] Fu Rootkit [ Not found ] Fuck`it Rootkit [ Not found ] GasKit Rootkit [ Not found ] Heroin LKM [ Not found ] HjC Kit [ Not found ] ignoKit Rootkit [ Not found ] IntoXonia-NG Rootkit [ Not found ] Irix Rootkit [ Not found ] Jynx Rootkit [ Not found ] Jynx2 Rootkit [ Not found ] KBeast Rootkit [ Not found ] Kitko Rootkit [ Not found ] Knark Rootkit [ Not found ] ld-linuxv.so Rootkit [ Not found ] Li0n Worm [ Not found ] Lockit / LJK2 Rootkit [ Not found ] Mokes backdoor [ Not found ] Mood-NT Rootkit [ Not found ] MRK Rootkit [ Not found ] Ni0 Rootkit [ Not found ] Ohhara Rootkit [ Not found ] Optic Kit (Tux) Worm [ Not found ] Oz Rootkit [ Not found ] Phalanx Rootkit [ Not found ] Phalanx2 Rootkit [ Not found ] Phalanx2 Rootkit (extended tests) [ Not found ] Portacelo Rootkit [ Not found ] R3dstorm Toolkit [ Not found ] RH-Sharpe's Rootkit [ Not found ] RSHA's Rootkit [ Not found ] Scalper Worm [ Not found ] Sebek LKM [ Not found ] Shutdown Rootkit [ Not found ] SHV4 Rootkit [ Not found ] SHV5 Rootkit [ Not found ] Sin Rootkit [ Not found ] Slapper Worm [ Not found ] Sneakin Rootkit [ Not found ] 'Spanish' Rootkit [ Not found ] Suckit Rootkit [ Not found ] Superkit Rootkit [ Not found ] TBD (Telnet BackDoor) [ Not found ] TeLeKiT Rootkit [ Not found ] T0rn Rootkit [ Not found ] trNkit Rootkit [ Not found ] Trojanit Kit [ Not found ] Tuxtendo Rootkit [ Not found ] URK Rootkit [ Not found ] Vampire Rootkit [ Not found ] VcKit Rootkit [ Not found ] Volc Rootkit [ Not found ] Xzibit Rootkit [ Not found ] zaRwT.KiT Rootkit [ Not found ] ZK Rootkit [ Not found ] [Press <ENTER> to continue] Performing additional rootkit checks Suckit Rootkit additional checks [ OK ] Checking for possible rootkit files and directories [ None found ] Checking for possible rootkit strings [ None found ] Performing malware checks Checking running processes for suspicious files [ None found ] Checking for hidden processes [ Skipped ] Checking for login backdoors [ None found ] Checking for sniffer log files [ None found ] Checking for suspicious directories [ None found ] Checking for Apache backdoor [ Not found ] Performing Linux specific checks Checking loaded kernel modules [ OK ] Checking kernel module names [ OK ] [Press <ENTER> to continue] Checking the network... Performing checks on the network ports Checking for backdoor ports [ None found ] Performing checks on the network interfaces Checking for promiscuous interfaces [ None found ] Checking the local host... Performing system boot checks Checking for local host name [ Found ] Checking for system startup files [ Found ] Checking system startup files for malware [ None found ] Performing group and account checks Checking for passwd file [ Found ] Checking for root equivalent (UID 0) accounts [ None found ] Checking for passwordless accounts [ None found ] Checking for passwd file changes [ Warning ] Checking for group file changes [ Warning ] Checking root account shell history files [ OK ] Performing system configuration file checks Checking for an SSH configuration file [ Found ] Checking if SSH root access is allowed [ Not set ] Checking if SSH protocol v1 is allowed [ Not set ] Checking for other suspicious configuration settings [ None found ] Checking for a running system logging daemon [ Found ] Checking for a system logging configuration file [ Found ] Checking if syslog remote logging is allowed [ Not allowed ] Performing filesystem checks Checking /dev for suspicious file types [ None found ] Checking for hidden files and directories [ None found ] [Press <ENTER> to continue] System checks summary ===================== File properties checks... Files checked: 127 Suspect files: 0 Rootkit checks... Rootkits checked : 493 Possible rootkits: 0 Applications checks... All checks skipped The system checks took: 7 minutes and 41 seconds All results have been written to the log file: /var/log/rkhunter/rkhunter.log One or more warnings have been found while checking the system. Please check the log file (/var/log/rkhunter/rkhunter.log) |
Tal y como indica la salida anterior podemos ver el registro completo del chequeo en el log de la herramienta situado en la ruta /var/log/rkhunter/rkhunter.log
Además del comando anterior podemos utilizar la opción –skip-keypress o –sk en su versión corta para evitar que solicite un prompt con cada verificación:
1 |
$ rkhunter --check --skip-keypress |
O, mostrar sólo los mensaje de waring con la opción –report-warnings-only o –rwo en su versión corta:
1 |
$ rkhunter --check --report-warnings-only |
Notificaciones por correo
Otra posibilidad es el envío de los resultados por correo electrónico en caso de que encuentre una amenaza en el sistema.
Para ello se debe indicar en el fichero /etc/rkhunter.conf con la siguiente variable indicando el correo en el cual queremos recibir la misma:
1 |
MAIL-ON-WARNING=user@domain |
O también, es posible configurar el comando que se ejecutará para el envío del correo:
1 |
MAIL_CMD=mail -s "[rkhunter] Se encontraron problemas para ${HOST_NAME}" |
Completado este paso, chequea la configuración tal y como indicamos anteriormente para empezar a recibir mails con los resultados de los análisis.
Esto es todo por el momento, espero que esta herramienta les sea muy útil en su día a día para evitar ataques a sus sistemas y como siempre, cualquier duda o sugerencia es bienvenida en la sección de comentarios.