Exploring Broken Access Control
Tags: cybersecurity, javascript, webdev, beginners
Published: 2023-11-08 14:22:59


## What is Access Control?

Access control is a method used by applications to regulate access to their features, functionalities, and resources. A common example of an access control mechanism is the process of login authentication, which we encounter almost daily.

## Access Control Mechanism in login authentication

Here is a simple Node.js script that demonstrates the login authentication process:

```javascript
const jwt = require("jsonwebtoken");
const { getUserByUsername } = require("./../db");
const bcrypt = require('bcrypt');

module.exports = async (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    const user = await getUserByUsername(username);

    if (!bcrypt.compare(password, user.password)) {
        return res.status(403).json({
            error: "invalid login"
        });
    }

    delete user.password;

    const token = jwt.sign(user, process.env.SECRET, { expiresIn: "1h" });

    res.cookie("token", token, {
        secure: true,
        httpOnly: true
    });
    
    return res.redirect("/home/");
}
```

In the code snippet above, this asynchronous function verifies the provided credentials. If the credentials are valid, it creates a JSON Web Token (JWT). If not, it responds with an error message 'invalid login.' JWTs are commonly used for login authentication, another popular method being session-based authentication. Once the token is created, it sets a cookie named "token" which will be stored on the client side.



| ![JSON webtoken in the cookie](https://details.bio/biMGI) |
|:--:|
<sub><center>JWT token in the cookie</center></sub>

## Middlewares

We also have middlewares which can be used to enforce privileged access to certain routes.

### `isAdmin.js` Middleware

```javascript
const jwt = require('jsonwebtoken');

exports.isAdmin = (req, res, next) => {
    const token = req.cookies.token;
    try {
        const username = jwt.verify(token, process.env.SECRET);
        req.username = username;
        if (username['username'] === "admin") {
            next();
        } else {
            res.clearCookie("token");
            return res.redirect("/");
        }
    } catch (err) {
        res.clearCookie("token");
        return res.redirect("/");
    }
}
```

### Usage

The middleware can be used in route definitions to protect endpoints:

```javascript
// express-js example code
app.post("/admin-panel/", isAdmin, (req, res) => {
    // ...admin only functionality
});
```

## Access Control in Login Systems

Access control is a broad term that encompasses mechanisms and policies that govern access to resources or features within an application or system. Middlewares are a fundamental component of access control in a login system.

## Components of Access Control

- **Authentication**: Verifying a user's identity, typically with a username and password, and possibly including multi-factor authentication (MFA), biometrics, or tokens.

- **Authorization**: Determining what a user is allowed to do after being authenticated, which includes defining permissions, roles, and access rights.

- **Access Policies**: Rules and restrictions on who can access which resources or perform specific actions. These can be role-based, attribute-based, or rule-based.

### Specific Methods of Access Control

- **Role-Based Access Control (RBAC)**: A model where permissions are linked to roles, and users are assigned to these roles, inheriting their permissions.

- **Attribute-Based Access Control (ABAC)**: A more flexible model considering various attributes, conditions, and contexts for access decisions.

- **Access Logs and Auditing**: Vital for monitoring user activities and potential security incidents.

- **Single Sign-On (SSO)**: Allows users to access multiple services with one set of credentials, simplifying the access control process.

- **Access Control Lists (ACLs)**: Specify access rights for users or system processes to objects.

**Broken Access Control** vulnerabilities highlight the risks and are often listed in the *OWASP Top 10 Vulnerabilities* due to their significant impact on API security and cybersecurity.

## Understanding Broken Access Control: Categories and Implications

Access control issues can open up systems to a range of security risks, among which broken access control is a critical concern.
Now that we have a basic understanding of access control, let's delve into the broad categories of broken access control, namely vertical and horizontal broken access control. These can lead to vertical and horizontal privilege escalation, respectively.

## Vertical Privilege Escalation

Vertical privilege escalation happens when users with limited permissions manage to gain unauthorized access to resources or data that should be restricted to more privileged users. This security flaw allows lower-level users to escalate their privileges within a system, reaching levels of access typically reserved for administrators or other high-level roles.

### Implications of Vertical Privilege Escalation

The consequences of a vertical privilege escalation can be substantial, presenting a severe threat to the integrity and security of systems. Such exploits could result in unauthorized access to sensitive information, modification of critical data, or even full control over system functions and operations.

### Causes of Vertical Privilege Escalation

There are several mechanisms by which a user might achieve vertical escalation of privileges:

- **Exploiting Software Vulnerabilities:** Attackers might find and exploit flaws or bugs in software that inadvertently allow for privilege escalation.
- **Permission Mishandling:** Incorrect configuration of access control lists or permission settings can leave open opportunities for users to increase their access levels.
- **Social Engineering:** Attackers may use deception to trick higher-level users into granting unauthorized access unintentionally.
- **Unprotected Functionality**
Unprotected administrative functionality may be accessible without direct linking in the user interface.
Administrative URLs might be disclosed in `robots.txt` or other public places.
Attackers could brute-force the administrative URL.

- **Unprotected Admin Functionality with Obscure URLs**
Relying on obscure URLs to hide sensitive functionality is not secure. JavaScript could accidentally expose an admin URL.

#### Example
```javascript
<script>
    var role = getCurrentUserRole();

    var adminURL = 'https://example.com/administrator-panel-8YXAXZ';
    var userURL = 'https://example.com/user-dashboard';
    
    var urlToDisplay = role === 'admin' ? adminURL : userURL;
    
    var link = document.createElement('a');
    link.href = urlToDisplay;
    link.textContent = 'Access Your Dashboard';
    
    document.body.appendChild(link);
</script>
```
Sensitive URLs in client-side code are security risks.

- **Parameter-Based Access Control**
Applications may store user role information in modifiable locations.

#### Example
```javascript
var request = new XMLHttpRequest();
request.open("GET", "https://example.com/some_protected_resource", true);
request.setRequestHeader("Role", "admin");

request.onreadystatechange = function () {
    if (request.readyState == 4 && request.status == 200) {
        console.log("Successfully accessed administrative resource.");
    }
};

request.send();
```
This illustrates how header manipulation can compromise access controls.

- **Broken Access Control Due to Platform Misconfiguration**
Access control enforced at the platform layer could be bypassed via URL overrides through non-standard headers.

- **Method-Based Access Control**
Using alternative HTTP methods, attackers might access restricted functionalities intended for other methods.

- **URL-Matching Discrepancies**
Inconsistent matching of request paths to defined endpoints can result in access control bypasses. Issues could arise from variations such as inconsistent capitalization or treatment of trailing slashes.

### Visual Representation

Here is an illustrative representation of how vertical privilege escalation might manifest in a system:

![Vertical Privilege Escalation](https://details.bio/KylQm)
<sub><center>Vertical privilege escalation</center></sub>

## Horizontal Privilege Escalation

Horizontal escalation in broken access control occurs when a user with standard permissions gains unauthorized access to resources or data belonging to another user at the same privilege level.

| ![Horizontal privilege escalation](https://details.bio/vUDNC) |
|:--:|
<sub><center>Horizontal privilege escalation [Source](https://www.digit.in/features/general/digit-mag-privilege-escalation-attacks-their-impact-on-enterprises-and-mitigation-53746.html) </center></sub>




- **Unprotected Functionality**

Similar to vertical privilege escalation, horizontal escalation can occur when features or functions that should be restricted to specific user roles are accessible by others with the same privilege level. This can happen due to unprotected functionality within the application.

- **Incorrect Session Control**

Proper session management is key to preventing horizontal escalation. If session tokens or cookies are insecure or can be manipulated, it could allow an attacker with a regular user account to hijack another user's session and access their data.

- **Inadequate Data Access Security**

Horizontal escalation can also stem from insufficient data access controls. When data retrieval systems don't enforce adequate access restrictions, users might be able to see or modify data they shouldn't have access to.

## Conclusion

Broken access control represents a serious security risk, potentially leading to unauthorized data access, security breaches, and other risks. It's vital for both developers and security professionals to understand the significance of robust access control systems and to put in place effective measures to guard against these types of vulnerabilities.



Here's an amazing resource for learning more on broken access control: [PortSwigger Web Security - Access Control](https://portswigger.net/web-security/access-control)