# Testing for Mass Assignment

|ID          |
|------------|
|WSTG-INPV-20|

## Summary

Modern web applications are very often based on frameworks. Many of these web application frameworks allow automatic binding of user input (in the form of HTTP request parameters) to internal objects. This is often called autobinding.
This feature can be sometimes exploited to access fields that were never intended to be modified from outside leading to privilege escalation, data tampering, bypass of security mechanisms, and more.
In this case there is a Mass Assignment vulnerability.

Examples of sensitive properties:

- **Permission-related properties**: should only be set by privileged users (e.g. `is_admin`, `role`, `approved`).
- **Process-dependent properties**: should only be set internally, after a process is completed (e.g. `balance`, `status`, `email_verified`)
- **Internal properties**: should only be set internally by the application (e.g. `created_at`, `updated_at`)

## Test Objectives

- Identify requests that modify objects
- Assess if it is possible to modify fields never intended to be modified from outside

## How to Test

The following is a classic example that can help to illustrate the issue.

Suppose a Java web application with a `User` object similar to the following:

```java
public class User {
   private String username;
   private String password;
   private String email;
   private boolean isAdmin;

   //Getters & Setters
}
```

To create a new `User` the web application implements the following view:

```html
<form action="/createUser" method="POST">
     <input name="username" type="text">
     <input name="password" type="text">
     <input name="email" text="text">
     <input type="submit" value="Create">
</form>
```

The controller that handles the creation request (Spring provides the automatic bind with the `User` model):

```java
@RequestMapping(value = "/createUser", method = RequestMethod.POST)
public String createUser(User user) {
   userService.add(user);
   return "successPage";
}
```

When the form is submitted, the following request is generated by the browser:

```http
POST /createUser
[...]
username=bob&password=supersecretpassword&email=bob@domain.test
```

However, due to the autobinding, an attacker can add the `isAdmin` parameter to the request, which the controller will automatically bind to the model.

```http
POST /createUser
[...]
username=bob&password=supersecretpassword&email=bob@domain.test&isAdmin=true
```

The user is then created with the `isAdmin` property set to `true`, giving them administrative rights on the application.

### Black-Box Testing

#### Detect Handlers

In order to determine which part of the application is vulnerable to mass assignment, enumerate all parts of the application that accept content from the user and can potentially be mapped with a model. This includes all HTTP requests (most likely GET, POST, and PUT) that appear to allow create or update operations on the back end.
One of the most simple indicators for potential mass assignments is the presence of bracket syntax for input parameter names, as for example:

```html
<input name="user[name]" type="text">
```

When such patterns are encountered try to add an input related to a non-exiting attribute (e.g. `user[nonexistingattribute]`) and analyze the response/behavior.
If the application does not implement any control (e.g. list of allowed fields) it is likely that it will respond with an error (e.g. 500) due to the fact that the application does not find the attribute associated to the object. More interestingly, those errors sometimes facilitate discovery of attribute names and value data types needed to exploit the issue, without access to the source code.

#### Identify Sensitive Fields

Since in black-box testing the tester does not have visibility on the source code, it is necessary to find other ways in order to gather information about the attributes associated to the objects.
Analyze the responses received by the back end, in particular pay attention to:

- HTML page source code
- Custom JavaScript code
- API responses

For example, very often, it is possible to exploit handlers that return details about an object in order to gather clues on the associated fields.
Suppose for example a handler that returns the profile of the user (e.g. `GET /profile`), this may include further attributes related to the user (in this example the `isAdmin` attribute looks particularly interesting).

```json
{"_id":12345,"username":"bob","age":38,"email":"bob@domain.test","isAdmin":false}
```

Then try to exploit handlers that allow the modification or creation of users, adding the `isAdmin` attribute configured to `true`.

Another approach is to use wordlists in order to try to enumerate all the potential attributes. The enumeration can then be automated (e.g. via wfuzz, Burp Intruder, ZAP fuzzer, etc.). The sqlmap tool includes a [common-columns.txt](https://github.com/sqlmapproject/sqlmap/blob/master/data/txt/common-columns.txt) wordlist that can be useful to identify potential sensitive attributes.
A small example of common interesting attribute names are the following:

- `is_admin`
- `is_administrator`
- `isAdmin`
- `isAdministrator`
- `admin`
- `administrator`
- `role`

When multiple roles are available try to compare requests made by different user levels (pay particular attention to privileged roles). For example, if extra parameters are included in requests made by an administrative user, try those as a low privileged/anonymous user.

#### Check Impact

The impact of a mass assignment can vary depending on the context therefore, for each test input attempted in the previous phase, analyze the result and determine if it represents a vulnerability that has a realistic impact on the web application's security.
For example, the modification of the `id` of an object can lead to application Denial of Service or privilege escalation. Another example is related to the possibility to modify the role/status of the user (e.g. `role` or `isAdmin`) leading to vertical privilege escalation.

### Gray-Box Testing

When the analysis is performed with a gray-box testing approach, it is possible to follow the same methodology to verify the issue. However, the greater knowledge on the application allows to more easily identify frameworks and handlers subject to mass assignment vulnerability.
In particular, when the source code is available, it is possible to search the input vectors more easily and accurately. During a source code review, use simple tools (such as the grep command) to search for one or more common patterns within the application code.
Access to the DB schema or to the source code allows also to easily identify sensitive fields.

#### Java

Spring MVC allows to automatically bind user input into object. Identify the controllers that handle state-changing requests (e.g. find the occurrences of `@RequestMapping`) then verify if controls are in place (both on the controller or on the involved models). Limitations on the exploitation of the mass assignment can be, for example, in the form of:

- list of bindable fields via `setAllowedFields` method of the `DataBinder` class (e.g. `binder.setAllowedFields(["username","password","email"])`)
- list of non-bindable fields via `setDisallowedFields` method of the `DataBinder` class (e.g. `binder.setDisallowedFields(["isAdmin"])`)

It is also advisable to pay attention to the use of the `@ModelAttribute` annotation that allows to specify a different name/key.

#### PHP

Laravel Eloquent ORM provides a `create` method which allows automatic assignment of attributes. However, the latest versions of Eloquent ORM provide default protection against mass assignment vulnerabilities requiring to explicitly specify allowed attributes that can be assigned automatically, through the `$fillable` array, or attributes that have to be protected (non-bindable), trough the `$guarded` array. Therefore by analyzing the models (classes that extend the `Model` class) it is possible to identify which attributes are allowed or denied and therefore point out potential vulnerabilities.

#### .NET

Model binding in ASP.NET automatically bind user inputs to object properties. This also works with complex types and it will automatically convert the input data to the properties if the properties' names match with the input.
Identify the controllers then verify if controls are in place (both inside the controller or in the involved models). Limitations on the exploitation of the mass assignment can be, for example, in the form of:

- fields declared as `ReadOnly`
- list of bindable fields via `Bind` attribute (e.g. `[Bind(Include = "FirstName, LastName")] Student std`), via `includeProperties` (e.g. `includeProperties: new[] { "FirstName, LastName" }`) or through `TryUpdateModel`
- list of non-bindable fields via `Bind` attribute (e.g. `[Bind(Exclude = "Status")] Student std`) or via `excludeProperties` (e.g. `excludeProperties: new[] { "Status" }`)

## Remediation

Use built-in features, provided by frameworks, to define bindable and non-bindable fields. An approach based on allowed fields (bindable), in which only the properties that should be updated by the user are explicitly defined, is preferable.
An architectural approach to prevent the issue is to use the *Data Transfer Object* (DTO) pattern in order to avoid direct binding. The DTO should include only the fields that are meant to be editable by the user.

## References

- [OWASP: API Security](https://github.com/OWASP/API-Security/blob/master/2019/en/src/0xa6-mass-assignment.md)
- [OWASP: Cheat Sheet Series](https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html)
- [CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes](https://cwe.mitre.org/data/definitions/915.html)
