• XSS.stack #1 – первый литературный журнал от юзеров форума

Статья Chum Bucket. Как я взломал 20-миллиардную корпорацию с помощью бесплатного сервиса

tabac

CPU register
Пользователь
Регистрация
30.09.2018
Сообщения
1 610
Решения
1
Реакции
3 332
Новостные сообщения о регулярных утечках данных — дело привычное. Однако каждому такому инциденту предшествует кропотливая работа: сбор и анализ информации, поиск брешей в защите и инструментов для атаки. Сегодня я расскажу о том, как взломал двадцатимиллиардную корпорацию TUI Group при помощи общедоступных бесплатных инструментов и природной смекалки.
Reconnaissance, или сбор информации, — это первый этап тестирования на проникновение, когда цель уже определена. Понемногу этот этап превратился в отдельную науку, объединив в себе целый комплекс тактик и методик, а также обзавелся множеством инструментов и сервисов, упрощающих рутину. Какие возможности это нам открывает?
  1. Охота без конкретной цели или «нанимателя».
  2. Поиск новых масштабных угроз.
  3. Быстрая оценка распространенности конкретной угрозы.
  4. Нетсталкинг и просто исследование ради развлечения.
Дальше я перечислю самые популярные сервисы, с помощью которых можно провести полноценные исследования, и продемонстрирую основные приемы работы с ними. Однако главной темой статьи будет сервис grayhatwarfare.com, с помощью которого я и взломал корпорацию TUI Group.


Ресурсы
Сервисы для сбора информации можно условно разделить на несколько категорий — по типу предоставляемых данных или по сферам применения. Перечислим наиболее известные из них.
  • Certificate Transparency — реестр привязанных к доменным именам цифровых сертификатов, в том числе и самых свежих, включая субдомены.
  • Chaos, dnsdb.info, intelx.io, securitytrails.com, Сertspotter, threatminer.org, crt.sh — базы данных доменных имен, сертификатов и всей остальной информации, связанной с доменами.
  • OpenIntel — отслеживает состояние глобальной системы доменных имен.
  • Internet-Wide Scan Data Repository — это публичный репозиторий результатов сканирования интернет-протоколов, сервисов и служб по всему интернету. Хостится командой ZMap. Помимо своих собственных датасетов, команда аккумулирует и выкладывает данные и других похожих проектов. Этот ресурс — отличная возможность поработать с сырыми и полными данными.
  • Rapid7 OpenData — то же самое, что и выше, только от создателей Metasploit Framework.
  • Shodan, Zoomeye, Censys, fofa.so, riddler.io, spyse.com, thingful.net — поисковики, которые исследуют почти всю топологию интернета, предоставляя возможность поиска по баннерам сервисов и протоколов, их хешам или содержанию HTML-страниц. С их помощью можно найти подключенные к сети устройства или работающие приложения различных типов. В недавнем обновлении в Shodan появилась даже возможность поиска по идентификационным номерам уязвимостей.
  • CommonCrawl — репозиторий многофункционального веб-краулера, собирающего массу интересной информации.
  • GreyNoise, BinaryEdge, cybergreen.net, projecthoneypot.org — просто кладезь знаний о текущих угрозах! Если ты не знаешь, что исследовать, или хочешь быть в курсе самых актуальных уязвимостей, тебе сюда. Тренды и топ-листы GreyNoise расскажут о техниках, которые, возможно, еще даже не были обнаружены специалистами ИБ, но активно эксплуатируются в реальном времени.
  • GrayHatWarfare — находит открытые для публичного доступа серверы Amazon AWS. Использует при поиске сразу несколько опенсорсных инструментов для сканирования, агрегируя все результаты. На данный момент GrayHatWarfare насканировал 279 тысяч доступных S3-бакетов и 4,5 миллиона файлов!
Подобных ресурсов достаточно много, и некоторые я даже специально пропустил — например, psbdmp.ws — из-за их чересчур узкой специализации. Однако сканировать весь интернет самостоятельно уж слишком долго и трудоемко. На гитхабе можно найти большой арсенал инструментов, адаптированных для работы почти с каждым из упомянутых сервисов. Но я постараюсь обратить твое внимание на упущенные кейсы и пробудить порыв к новаторству!

В конце статьи я кратко расскажу о моих экспериментах с, казалось бы, банальным Shodan. Ты, наверное, даже слышал об их последствиях, об этом писали и в «Хакере». Я свято верю, что не нарушил никаких законов, так что смело раскрою свое авторство и некоторые оставшиеся за кадром подробности.


Кто чем занят
Если вспомнить большинство громких утечек за последние год-полтора, то можно выделить современные тенденции и цели атакующих. Я их перечислю:
  • серверы MongoDB;
  • Rsync-демоны;
  • Elasticsearch;
  • DigitalOcean;
  • Azure Blobs;
  • Google Storage.
Очевидно, под угрозой в основном плохо настроенные серверы и приложения, в которых авторизация зачастую отсутствует вовсе. Для сканирования используются все те же инструменты с открытым исходным кодом, которые можно найти на гитхабе, так что я не стану их перечислять. Некоторые атакующие используют для поиска Shodan, другие сканируют сеть самостоятельно.

Я не добавил AWS S3-бакеты в список неслучайно. Если посмотреть хронологию утечек информации из бакетов, то можно заметить явное снижение зафиксированных после 2018 года инцидентов. Этому поспособствовал ряд причин: шумиха, принятые Amazon меры, вооруженные сканерами баг-хантеры и так далее.

Конечно, можно купить хостинг, обзавестись новейшим софтом и принять участие в гонке сканеров, но мы не ищем легких путей! Подкрутить потоки и поковырять настройки какого-нибудь приложения может каждый, но самое интересное начинается там, где приходится использовать смекалку.


Обделенный Grayhat
Несмотря на обилие публикаций на тематических площадках, у довольно популярного и давно присутствующего на рынке GrayHatWarfare долго не было ни одного приложения или библиотеки для полноценной работы с предоставляемым им API. Все, что я нашел на гитхабе, — это криво написанный веб-парсер на python-mechanize.

Оказалось, этому есть причины: использование услуг этого сервиса стоит немалых денег, а условия бесплатного аккаунта не позволяют рассчитывать на достойный результат. Хотя я могу ошибаться. Язык запросов API настолько прост и лаконичен, что писать код по большому счету не нужно. Тем не менее я решил создать инструмент для работы с GrayHatWarfare, а вместе с этим реализовать многопоточность и обойти лимиты выдачи сервиса. Раз уж писать, то как следует!


Обходим ограничения бесплатного тарифа
Поиск по всем проиндексированным файлам ограничен 2000 результатов. Файлы же в обособленном бакете можно листать почти без ограничений, особенно когда мы ищем конкретные расширения файлов и используем исключающие ключевые слова. Так что я подменил один метод другим и реализовал перебор ID всех доступных бакетов. Таким образом, поиск всех имеющихся файлов с расширением .zip займет всего 20–30 минут. Ровно столько времени у меня ушло, чтобы скормить API 91 тысячу реквестов без единого фейла!


Логика и инструкции поиска
Итак, мы можем искать файлы с любыми расширениями. Между тем в API предусмотрена возможность добавлять к запросам ключевые слова, но только исключающие, иначе поиск ломается. Эти слова проверяются в каждой отдельной части полного URL-адреса искомого файла. Такой радикализм оправдан. В бакетах куча мусора типа медиафайлов, фронтенда и всяких опенсорсных бэкенд-модулей. Однако не бойся экспериментировать: все отброшенные урлы все равно запишутся в отдельный файлик trash.txt. Чтобы добавить свои собственные исключающие ключевики, сохрани их в файл exclude.txt.

