- Статья THC-Hydra: очень быстрый взломщик сетевого входа в систему (часть первая)
- How to Use Hydra to Hack Passwords – Penetration Testing Tutorial
- How to Install Hydra
- How to Work with Hydra
- How to Perform a Single Username/Password Attack with Hydra
- How to Perform a Password Spraying Attack with Hydra
- How to Perform a Dictionary Attack with Hydra
- How to Use the Verbosity and Debugging Flags in Hydra
- How to Save Your Results in Hydra
- More flags and formats
- Service specification
- How to resume attacks
- How to use custom ports
- How to attack multiple hosts
- Targeted combinations
- How to Defend Against Hydra
- Summary
Статья THC-Hydra: очень быстрый взломщик сетевого входа в систему (часть первая)
Программа hydra поддерживает огромное количество служб, благодаря своей быстроте и надёжности она завоевала заслуженную признательность среди тестеров на проникновение. Будучи очень мощной и гибкой, программу hydra нельзя отнести к простым и легко дающимся новичкам. Не надо отчаиваться, если вам не удалось оседлать hydra, я рекомендую вам посмотреть на программу BruteX. Она значительно автоматизирует процесс подбора, более того, она использует ту же самую hydra, но сама вводит необходимые ключи и даже не нужно искать файлы с именами и паролями, поскольку они поставляются вместе с программой. Если я вас заинтересовал, то рекомендую статью «BruteX: программа для автоматического брутфорса всех служб».
Этот инструмент — THC-Hydra — предназначен только для законных целей.
Программа прекрасно компилируется и работает на Linux, Windows/Cygwin, Solaris, FreeBSD/OpenBSD, QNX (Blackberry 10) и OSX. Лучше всех пользователям Kali Linux – у них программа уже установлена.
В настоящее время поддерживаются следующие протоколы: Asterisk, AFP, Cisco AAA, Cisco auth, Cisco enable, CVS, Firebird, FTP, HTTP-FORM-GET, HTTP-FORM-POST, HTTP-GET, HTTP-HEAD, HTTP-PROXY, HTTPS-FORM-GET, HTTPS-FORM-POST, HTTPS-GET, HTTPS-HEAD, HTTP-Proxy, ICQ, IMAP, IRC, LDAP, MS-SQL, MYSQL, NCP, NNTP, Oracle Listener, Oracle SID, Oracle, PC-Anywhere, PCNFS, POP3, POSTGRES, RDP, Rexec, Rlogin, Rsh, SAP/R3, SIP, SMB, SMTP, SMTP Enum, SNMP v1+v2+v3, SOCKS5, SSH (v1 и v2), SSHKEY, Subversion, Teamspeak (TS2), Telnet, VMware-Auth, VNC и XMPP.
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] [-SuvVd46] [service://server[:PORT][/OPT]]
Прибавилось ли понимания после увиденного синтаксиса? )) Не переживайте, сейчас рассмотрим опции THC-Hydra, а потом углубимся в понимание работы с этой программой.
-R восстановить предыдущую прерванную/оборванную сессию -S выполнить SSL соединение -s ПОРТ если служба не на порту по умолчанию, то можно задать порт здесь -l ЛОГИН или -L ФАЙЛ с ЛОГИНАМИ (именами), или загрузить несколько логинов из ФАЙЛА -p ПАРОЛЬ или -P ФАЙЛ с паролями для перебора, или загрузить несколько паролей из ФАЙЛА -x МИНИМУМ:МАКСИМУМ:НАБОР_СИМВОЛОВ генерация паролей для брутфорса, наберите "-x -h" для помощи -e nsr "n" — пробовать с пустым паролем, "s" — логин в качестве пароля и/или "r" — реверс учётных данных -u зацикливаться на пользователя, а не на парлях (эффективно! подразумевается с использованием опции -x) -C ФАЙЛ формат где "логин:пароль" разделены двоеточиями, вместо опции -L/-P -M ФАЙЛ список серверов для атак, одна запись на строку, после двоеточия ':' можно задать порт -o ФАЙЛ записывать найденные пары логин/пароль в ФАЙЛ вместо стандартного вывода -f / -F выйти, когда пара логин/пароль подобрана (-M: -f для хоста, -F глобально) -t ЗАДАЧИ количество запущенных параллельно ЗАДАЧ (на хост, по умолчанию: 16) -w / -W ВРЕМЯ время ожидания ответов (32 секунды) / между соединениями на поток -4 / -6 предпочитать IPv4 (по умолчанию) или IPv6 адреса -v / -V / -d вербальный режим / показывать логин+пароль для каждой попытки / режим отладки -q не печатать сообщения об ошибках соединения -U подробные сведения об использовании модуля server цель: DNS, IP или 192.168.0.0/24 (эта ИЛИ опция -M) service служба для взлома (смотрите список поддерживаемых протоколов) OPT некоторые модули служб поддерживают дополнительный ввод (-U для справки по модулю)
Как использовать hydra
THC-Hydra поставляется без логинов/паролей. Нам нужно самим где-то их раздобыть. И вот здесь нам поможет недавняя статья «Списки слов для атаки по словарю: пароли, имена пользователей, каталоги». Изучайте её, скачивайте свои пароли.
Ещё файлы с дефолтными паролями позволяет генерировать утилита от hydra — dpl4hydra.sh. Чтобы узнать, какие устройства есть в базе, зайдите
Чтобы воспользоваться программой dpl4hydra.sh на Kali Linux, нам сначала нужно её скачать (по какой-то причине авторы Kali не включили её в стандартную установку).
wget https://raw.githubusercontent.com/vanhauser-thc/thc-hydra/master/dpl4hydra.sh
touch /usr/local/etc/dpl4hydra_full.csv /usr/local/etc/dpl4hydra_local.csv
How to Use Hydra to Hack Passwords – Penetration Testing Tutorial
Manish Shivanandhan
Hydra is a brute-forcing tool that helps penetration testers and ethical hackers crack the passwords of network services.
Hydra can perform rapid dictionary attacks against more than 50 protocols. This includes telnet, FTP, HTTP, HTTPS, SMB, databases, and several other services.
Hydra was developed by the hacker group “The Hacker’s Choice”. Hydra was first released in 2000 as a proof of concept tool that demonstrated how you can perform attacks on network logon services.
Hydra is also a parallelized login cracker. This means you can have more than one connection in parallel. Unlike in sequential brute-forcing, this reduces the time required to crack a password.
In my last article, I explained another brute-force tool called John the Ripper. Though John and Hydra are brute-force tools, John works offline while Hydra works online.
In this article, we will look at how Hydra works followed by a few real-world use cases.
Note: All my articles are for educational purposes. If you use it illegally and get into trouble, I am not responsible. Always get permission from the owner before scanning / brute-forcing / exploiting a system.
How to Install Hydra
Hydra comes pre-installed with Kali Linux and Parros OS. So if you are using one of them, you can start working with Hydra right away.
On Ubuntu, you can use the apt package manager to install it:
In Mac, you can find Hydra under Homebrew:
If you are using Windows, I would recommend using a virtual box and installing Linux. Personally, I don’t recommend using Windows if you want to be a professional penetration tester.
How to Work with Hydra
Let’s look at how to work with Hydra. We will go through the common formats and options that Hydra provides for brute-forcing usernames and passwords. This includes single username/password attacks, password spraying, and dictionary attacks.
If you have installed Hydra, you can start with the help command like this:
This will give you the list of flags and options that you can use as a reference when working with Hydra.
How to Perform a Single Username/Password Attack with Hydra
Let’s start with a simple attack. If we have the username and password that we expect a system to have, we can use Hydra to test it.
Let’s assume we have a user named “molly” with a password of “butterfly” hosted at 10.10.137.76. Here is how we can use Hydra to test the credentials for SSH:
$ hydra -l molly -p butterfly 10.10.137.76 ssh
If it works, here is what the result will look like:
How to Perform a Password Spraying Attack with Hydra
What if we know a password that someone is using, but we are not sure who it is? We can use a password spray attack to determine the username.
A password spray attack is where we use a single password and run it against a number of users. If someone is using the password, Hydra will find the match for us.
This attack assumes we know a list of users in the system. For this example, we will create a file called users.txt with the following users:
root admin user molly steve richard
Now we are going to test who has the password “butterfly”. Here is how we can run a password spray attack using Hydra.
$ hydra -L users.txt -p butterfly 10.10.137.76 ssh
We will get a similar result to the following output if any of the users match with the given password. You should also notice that we have used the flag -L instead of -l. -l is for a single username and -L is for a list of usernames.
How to Perform a Dictionary Attack with Hydra
Let’s look at how to perform a dictionary attack. In real-world scenarios, this is what we will be using Hydra regularly for.
A dictionary attack is where we have single/multiple usernames and we provide a password wordlist to Hydra. Hydra then tests all these passwords against every user in the list.
I am going to use the Rockyou wordlist for this example along with the users.txt file we created in the previous attack. If you are using Kali Linux, you can find the RockYou wordlist under /usr/share/wordlists/rockyou.txt.
Here is the command for a dictionary attack:
$ hydra -L users.txt -P /usr/share/wordlists/rockyou.txt 1010.137.76 ssh
If this attack is successful, we will see a similar result to the other two commands. Hydra will highlight the successful username/password combinations in green for all the matches.
How to Use the Verbosity and Debugging Flags in Hydra
Hydra can be awfully quiet when running large brute-force attacks. If we have to make sure Hydra is doing what it is expected to do, there are two flags we can use.
The verbosity (-v) flag will show us the login attempt for each username/password combination. This can be a bit much when there are a lot of combinations to go through, but if it is something you need, we can use the verbosity flag.
Here is a sample result. We can see that Hydra prints information about failed attempts in addition to the successful matches.
We can also use the debug (-d) flag to gather even more information. Here is the same result when using the debug flag:
We can see that Hydra prints way more information than we need. We will only use debug mode rarely, but it is good to know that we have the option to watch every action Hydra takes when brute-forcing a service.
How to Save Your Results in Hydra
Let’s look at how to save results. There is no point in spending hours cracking a password and losing it due to a system crash.
We can use the -o flag and specify a file name to save the result. Here is the syntax.
More flags and formats
Hydra also offers a few additional flags and formats that will be useful for us as pen testers. Here are a few:
Service specification
Instead of specifying the service separately, we can use it with the IP address. For example, to brute force SSH, we can use the following command:
How to resume attacks
If Hydra’s session exits when an attack is in progress, we can resume the attack using the -R flag instead of starting from scratch.
How to use custom ports
Sometimes system administrators will change the default ports for service. For example, FTP can run in port 3000 instead of its default port 21. In those cases, we can specify ports using the -s flag.
How to attack multiple hosts
What if we have multiple hosts to attack? Easy, we can use the -M flag. The files.txt will contain a list of IP addresses or hosts instead of a single IP address.
Targeted combinations
If we have a list of usernames and passwords, we can implement a dictionary attack. But if we have more information on which usernames are likely to have a set of passwords, we can prepare a custom list for Hydra.
For example, we can create a list of usernames and passwords separated by semicolons like the one below.
username1:password1 username2:password2 username3:password3
We can then use the -C flag to tell Hydra to run these specific combinations instead of looping through all the users and passwords. This drastically reduces the time taken to complete a brute-force attack.
We have seen how to work with Hydra in detail. Now you should be ready to perform real-world audits of network services like FTP, SSH, and Telnet.
But as a pen-tester, it is important to understand how to defend against these attacks. Remember, we are the good actors 😎.
How to Defend Against Hydra
The clear solution to help you defend against brute-force attacks is to set strong passwords. The stronger a password is, the harder it is to apply brute-force techniques.
We can also enforce password policies to change passwords every few weeks. Unfortunately, many individuals and businesses use the same passwords for years. This makes them easy targets for brute-force attacks.
Another way to prevent network-based brute-forcing is to limit authorization attempts. Brute-force attacks do not work if we lock accounts after a few failed login attempts. This is common in apps like Google and Facebook that lock your account if you fail a few login attempts.
Finally, tools like re-captcha can be a great way to prevent brute-force attacks. Automation tools like Hydra cannot solve captchas like a real human being.
Summary
Hydra is a fast and flexible network brute-forcing tool to attack services like SSH, and FTP. With a modular architecture and support for parallelization, Hydra can be extended to include new protocols and services easily.
Hydra is undoubtedly a powerful tool to have in your pen-testing toolkit.
Hope this article helped you to understand how Hydra works. If you have any questions, let me know in the comments.
You can connect with me or signup for the Stealth Security Newsletter. If you really enjoyed the article, you can buy me a coffee here.