Как подключиться к hack the box

Обновлено: 04.07.2024

Over at Hack The Box, we use OpenVPN connections to create links between you and our labs and machines.

The configuration files needed to auto-configure your OpenVPN client and to initialize the connection to our servers are called .ovpn packs, or tickets for short.

These will place you in the same IP subnet as the vulnerable machines, allowing you to contact them (and attack them).

A Hack The Box account.

The latest version of OpenVPN. (pre-installed with Kali Linux and ParrotOS)

A working internet connection.

Tutorial VPN packs

Starting Point EU Free Access

Starting Point US Free Access

Free VPN packs

EU Lab Free Access

US Lab Free Access

AU Lab Free Access

SG Lab Free Access

If you’ve bought a VIP Subscription, you will be able to see the VIP packs as well. These look the same as the Free VPN packs listed above, with the "Free" part changed to "VIP".

VIP account - Playing on a Machine

As a VIP user, you will need to boot up an instance of the machine you’d like to tackle. The reason for this is that there’s a high number of VIP servers. While we can’t keep all the Machines running all of the time for all of these servers, we can give the users the option to start and stop a Machine on demand.


Following the steps above, you should already have an .ovpn connection pack ready and waiting in your

/Downloads folder. From there, you only need to boot up your OpenVPN session with the following command after navigating to the

/Downloads folder.


After you get the Initialization Sequence Completed message at the end of the OpenVPN log, you can open a new terminal tab and try to ping the box’s IP address.

Visiting the Machine page, you can see all the required information, as seen above.

Navigating to the Machines page

You’ll need to navigate to the left-hand side menu and click on Labs, then Machines from your dashboard.

This will take you to the Boxes line-up page, where you can find all controls required for you to play the Boxes. This includes VPN connection details and controls, Active and Retired Boxes, a to-do list, and more.

Stopping a Machine

Once you are done attacking a Box and would like to take on a different one, you will first need to shut down the previously owned instance. The platform will not let anyone have two active instances simultaneously, so you will have to click on the Stop Machine button to shut your previous one-off.


VPN Server selection

Connecting to Boxes has gotten a whole lot easier. You are now able to interact directly on the Dashboard.

If you want to view and use the currently available VPN controls, you can do so from any page by clicking on the Connections icon next to your profile picture at the top right of the page you're currently on.

The first of the two available options would be to change your OpenVPN settings. By clicking that, you will be met with the server picker menu. The VPN Access selection will dictate the regional localization of the VPN server and the type: VIP or Free.

The selection below will allow you to choose which specific VPN Server you'd like to connect to enable you and your friends to compete against each other on the same instance of any box.

After selecting the appropriate VPN Server, you can click the Download VPN button, prompting a download for your personalized .ovpn pack.

After selecting the appropriate VPN Server, the command mentioned below the button references what you need to run on your terminal to initialize the OpenVPN connection using the newly downloaded .ovpn file.

VPN Server selection

If you'd like to learn more about using the VPN ticketing system and subsequently connect to the labs to access the Boxes, we have a dedicated article on the topic.

Click the button below to learn how more about Lab Access:

Resetting a Machine

Sometimes a Box gets stuck, or one of its services is manipulated by another user into failing. This requires a reset. To do so, you only need to press the Reset Machine button on the status section.


Resets will clear the progress for any other user, including you, so please make sure that there’s actually something wrong with the services and it’s not localized to your own attack process before issuing a reset. A best practice will be to ask other users if there’s something wrong with the Box or how you are trying to tackle it.

Hack The Box - вторая часть руководства, в которой проанализируем несколько машин из HTB

Всем привет. Это вторая часть руководства по Hack The Box. В ней мы проанализируем несколько машин из HTB, проверим ваши знания командной строки lInux и изучим несколько утилит для сканирования.

Поискав на YouTube, я нашел отличнейший плейлист, из которого мы возьмем видеоролики, где проводят сканирование, и разберем парочку:

Просмотрев начало любого видеоролика, вы увидите сканирование IP адреса машины утилитой Nmap. Давайте посмотрим команды, используемы в видеоролике, и найдем к ним справку. Это можно проделать почти с каждой командой.

Получение справки к каждой команде.
Чтобы создать данный курс, я установил Kali Linux на виртуальную машину: Настраиваем Kali linux + VirtualBox