Найденные файлы можно фильтровать и по размеру. Он указывается во время запуска программы. Чтобы запустить приложение, выполни в терминале следующие команды:
Код:
~$ git clone https://github.com/d34db33f-1007/grayhat2.git
~$ cd grayhat2 && python3 main.py
Деньги есть, ума не надо!
Фильтрация файлов по размеру — встроенная фича GrayHatWarfare API, но исключительно для оплаченных аккаунтов. В нашей реализации программы мы можем получать размеры файлов нативным образом только потому, что по факту мы не выполняем поиск, а просто листаем содержимое бакетов одно за другим.

Выходит, любой пользователь с оплаченным аккаунтом может просто запросить у API «топ-1000» самых тяжелых файлов, которые нередко и оказываются набором пользовательских данных, то есть пресловутой «утечкой». Значит, искать там больше нечего? А вот и нет!


Убиваем мейнстрим
Я попытался искать с помощью GrayHatWarfare файлы .csv тяжелее 500 Мбайт. Среди них попадались интересные находки, но их оказалось недостаточно, чтобы ликовать и праздновать победу.

Второе, что мне пришло в голову, — это поиск приватных RSA/SSH-ключей. Вот тут мне повезло! Я проверил по очереди два расширения файлов: .priv и .key. К моему удивлению, уже через час после того, как я накатал на коленке свой питоновский скрипт, я обнаружил сразу три утечки! Как известно, беда не приходит одна. На серверах с приватными ключами я также нашел следующее:

  • пользовательские данные фитнес-приложения с миллионом установок в Play Market;
  • секретный токен аккаунта Amazon AWS от некоего uland.com.br;
  • и самое стоящее — секретный токен Amazon AWS и приватный SSH-ключ веб-приложения Musement.com. Это итальянский стартап изначальной стоимостью в 60 миллионов долларов, теперь принадлежащий корпорации TUI Group.
По первым двум инцидентам мне не удалось связаться с владельцами ресурсов, но я уведомил Google и Amazon о произошедшем, хотя четкого ответа также не последовало. В TUI Group мне ответили на следующий день после обращения и залатали дыру уже спустя неделю.

Дальше я поэтапно опишу, как получил полный доступ с правами суперпользователя к продакшен EC2-инстансу Musement. Забавно, что такой очевидный инцидент до сих пор оставался незамеченным. Это тревожный звоночек: если тенденция стала мейнстримом, лучше всего ее избегать.


Первые результаты. Что дальше?
Разработчики любезно оставили нам ключи

Разработчики любезно оставили нам ключи

Собрав access-ключики, которые разработчики так любезно оставили в своем питоновском скрипте, я успешно авторизовался в аккаунте Amazon. Попробовав выполнить разные команды, я понял, что у меня имеется доступ только на чтение, причем далеко не везде. К тому же сервер, к которому я хотел подключиться по SSH, разрешал соединения только с IP-адресов из белого списка.


Собираем всю информацию об инфраструктуре
Недолго думая, я нашел на гитхабе популярный awesome-лист, посвященный пентесту Amazon, и начал с самого простого. Первым делом я собрал все публичные адреса EC2-машин, а также все IP-адреса из политик NACL (Network Access Control List) с помощью утилиты aws_public_ips. В сумме набралось где-то тридцать адресов.

Собранные адреса я начал сканировать на наличие открытых портов в диапазоне 1–64 000 с помощью утилиты masscan. Пока шло сканирование, я запустил еще две классические утилиты, которые позволяют получить более обширную и подробную информацию об имеющейся в твоем распоряжении облачной инфраструктуре:
  • ScoutSuite2 — аудитор безопасности AWS. Незаменимый инструмент, который заглянет в каждый уголок облака и создаст максимально удобный для изучения отчет;
  • pacu — то же самое, но заточен именно на поиск и эксплуатацию уязвимостей в облаке, в том числе на повышение привилегий, персистенцию, да и постэксплуатацию в целом.
Результаты оказались неожиданно приятными. Даже несмотря на то, что SGP (Security Group Policies) и IAM-права для утекшего аккаунта были настроены корректно. Для начала pacu нашел способ повысить привилегии, пользоваться которым мне не позволяют этические принципы. Метод заключался в эксплуатации уязвимости CloudTrail CSV Injection. Имея возможность создавать trail (грубо говоря, события), я мог попытаться создать trail с вредоносной Excel-формулой в качестве названия. Эта попытка провалилась бы, но в логах осталось бы название. При импорте такого лога в формате .csv в Excel возникает опасность выполнения вредоносного кода на машине администратора.

ScoutSuite удивил меня еще больше. Ниже приведены частичные примеры того, что он смог нарыть в облаке.

Учетные данные суперпользователей в Tomcat-сервере

Учетные данные суперпользователей в Tomcat-сервере

Некоторые лицензионные ключики

Некоторые лицензионные ключики

Спокойно брутим Basic HTTP auth ;)

Спокойно брутим Basic HTTP auth

Кроме того, на самом S3-бакете лежали очень интересные бэкенд-файлики. В общей сумме я смог вытянуть из пользовательских данных EC2-машин где-то 400 с лишним скриптов и конфигов.

Обходим защиту AWS SGP
Результаты сканирования EC2-машин

Результаты сканирования EC2-машин

Результаты сканирования внешних IP-адресов EC2-машин не сильно радовали, пока я не обнаружил роутеры с дефолтными админ-паролями и функцией VPN.
Код:
93.62.224.145   ::   Huawei AR Web Platform
93.62.224.151   ::   Huawei AR Web Platform
Главное достоинство этих роутеров заключалось в том, что они находились в белом списке NACL для входящего и исходящего трафика по всем портам, включая SSH, а также позволяли маршрутизировать трафик сквозь себя.

Роутеры позволяли маршрутизировать трафик

Роутеры позволяли маршрутизировать трафик

Теперь я мог спокойно подключиться к главному продакшен-серверу с root-правами, используя найденный приватный SSH-ключ.
Подключаемся к главному продакшен-серверу

Подключаемся к главному продакшен-серверу

Более подробные сведения о различиях между SGP и NACL

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

Для меня этот опыт — неприятное напоминание о том, что часто IT-компании ориентируются на гигантов индустрии, но игнорируют аспекты, связанные с безопасностью своего продукта и конечных пользователей. Поэтому давай сделаем мир безопаснее общими усилиями!


Не бакетами едиными!
Уже качаешь очередной hawkeye? Вот и правильно! Но не вздумай останавливаться на серых шляпах: попробуй совместить Google-дорки с Shodan’ом или поиграть с его родными тегами в трендах. Из этой затеи вполне может получиться что-нибудь интересное.

«Хакер» в этом году писал об уязвимых видеорегистраторах LILIN. Эти уязвимые регистраторы изначально нашел я, заинтересовался и начал реверсить. Поэтому ответственно заявляю: в Qihoo 360 нагло приврали о количестве уязвимых устройств. На самом деле их было не 5К, а более 300К. Вот оригинальный дорк:
Код:
http.html_hash:"1640961097"

В итоге мне даже удалось продать найденные баги. Продавать я их пытался на легальных площадках вроде Zerodium, но не везде они котировались. Видимо, информация об уязвимости утекла в паблик с одной из таких платформ. В моем гитхабе ты можешь найти больше информации об этом инциденте.

Еще «Хакер» как-то писал об умных, но уязвимых колонках Sonos. Да, и тут без меня не обошлось :) Потенциал открытых данных безграничен! Особенно — если проявлять смекалку при использовании общедоступных инструментов OSINT.

Автор @d34db33f
telegram @asleep_cg
 
Утечку компания пофиксила быстро, но, к сожалению, ни вознаграждения, ни даже банальной благодарности я от них не получил. Вместо этого мне сообщили, что на меня не станут подавать в суд
какие же жадные ушлепки) сорри
 
Прикольно. К стати, не знал про сервис Fofa. Сравнил его с Shodan. У Fofa нашлось больше результатов, чем у Shodan по имени домена. Однозначно, добавляю в закладки.
 
Отличная статья! ?

Утечку компания пофиксила быстро, но, к сожалению, ни вознаграждения, ни даже банальной благодарности я от них не получил.
Все правильно сделали. ? Ибо как вас упоротых робингудов еще лечить?!

Вместо этого мне сообщили, что на меня не станут подавать в суд
А это зря. ? Ибо как вас упоротых робингудов еще лечить?!
 
Пожалуйста, обратите внимание, что пользователь заблокирован
News reports of regular data breaches are commonplace. However, each such incident is preceded by painstaking work: collecting and analyzing information, looking for security holes and tools for attack. Today, I'm going to talk about how I hacked the $ 20 billion TUI Group using publicly available free tools and natural ingenuity.
Reconnaissance, or information gathering, is the first stage of penetration testing when the target has already been identified. Gradually, this stage turned into a separate science, combining a whole range of tactics and techniques, and also acquired many tools and services that simplify the routine. What opportunities does this open to us?
  1. Hunting without a specific target or "employer".
  2. Search for new large-scale threats.
  3. A quick assessment of the prevalence of a specific threat.
  4. No stalking and just exploration for fun.
Next, I will list the most popular services with which you can conduct full-fledged research, and demonstrate the basic techniques for working with them. However, the main topic of the article will be the grayhatwarfare.com service , with the help of which I hacked the TUI Group corporation.


Resources
Services for collecting information can be conditionally divided into several categories - according to the type of data provided or according to areas of application. Let's list the most famous of them.
  • Certificate Transparency is a registry of digital certificates linked to domain names, including the most recent ones, including subdomains.
  • Chaos , dnsdb.info , intelx.io , securitytrails.com , Сertspotter , threatminer.org , crt.sh - databases of domain names, certificates and all other information related to domains.
  • OpenIntel - Monitors the state of the global domain name system.
  • The Internet-Wide Scan Data Repository is a public repository of scan results for Internet protocols, services, and services across the Internet. Hosted by the ZMap Team . In addition to their own datasets, the team accumulates and uploads data from other similar projects. This resource is a great opportunity to work with raw and complete data.
  • Rapid7 OpenData - Same as above, only from the creators of the Metasploit Framework .
  • Shodan , Zoomeye , Censys , fofa.so , riddler.io , spyse.com , thingful.net are search engines that explore almost the entire topology of the Internet, providing the ability to search by banners of services and protocols, their hashes or the content of HTML pages. They can be used to find devices connected to the network or running applications of various types. In a recent update, Shodan even has the ability to search by vulnerability ID numbers.
  • CommonCrawl is a multipurpose web crawler repository that collects tons of interesting information.
  • GreyNoise , BinaryEdge , cybergreen.net , projecthoneypot.org are a treasure trove of knowledge about current threats! If you don't know what to investigate, or want to keep abreast of the most pressing vulnerabilities, this is the place for you. GreyNoise trends and top lists will tell you about techniques that may not have even been discovered by information security specialists yet, but are actively exploited in real time.
  • GrayHatWarfare - Finds publicly accessible Amazon AWS servers. It uses several open source scanning tools when searching, aggregating all the results. So far GrayHatWarfare has scanned 279k available S3 buckets and 4.5 million files!
There are a lot of such resources, and I even specifically skipped some - for example, psbdmp.ws - because of their overly narrow specialization. However, scanning the entire Internet on your own is too time-consuming and laborious. On github, you can find a large arsenal of tools adapted to work with almost every of the mentioned services. But I will try to draw your attention to the missed cases and awaken the impulse to innovate!

At the end of the article, I will briefly talk about my experiments with the seemingly banal Shodan. You've probably even heard about their consequences, they wrote about it in "Hacker". I firmly believe that I have not violated any laws, so I will boldly disclose my authorship and some details left behind the scenes.


Who is doing what
If we recall most of the high-profile leaks over the past year and a half, then we can highlight the current trends and goals of the attackers. I will list them:
  • MongoDB servers;
  • Rsync daemons;
  • Elasticsearch;
  • DigitalOcean;
  • Azure Blobs;
  • Google Storage.
Obviously, the threat is mainly poorly configured servers and applications, in which authorization is often absent. All the same open source tools that can be found on github are used for scanning, so I will not list them. Some attackers use Shodan to search, others scan the network on their own.

It's no coincidence that I haven't added AWS S3 buckets to the list. If you look at the chronology of information leaks from buckets , you can see a clear decrease in incidents recorded after 2018. A number of reasons contributed to this: the hype, the measures taken by Amazon, the bug hunters armed with scanners, and so on.

Of course, you can buy hosting, get the latest software and take part in the scanner race, but we are not looking for easy ways! Anyone can tweak the streams and tweak the settings of an application, but the most interesting begins where you have to use ingenuity.


Disadvantaged grayhat
Despite the abundance of publications on thematic sites, the rather popular and long-standing presence on the market, GrayHatWarfare, for a long time did not have a single application or library to fully work with the API provided by it. All I found on github is a crookedly written web parser in python-mechanize.

It turned out that there are reasons for this: using the services of this service costs a lot of money, and the conditions of a free account do not allow you to count on a decent result. I could be wrong though. The API query language is so simple and concise that you don't need to write any code. Nevertheless, I decided to create a tool for working with GrayHatWarfare , and at the same time implement multithreading and bypass the service delivery limits. Since I'm writing, it's how it should


Bypassing the restrictions of the free plan
Search for all indexed files is limited to 2000 results. Files in a separate bucket can be scrolled almost without restrictions, especially when we are looking for specific file extensions and use excluding keywords. So I replaced one method for another and implemented an iteration over the IDs of all available buckets. Thus, searching for all available .zip files will take only 20-30 minutes. It took me exactly so much time to feed the API 91 thousand requests without a single failure!


Search logic and instructions
So, we can search for files with any extensions. Meanwhile, the API provides the ability to add keywords to queries, but only exclusive ones, otherwise the search breaks. These words are checked against every single part of the full URL of the file you are looking for. Such radicalism is justified. Buckets contain a lot of garbage like media files, frontend and all sorts of open source backend modules. However, don't be afraid to experiment: all discarded urls will still be written to a separate file trash.txt. To add your own exclusion keywords, save them to the exclude.txt file.

Found files can be filtered by size. It is indicated during the start of the program. To start the application, run the following commands in the terminal:
Код:
 ~ $ git clone https://github.com/d34db33f-1007/grayhat2.git
~ $ cd grayhat2 && python3 main.py [/ CODE]
[SIZE = 6] [B] There is money, no mind! [/ B] [/ SIZE]
File size filtering is a built-in feature of the GrayHatWarfare API, but only for paid accounts. In our implementation of the program, we can get the file sizes in a native way only because in fact we are not performing a search, but simply leafing through the contents of the buckets one by one.

It turns out that any user with a paid account can simply request from the API "top 1000" of the heaviest files, which often turn out to be a set of user data, that is, the notorious "leak". So there is nothing more to look for? But no!


[SIZE = 5] [B] Killing the mainstream [/ B] [/ SIZE]
I tried to search with GrayHatWarfare for .csv files heavier than 500MB. Among them, there were interesting finds, but they were not enough to rejoice and celebrate the victory.

The second thing that came to my mind was looking for private RSA / SSH keys. Here I was lucky! I checked in turn two file extensions: .priv and .key. To my surprise, within an hour after I rolled my Python script on my knee, I found three leaks at once! As you know, trouble does not come alone. On servers with private keys, I also found the following:

[LIST]
[*] fitness app [URL = 'https: //buckets.grayhatwarfare.com/bucket/13813/0? keywords = mailing_report_20170704.csv'] user data [/ URL] with a million installs in the Play Market;
[*] [URL = 'https: //buckets.grayhatwarfare.com/bucket/64338/0? Keywords = credentials.csv'] a secret token of an [/ URL] Amazon AWS account from a certain [URL = 'http : //uland.com.br/ '] uland.com.br [/ url];
[*] and the most worthwhile is the Amazon AWS secret token and the [URL = 'https: //www.musement.com/'] Musement.com [/ URL] web application private SSH key. It is a $ 60 million Italian startup now owned by the TUI Group.
[/ LIST]
For the first two incidents, I was unable to contact the resource owners, but I notified Google and Amazon about the incident, although there was also no clear answer. The TUI Group responded to me the day after the appeal and patched the hole a week later.

Next, I will describe step by step how I got full access with superuser rights to the production EC2 Musement instance. It's funny that such an obvious incident has gone unnoticed until now. This is a wake-up call: if a trend has gone mainstream, it's best to avoid it.


[SIZE = 6] [B] First results. What's next? [/ B] [/ SIZE]
[IMG alt = "The developers have kindly left us the keys"] https://st768.s3.eu-central-1.amazonaws.com/3a0b4b37117c08bcd1dc8e4b54c00578/14637/1.png [/ IMG]
[I] The developers have kindly left us the keys [/ I]

After collecting the access keys that the developers so kindly left in their Python script, I successfully logged into my Amazon account. After trying to execute different commands, I realized that I have read-only access, and not everywhere. In addition, the server I wanted to SSH to only allowed connections from whitelisted IP addresses.


[SIZE = 5] [B] We collect all information about the infrastructure [/ B] [/ SIZE]
Without thinking twice, I found a popular Amazon penetration test [URL = 'https: //github.com/toniblyx/my-arsenal-of-aws-security-tools'] awesome list [/ URL] on github and started with the simplest. First, I collected all the public addresses of EC2 machines, as well as all IP addresses from the NACL (Network Access Control List) policies using the aws_public_ips utility. In total, there were about thirty addresses.

I started to scan the collected addresses for open ports in the range 1–64,000 using the masscan utility. While the scan was in progress, I launched two more classic utilities that allow you to get more extensive and detailed information about the cloud infrastructure at your disposal:
[LIST]
[*] [URL = 'https: //github.com/nccgroup/ScoutSuite'] ScoutSuite2 [/ URL] is an AWS Security Auditor. An indispensable tool that will look into every corner of the cloud and create the most convenient report for studying;
[*] [URL = 'https: //github.com/RhinoSecurityLabs/pacu'] pacu [/ URL] - the same thing, but it is [URL = 'https: //github.com/RhinoSecurityLabs/pacu'] geared [/ URL] specifically to finding and exploiting vulnerabilities in the cloud, including privilege escalation, persistence, and post-exploitation in general.
[/ LIST]
The results were surprisingly pleasant. Even though SGP (Security Group Policies) and IAM rights for the leaked account were configured correctly. To begin with, pacu found a way to elevate privileges that ethical principles would not allow me to use. The method consisted of exploiting the CloudTrail CSV Injection vulnerability. Having the ability to create trail (roughly speaking, events), I could try to create a trail with a malicious Excel formula as its name. This attempt would have failed, but the name would remain in the logs. When importing such a log in .csv format into Excel, there is a danger of malicious code executing on the administrator's machine.

ScoutSuite surprised me even more. Below are partial examples of what he was able to dig up in the cloud.

[IMG alt = "Superuser credentials in Tomcat server"] https://st768.s3.eu-central-1.amazonaws.com/3a0b4b37117c08bcd1dc8e4b54c00578/14638/2.png [/ IMG]
[I] Superuser credentials in Tomcat server [/ I]

[IMG alt = "Some license keys"] https://st768.s3.eu-central-1.amazonaws.com/3a0b4b37117c08bcd1dc8e4b54c00578/14639/3.png [/ IMG]
[I] Some license keys [/ I]

[IMG alt = "Calmly brute force Basic HTTP auth;)"] https://st768.s3.eu-central-1.amazonaws.com/3a0b4b37117c08bcd1dc8e4b54c00578/14640/4.png [/ IMG]
[I] Calmly brute Basic HTTP auth [/ I]

In addition, the S3 bucket itself contained very interesting backend files. In total, I was able to pull out about 400+ scripts and configs from the user data of EC2 machines.

[SIZE = 6] [B] Bypassing AWS SGP Protection [/ B] [/ SIZE]
[IMG alt = "EC2 scan results"] https://st768.s3.eu-central-1.amazonaws.com/3a0b4b37117c08bcd1dc8e4b54c00578/14641/5.png [/ IMG]
[I] EC2 scan results [/ I]

The results of scanning the external IP addresses of EC2 machines were not very encouraging until I discovered routers with default admin passwords and VPN functionality.
[CODE] 93.62.224.145 :: Huawei AR Web Platform
93.62.224.151 :: Huawei AR Web Platform [/ CODE]
The main advantage of these routers was that they were on the NACL whitelist for incoming and outgoing traffic on all ports, including SSH, and also allowed traffic to be routed through themselves.

[IMG alt = "Routers allowed to route traffic"] https://st768.s3.eu-central-1.amazonaws.com/3a0b4b37117c08bcd1dc8e4b54c00578/14642/6.png [/ IMG]
[I] Routers allowed to route traffic [/ I]

Now I could safely connect to the main production server as root using the private SSH key I found.
[IMG width = "935px" alt = "Connecting to the main production server"] https://st768.s3.eu-central-1.amazonaws.com/3a0b4b37117c08bcd1dc8e4b54c00578/14643/7.png [/ IMG]
[I] Connecting to the main production server [/ I]

For more [URL = 'https: //docs.aws.amazon.com/vpc/latest/userguide/VPC_Security.html#VPC_Security_Comparison'] information about the differences between the SGP and NACL [/ URL]

[SIZE = 6] [B] Ethics as it is [/ B] [/ SIZE]
The company quickly fixed the leak, but, unfortunately, I received neither a reward, nor even a banal thanks from them. Instead, I was informed that they would not sue me, since during testing I followed the instructions they sent me by mail in response to my letter.

For me, this experience is an unpleasant reminder that often IT companies target industry giants, but ignore aspects related to the security of their product and end users. So let's make the world a safer place together!


[SIZE = 6] [B] Not single buckets! [/ B] [/ SIZE]
Already downloading another [URL = 'https: //github.com/Ice3man543/hawkeye'] hawkeye [/ URL]? That's right! But do not try to stop at gray hats: try to [URL = 'https: //www.exploit-db.com/google-hacking-database'] combine Google-dorks [/ URL] with Shodan or play with his native tags in trends. Something interesting may well come out of this venture.

The "hacker" wrote about vulnerable LILIN DVRs this year. I initially found these vulnerable registrars, became interested and began to reverse. Therefore, I declare responsibly: Qihoo 360 blatantly lied about the number of vulnerable devices. In fact, there were not 5K, but more than 300K. Here is the original dork:
[CODE] http.html_hash: "1640961097" [/ CODE]

As a result, I even managed to sell the found bugs. I tried to sell them on legal platforms like [URL = 'https: //zerodium.com/'] Zerodium [/ URL], but they were not quoted everywhere. Apparently, information about the vulnerability was leaked to the public from one of these platforms. You can find more information on this incident in [URL = 'https: //github.com/d34db33f-1007/'] my github [/ URL].

Another "Hacker" wrote about the smart but vulnerable Sonos speakers. Yes, and here it was not without me :) The potential of open data is limitless! Especially if you are smart about using the open source OSINT tools.

Author @ d34db33f
telegram @asleep_cg
[/ QUOTE] [/ CODE]
[/QUOTE]
nice information??
 


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх