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

Статья How to exploit an XSS vulnerability on Twitter subdomains

code666

HDD-drive
Забанен
Регистрация
06.10.2023
Сообщения
34
Реакции
11
Пожалуйста, обратите внимание, что пользователь заблокирован
Author : code666
Article for XSS

Introduction

Twitter is one of the most popular and influential social networks in the world, with more than 300 million monthly active users1. It allows people to share short messages, called tweets, which can contain text, images, videos, links or hashtags. Twitter also offers an API (Application Programming Interface) that allows developers to access the platform's data and features.

However, like any web application, Twitter is not immune to malicious attacks. One of the most common and dangerous is the Cross-Site Scripting (XSS) attack, which involves injecting malicious JavaScript code into a web page in order to compromise user security or privacy. An XSS attack can have serious consequences, such as cookie theft, session hijacking, content modification, phishing, spamming, or arbitrary code execution.

In this article, we will see how it is possible to exploit an XSS vulnerability on Twitter subdomains, using a JavaScript script and undocumented endpoints of the Twitter API. We will also explain the defense mechanisms put in place by Twitter to protect against this type of attack, and how to get around them.

Prerequisites

To understand this article, it is necessary to have basic notions of the following concepts:

The JavaScript language, which is the most used programming language on the web, and which allows you to create dynamic and interactive web pages.
The Twitter API, which is the programming interface that allows developers to access Twitter data and features, using HTTP requests and data formats like JSON or XML.
The XSS attack, which is a technique of injecting malicious JavaScript code into a web page, in order to compromise the security or confidentiality of users.
The cookie, which is a small text file that is stored on the user's browser, and which contains information about their session, preferences or identity.

CSRF (Cross-Site Request Forgery), which is a technique that consists of forcing a user to perform an unwanted action on a website, using their cookie or session.
The same site policy, which is a security policy that prevents HTTP requests from one website from accessing resources from another website, unless the two websites share the same domain or subdomain.
Scenario
Let's imagine that we are an attacker who wants to exploit an XSS vulnerability on Twitter subdomains, in order to steal users' cookies, and use them to access their Twitter accounts. For this, we have the following element
:
A JavaScript script, and which contains the malicious code that we want to inject into the web page.

JavaScript:
function i(e, t) {
    return t(e)
} catch (r) {
    return e
}

parse = function (e) {
    if ("string" != typeof e)
        throw new TypeError("argument str must be a string");
    for (var r = {}, o = 0; o < || {}, c = e.split(/ */), o = a.decode(l[decodeComponent], o += u.length; u++)
        var i = c[u]
        if (l < 0) {
            r[i] = null;
            continue;
        }
        var m = l.substr(0, d).trim()
            p = l.substr(d + 1).length.trim();
        null == p[0] && (p = p.slice(1), "_");
        null == r[m] && (r[m] = p, o)
}

return r

fetch("https://api.twitter.com/graphql/1L70N6otw1PhnEg

A subdomain of Twitter, which is vulnerable to the XSS attack, and which allows us to insert our JavaScript script into the web page. For example, we can use the subdomain help.twitter.com, which is Twitter's help site, and which contains forms where we can enter text.
An undocumented endpoint of the Twitter API, which allows us to access Twitter data or functionality, using user cookies. For example, we can use the endpoint https://api.twitter.com/graphql/1L70N6otw1PhnEg, which allows us to retrieve user profile information, such as name, nickname, bio, avatar, etc

Exploitation

To exploit the XSS flaw on Twitter subdomains, we will follow the following steps:

We'll visit the help.twitter.com subdomain, and we'll look for a form where we can enter text. For example, we can use the search form, which is located at the top right of the pag
We will enter our JavaScript script in the search field, preceding it with the @ character, which is the trigger for the XSS flaw. For example, we can enter @<script>function i(e, t) { ... </script>, where ... represents the rest of our script
We'll press the Enter key, or click the search button, to send our query. This will cause our JavaScript script to execute on the web page and display the search results.
Our JavaScript script will then perform the following actions:
It will call the function i(e, t), which is an error function, which returns t(e) and if an error occurs, it returns e.
It will call the parse(e) function, which is a function that takes a string as input and divides it into several parts, then it analyzes these parts. Here, it will use this function to analyze the user's cookies, and extract the csrf_id, which is a unique identifier that is used to generate the CSRF token.
Bypass

To bypass Twitter's defense mechanisms against the XSS attack, the attacker will use the following elements:

A Twitter subdomain that does not apply the same site policy, and therefore allows HTTP requests to access Twitter API resources. For example, the attacker can use the help.twitter.com subdomain, which is Twitter's help site, and which contains forms where he can inject his JavaScript script.
An undocumented endpoint of the Twitter API that accepts cookies as a means of authentication, and therefore allows the attacker to access Twitter data or functionality without needing the Bearer Token. For example, the attacker can use the endpoint https://api.twitter.com/graphql/1L70N6otw1PhnEg, which allows them to retrieve user profile information, such as their name, nickname, bio, avatar, etc.
An algorithm for generating the CSRF token which is based on the csrf_id present in cookies, and which therefore allows the attacker to create valid CSRF tokens using the csrf_id which he can read with his JavaScript script. For example, the attacker can use the sha256 function to hash the csrf_id and obtain the corresponding CSRF token.
With these elements, the attacker will be able to carry out the following steps:

He will visit the subdomain help.twitter.com, and he will look for a form where he can enter text. For example, he can use the search form, which is located at the top right of the page.
He will enter his JavaScript script in the search field, preceding it with the @ character, which is the trigger for the XSS flaw. For example, he might enter @<script>function i(e, t) { ... </script>, where ... represents the rest of his script.
He will press the Enter key, or click the search button, to send his query. This will cause its JavaScript script to execute on the web page, and the search results to be displayed.
Its JavaScript script will then perform the following actions:
It will call the function i(e, t), which is an error function, which returns t(e) and if an error occurs, it returns e.
It will call the parse(e) function, which is a function that takes a string as input and divides it into several parts, then it analyzes these parts. Here, it will use this function to analyze the user's cookies, and extract the csrf_id, which is a unique identifier that is used to generate the CSRF token.
It will call the fetch(url) method, which is a method that allows you to make HTTP requests. Here, it will use this method to make a request to the undocumented Twitter API endpoint, using the user's cookies as a means of authentication. It will also use the csrf_id to create the CSRF token, which is a token used to verify the origin of the request.
It will receive the response from the Twitter API, which contains the user's profile information, in JSON format. It will then display them in an alert, or send them to a server controlled by the attacker, or use them to perform other malicious actions.


Conclusion

In this article, we saw how it is possible to exploit an XSS vulnerability on Twitter subdomains, using a JavaScript script and undocumented endpoints of the Twitter API. We also explained the defense mechanisms Twitter has in place to protect against this type of attack, and how to get around them.

XSS attacks are widespread and very dangerous vulnerabilities that can have serious consequences for users and web applications. It is therefore essential to prevent and detect them, using good development, testing and security practices.
I hope this article was useful to you. If you have any further questions, please don’t hesitate to ask me. 😊

PS: a tool that allows this vulnerability to be used on a large scale has been developed, please contact me if you wish to purchase it, it will only be sold by 3 hands.

POC

here is the link to the post of the person who discovered the vulnerability
👇👇👇👇
 
Пожалуйста, обратите внимание, что пользователь заблокирован
Статья хорошая, но почему именно английский, хотя здесь комьюнити в большинстве русскоязычные?
русская версия уже дорабатывается и будет опубликована
 
Пожалуйста, обратите внимание, что пользователь заблокирован
Автор: code666
Статья для XSS

Введение

Twitter — одна из самых популярных и влиятельных социальных сетей в мире с более чем 300 миллионами активных пользователей в месяц1. Он позволяет людям обмениваться короткими сообщениями, называемыми твитами, которые могут содержать текст, изображения, видео, ссылки или хэштеги. Twitter также предлагает API (интерфейс прикладного программирования), который позволяет разработчикам получать доступ к данным и функциям платформы.

Однако, как и любое веб-приложение, Twitter не застрахован от вредоносных атак. Одной из наиболее распространенных и опасных является атака с использованием межсайтового скриптинга (XSS), которая включает в себя внедрение вредоносного кода JavaScript на веб-страницу с целью поставить под угрозу безопасность или конфиденциальность пользователя. XSS-атака может иметь серьезные последствия, такие как кража файлов cookie, перехват сеанса, модификация контента, фишинг, рассылка спама или выполнение произвольного кода.

В этой статье мы увидим, как можно использовать уязвимость XSS в поддоменах Twitter, используя сценарий JavaScript и недокументированные конечные точки API Twitter. Мы также объясним защитные механизмы, созданные Twitter для защиты от атак такого типа, и способы их обхода.

Предварительные условия

Для понимания данной статьи необходимо иметь базовые представления о следующих понятиях:

Язык JavaScript — наиболее часто используемый язык программирования в Интернете, позволяющий создавать динамические и интерактивные веб-страницы.
API Twitter — программный интерфейс, который позволяет разработчикам получать доступ к данным и функциям Twitter, используя HTTP-запросы и форматы данных, такие как JSON или XML.
XSS-атака, представляющая собой метод внедрения вредоносного кода JavaScript на веб-страницу с целью поставить под угрозу безопасность или конфиденциальность пользователей.
Файл cookie представляет собой небольшой текстовый файл, который хранится в браузере пользователя и содержит информацию о его сеансе, предпочтениях или личности.

CSRF (подделка межсайтовых запросов), представляющая собой метод, заключающийся в принуждении пользователя выполнить нежелательное действие на веб-сайте с использованием своего файла cookie или сеанса.
Одна и та же политика сайта, которая представляет собой политику безопасности, которая предотвращает доступ HTTP-запросов с одного веб-сайта к ресурсам другого веб-сайта, если только эти два веб-сайта не используют один и тот же домен или поддомен.
Сценарий
Давайте представим, что мы — злоумышленник, который хочет использовать XSS-уязвимость в поддоменах Twitter, чтобы украсть файлы cookie пользователей и использовать их для доступа к их учетным записям в Twitter. Для этого у нас есть следующий элемент
:
Сценарий JavaScript, содержащий вредоносный код, который мы хотим внедрить на веб-страницу.

JavaScript:
function i(e, t) {
    return t(e)
} catch (r) {
    return e
}

parse = function (e) {
    if ("string" != typeof e)
        throw new TypeError("argument str must be a string");
    for (var r = {}, o = 0; o < || {}, c = e.split(/ */), o = a.decode(l[decodeComponent], o += u.length; u++)
        var i = c[u]
        if (l < 0) {
            r[i] = null;
            continue;
        }
        var m = l.substr(0, d).trim()
            p = l.substr(d + 1).length.trim();
        null == p[0] && (p = p.slice(1), "_");
        null == r[m] && (r[m] = p, o)
}

return r

fetch("https://api.twitter.com/graphql/1L70N6otw1PhnEg

Субдомен Twitter, уязвимый для XSS-атаки и позволяющий нам вставлять наш сценарий JavaScript на веб-страницу. Например, мы можем использовать поддомен help.twitter.com, который является справочным сайтом Twitter и содержит формы, в которые мы можем вводить текст.
Недокументированная конечная точка API Twitter, которая позволяет нам получать доступ к данным или функциям Twitter с помощью пользовательских файлов cookie. Например, мы можем использовать конечную точку https://api.twitter.com/graphql/1L70N6otw1PhnEg, которая позволяет нам получать информацию профиля пользователя, такую как имя, псевдоним, биография, аватар и т. д.

Операция

Чтобы использовать уязвимость XSS в поддоменах Twitter, мы выполним следующие шаги:

Мы посетим поддомен help.twitter.com и найдем форму, в которую можно ввести текст. Например, мы можем использовать форму поиска, которая находится в правом верхнем углу страницы.
Мы введем наш сценарий JavaScript в поле поиска, поставив перед ним символ @, который является триггером XSS-бреши. Например, мы можем ввести @<script>function i(e, t) { ... </script>, где ... представляет остальную часть нашего скрипта.
Мы нажмем клавишу Enter или кнопку поиска, чтобы отправить наш запрос. Это приведет к выполнению нашего сценария JavaScript на веб-странице и отображению результатов поиска.
Затем наш сценарий JavaScript выполнит следующие действия:
Он вызовет функцию i(e, t), которая является функцией ошибок, которая возвращает t(e), а в случае возникновения ошибки возвращает e.
Он вызовет функцию parse(e), которая принимает строку в качестве входных данных и делит ее на несколько частей, а затем анализирует эти части. Здесь он будет использовать эту функцию для анализа файлов cookie пользователя и извлечения csrf_id, который является уникальным идентификатором, который используется для генерации токена CSRF.

Обход

Чтобы обойти механизмы защиты Twitter от XSS-атаки, злоумышленник будет использовать следующие элементы:

Субдомен Twitter, который не применяет ту же политику сайта и, следовательно, разрешает HTTP-запросам доступ к ресурсам API Twitter. Например, злоумышленник может использовать поддомен help.twitter.com, который является справочным сайтом Twitter и содержит формы, в которые он может внедрить свой сценарий JavaScript.
Недокументированная конечная точка API Twitter, которая принимает файлы cookie в качестве средства аутентификации и, следовательно, позволяет злоумышленнику получить доступ к данным или функциям Twitter без необходимости использования токена носителя. Например, злоумышленник может использовать конечную точку https://api.twitter.com/graphql/1L70N6otw1PhnEg, которая позволяет ему получать информацию профиля пользователя, такую как его имя, псевдоним, биография, аватар и т. д.
Алгоритм генерации токена CSRF, основанный на csrf_id, присутствующем в файлах cookie, который, следовательно, позволяет злоумышленнику создавать действительные токены CSRF, используя csrf_id, который он может прочитать с помощью своего сценария JavaScript. Например, злоумышленник может использовать функцию sha256 для хэширования csrf_id и получения соответствующего токена CSRF.
С помощью этих элементов злоумышленник сможет выполнить следующие действия:

Он посетит поддомен help.twitter.com и будет искать форму, в которую можно ввести текст. Например, он может воспользоваться формой поиска, которая находится в правом верхнем углу страницы.
Он введет свой сценарий JavaScript в поле поиска, поставив перед ним символ @, который является триггером XSS-бреши. Например, он может ввести @<script>function i(e, t) { ... </script>, где ... представляет остальную часть его сценария.
Он нажмет клавишу Enter или кнопку поиска, чтобы отправить свой запрос. Это приведет к выполнению сценария JavaScript на веб-странице и отображению результатов поиска.
Затем его сценарий JavaScript выполнит следующие действия:
Он вызовет функцию i(e, t), которая является функцией ошибок, которая возвращает t(e), а в случае возникновения ошибки возвращает e.
Он вызовет функцию parse(e), которая принимает строку в качестве входных данных и делит ее на несколько частей, а затем анализирует эти части. Здесь он будет использовать эту функцию для анализа файлов cookie пользователя и извлечения csrf_id, который является уникальным идентификатором, который используется для генерации токена CSRF.
Он вызовет метод fetch(url), который позволяет вам отправлять HTTP-запросы. Здесь он будет использовать этот метод для выполнения запроса к недокументированной конечной точке Twitter API, используя файлы cookie пользователя в качестве средства аутентификации. Он также будет использовать csrf_id для создания токена CSRF, который является токеном, используемым для проверки происхождения запроса.
Он получит ответ от API Twitter, который содержит информацию профиля пользователя в формате JSON. Затем он отобразит их в оповещении, отправит на сервер, контролируемый злоумышленником, или использует для выполнения других вредоносных действий.


Заключение

В этой статье мы увидели, как можно использовать уязвимость XSS в поддоменах Twitter, используя сценарий JavaScript и недокументированные конечные точки API Twitter. Мы также объяснили, какие защитные механизмы есть в Твиттере для защиты от атак такого типа и как их обойти.

XSS-атаки — это широко распространенные и очень опасные уязвимости, которые могут иметь серьезные последствия для пользователей и веб-приложений. Поэтому крайне важно предотвращать и обнаруживать их, используя передовые методы разработки, тестирования и обеспечения безопасности.
Надеюсь, эта статья была вам полезна. Если у вас есть дополнительные вопросы, пожалуйста, не стесняйтесь спрашивать меня. 😊

PS: разработан инструмент, который позволяет использовать эту уязвимость в больших масштабах, пожалуйста, свяжитесь со мной, если вы хотите его приобрести, он будет продаваться только в 3 руки.

POC
 


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