Получить справку можно двумя способами:

1.jpg

С помощью man нам выводится подробнейшая документация на русском языке, которую мы можем изучить:

2.jpg

3.jpg

Здесь выводится краткая справка на английском:

4.jpg

У всех популярных команд есть официальный сайт с документацией. Официальная документация команды, которую мы сейчас рассматриваем находится по адресу: Справочное руководство Nmap (Man Page) | . Получив документацию, мы разберем команды, которые использовались в видеороликах.

5.jpg

У Nmap используется такой синтаксис:

1) -sC
В документации написано -script=default, что значит - запускать скрипт по умолчанию.
2) -sV
Исследовать открытые порты для определения информации о службе/версии.
3) -oA <базовове_имя_файла>
Сохраняет вывод Nmap в 3 файла с расширениями .nmap, .gnmap, .xml.
4) Nmap/Sunday
Место сохранения вывода. Папка/название файла
5) 10.10.10.76
Цель сканирования, IP адрес машины HTB.

И еще была команда с такой опцией:

6.jpg

1) -vvv
Максимум verbosity, так найденные порты будут показаны по ходу сканирования а не после завершения.
Эти опции вам придется использовать довольно часто, поэтому постарайтесь их запомнить.

Анализ вывода утилиты Nmap
Сейчас мы рассмотрим выводы Nmap у IppSec, а потом сами проведем сканирование.

Первый результат вывода.

7.jpg

В выводе мы видим открытые порты 79 и 111. Также важной информацией может быть операционная система и ее версия. В нашем случае данных о версии операционной системы нет, но это можно узнать. В следующей части мы тоже об этом поговорим. Кстати версия 5.11.

Второй результат вывода.

Подключение к VPN
1) Скачиваем файл конфигурации OpenVPN

9.jpg

2) Установка файла конфигурации (Kali Linux)
Для начала мы переходим в директорию, в которую скачали файл. И используем команду: openvpn [Вай ник].ovpn.

10.jpg

Никнейм замазан, чтобы мой аккаунт не забанили на HTB за нарушение правил. Не закрывая это окно, открываем новый терминал и начинаем сканирование. Перед этим выберем машину, среди рабочих я выбрал любую, которая стоит на Linux.

11.jpg

Самое простое, что можно сделать – это запустить Nmap без опций.
Nmap 10.10.10.150
Результат:

12.jpg

nmap -sC -sV -oA [папка/название файла] 10.10.10.150

13.jpg

Мы сразу видим вывод, но он сохранился и в нашу папку. Это удобно, когда мы работаем с большими файлами, поскольку в редакторе можно легко проводить поиск нужной вам информации. Посмотреть записанный вывод можно командой:
Less [имя файла].nmap

Теперь разберем вывод:

14.jpg

1) Открытый SSH порт.
Здесь используется 22 порт, который обычно стоит по умолчанию. Есть вероятность того, что SSH настроен с ошибками, и тогда мы сможем легко получить доступ, хотя такое бывает редко.

3) Информация о версии ОС.
Информация о версии ОС будет очень полезна для поиска эксплоита, чтобы получить Root доступ. Поиск и работу с эксплоитами мы разберем позже.

Узнаем версию Joomla
Введя в поиск «Определение версии Joomla», мне сразу же высветились множества сайтов. Вот один из них: Как узнать, определить версию Joomla на чужом сайте?

Прочитав, можно понять, что нам надо перейти: domain_name/language/en-GB/en-GB.xml.

Переходим по ссылке, и видим версию Joomla:

15.jpg

Тут еще хранится email админа, но в этой машине он нам не понадобится.

Результат выглядит примерно так:

16.jpg

Помочь собрать нам побольше информации поможет нам Nikto. На портале Codeby есть статья на эту тему: ХА. НАШЕЛ УЯЗВИМОСТЬ. - Или использование Nikto. Используя команду: nikto -host адрес утилита проведет комплексную проверку на интересные файлы и ошибки. Используя ее, готовьтесь ждать от 15 минут. Вот результат вывода моей программы:

17.jpg

  • Какими двумя способами можно получить справку в командной строке linux?
  • Какие опции в основном используются в Nmap?
  • Какой порт использует SSH по умолчанию?
  • Что делает утилита Nikto?
  • Что такое SSH?*
  • На каких сайтах есть эксплоиты и их описание?*
  • Что такое XSS атака и какие разновидности бывают?*

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

В случае непонимания уязвимости, я с радостью готов помочь вам. (Не отвечаю, если ответ на ваш вопрос есть в гугле)

На выбор у нас есть 3 площадки:

BWAPP
Моя любимая площадка. Именно её я выбрал, когда обучался использовать веб уязвимости. Позже я объясню почему.

DVWA
Площадку создали британские специалисты. Очень схожий функционал с BWAPP. Ещё мне очень понравилась их страница wiki: ethicalhack3r/DVWA.

Mutillidae
Созданная платформа специалистом по ИБ. Сам создал эту платформу. Хорошо читаемый и закомментированный код позволяет новичку легко разобраться.

OWASP Top 10
Для начала проведем обзор этих 10 уязвимостей:

image30.jpg

Мы рассмотрим установку и настройку площадки BWAPP, после чего пройдём несколько уровней.

  • Установка на локальный сервер
  • Установка виртуальной машины bee-box

Установка на локальный сервер
Мы будем использовать XAMPP. Сейчас это одна из самых лучших программ. Если у вас есть свой локальный сервер, то можете пропустить эту часть.

image1.jpg

У вас откроется такое окно. Теперь в меню пуск у вас есть папка XAMPP. В ней будет XAMPP htdocs folder. Вам нужно нажать на нее.

image11.jpg

Все это нужно удалить. После этого вам нужно разархивировать bWAPP в эту папку. Получится так.

image17.jpg

После этого вы должны зайти в bWAPP → admin → settings.php. И открыть через текстовый редактор.

Сделайте все так. После этого входите в панель XAMPP и нажимаете MySQL → Config.

image12.jpg

И вписываете там эту строку, после чего сохраняете.

Появится такая страничка:

image19.jpg

Нажмите на кнопку HERE. Установка на локальный сервер закончена.

Установка виртуальной машины bee-box
Чтобы установить bee-box вам потребуется установленный VirtualBox.

Установка:
Запускаем VirtualBox и жмем Создать.

image24.jpg

В открывшемся окне пишем название машины. Выбираем тип → Linux, версия → Ubuntu. Жмём далее.

image9.jpg

Количество оперативной памяти выбираем до 512 мб. Большее количество ничего не даст, а только замедлит ваш компьютер. Жмём далее.

image3.jpg

Нажимаем на жёлтую папку.

image6.jpg

Жмём на добавить, после чего выбираем скачанный виртуальный диск bee-box.vmdk. Жмём кнопку выбрать → создать.

image27.jpg

На этом установка завершена.

Запуск и использование:

Заходим в терминал.

image23.jpg

Командой ip a узнаем ip машины

image13.jpg

На основной машине введите в адресную строку ip адрес

image4.jpg

Проходим несколько первых уровней
Выбор нужного уровня и сложности
Уровень можно выбрать из выпадающего меню под названием “Choose Your Bug”, после чего надо нажать кнопку Hack, чтобы приступить к уровню.

У bWAPP есть 3 уровня сложности: low, medium, high. Изменить уровень сложности можно выбрав его и нажав кнопку Set в определенном уровне.

image14.jpg

HTML Injection - Reflected (POST)

image25.jpg

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

image10.jpg

XML/XPath Injection (Login Form)
XPath — язык запросов для XML документов, в общем похожий на SQL для баз данных. При уязвимостях на сайте, вы можете залогиниться под любым пользователем, с любым правами.

image2.jpg

Вы можете использовать строку 'or'1’=’1 для того, чтобы залогиниться под первым пользователем в файле, где хранятся данные от всех пользователей.

image29.jpg

CSRF (Change Password)

На данном скриншоте у формы есть уязвимость XSS, теперь сгенерируем ссылку для CSRF уязвимости, чтобы изменить пароль для пользователя. Я вошёл в bWAPP, как bee с паролем bug, теперь мы попытаемся изменить его с помощью межсайтового скриптинга. Данной строкой мы изменяем свой пароль на lol. Отправив такую ссылку пользователю, вы меняете его пароль на свой, что повлечет большие проблемы.

?password_new=lol&password_conf=lol&action=change

image15.jpg

image16.jpg

Изучение кода
Важно. Это возможно только при установке bWAPP на локальный сервер.

Изучение кода необходимо для самостоятельного нахождения уязвимостей. Чтобы найти файл с кодом, смотрим на адресную строку и видим, что мы находимся в файле с названием htmli-post.php

image22.jpg

Заходим в папку с bWAPP и ищем этот файл.

image5.jpg

Теперь ищим в файле функцию фильтрации содержимого. В нашем случае это xss_check_1.

Теперь перейдем к файлу, в котором находятся все функции фильтрации содержимого - functions-external.php.

image7.jpg

Теперь, с помощью функции поиска в редакторе кода (обычно вызывается сочетанием клавиш ctrl + f) находим xss_check_1. Тут у нас есть краткая информация о том, что фильтрует функция.

image21.jpg

Так, например, вы можете вбить в google: “Как обойти фильтрацию функцией str_replace?”, и пройти уровень.

Задание
Практика нахождения уязвимостей. Вам стоит провести все атаки от A1 до A10. В интернете полно информации о многих уязвимостях, в то время, как о других нет ни слова.

Highlights

On the Machines/Boxes page, you will see the highlighted Boxes at the top. These can be any number of highlights, such as the staff pick, the next Box to retire, and the newly announced Box for the week.


For the Boxes that have an upcoming launch date announced, there will be a timer to the actual release of the Box along with some basic information about it.

For the Boxes that have a retiring date set, there will also be a timer until retirement along with the option to Play Machine, which will start an instance of that machine on your selected VPN server.

Picking a Box to play on

Once you get accustomed to the line-up interface, you can pick a machine that you’d like to tackle. In this example, we’ll be using Sauna.

Note that some of the items you will see here will be restricted to VIP accounts. You will not need to start up or stop the machine to play it for a free user account.

You can find the general Box information in the header at the top. This will display the logo and name of the box, the difficulty rating, and the number of points offered upon completion for the box.


You can find the Box state, control buttons, and other links on the left of the page. If you’re a VIP user, you can start or stop the Box from here.

All other users can add the Box to their To-Do List, submit a review of it or visit the Forum link associated with it.

The Forum Thread link should be handy to beginners as this is where You can find posts about certain challenging tasks within the machine.


On the main section of the Machine page, you can find the tabs related to general information, statistics, activity of other users, changelog for this Box, other users' reviews, and walkthroughs (once this Box retires).

Take your time getting accustomed to each of them before proceeding.

The IP address of the Box can be seen below the machine state, on the left-hand side. For VIP users, this IP address will only become visible after the machine is powered on.


Machine difficulties

Machines/Boxes come in four separate difficulty levels; Easy, Medium, Hard, and Insane.

They are named appropriately and have their own respective logo language:





Submitting found flags

Once you’ve found a flag, submit it immediately! There is a flag rotation mechanism in place, and if someone resets the Box, you can lose all progress on your current instance as the instance will boot up from scratch, and the flag will be rotated.

To submit a flag, you can press the Submit Flag button on the status section.


Please note that you will be required to rate the Machine before the platform lets you press the Submit Flag button.

Extending a Machine’s time

Any instance on any VIP server has a lifetime. Once this lifetime expires, the Box is automatically shut off. If you are in the process of attacking an already close-to-expiry instance and wouldn’t like to be interrupted by it shutting down, you can extend the Box’s time. This will give you ownership over that instance and extend the lifetime to a maximum of 24 hours.


Menus

There are three menus that you can select from to filter through the Boxes lineup.

Active Boxes

Retired Boxes

Boxes To-Do List

Active Machines

The Active Machines list displays the Boxes available to everyone, both VIP and free account users.

In the case of VIP users, these, like any other Box, will need to be booted up by the user attempting to attack them. In the case of free users, these Boxes will always be online on their respective Free Lab VPN servers.

Retired Machines

The Retired Machines list displays the Boxes that have been retired and offer no more points upon completion. However, these Boxes provide both the official and user-submitted write-ups for the educational advancement of users. You can use these write-ups to learn how to tackle the Box and how different services and setup configurations can be abused to access a vulnerable system.

The list is split into two sections. The Free Retired Machines section contains a shortlist of recently retired Boxes made available to free users. The Boxes on this list are the only retired Boxes that you can play without a VIP subscription.

The VIP Retired Machines section contains all retired Boxes, including the few available to free users.


Machines To-Do List

The Machines To-Do List contains Boxes (both Active and Retired) that you’ve added to your own personal to-do list. To find out more about how to add a Box to your to-do list, please read below.

GS: How to play Machines

Following the new version of the Hack The Box platform, we are putting out guides on how to navigate the new interface.

Whether you’re a new player or a veteran in Hack The Box, this guide will give you some useful tips and guidance on how to play Machines (commonly referred to as Boxes) in the new platform design.

Booting up OpenVPN

To play Boxes, you must be connected to a VPN through your virtual machine.

After you click the Download button, your pack.ovpn file should be found, by default, in the Downloads folder of your Linux distro. You will be using this file as the configuration for your OpenVPN initialization process.


Open up a terminal and navigate to your Downloads folder.

Then, boot up the OpenVPN initialization process using your pack.ovpn as the configuration file.


Once the Initialization Sequence Completed message appears, you can open a new terminal tab or window and start attacking the boxes.

Please note that you will need to keep this terminal window open to keep the OpenVPN process running.

If you encounter any issues related to your VPN configuration, we have an article dedicated to troubleshooting VPN connection issues.

Check out the article below to start troubleshooting:

Below you can find an explanation of all the VPN control menus:

Access

Under the Access menu, you can select from all the different available labs for the main Boxes lineup. This includes both free and VIP servers, the latter now including the much-requested AU VIP, SG Free, and SG VIP servers!

As a best practice, select the closest lab to you while also considering your account’s VIP status.

VIP servers will, of course, have fewer users on them as there are many more than just the free VPN servers. Fewer members mean less traffic and, more importantly, fewer people trying to attack the same Boxes as you.

Server

From the Server menu, you can select the actual VPN server you want to connect to. After this step, you should be able to download your .ovpn connection pack directly and proceed with engaging in attacks over the Boxes.

We have implemented this method of server selection instead of randomly assigning users to the least populated ones due to several requests for multiple teammates attacking the same Boxes on the same VPN server to compete against each other. We hope that this will further improve collaboration between teammates and bring your educational progress to the next level for both you and your team or organization!

Download

The button to the right of the Server selection menu is the Download button for your now newly generated .ovpn pack. Once clicked, it will initialize a download for your .ovpn pack, which you can use to start up the OpenVPN process on your Linux distro that will allow you to connect to the Boxes in our labs.

Regenerate

In the case where your .ovpn file might be incorrectly generated due to an error, you can regenerate the file by switching back and forth between the Servers on the lab you’ve selected. This will generate the new .ovpn file, which you can directly download to your OS.

If even after regenerating, the .ovpn file is still invalid, our support team would be happy to assist you!

Free account - Playing on a Box

If you’re using a free account, you only need to make sure your VPN is connected. You will not have the machine start/stop buttons because the Boxes on the active line-up for the free servers will be online at all times for you to attack.

Following the steps above, you should already have an .ovpn connection pack ready and waiting in your

/Downloads folder. From there, you only need to boot up your OpenVPN session with the following command after navigating to the

/Downloads folder.


After you get the Initialization Sequence Completed message at the end of the OpenVPN log, you can open a new terminal tab and try to ping the box’s IP address.

Visiting the machine page, you can see all the required information, as seen above.

Filters

You can filter each of the above lists according to your needs. The filter options are listed as drop-down menus above the machine entries in the respective list. These consist of the following:


Status (Complete, Incomplete, both)

Sort By (Release Date, Name, User Owns, Systems Owns, Rating, User Difficulty)

Difficulty (Easy, Medium, Hard, Insane)

OS (Linux, Windows, FreeBSD, Other)

You can also use the Advanced Search on the Retired Machines menu. This will allow you to filter in more detail according to the Attack Path, Attack Sub, and Programming Languages used during the attacks.

Remember to clear your filters if you’re looking for a certain Box that you can’t find!

Reviewing a Machine

We highly encourage everyone to participate in the development of future Boxes in Hack The Box by posting their opinions about the current ones that they are tackling! Once a Box is owned by you, you can submit your review by clicking the Review Machine button.

Читайте также: