• General Solutions
  • Ruby On Rails
  • Jackson (JSON Object Mapper)
  • GSON (JSON Object Mapper)
  • JSON-Lib (JSON Object Mapper)
  • Flexjson (JSON Object Mapper)
  • References and future reading
  • Microservices Security
  • Microservices based Security Arch Doc
  • Mobile Application Security
  • Multifactor Authentication
  • NPM Security
  • Network Segmentation
  • NodeJS Docker
  • Nodejs Security
  • OS Command Injection Defense
  • PHP Configuration
  • Password Storage
  • Prototype Pollution Prevention
  • Query Parameterization
  • REST Assessment
  • REST Security
  • Ruby on Rails
  • SAML Security
  • SQL Injection Prevention
  • Secrets Management
  • Secure Cloud Architecture
  • Secure Product Design
  • Securing Cascading Style Sheets
  • Server Side Request Forgery Prevention
  • Session Management
  • Software Supply Chain Security.md
  • TLS Cipher String
  • Third Party Javascript Management
  • Threat Modeling
  • Transaction Authorization
  • Transport Layer Protection
  • Transport Layer Security
  • Unvalidated Redirects and Forwards
  • User Privacy Protection
  • Virtual Patching
  • Vulnerability Disclosure
  • Vulnerable Dependency Management
  • Web Service Security
  • XML External Entity Prevention
  • XML Security
  • XSS Filter Evasion

Mass Assignment Cheat Sheet ¶

Introduction ¶, definition ¶.

Software frameworks sometime allow developers to automatically bind HTTP request parameters into program code variables or objects to make using that framework easier on developers. This can sometimes cause harm.

Attackers can sometimes use this methodology to create new parameters that the developer never intended which in turn creates or overwrites new variable or objects in program code that was not intended.

This is called a Mass Assignment vulnerability.

Alternative Names ¶

Depending on the language/framework in question, this vulnerability can have several alternative names :

  • Mass Assignment: Ruby on Rails, NodeJS.
  • Autobinding: Spring MVC, ASP NET MVC.
  • Object injection: PHP.

Example ¶

Suppose there is a form for editing a user's account information:

Here is the object that the form is binding to:

Here is the controller handling the request:

Here is the typical request:

And here is the exploit in which we set the value of the attribute isAdmin of the instance of the class User :

Exploitability ¶

This functionality becomes exploitable when:

  • Attacker can guess common sensitive fields.
  • Attacker has access to source code and can review the models for sensitive fields.
  • AND the object with sensitive fields has an empty constructor.

GitHub case study ¶

In 2012, GitHub was hacked using mass assignment. A user was able to upload his public key to any organization and thus make any subsequent changes in their repositories. GitHub's Blog Post .

Solutions ¶

  • Allow-list the bindable, non-sensitive fields.
  • Block-list the non-bindable, sensitive fields.
  • Use Data Transfer Objects (DTOs).

General Solutions ¶

An architectural approach is to create Data Transfer Objects and avoid binding input directly to domain objects. Only the fields that are meant to be editable by the user are included in the DTO.

Language & Framework specific solutions ¶

Spring mvc ¶, allow-listing ¶.

Take a look here for the documentation.

Block-listing ¶

Nodejs + mongoose ¶, ruby on rails ¶, django ¶, asp net ¶, php laravel + eloquent ¶, grails ¶, play ¶, jackson (json object mapper) ¶.

Take a look here and here for the documentation.

GSON (JSON Object Mapper) ¶

Take a look here and here for the document.

JSON-Lib (JSON Object Mapper) ¶

Flexjson (json object mapper) ¶, references and future reading ¶.

  • Mass Assignment, Rails and You
  • Browse topics

SNYK LEARN LOGIN

  • 🌍 Snyk (recommended)

OTHER REGIONS

For Snyk Enterprise customers with regional contracts. More info

  • 🇦🇺 Snyk AUS

Mass assignment

Be careful with parameters that are automatically bound from requests to objects, select your ecosystem, mass assignment: the basics, what are mass assignment vulnerabilities.

To make it easier to save data submitted via an HTML form into a database or object, many web application frameworks have included libraries to automatically bind HTTP request parameters (typically sent via forms) to the fields of database models or members of an object, requiring only minimal coding.

Let’s say we have a (very simple) HTML form:

When the form is submitted to the web application, it will send the form data as HTTP request parameters, and the backend code will have to read each parameter individually into a corresponding variable. Then, once all the fields have been read, the application will usually execute a database update or insert operation to save the data.

Mass Assignment makes it possible to write less code to handle this process - think about how much coding this technique could save if it was an object that had dozens of fields, and multiply this across a complex application that has many of these objects in its database.

Mass assignment vulnerabilities occur when the database model that is being assigned contains security-relevant fields, and the application user can supply values in the POST request that are saved to those fields, even though they are not present in the HTML form.

For example, if the User model contained a field isAdmin: Boolean , the user could add the POST body parameter isAdmin=true and make themselves an administrator.

For this to occur, an attacker would need to guess the names of the sensitive fields, or the source code for the vulnerable application would have to be available to the attacker (allowing them to see what sensitive fields are present in the data model).

Impacts of this attack can include bypassing authentication or authorization logic or elevation of privilege. This could then result in the destruction or disclosure of data within the application.

About this lesson

In this lesson, you will learn how mass assignment vulnerabilities work and how to protect your applications against them. We will begin by exploiting a Mass Assignment vulnerability in a simple application. Then we will analyze the vulnerable code and explore some options for remediation and prevention.

Mass assignment in the wild

In 2012, a GitHub user exploited a Mass Assignment vulnerability in GitHub’s public key update form. The flaw allowed the user to add their public key to another organization they were not a member of. The user added their key to the Ruby on Rails organization. To demonstrate proof of the exploit, the user added a file to the Rails project repository. GitHub responded, quickly fixing the vulnerability and they conducted a wide audit of their code to ensure the issue was detected and fixed if it existed anywhere else.

Mass assignment in action

New SaaS startup SuperCloudCRM recently launched their web platform designed to help businesses boost their sales and marketing efforts.

Setting the stage

SuperCloudCRM recently launched its web platform. Unfortunately, they suffered a security breach, resulting in data being leaked. What went wrong?

Mass assignment details

As mentioned, SuperCloudCRM’s developers had been logging request data for API endpoints like the POST /user/create endpoint, which creates new user accounts when a user submits the signup form.

A typical JSON payload in the request sent to the /user/create endpoint was supposed to look like this:

But a search of the /user/create endpoint’s logs for the [email protected] account around the time the user was created, found JSON POST data starting with the following excerpt:

It was different to the normal requests, and had a long request body with dozens more fields all starting with the letter r . What was the attacker doing? All of these weird field names that weren’t part of the user model schema, which was:

After doing some testing like the scenario above showed, a few things were discovered.

First, the new user account’s password was apparently being saved to the database in plaintext. Not good! But what stuck out was that the application ignored the non-existent fields and just assigned the fields that were actually part of the User model schema.

The data from the new User document was sent back to the API client and the attacker could then infer which of the list of fields starting with r were part of the User model schema, because if a field existed it was saved and echoed back in the response with the other user data.

A search of the /user/create endpoint’s request log entries around the same time revealed that thousands of similar requests had been sent. Each request testing lists of possible field names in the User model schema.

It was concluded that the attackers had brute-forced HTTP requests with various field name guesses to enumerate the organization and role fields in the schema. Despite them not being referred to anywhere in the client-side JavaScript code, the attackers were able to discover these security-related field names.

So, if the attackers knew these field names, what would they do then? Well, this could have led to a possible mass assignment attack. After hours of reviewing logs for the POST /user/create and POST /user/update endpoints the incident response team found dozens of requests had been submitted to the application, which looked similar to:

The requests appeared to be successful. Each of the requests changed the organization to a different customer, essentially giving the attackers access to each of them as admins. The last request was:

This seemed to explain why [email protected] was an administrator in the Cowmoo Industries organization.

By exploiting this mass assignment vulnerability and adding themselves as the administrator for various customers, the attackers were able to access the organizations’ data within SuperCloudCRM and steal it.

Mass assignment by different names

The concept of mass assignment is known by different names in various programming languages or frameworks. NodeJS and Ruby on Rails call it mass assignment. It is referred to as autobinding in Java Spring MVC and ASP NET MVC. PHP calls it object injection.

Mass assignment under the hood

Let’s have a look at this vulnerable application in more detail by going through the server-side code.

The schema for the User model is defined here, with the user’s credentials, email address, plus their role and organization they belong to. During signup, the credentials and email address are the only values that are supposed to be supplied by the user and accepted by the application.

Firstly, let's recap what took place in the example above.

  • The User schema consisted of several fields: username, password, email, role and organization.
  • Only the username, password and email fields were sent from the web browser to the /user/create endpoint
  • The API endpoint used mass assignment to blindly assign any field from the POST request’s JSON data to the User model in the database (if the field existed in the User schema).
  • The attackers were able to determine the names of security-related fields in the schema (role and organization)
  • The attackers could supply arbitrary values for these fields when creating or updating a user account
  • This let the attackers add themselves to other organizations and elevate their privileges to those of an administrator

Here ( $user = new User($request->post()); ), the endpoint creates a new User object and in doing so, passes all contents of the POST request to the constructor. PHP can “smartly” figure out which parameters go to which attributes of the class; however, this isn’t so smart when those attributes are certain things that shouldn’t be assignable! Even if the form only accepts inputs with username , password and email , a malicious actor can guess the other forms and simply add those fields to the JSON manually. As PHP has no way of discerning what it receives from “good” and “bad”, it simply updates them all. If only there were a way to tell PHP exactly which fields we don’t want to be assignable like that!

Impacts of mass assignment

By exploiting mass assignment vulnerabilities, a malicious actor could create multiple security problems including

  • Data tampering : Attackers can modify sensitive information in the database, such as password or account balance
  • Data theft : Attackers can gain access to confidential information stored in the database
  • Elevation of privilege : Attackers can manipulate the properties of an object to gain additional privileges, such as administrator access
  • Unauthorized access : Attackers can manipulate the properties of an object to gain unauthorized access to sensitive resources

Scan your code & stay secure with Snyk - for FREE!

Did you know you can use Snyk for free to verify that your code doesn't include this or other vulnerabilities?

Mass assignment mitigation

Use an allowlist of fields that can be assigned to.

Most mass assignment libraries or helper libraries should provide the ability to restrict the fields that will be read from a request and assigned to the data model. By restricting the assignment of user-supplied fields to only fields in the schema that are known safe ones, the values of security-sensitive fields will be prevented from tampering.

Using this strategy, the code for the application would be changed to add an allowlist using the pick() method of the underscore package and listing the allowed fields in the userCreateSafeFields array:

Laravel provides a library, eloquent , which, among other things, introduces object injection protection features! It gives you the ability to indicate variables that can be assigned, or otherwise, you can indicate variables that you don’t want assignable. This means that when you use mass assignment to populate a class with request data, the Laravel backend can (with your guiding hand) separate POST request input data from fields that should be populated and those that should not!

Using this strategy, the code for the application can be changed to add an allow-list of class attributes, enforcing that only these will be updated:

Use a Data Transfer Object (DTO)

Another option is to create an intermediary object (the DTO) that only has safe, assignable properties, which would be a subset of the target object that has those same fields plus any sensitive fields. Using our User example, the DTO would be:

The mass assignment operation can assign any user-supplied data to the DTO without the risk of inadvertently assigning any sensitive fields. The DTO can be copied to the final object, and during this process, any sensitive fields can be set to secure default values.

This method might require much more coding though. DTOs need to be created for all classes with sensitive fields. If there are many schemas with sensitive fields that require corresponding DTOs, then this becomes nearly as much work as not using mass assignment.

Use a denylist to declare fields that can’t be assigned to

The opposite of using an allowlist to define fields that are allowed to be assigned is to use a denylist of fields that shouldn’t be assigned. Security wisdom says to use allowlisting over denylisting because it’s safer to accidentally not include a safe field than to accidentally omit a dangerous field. So, following this advice, a denylist would be the less preferred option of the two. If there are 50 fields in a schema and only one is security-sensitive, then it is obviously much quicker to just denylist the one sensitive field. The danger here though would be if additional sensitive fields were added to the schema later and the developer forgot to add them to the denylist, then you would have a mass assignment vulnerability.

To use denylists, the code for the application would be changed in a similar manner to the code shown in the allow-list strategy shown earlier, except it would use the omit() method of the underscore package and listing the disallowed fields in the userCreateDisallowedFields array:

To use deny-lists, the code for the application would be changed in a similar manner to the code shown in the allow-list strategy shown earlier, the only difference being the User class is changed to have a “hidden” array:

Utilize a static analysis tool

Adding a static application security testing ( SAST ) tool to your devops pipeline as an additional line of defense is an excellent way to catch vulnerabilities before they make it to production. There are many, but Snyk Code is our personal favorite, as it scans in real-time, provides actionable remediation advice, and is available from your favorite IDE.

Keep learning

To learn more about mass assignment vulnerabilities, check out some other great content:

  • OWASP guide to mass assignment vulnerabilties
  • Find mass assignment in our top 10 list

Congratulations

You have taken your first step into learning what mass assignment is, how it works, what the impacts are, and how to protect your own applications. We hope that you will apply this knowledge to make your applications safer.

What is mass assignment?

Mass assignment is a type of security vulnerability that occurs when an application code allows user-provided data to be used to set properties on an object without verifying that the user has the right to do so.

What to learn next?

Insecure default variable initialization, uncaught exception, insufficient encapsulation.

Mass Assignment Vulnerability: How It Works & 6 Defensive Measures

what is mass assignment security

What Is a Mass Assignment Vulnerability? 

Mass assignment vulnerabilities occur when an application automatically assigns user input to model properties without proper filtering or validation. This allows attackers to modify object properties they shouldn't be able to access, such as changing a user's permissions, email, or password.

These vulnerabilities often occur in applications that use frameworks allowing mass assignment from request parameters. Without strict controls, attackers can supply unexpected parameters through common methods like POST requests, leading to unauthorized changes in the application's data.

This is part of a series of articles about application security.

In this article:

The Impact of a Mass Assignment Vulnerability

How mass assignment vulnerabilities work .

  • Example of a Mass Assignment Attack
  • 1. Allowlist Allowed Attributes ‍
  • 2. Sanitize and Validate Input ‍
  • 3. Keep Dependencies Up-to-Date ‍
  • 4. Employ Strong Authentication and Authorization ‍

5. Use Role-Based Access Control (RBAC)

The impact can be severe, depending on the data an attacker can modify. It might lead to privilege escalation, data leakage, or full account takeover. This could result in significant financial losses, legal penalties, or damage to an organization's reputation.

By exploiting mass assignment vulnerabilities, attackers can bypass usual access controls, altering critical system settings or user data without detection. The scale of the attack often hinges on the application's data sensitivity and what the altered parameters control.

Mass assignment vulnerabilities exploit how frameworks handle user input. When an application doesn’t differentiate between which parameters should and shouldn’t be modified directly by a user, it opens up a vector for attack. Once such a weak point is identified, the attacker crafts malicious HTTP requests that include parameters targeting these unprotected attributes.

For example, consider a scenario where an application uses an object to store user profile information. The attacker can send a POST request with additional, unanticipated parameters such as role=admin or status=disabled. If these parameters are not explicitly filtered out or validated against an allowlist, the application's backend logic might accept these as legitimate and alter the user object’s properties accordingly. 

Thus, attackers can gain elevated privileges or disrupt services by manipulating key object attributes through seemingly innocuous user input. These attacks are made possible by the common practice of binding form or API input directly to data models. Without rigorous checks and balances, such as field-level validation, attackers can easily insert unauthorized data into these models. 

This is particularly dangerous when combined with other vulnerabilities or weak points within the application, such as insecure direct object references or insufficient logging and monitoring, which can mask or facilitate unauthorized access and modifications.

Example of a Mass Assignment Attack 

This example was adapted from the official OWASP cheat sheet . Let’s look at a scenario where a mass assignment vulnerability exists in a basic web application designed for editing user account information.  ‍

The application comprises a straightforward HTML form that captures a user's ID, password, and email address. This form interacts with a backend controller upon submission, binding user input to a corresponding User object.

The form is outlined as follows:

The User object, meant to receive the form data, looks like this:

The server-side handling of the form submission is managed by a controller mapped to /addUser and designed to process POST requests. Upon receiving a form submission, it invokes a service method to add the user data to the system:

A typical, legitimate request to this endpoint might look like this:

However, exploiting the mass assignment vulnerability involves manipulating the request to include an isAdmin parameter, which is not intended to be modified directly by end users through the form. By appending &isAdmin=true to the request, an attacker can alter the isAdmin property of the User object, granting themselves administrative privileges:

This exploit demonstrates the risk associated with indiscriminately binding user input to model attributes, especially when sensitive properties like isAdmin are involved. Without adequate filtering or validation, this vulnerability can compromise the integrity of the application.

6 Ways to Mitigate the Security Risks of Mass Assignment 

Here are some of the measures that can be used to prevent mass assignment attacks.

1. Allowlist Allowed Attributes

Define which attributes can be safely exposed to mass assignment. Using an allowlist approach ensures only specified attributes can be updated through user input.

This method requires explicitly listing allowed parameters, making unintended data modifications less likely. Regularly review and update the allowlist to accommodate changes in the application’s functionality.

2. Sanitize and Validate Input

Sanitizing input involves stripping harmful data before it’s processed, whereas validation ensures the data meets specific criteria. Together, they can prevent attackers from submitting malicious or unexpected data through mass assignment.

Input should be sanitized to remove potential executable code or SQL commands. Validation rules, like checking for allowable values or correct data types, further reduce the risk of unauthorized modifications.

3. Keep Dependencies Up-to-Date

Applications often rely on external libraries or frameworks that might contain vulnerabilities, including those leading to mass assignment issues. Regularly update these dependencies to ensure that known vulnerabilities are patched.

Subscribe to notifications from dependency providers and security bulletins to stay informed about relevant security updates. Automated tools can help identify outdated dependencies in a project, simplifying the update process.

4. Employ Strong Authentication and Authorization

Authentication mechanisms ensure that users are who they claim to be, while authorization checks confirm they have permission for the requested actions. Ensuring both are in place can significantly reduce the risk of mass assignment vulnerabilities being exploited. ‍

Authorization checks should occur at every stage of data processing, especially before sensitive operations like data updates. This prevents unauthorized users from exploiting mass assignment vulnerabilities to access or modify data.

RBAC ensures users can only interact with data and actions appropriate for their role. This helps mitigate risks by limiting what authenticated users can modify, even if a mass assignment vulnerability exists.

RBAC requires defining roles and permissions carefully, ensuring they align with the principle of least privilege. This means users get only the access necessary for their role, reducing the potential impact of a mass assignment vulnerability.

6. Monitor and Log Activities

Monitoring and logging access and modification of sensitive data help detect unauthorized attempts to exploit mass assignment vulnerabilities. Automated alerts can notify administrators of suspicious activities, enabling rapid response to potential breaches.

Logs should capture sufficient detail to understand the nature of each attempt, including who made the request and what was attempted. Regular analysis of logs can also help identify patterns indicating unaddressed vulnerabilities.

API Security with Pynt

Pynt is an innovative API Security Testing platform exposing verified API threats through simulated attacks. We help hundreds of companies such as Telefonica, Sage, Halodoc, and more, to continuously monitor, classify and attack poorly secured APIs, before hackers do. 

Pynt's leverages an integrated shift-left approach, and unique hack technology using home-grown attack scenarios, to detect real threats, discover APIs, suggest fixes to verified vulnerabilities, thereby eliminating the API attack surface risk.

Thousands of companies rely on Pynt to secure the no. 1 attack surface - APIs, as part of their AppSec strategy. 

Learn more about Pynt and get started free

what is mass assignment security

Want to learn more about Pynt’s secret sauce?

HackerWhite

Point of Contact

  • Vulnerability 101

Mass Assignment Vulnerability: Understanding & Mitigating the Risks in API

Mass assignment vulnerability is a critical security concern that often goes unnoticed in API development. Understanding the risks associated with this vulnerability is crucial for protecting sensitive user data. In this article, we will delve into the details of mass assignment vulnerabilities and explore effective mitigation strategies.

Introduction:

The "Mass Assignment" vulnerability is a security flaw that occurs when an application assigns user input directly to model attributes without proper validation or sanitization. This can lead to unauthorized access and modification of sensitive data, potentially compromising the security of the application and its users.

Addressing the "Mass Assignment" vulnerability is crucial for developers as it can have serious consequences, including data breaches, unauthorized access, and legal implications. Understanding and mitigating this vulnerability is essential to ensure the integrity and security of an application.

Understanding the "Mass Assignment" Vulnerability:

The "Mass Assignment" vulnerability occurs when an attacker is able to manipulate the values of model attributes by submitting unexpected or malicious data. This can happen when developers use frameworks or libraries that automatically map user input to object properties without proper validation or filtering.

Common scenarios where developers may unintentionally introduce the "Mass Assignment" vulnerability include:

  • Using frameworks or libraries that provide automatic mapping of user input to object properties without considering the security implications.
  • Allowing users to submit data that directly maps to sensitive attributes without proper validation.
  • Failing to implement proper input validation and sanitization techniques.

The impact of the "Mass Assignment" vulnerability can be severe. Attackers can exploit this vulnerability to gain unauthorized access to sensitive data, modify user privileges, or even execute arbitrary code on the server. This can lead to data breaches, compromised user accounts, and potential legal issues.

Common Examples of "Mass Assignment":

There are several common examples of the "Mass Assignment" vulnerability. Let's explore a few of them:

User Profile Update: Suppose an application allows users to update their profile information, including their email address and password. If the application blindly maps user input to the corresponding model attributes without proper validation, an attacker can manipulate the request to update other sensitive fields such as admin privileges.

Role-Based Access Control: In applications with role-based access control, developers often use a single parameter to assign roles to users. If this parameter is not properly validated, an attacker can modify it to gain unauthorized access to sensitive functionality or elevate their privileges.

API Endpoints: APIs that accept JSON or XML payloads are also susceptible to the "Mass Assignment" vulnerability. If the API endpoint maps the incoming request directly to model attributes without proper validation, an attacker can manipulate the payload to modify sensitive data or gain unauthorized access.

These examples highlight the importance of implementing proper validation and sanitization techniques to mitigate the risks associated with the "Mass Assignment" vulnerability.

Risks and Consequences:

The "Mass Assignment" vulnerability poses significant risks and consequences for both developers and users. Some of the potential risks and consequences include:

Data Breaches: Exploiting the "Mass Assignment" vulnerability can lead to unauthorized access to sensitive data, including personal information, financial records, and confidential business data. This can result in serious privacy breaches and financial losses.

Unauthorized Access and Privilege Escalation: Attackers can manipulate the values of model attributes to gain unauthorized access to restricted functionality or elevate their privileges within the application. This can lead to unauthorized actions, such as modifying critical settings, accessing sensitive data, or impersonating other users.

Reputation Damage: Security breaches resulting from the "Mass Assignment" vulnerability can severely damage the reputation of the application and its developers. Users lose trust in the application's ability to protect their data, leading to a loss of user base and potential legal consequences.

Legal Implications: Depending on the nature of the application and the data involved, security breaches resulting from the "Mass Assignment" vulnerability can have legal implications. Developers may face legal actions, regulatory fines, and potential lawsuits for failing to protect user data adequately.

Real-world examples of security breaches resulting from the "Mass Assignment" vulnerability include the 2012 GitHub incident, where an attacker exploited the vulnerability to gain administrative access to repositories. This incident highlighted the severity and impact of this vulnerability.

Best Practices for Mitigating the "Mass Assignment" Vulnerability:

To mitigate the risks associated with the "Mass Assignment" vulnerability, developers should follow these best practices:

Whitelist Input Validation: Developers should implement strong input validation techniques to ensure that only expected and valid data is accepted. This includes whitelisting allowed attributes and rejecting any unexpected or malicious input.

Use Role-Based Access Control (RBAC): Implement RBAC to control user privileges and access to sensitive functionality. Do not rely solely on user input to determine roles and permissions.

Implement Attribute-Level Access Controls: Instead of blindly mapping all user input to corresponding attributes, developers should implement attribute-level access controls. This ensures that only authorized users can modify specific attributes.

Sanitize and Filter User Input: Before assigning user input to model attributes, developers should sanitize and filter the data to remove any potential malicious content. This includes validating data types, length restrictions, and ensuring data integrity.

Implement Secure Coding Practices: Follow secure coding practices, such as avoiding dynamic attribute assignment, using strong encryption for sensitive data, and regularly updating frameworks and libraries to their latest secure versions.

Regular Security Testing and Auditing: Conduct regular security testing and auditing of the application to identify and mitigate any vulnerabilities, including the "Mass Assignment" vulnerability. This includes penetration testing, code review, and vulnerability scanning.

Tools and Resources:

To aid developers in addressing the "Mass Assignment" vulnerability, the following tools, libraries, and resources can be helpful:

OWASP Cheat Sheet - Mass Assignment: The OWASP Cheat Sheet provides guidelines and recommendations for securing web applications against the "Mass Assignment" vulnerability. It offers practical advice and code snippets for developers to implement secure coding practices.

Security-Focused Libraries and Frameworks: Many programming languages and frameworks provide security-focused libraries and modules that can help mitigate the "Mass Assignment" vulnerability. Examples include Django's ModelForm, Laravel's Mass Assignment Protection, and Ruby on Rails' Strong Parameters.

Platform-Specific Security Guidelines: Developers should refer to platform-specific security guidelines and resources provided by the framework or platform they are using. These guidelines often include best practices and recommendations for securing applications against common vulnerabilities, including "Mass Assignment."

Code Review and Testing Tools: Developers should leverage code review and testing tools to identify and mitigate the "Mass Assignment" vulnerability. Tools like SonarQube, OWASP ZAP, and Burp Suite can help identify security flaws in the code and test the application for vulnerabilities.

The Role of Security Testing and Auditing:

Regular security testing and auditing play a crucial role in identifying and mitigating the "Mass Assignment" vulnerability. Various testing techniques can be employed, including:

Penetration Testing: Conducting penetration tests can help identify vulnerabilities and potential attack vectors, including the "Mass Assignment" vulnerability. Ethical hackers simulate real-world attacks to identify security weaknesses and provide recommendations for improvement.

Code Review: Manual code review or automated tools can help identify insecure coding practices, including instances of the "Mass Assignment" vulnerability. Developers should review their code regularly and ensure it follows best practices for secure coding.

Vulnerability Scanning: Automated vulnerability scanning tools can scan the application for known vulnerabilities, including the "Mass Assignment" vulnerability. These tools can help identify potential weaknesses and provide guidance on how to address them.

By employing these testing techniques, developers can proactively identify and mitigate the "Mass Assignment" vulnerability, ensuring the security and integrity of their applications.

Conclusion:

Addressing the "Mass Assignment" vulnerability is crucial for developers to protect the integrity and security of their applications. By understanding the definition, risks, and consequences of the vulnerability, developers can take proactive measures to mitigate its impact.

Implementing best practices, such as whitelisting input validation, utilizing role-based access control, and regular security testing and auditing, can significantly reduce the risks associated with the "Mass Assignment" vulnerability.

Need Help? Hire us part-time

Hire a dedicated, part-time security consultant with over 10+ years of experience to work closely with your dev/security team. you only pay for the time you need, with no long-term contracts. learn more.

Secured High Growth Companies Worldwide

Let's find out if we are a good fit with a 30-min intro call

Plans start from $1,000. No Contracts, Cancel Anytime.

Mass Assignment

Introduction.

Software frameworks sometime allow developers to automatically bind HTTP request parameters into program code variables or objects to make using that framework easier on developers. This can sometimes cause harm.

Attackers can sometimes use this methodology to create new parameters that the developer never intended which in turn creates or overwrites new variable or objects in program code that was not intended.

This is called a Mass Assignment vulnerability.

Alternative Names

Depending on the language/framework in question, this vulnerability can have several alternative names :

  • Mass Assignment: Ruby on Rails, NodeJS.
  • Autobinding: Spring MVC, ASP NET MVC.
  • Object injection: PHP.

Suppose there is a form for editing a user's account information:

Here is the object that the form is binding to:

Here is the controller handling the request:

Here is the typical request:

And here is the exploit in which we set the value of the attribute isAdmin of the instance of the class User :

Exploitability

This functionality becomes exploitable when:

  • Attacker can guess common sensitive fields.
  • Attacker has access to source code and can review the models for sensitive fields.
  • AND the object with sensitive fields has an empty constructor.

GitHub case study

In 2012, GitHub was hacked using mass assignment. A user was able to upload his public key to any organization and thus make any subsequent changes in their repositories. GitHub's Blog Post .

  • Whitelist the bindable, non-sensitive fields.
  • Blacklist the non-bindable, sensitive fields.
  • Use Data Transfer Objects (DTOs).

General Solutions

An architectural approach is to create Data Transfer Objects and avoid binding input directly to domain objects. Only the fields that are meant to be editable by the user are included in the DTO.

Language & Framework specific solutions

Whitelisting.

Take a look here for the documentation.

Blacklisting

Nodejs + mongoose, ruby on rails, php laravel + eloquent, jackson (json object mapper).

Take a look here and here for the documentation.

GSON (JSON Object Mapper)

Take a look here and here for the document.

JSON-Lib (JSON Object Mapper)

Flexjson (json object mapper), references and future reading.

  • Mass Assignment, Rails and You

Authors and Primary Editors

Abashkin Anton - [email protected]

results matching " "

No results matching " ".

VAADATA – Ethical Hacking Services

What is Mass Assignment? Attacks and Security Tips

What is a mass assignment vulnerability.

what is mass assignment security

To make things easier for developers, many frameworks include features that automatically associate the parameters of an HTTP request with variables linked to an object in the application code.

A Mass Assignment vulnerability occurs when the server does not correctly filter the data transmitted by the user and associates it directly with an object without verification.

In this way, an attacker can add new parameters to the HTTP request, which will create or replace variables in the application code although this was not initially intended.

Depending on the framework, these are also known as “autobinding” or “object injection” vulnerabilities.

Impact of a Mass Assignment vulnerability

The main impact of a Mass Assignment vulnerability is linked to modifying or creating variables. Depending on the variables or objects affected, the impact can be more or less significant, ranging from the simple modification of a value with no impact to a privilege escalation.

Indeed, when the vulnerability is present in a feature linked to the creation or modification of users, it is not uncommon to be able to escalate privileges.

This was the case, for example, on the Github platform in 2012, when a Mass Assignment vulnerability enabled users to upload their SSH public key to any organisation, potentially resulting in a massive data leak.

Such a vulnerability is not to be taken lightly, as it can have a severe impact.

How to identify this type of vulnerability?

As an attacker or pentester does not necessarily have a list of all the variables and values associated with the modified object on the server side, identifying a Mass Assignment vulnerability can be complex.

Depending on the technical conditions of the pentest, here are a few ways of identifying this type of security flaw:

  • In white box, i.e. with access to the source code, it is possible to refer to the data models to identify sensitive fields that would not be transmitted by default in HTTP requests.
  • Without access to the source code, this is more complex. One technique is to test known or probable parameters. This involves fuzzing the parameters. For example, adding a “role” field to the user creation request with standard values such as “admin” or “root” can lead to a privilege escalation in the event of Mass Assignment.
  • In some cases, using the API documentation, it is possible to identify parameters that are not used by default. For example, with access to the introspection of a GraphQL API, i.e. to the list of fields associated with an entity, it is possible to try to add a variable in certain queries or mutations in the hope that this will be taken into account.
  • Another technique is to observe the server responses. If additional fields are returned, it may be useful to reuse them in requests to detect Mass Assignment. Let’s imagine, for example, that we have access to the list of users. If you access the API route used to list users, you can see a “role” field associated with each user in the server response. It may therefore be useful to add this role parameter with a valid value in the request used to modify the profile information or the request used to create a user.

What are the common exploits of Mass Assignment vulnerabilities?

Mass assignment and privilege escalation.

During a grey box pentest , we had access to an application with several levels of user privileges. We had a user access (not admin), but which nevertheless allowed us to create other users with the same level of privileges.

Using the graphic interface, the request to add a user looked like this:

what is mass assignment security

The content of the server response in JSON was as follows:

what is mass assignment security

As we can see, a “Profiles” field is returned in the JSON object corresponding to the new user we have just created. It seems to correspond to the user’s rights. This field has been added automatically. In particular, we can see that the newly created user has a profile of type “customer” associated with ID 5. This profile has certain roles.

The fact that this “Profiles” field is present in the response even though it was not initially filled in should immediately alert us. We can now try to replay the creation of a user by adding a “Profiles” field.

Here, we know that profile ID 5 corresponds to a “customer” type user. Let’s try this with ID 1. We’ve left the other fields empty because we didn’t know the existing values:

what is mass assignment security

Server response:

what is mass assignment security

The Mass Assignment attack has been taken into account. The profile ID “1” has been associated with the user we have just created. The response tells us that we have successfully created an administrator type user.

This means that on the server side, the entire JSON object sent by the attacker is used to link the transmitted fields to the user object created. This is done without checking what data is being transmitted and by accepting an unexpected field.

We can now connect with the new user. Our privileges have been escalated and we can perform all the actions restricted to administrators.

Mass Assignment on a GraphQL API and privilege escalation

During a pentest on an application running with a GraphQL API, a mutation was used to update the user’s profile. By default and using the graphical interface, the mutation transmitted was as follows:

what is mass assignment security

At first glance, there’s nothing particularly interesting about this mutation. It allows a user to change his/her surname, first name and telephone number.

However, we had access to GraphQL introspection (the equivalent of the documentation for a classic API) and we were able to see that the GraphQL “User” object also had a “role” field.

By modifying the previous mutation, we were able to change the role of our user due to a Mass Assignment. This enabled us to escalate our privileges:

what is mass assignment security

Full request:

what is mass assignment security

Following this request, our user became an administrator because the mutation took into account the role field even though it was not sent by default.

How to prevent Mass Assignment vulnerabilities?

Fortunately, preventing or correcting this type of vulnerability is fairly straightforward.

It involves setting up a white list of fields that are authorised to be used on the server side to create or modify an object. In addition, only non-sensitive fields should be authorised. And if other fields are present in the request received, they must not be taken into account by the server.

Frameworks often allow this type of whitelist to be configured simply. A list of potential existing solutions by framework can be found on the OWASP website.

If we go back to the previous examples, in the first case, the white list must not include the “profiles” field. If a user tries to send a value for this field, the value transmitted should not be taken into account when creating the user.

In the second case, the mutation used to modify the profile must not accept the “role” value. It must be limited to the “first_name”, “last_name” and “language” parameters only.

Author : Yoan MONTOYA – Pentester @Vaadata

Related Posts

What is rfi remote file inclusion exploitations and security tips, introduction to nuclei, an open source vulnerability scanner, what is prototype pollution exploitations and security tips.

See our Fast Start promotion and start your first pentest on The Cobalt Offensive Security Testing Platform for only $4,950.

  • Application Pentest
  • Secure Code Review
  • LLM Pentest
  • Network Pentest
  • Red Teaming
  • Digital Risk Assessment
  • Social Engineering
  • Device Hardening
  • IoT Testing

Gigaom_Pentest_as_a_Service_menu_featured_image_041923

  • get started

Cobalt-linkedin-img

Mass Assignment & APIs - Exploitation in the Wild

what is mass assignment security

The APIs (Application Programmable Interfaces) are widely used to power applications, and one of the popular choices for implementing API is  REST APIs . With this increase in popularity and usage, many security risks also come into the picture. 

APIs have their own  OWASP API Top 10  list, which describes the vulnerabilities commonly found in the APIs, including Mass Assignment. 

This blog will dive deeply into understanding and exploiting mass assignment vulnerabilities. 

Mass Assignment - A 20ft Overview: 

Modern frameworks allow developers a convenient mass assignment functionality that lets developers directly take a “user-supplied Key-Value Pair” input to the object database. This reduces the requirement of writing code for such custom Key-Value pairs and increases the development efficiency but at the cost of security risks if not implemented correctly. 

A mass assignment without a whitelist of allowed “Key-Value Pairs” could allow an attacker to use arbitrary values to create or update the resources abusing the applications’ regular workflow. Privilege escalation is one of the most common vulnerabilities arising from Mass Assignment vulnerability. 

According to OWASPthis  vulnerability  depends on the language/framework in question can have several alternative names:

Mass Assignment: Ruby on Rails, NodeJS.

Autobinding: Spring MVC, ASP NET MVC.

Object injection: PHP.

For example, consider an API that allows users to update their profile information. The API may accept a JSON payload that contains multiple fields such as name, email, and address. Without proper validation, an attacker can add additional fields such as "isAdmin":true” or "isSuperUser":true and gain elevated privileges as an admin or superuser. 

Let’s understand this attack further with the help of a vulnerable code snippet as described below: 

const express = require('express');

const app = express();

app.post('/users', (req, res) => {

  const newUser = {

    username: req.body.username,

    password: req.body.password,

    isAdmin: req.body.isAdmin

  };

  // Save new user to database

app.listen(3000, () => {

  console.log('Server started on port 3000');

In the above code, the “newUser” object is created from the request body without validation or filtering. An attacker can attempt to craft a request with an additional field named “isAdmin”:true and send it to the server to escalate the privileges. 

To remotely exploit this issue, an attacker can send a POST request with an additional "isAdmin" field set to "true" to register as an administrator. In this case, isAdmin is an optional body parameter.

POST /users HTTP/1.1

Host: example.com

Content-Type: application/json

  "username": "attacker",

  "password": "password",

  "isAdmin": true

Now, to mitigate this issue, simply adding a check to ensure that only the user with an admin session can trigger this parameter will fix the underlying vulnerability as described in below code: 

Const port = 3000;

    password: req.body.password

if (req.user.isAdmin && req.body.isAdmin) {

  // Only admins can set isAdmin field

  newUser.isAdmin = req.body.isAdmin;

app.listen(port, () => {

  console.log(`Server started on port {port}`);

Hunting for Mass Assignment Attack in the Wild - A Practical Approach

Mass Assignment is not necessarily to be found in the user profile to perform privilege escalations. You can find it on any API endpoint, which could be using a parameter of interest to the attacker, causing significant damage to the application and its user’s reputation. 

Note: Always read the API documentation to understand and identify interesting parameters/key-value pairs that could cause significant impact.

Let’s understand how to approach the Mass Assignment Attack in a black-box/grey-box assessment with the help of the “crAPI” Demo Lab. 

Locally set up the  crAPI demo lab .

Navigate to the shop -  http://127.0.0.1:8888/shop

Screenshot 2023-04-18 at 11.24.51 AM

Note that the Available Balance by default is $100, and now Buy any item while capturing the request in Burp Suite or another proxy tool. 

Send the Request to the repeater for later use.

Screenshot 2023-04-18 at 11.24.58 AM

Observe after purchasing the items; Available Balance is changed. 

Screenshot 2023-04-18 at 11.25.05 AM

In the repeater tab, modify the request by changing the request method to  GET  and adding “/all” route to retrieve the information of all orders.

Screenshot 2023-04-18 at 11.25.11 AM

Observe that the application has returned all information about past orders.

Modify the request, and change the “all” to any random order ID. 

Send the request, and observe the methods allowed and the order status.

Screenshot 2023-04-18 at 11.25.17 AM

Again, modify the request by changing the request method to  PUT  and adding the status as a return.

Send the request and observe the error message in the response.

Screenshot 2023-04-18 at 11.25.23 AM-1

Send the request again by adding the status as returned and observing that the order status has changed to returned.

Screenshot 2023-04-18 at 11.25.32 AM

Navigate to the shop, and observe that credit transfers to the account.

Screenshot 2023-04-18 at 11.25.39 AM

In the above lab scenario, as an attacker, it was possible to mark a delivered item as returned to get the cashback allowing an attacker to financially abuse the application with the help of a mass assignment attack. 

Since now you know what chaos this attack can bring to the organization from the user integrity and the financial aspects, it is essential to understand how to implement a fix to prevent such attacks. 

Fixing Mass Assignment - Remediation Approach 

Some common ways to fix mass assignment issues include:

  • Disable Automatic Property Mapping: Ensure that your applications have the automatic mapping disabled and always map the properties manually.
  • Read-Only Key-Value Pairs: Ensure to set the fields retrieved from the “request body” that is not present in the “request body” should be read-only, and a user should not be allowed to tamper them.

You can find a detailed remediation guide  here .

References and Further Reads

https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html

https://www.impart.security/post/mass-assignment-101

https://crashtest-security.com/api-mass-assignment/

https://www.wallarm.com/what/mass-assignment

About Harsh Bothra

Related resources.

Sever-side request forgery cover image

Secure Software Best Practices: Protect Against Server-Side Request Forgery

Validate User Input cover image

Secure Software Best Practices: Validate User Input

Source Code Review cover image

Source Code Review

Never miss a story.

  • schedule a demo
  • Cobalt Platform
  • Offensive Security
  • Application Security
  • Network Security
  • Cloud Security
  • Brand Protection
  • Device Security
  • Core Community
  • Product Documentation
  • Resource Library
  • Events & Webinars
  • Vulnerability Wiki
  • Trust Center

Cobalt-linkedin-img-alt

This is a title

Cobalt-twitter-X-img-alt

  • © 2024 Cobalt
  • Terms of use
  • Your privacy settings
  • Do not sell my data

what is mass assignment security

Mass Assignment 101

In this blog post, we'll take a look at what mass assignment attacks are, how they work, and why it's important for businesses and organizations to be aware of them. We'll also discuss some best practices for preventing mass assignment attacks and protecting your API from this type of threat. By understanding mass assignment attacks and taking steps to prevent them, you can help to keep your API and your business secure.

What is a Mass Assignment attack?

A mass assignment attack is a type of security vulnerability that occurs when an attacker is able to modify the values of multiple object's properties by passing them in as part of an HTTP request.  This is typically done in bulk where multiple objects are changed at once using attack automation tooling.  

This can allow the attacker to set the values of sensitive properties, such as passwords or security permissions, without the proper authorization which can result in significant risk exposure, exfiltration of data, or data loss.

Mass assignment attacks are often made possible by insufficient input validation or the lack of an object-level access control mechanism. For example, if an application allows users to submit an HTTP request with a JSON or XML payload that includes all of the properties of an object, an attacker may be able to manipulate the values of these properties in order to gain unauthorized access or permissions.

Here's an example of an API vulnerable to Mass Assignment attack:

@app.route('/users', methods=['POST']) def create_user():  user_data = request.json  user = User(user_data)  user.save()  return jsonify(user.to_dict())

In this example, the create_user endpoint accepts a JSON object containing the user's username and password. It then creates a User object using the data from the request and saves it to the database.

However, this code is vulnerable to a mass assignment attack, because it allows an attacker to specify arbitrary attributes for the User object by including them in the JSON object that is sent in the request. For example, an attacker could add an admin attribute to the JSON object, and the User object would be created with that attribute set to true, giving the attacker administrator access to the system.

Why you need to know about Mass Assignment

Mass assignment attacks are a type of vulnerability that can affect APIs, and are a serious concern for businesses and organizations. These attacks can allow attackers to gain unauthorized access to sensitive data, or to take control of the API and perform actions that they should not be able to. This can have serious consequences for the business, such as data breaches, loss of customer trust, and financial losses.

In addition to the direct impact on the business, mass assignment attacks can also have indirect effects. For example, if an attacker is able to take control of an API, they may be able to use it to launch other attacks, such as denial of service attacks or injection attacks. This can have even wider-reaching consequences for the business, and can cause significant damage to the organization's reputation and bottom line.

How to prevent mass assignment attacks

To prevent mass assignment attacks, it is important to properly validate user input and implement object-level access controls to ensure that only authorized users can modify the values of sensitive properties. This can include restricting the properties that can be modified in an HTTP request, as well as verifying the user's permissions before allowing them to make any changes.

One way to prevent your API from being attacked by a mass assignment attack is to validate and sanitize your API inputs.  use an input validation and sanitization tool. This approach can help you ensure that only authorized parameters are accepted by your API, and that any potentially harmful input is sanitized or rejected.  However, this type of solution can be difficult to implement in real life and is best supplemented with other approaches as well.

Another way to prevent mass assignment attacks is to use an API runtime protection tool that provides built-in protection against mass assignment attacks. An runtime protection tool acts as a layer of protection between your API and the outside world, and can help prevent unauthorized or malicious requests from reaching your API.  Unfortunately, most runtime protection tools (like WAFs or API Gateways) lack the intelligence to recognize mass assignment attacks.  

Another way to prevent mass assignment attacks is to use a whitelist-based approach to parameter validation. This means only allowing specific, authorized parameters to be accepted by your API, and rejecting any other input.  This approach is sometimes referred to as implementing a positive security model.

Additionally, you can use a combination of these approaches to provide a more robust defense against mass assignment attacks. By using input validation and sanitization tools, a runtime protection solution, and a whitelist-based approach, you can help protect your API from mass assignment attacks and other threats.  Bringing all of these approaches together in a seamless solution is the best path forward and what we're building at Impart Security.

Overall, it's important for businesses and organizations to be aware of mass assignment attacks and to take steps to prevent them. By understanding this type of attack and implementing appropriate safeguards, you can help to keep your API and your business secure.  

Please contact us if you'd like to learn more or try our closed beta!

Want to learn more about API security? Subscribe to our newsletter for updates.

See why security teams love us

  • Mass Assignment

What is a Mass Assignment Attack?

In order to reduce the work for developers, many frameworks provide convenient mass-assignment functionality. This lets developers inject an entire set of user-entered data from a form directly into an object or database. Without it, developers would be forced to tediously add code specifically for each field of data, cluttering the code base with repeated form mapping code.

The downside of this functionality is that it is often implemented without a whitelist that prevents users from assigning data to protected fields. An attacker may exploit this vulnerability to gain access to sensitive data or to cause data loss.

As demonstrated by prominent cases , even the best teams of developers can miss this non-obvious vulnerability.

An Example of a Vulnerability

In this example, a web shop allows users to sign up and keep track of their orders. The owner of the web shop has a special administrator account that allows them to manage other users and their orders. The administrator account is created in the database, just like a regular user account, except it has an is_administrator flag set.

On the sign up page, the user is asked to enter their email address and select a password:

The corresponding controller action creates the user in the database:

An attacker may inject their own HTML into form (or otherwise modify the request):

The controller action will create the user, letting the attacker gain complete control of the web shop:

How To Defend Against Mass Assignment Attacks

In the example above, the developer should change the code to either explicitly assign the attributes for the allowed fields, or use a whitelisting function provided by the framework (Ruby on Rails in this case):

More useful information may be found at:

  • https://www.owasp.org/index.php/Mass_Assignment_Cheat_Sheet
  • http://guides.rubyonrails.org/v3.2.9/security.html#mass-assignment
  • https://laravel.com/docs/5.0/eloquent#mass-assignment
  • https://odetocode.com/Blogs/scott/archive/2012/03/11/complete-guide-to-mass-assignment-in-asp-net-mvc.aspx
  • https://coffeeonthekeyboard.com/mass-assignment-security-part-10-855/
  • https://nvisium.com/resources/blog/2014/01/17/insecure-mass-assignment-prevention.html

Let Us Review Your Software

We provide code security reviews as a service. Based on our extensive experience in the field of sofware engineering and IT security, we know how to efficiently review entire code bases and identify security critical parts of the software.

This enables us to provide our security code review service at a fixed rate per review, providing our customers a transparent, efficient and reliable process.

  • Security review of your software by experts
  • OWASP Top 10 vulnerability check
  • Security Report with recommendations
  • Invaluable insights into the state of security in your application

Fixed Price per Review

  • Broken Access Control
  • Broken Authentication
  • Cross-Site Request Forgery (CSRF)
  • Cross-Site Scripting (XSS)
  • Insecure Direct Object Reference
  • Security Misconfiguration
  • Sensitive Data Exposure
  • SQL Injection
  • Timing Attack
  • Unvalidated Redirection
  • Vulnerable Dependencies

Technologies

  • Microsoft .Net
  • Ruby on Rails

ROPE Security is a Software Security Consultancy Firm based in Denmark. Our clients range from large international enterprises to start-ups and small businesses.

If you have any questions, do not hesitate to contact us at [email protected]

what is mass assignment security

Popular with:

What is mass assignment.

Have you ever wondered about the potential dangers of seemingly innocent features within your codebase?

Mass Assignment - a seemingly innocent feature that can play the role of either your app's Achilles' heel or a hidden shield against security breaches.

Back in 2012, GitHub learned their lesson the hard way when a seemingly innocent feature turned into a gaping security hole. A GitHub user exploited a Mass Assignment vulnerability in the public key update form, enabling them to add their public key to an organization they didn't belong to - the Ruby on Rails organization, no less!

Mass Assignment refers to the process of directly assigning values to object properties during data processing, often done through user input. While seemingly innocuous, improper handling of this feature can lead to unauthorized access, data manipulation, and potential security breaches.

Understanding Mass Assignment in Web Development

When it comes to web application development, Mass Assignment is a pivotal concept that can either empower users or expose your application to grave security risks. In simple terms, Mass Assignment allows users to submit data that is then used to update the corresponding model attributes with ease. It streamlines the process, enabling developers to set multiple attributes of a model using a single request, which significantly enhances efficiency and user experience.

However, behind this seemingly convenient feature lies a potential Pandora's box. If not handled diligently, Mass Assignment can become a lurking vulnerability, granting unauthorized users access to sensitive areas and the ability to tamper with critical data. One wrong move and your application might be susceptible to data breaches, malicious exploits, and even complete system compromise

How Mass Assignment Works

Mass Assignment works like a well-choreographed dance, seamlessly linking user input to the attributes of the underlying data model. In the world of web applications, it streamlines the process of updating object properties, making it feel effortless.

When a user submits a form with various fields, such as username, email, and role. As this data reaches the server, the application takes center stage. It extracts the user's input, typically through request parameters or form data. Here comes the best part - the application dynamically maps the data from user input to the corresponding attributes of the underlying data model.

In our earlier example, the data sent by the user would be mapped to the User model's username, email, and role attributes. Thanks to Mass Assignment, developers don't need to tediously set each attribute manually; instead, the data is automatically assigned to its rightful place.

The Security Implications of Mass Assignment

Ah, Mass Assignment, the seemingly innocent enabler of web application efficiency! But beware, for beneath its charm lies a world of security implications that demand our utmost attention. 

Unauthorized Changes to Critical Attributes

Mass Assignment can be exploited by attackers to manipulate crucial attributes, granting them unauthorized access and control over sensitive functionalities. For example, an attacker could elevate their privileges by updating a role attribute from a regular user to an admin, potentially compromising the entire system.

Manipulation of Hidden or Restricted Attributes

Crafty attackers may attempt to manipulate attributes that are not directly exposed in forms or interfaces but play a crucial role in the application's functionality. These hidden attributes could be mistakenly updated through Mass Assignment that leads to unforeseen consequences or security vulnerabilities.

Data Breaches and Exposure of Sensitive Information

Mass Assignment could inadvertently allow attackers to update sensitive data fields that should remain restricted. For instance, a user might have access to their own account details but could manipulate the request to modify someone else's private information, potentially leading to data breaches and privacy violations.

Elevated Privileges

Mass Assignment can enable attackers to grant themselves elevated privileges by modifying attributes related to user roles or permissions. This may give them access to administrative functions or other sensitive areas within the application.

Injection Attacks

Attackers can use Mass Assignment as a vector to inject malicious code into the application, causing it to execute unintended actions or open security vulnerabilities.

Data Corruption

Improper Mass Assignment handling can lead to unintended updates to data, potentially corrupting the database or causing unintended side effects

How to Mitigate the Security Risks of Mass Assignment

  • Whitelist Allowed Attributes. Implement a whitelist approach where you explicitly define the attributes that are allowed to be updated through Mass Assignment. This restricts the input to only those attributes deemed safe, preventing attackers from manipulating critical or restricted fields.
  • Blacklist Unsafe Attributes. On the flip side, maintain a blacklist of attributes that should never be updated using Mass Assignment. By explicitly excluding certain attributes, you can safeguard against potential vulnerabilities.
  • Use Role-Based Access Control (RBAC). Role-Based Access Control ensures that users can only update attributes based on their roles and permissions. This prevents unauthorized elevation of privileges and unauthorized data access.
  • Sanitize and Validate Input. Always validate and sanitize the user input before processing it through Mass Assignment. Ensure that the data adheres to the expected format and is free from malicious content to prevent injection attacks.
  • Employ Strong Authentication and Authorization. Robust authentication mechanisms and authorization checks ensure that only authorized users have access to sensitive functionalities.
  • Implement Two-Factor Authentication (2FA). For critical operations, Two-Factor Authentication adds an extra layer of security to reduce the risk of unauthorized access even if an attacker gains control over user credentials.
  • Monitor and Log Activities. Comprehensive logging and monitoring mechanisms help to keep track of Mass Assignment activities. Regularly review the logs to detect any suspicious behavior and respond promptly to potential threats.
  • Regular Security Audits. Conduct regular security audits and code reviews to identify potential vulnerabilities related to Mass Assignment or other aspects of your application's security.
  • Keep Dependencies Up-to-date. Ensure that all third-party libraries and frameworks used in your application are up-to-date, as outdated dependencies may have known vulnerabilities that attackers can exploit.
  • Educate Developers. Train your development team about the security risks associated with Mass Assignment and educate them on best practices for secure coding.

AppSecEngineer Empowering Users without Compromising Security

As security-conscious developers and engineers, we must strive to strike the delicate balance between user empowerment and safeguarding our applications against potential vulnerabilities. 

Now, to take our security practices to the next level, we can be your ally that can significantly boost our defenses. As a full-stack application security platform, AppSecEngineer equips security engineers with a comprehensive suite of tools and features to detect, prevent, and remediate security threats.

With AppSecEngineer backing you up, you can confidently showcase your expertise as a security engineer , impress potential employers, and increase your chances of landing interviews in the competitive information security landscape.

Abhay Bhargav

Abhay Bhargav

Abhay is a speaker and trainer at major industry events including DEF CON, BlackHat, OWASP AppSecUSA. He loves golf (don't get him started).

what is mass assignment security

Ready to Elevate Your Security Training?

what is mass assignment security

Contact Support [email protected] ‍ 1603 Capitol Avenue, Suite 413A #2898, Cheyenne, Wyoming 82001, United States

what is mass assignment security

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

0xa6-mass-assignment.md

Latest commit, file metadata and controls, api6:2019 - mass assignment.

Threat agents/Attack vectors Security Weakness Impacts
API Specific : Exploitability Prevalence : Detectability Technical : Business Specific
Exploitation usually requires an understanding of the business logic, objects' relations, and the API structure. Exploitation of mass assignment is easier in APIs, since by design they expose the underlying implementation of the application along with the properties’ names. Modern frameworks encourage developers to use functions that automatically bind input from the client into code variables and internal objects. Attackers can use this methodology to update or overwrite sensitive object’s properties that the developers never intended to expose. Exploitation may lead to privilege escalation, data tampering, bypass of security mechanisms, and more.

Is the API Vulnerable?

Objects in modern applications might contain many properties. Some of these properties should be updated directly by the client (e.g., user.first_name or user.address ) and some of them should not (e.g., user.is_vip flag).

An API endpoint is vulnerable if it automatically converts client parameters into internal object properties, without considering the sensitivity and the exposure level of these properties. This could allow an attacker to update object properties that they should not have access to.

Examples for sensitive properties:

  • Permission-related properties : user.is_admin , user.is_vip should only be set by admins.
  • Process-dependent properties : user.cash should only be set internally after payment verification.
  • Internal properties : article.created_time should only be set internally by the application.

Example Attack Scenarios

Scenario #1.

A ride sharing application provides a user the option to edit basic information for their profile. During this process, an API call is sent to PUT /api/v1/users/me with the following legitimate JSON object:

The request GET /api/v1/users/me includes an additional credit_balance property:

The attacker replays the first request with the following payload:

Since the endpoint is vulnerable to mass assignment, the attacker receives credits without paying.

Scenario #2

A video sharing portal allows users to upload content and download content in different formats. An attacker who explores the API found that the endpoint GET /api/v1/videos/{video_id}/meta_data returns a JSON object with the video’s properties. One of the properties is "mp4_conversion_params":"-v codec h264" , which indicates that the application uses a shell command to convert the video.

The attacker also found the endpoint POST /api/v1/videos/new is vulnerable to mass assignment and allows the client to set any property of the video object. The attacker sets a malicious value as follows: "mp4_conversion_params":"-v codec h264 && format C:/" . This value will cause a shell command injection once the attacker downloads the video as MP4.

How To Prevent

  • If possible, avoid using functions that automatically bind a client’s input into code variables or internal objects.
  • Whitelist only the properties that should be updated by the client.
  • Use built-in features to blacklist properties that should not be accessed by clients.
  • If applicable, explicitly define and enforce schemas for the input data payloads.
  • CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes

What is Mass Assignment: How We Can Help

2023 UPDATE: In the 2023 OWASP API Top 10 vulnerabilities list , Excessive Data Exposure and Mass Assignment are combined into a new entry, Broken Object Property Level Authorization. OWASP made this change to focus on the root cause of these two vulnerabilities: the lack of or improper authorization at the object property level. This can lead to unauthorized parties getting access to or manipulating sensitive data.  

Get details on Broken Object Property Level Authorization .

OWASP says of mass assignment, “Binding client provided data (e.g., JSON) to data models, without proper properties filtering based on an allowlist, usually leads to Mass Assignment. Either guessing objects properties, exploring other API endpoints, reading the documentation, or providing additional object properties in request payloads, allows attackers to modify object properties they are not supposed to.” 

Mass assignment exploits can be considered a variant of BOLA attacks. In both cases, a successful attacker is able to send requests containing unexpected data properties to valid endpoints in order to gain access to functionality not intended by the application developers. Unlike BOLA, mass assignment exploits apply specifically to APIs that deal with modifying a bulk collection of resources. 

How Do Mass Assignment Exploits Work?  

Mass assignment is actually a feature of many API server frameworks, and it’s intended to make life easier for API client developers. However, as OWASP mentions above, without proper properties filtering based on a set of allowed object properties, an attacker could modify private, internal, reserved, and/or hidden properties and gain access to sensitive data, typically through privilege escalation. 

For example, imagine an application containing an API endpoint allowing authorized users to update user information. This API functionality may have been intended for corporate accounts who need to make updates in bulk to coincide with personnel changes.

But imagine this innocuous bulk-update were to be used by a malicious individual intent on causing mischief or worse: 

In this hypothetical example, the attacker modifies the “email” property in order to update the user’s email to an attacker owned inbox. If the updated account has elevated permissions within the application and the attacker leverages the password reset functionality to send an updated password to their inbox, they now have elevated permissions within the application. 

This is a contrived example, but all mass assignment exploits rely on API validation logic, intended for typically mundane bulk-level functions, being misused to grant unintended powers to unauthorized clients. 

Learn why an attacker-centric approach is critical when detecting and preventing threats from exploiting vulnerabilities with mass assignment:   Why an Attacker-Centric Approach Is Key to API Protection .

How to Prevent Mass Assignment  

Similar to BOLA, prevention starts with defensive programming techniques, such as enforcing a standardized authorization strategy within all endpoints of your API, taking into account the user authorization level and the authorization requirements of all referenced resources, and rigorously maintaining security policies controlling which fields are editable (“allowlists”).  

How ThreatX Can Help  

ThreatX can help both identify this vulnerability and block its exploitation. Due to our attacker-centric behavioral analytics , ThreatX can flag, watch, and, if necessary, block behavior that indicates a mass assignment attack in progress.   

Watching and Blocking Mass Assignment   

It can be difficult to detect if an attacker has exploited an instance of this vulnerability because the application would show no signs of an error. However, ThreatX continuously monitors each unique client/user and would detect probing/reconnaissance activity targeting this vulnerability. Other suspicious activity, such as repeated error responses, typically indicate an attacker is up to no good. If these behaviors reached a certain risk threshold, or are observed in conjunction with other suspicious attacker behavior (which they frequently are), we would block the attacker and record the events for later review. 

Identifying Mass Assignment   

In addition, ThreatX provides visibility on potentially vulnerable API endpoints through several data points. First, the details for each attack are correlated to each endpoint targeted. Second, we compare observed requests for each endpoint against the expected usage defined in the approved API schema. Finally, failed requests are analyzed for various error conditions that indicate potential vulnerabilities.    

Get started protecting your APIs against mass assignment by requesting a 1:1 demo  of the ThreatX solution.

How Our Approach Is Unique   

Real-time blocking      .

Some API security solutions simply highlight potential API vulnerabilities, leaving security teams to investigate and recommend code changes. Other API solutions can identify an attacking IP, but require security teams to try to model the complex behavior in a third-party WAF (or try to block one IP at a time after the fact). ThreatX doesn’t just tell you about your API vulnerabilities or attempted attacks; we also block API attacks in real-time. ThreatX proxies and scans all inbound API traffic – in real time – identifying and blocking attacks.    

ThreatX recognizes attacker behavior indicative of an attempt to exploit mass assignment, then flags and watches that user. This real-time monitoring enables ThreatX to execute advanced threat engagement techniques, such as IP interrogation, fingerprinting, and tarpitting. When a series of user interactions cross our default (or your customized) risk threshold, we block the attack.     

Step One of N…     

In many cases, attackers aren’t just going to attack with a mass assignment exploit; they’re going to string together a series of attacks over time, often using federated and sophisticated botnets. Countering this approach requires the ability to correlate attack traffic across multiple IPs, the use of  advanced bot protection , and the ability to detect identifiers and techniques to associate the traffic to a unique attacker. Rather than requiring a single, significantly risky event or identifying a known signature, ThreatX analyzes behaviors from multiple vantage points. This lets the ThreatX Platform identify and block more threats, more accurately than competing API security tools.   

Less False Positives      

As risk rises, ThreatX immediately blocks an attack – stopping the threat in its tracks. ThreatX’s blocking modes are designed to block malicious requests and deter suspicious entities from attacking your APIs, while allowing benign traffic and real users through. Legacy WAFs struggle with false positives because they only make blocking decisions based on rules, but attackers and legitimate users don’t always follow the rules. Sometimes a legitimate user who forgot their password looks like an attacker, and sometimes an attacker cycling through usernames and passwords looks like a legitimate user. ThreatX can tell the difference.    

Identifying Risk     

Attackers camouflage their attempts to exploit an API with mass assignment by generating more suspicious or elevated application traffic. ThreatX detects and blocks potential threats based on behavior, but also identifies risky attributes being used in API traffic. ThreatX’s API Dashboard details API endpoint usage and how it compares to expected behavior defined by an organization’s API schema specifications. In the case of mass assignment, the ThreatX API Dashboard will detect attempts to use authorization parameters that are not part of a valid schema. With this visibility, customers can identify those back doors and shut them against these sophisticated, multi-vector attacks that are becoming a common threat. 

Learn more about the OWASP API Top 10:

  • Broken user authentication
  • Excessive data exposure
  • Lack of resources and rate limiting
  • Broken functional-level authorization

About the Author

Bret settle.

Bret has served in multiple executive roles for Corporate Express/Staples and BMC Software and has extensive knowledge of the software development and security products industries. Bret has been responsible for enterprise security in multiple roles and has been an innovator throughout his career and has a proven track record of building and developing high performing organizations and dynamic cyber security teams.

Subscribe for updates

Sign up for exclusive API and application threat research, guidance, and strategy.

ThreatX

Related Content

Credential stuffing, ddos attacks, bots, and more create a formidable iceberg of risk, new whitepaper: all you need to know about protecting against runtime threats to apis and applications, api vulnerability lives at the heart of the breach, join our newsletter.

Discord logo.

Join Our Community on Discord

Duis vehicula hendrerit finibus. In hac habitasse platea dictumst. Quisque aliquet, lacus eget feugiat viverra, diam dui dapibus mauris, at vehicula diam sem vitae nibh.

what is mass assignment security

Mass Assignment

Right now, we’re going to go through Mass Assignment vulnerabilities and what they look like, along with a few ways to avoid them. First, a quick recap: Mass Assignment is a vulnerability where API endpoints don’t restrict which properties of their associated object can be modified by a user. 

This vulnerability can occur when making use of a library/framework that allows for the automatic binding of HTTP parameters onto a model that then goes on to be used without any validation. 

The use of the automatic binding from a request onto an object can be extremely helpful at times, but it can also lead to security issues if the model has properties that aren’t meant to be accessible to the user.

We’re going to use the example of a web page where a user can change details, like their name, email address, and other similar stuff. We have a User model defined as:

public class UserModel {     public long Id { get; set; }     public string Name { get; set; }     public string PasswordHash { get; set; }      public string EmailAddress { get; set; }      public bool IsAdmin { get; set; } } The frontend part defines a form as following. Note the absence of the `IsAdmin` value: <form method="POST">      <input name="Id" type="hidden">      <input name="Name" type="text">      <input name="EmailAddress" type="text">      <input type="submit"> </form>   The controller defines an endpoint as following. By having the `UserModel` as a parameter, our framework will automatically map the respective properties onto this model for us: [HttpPost] public bool UpdateUser(UserModel model) {     // Ensure the user only updates themselves     model.Id = Request.User.UserId;     var success = UserService.UpdateUser(model);     return success;     }

From here, we can assume that the ‘UserService.UpdateUser’ method doesn’t do any further validation in terms of authorization, and simply just saves the provided user object. 

(If no value is provided for a property, it just keeps the existing value) 

This means that a user could submit a request with the ‘IsAdmin’, which would override the current value and make the user an admin like so:

<form method="POST">      <input name="Id" type="hidden" value="666">      <input name="Name" type="text" value="Bad guy">      <input name="EmailAddress" type="text" value="[email protected]">      <input name="IsAdmin" type="hidden" value="true">      <input type="submit"> </form>  

Mitigation strategies.

Below are a few mitigation strategies to consider when it comes to avoiding Mass Assignment vulnerabilities.

Avoid re-using data models for request models

It's important to keep your data models (which may be persisted in a database) separate from the models that get used when communicating with a client. Handling a form submission to a controller is a very different concern from persisting data in a database and how it's represented in the database. This creates a far higher level of coupling between the frontend and the persistence layer than is good. 

Be explicit in your mappings

The problem with automatic binding (or mapping) is that the lack of explicit mappings makes it easy to expose properties that aren’t meant to be accessible on the model. By being explicit in mappings between request models, and the rest of your backend, you can prevent these types of exposures from the start.

This could be done by using different models for requests and data. This doesn't prevent you from using an automatic mapper between the request and data model, as your request model should not expose properties that are not allowed for the specific request.

Further Examples

Below, we’ve got some additional examples in different languages of what this can look like. 

C# - insecure

public class User {      public long Id { get; set; }     public string FirstName { get; set; }     public string LastName { get; set; }     public string PasswordHash { get; set; }     public string Country { get; set; }     public string Role { get; set; } } [HttpPost] public ViewResult Edit( User user) {     // Just saves the user as provided     UserService.UpdateUser(user);     return Ok(); }

C# - secure

public class User {      public long Id { get; set; }     public string FirstName { get; set; }     public string LastName { get; set; }     public string PasswordHash { get; set; }     public string Country { get; set; }     public string Role { get; set; } } public class UpdateUserViewModel {     public string FirstName { get; set; }     public string LastName { get; set; }        public string Country { get; set; } } [HttpPost] public ViewResult Edit(UpdateUserViewModel userModel) {     var user = Request.User;     user.FirstName = userModel.FirstName;     user.LastName = userModel.LastName;     user.Country = userModel.Country;     UserService.UpdateUser(user);      return Ok(); }

C# - alternative - excludes parameters

public class User {      public long Id { get; set; }     public string FirstName { get; set; }     public string LastName { get; set; }     public string PasswordHash { get; set; }     public string Country { get; set; }     public string Role { get; set; } } [HttpPost] public ViewResult Edit([Bind(Include = "FirstName,LastName,Country")] User user) {     if(Request.User.Id != user.Id) {         return Forbidden("Requesting changing of another user");     }     var existingUser = Request.User;     user.PasswordHash = existingUser.PasswordHash;     user.Role = existingUser.Role;     UserService.UpdateUser(user);         return Ok(); }

Java - insecure

public class User {     public int id;     public String firstName;     public String lastName;     public String passwordHash;     public String country;     public String role; } @RequestMapping(value = "/updateUser", method = RequestMethod.POST) public String updateUser(User user) {         userService.update(user);         return "userUpdatedPage"; }

‍ Java - secure

public class UserViewModel {    public String firstName;    public String lastName;    public String country; } public class User {    public int id;    public String firstName;    public String lastName;    public String passwordHash;    public String country;    public String role; } @RequestMapping(value = "/updateUser", method = RequestMethod.POST) public String updateUser(@AuthenticationPrincipal User currentUser, UserViewModel userViewModel) {        currentUser.firstName = userViewModel.firstName;        currentUser.lastName = userViewModel.lastName;        currentUser.country = userViewModel.country;                userService.update(currentUser);        return "userUpdatedPage"; }

Javascript - insecure

app.get('/user/update',  (req, res) => {     var user = req.user;     Object.assign(user, req.body);     UserService.Update(user);      return "User has been updated"; })

Javascript - secure

app.get('/user/update',  (req, res) => {     var user = req.user;     user.firstName = req.body.firstName;     user.lastName = req.body.lastName;     user.country = req.body.country;     UserService.Update(user);     return "User has been updated"; })

Python - Insecure

@app.route("/user/update", methods=['POST']) def update_user():     user = request.user     form = request.form.to_dict(flat=True)     for key, value in form.items():         setattr(user, key, value)     UserService.UpdateUser(user)         return redirect("/user", code=201)

Python - Secure

@app.route("/user/update", methods=['POST']) def update_user():     user = request.user     form = request.form     user.firstName = form.firstName     user.lastName = form.lastName     UserService.UpdateUser(user)     return redirect("/user", code=201)

what is mass assignment security

Injection - XSS

what is mass assignment security

Injection - Path Traversal

what is mass assignment security

Using Components with Known Vulnerabilities

what is mass assignment security

Insufficient Logging and Monitoring

what is mass assignment security

Security misconfiguration - XXE detailed

what is mass assignment security

Security Misconfiguration

what is mass assignment security

Server-Side Request Forgery

what is mass assignment security

Password Storage

what is mass assignment security

Authentication and Authorization

what is mass assignment security

File Upload

Injection 101, sql injection.

what is mass assignment security

Command Injection

Secure Code Warrior Learning Platform

Discover the Secure Code Warrior Learning Platform

We secure software through developer-driven security at the start of the software development lifecycle.

websights

Burp Scanner

Burp Suite's web vulnerability scanner

Burp Suite's web vulnerability scanner'

Product comparison

What's the difference between Pro and Enterprise Edition?

Burp Suite Professional vs Burp Suite Enterprise Edition

Download the latest version of Burp Suite.

The latest version of Burp Suite software for download

  • Web Security Academy
  • API testing

Lab: Exploiting a mass assignment vulnerability

PRACTITIONER

To solve the lab, find and exploit a mass assignment vulnerability to buy a Lightweight l33t Leather Jacket . You can log in to your own account using the following credentials: wiener:peter .

Required knowledge

To solve this lab, you'll need to know:

  • What mass assignment is.
  • Why mass assignment may result in hidden parameters.
  • How to identify hidden parameters.
  • How to exploit mass assignment vulnerabilities.

These points are covered in our API Testing Academy topic.

Launching labs may take some time, please hold on while we build your environment.

In Burp's browser, log in to the application using the credentials wiener:peter .

Click on the Lightweight "l33t" Leather Jacket product and add it to your basket.

Go to your basket and click Place order . Notice that you don't have enough credit for the purchase.

In Proxy > HTTP history , notice both the GET and POST API requests for /api/checkout .

Notice that the response to the GET request contains the same JSON structure as the POST request. Observe that the JSON structure in the GET response includes a chosen_discount parameter, which is not present in the POST request.

Right-click the POST /api/checkout request and select Send to Repeater .

In Repeater, add the chosen_discount parameter to the request. The JSON should look like the following:

{ "chosen_discount":{ "percentage":0 }, "chosen_products":[ { "product_id":"1", "quantity":1 } ] }

Send the request. Notice that adding the chosen_discount parameter doesn't cause an error.

Change the chosen_discount value to the string "x" , then send the request. Observe that this results in an error message as the parameter value isn't a number. This may indicate that the user input is being processed.

Change the chosen_discount percentage to 100 , then send the request to solve the lab.

Community solutions

Register for free to track your learning progress

The benefits of working through PortSwigger's Web Security Academy

Practise exploiting vulnerabilities on realistic targets.

Record your progression from Apprentice to Expert.

See where you rank in our Hall of Fame.

Already got an account? Login here

Test APIs for vulnerabilities using Burp Suite

What is a mass-assignment attack?

Mass-assignment, sometimes also referred to as an over-posting attack, is an attack on (web) applications in which an attacker can arbitrarily modify elements of an object. Applications that use model binding in a request in particular can be vulnerable to this attack. With model binding, a developer does not have to write code which fields are entered within a form. This is used to save code. However, an attacker can use this to change other fields from the database/object.

How does mass assignment work?

Suppose an application has an object or table with the following fields:

name = "John" isAdmin = False

The application has a form to change the name. When this is sent, the client sends the following request:

POST /profile HTTP/1.1 Host: example.com

field[name]=John

Now we modify the request to the following:

field[isAdmin]=True

If the application is vulnerable, it will modify the isAdmin field instead of the name field.

In practice

Mass-assignment vulnerabilities are often difficult to find manually, because the attacker needs to know how the data model of the application works. In the above example, the attacker just needs to know that the “isAdmin” property exists. Yet such vulnerabilities do occur, often with major consequences. A well-known example is the vulnerability on GitHub, which allows the attacker to take over random repositories via over posting . The best way to detect such vulnerabilities is to use a Static Code Analyzer, such as Fortify. In the case of Fortify, the tool will give a finding called “Mass assignment secure binder”.

How to prevent?

The solution is not immediately obvious, since each framework has its own implementation of binding. However, it is often possible to indicate which properties may and may not be modified. A more generic solution is to check which fields come in before binding. During a pentest we check for mass-assignment attacks. Wondering if your application is vulnerable? Please contact with us.

  • Network Pentest
  • Website Security Check
  • Phishing Campaign
  • Mystery Guest
  • Why CyberAnt
  • Knowledge base

Marconiweg 1 3899 BR Zeewolde

[email protected] +31 (0)85 047 1590

what is mass assignment security

Deze site maakt gebruik van cookies. Door verder te surfen op de site gaat u akkoord met ons gebruik van cookies.

Cookie and Privacy Settings

We may request cookies to be set on your device. We use cookies to let us know when you visit our websites, how you interact with us, to enrich your user experience, and to customize your relationship with our website.

Click on the different category headings to find out more. You can also change some of your preferences. Note that blocking some types of cookies may impact your experience on our websites and the services we are able to offer.

These cookies are strictly necessary to provide you with services available through our website and to use some of its features.

Because these cookies are strictly necessary to deliver the website, refusing them will have impact how our site functions. You always can block or delete cookies by changing your browser settings and force blocking all cookies on this website. But this will always prompt you to accept/refuse cookies when revisiting our site.

We fully respect if you want to refuse cookies but to avoid asking you again and again kindly allow us to store a cookie for that. You are free to opt out any time or opt in for other cookies to get a better experience. If you refuse cookies we will remove all set cookies in our domain.

We provide you with a list of stored cookies on your computer in our domain so you can check what we stored. Due to security reasons we are not able to show or modify cookies from other domains. You can check these in your browser security settings.

We also use different external services like Google Webfonts, Google Maps, and external Video providers. Since these providers may collect personal data like your IP address we allow you to block them here. Please be aware that this might heavily reduce the functionality and appearance of our site. Changes will take effect once you reload the page.

Google Webfont Settings:

Google Map Settings:

Google reCaptcha Settings:

Vimeo and Youtube video embeds:

You can read about our cookies and privacy settings in detail on our Privacy Policy Page.

LRQA Nettitude Labs Logo

LRQA Nettitude Command & Control Framework - Free and Open Source

Vulnerability research, regular vulnerability disclosures, red team training, learn to be the best, from the best, explaining mass assignment vulnerabilities.

Programming frameworks have gained popularity due to their ability to make software development easier than using the underlying language alone. However, when developers don’t fully understand how framework functionality can be abused by attackers, vulnerabilities are often introduced.

One commonly used framework feature is known as mass assignment, a technique designed to help match front end variables to their back end fields, for easy model updating.

Implementing mass assignment

We’ll be using PHP/Laravel as an example to demonstrate how mass assignment works via the Laravel framework. Let’s imagine you have a form which allows a user to update some of their profile details, and that form contains the following fields:

Within the Laravel controller, one way to update those fields would be as follows:

An alternative way to do this would be to take advantage of mass assignment, which would look something like this:

This code updates the User model with the values from the Request (in this case the HTML fields for name, email, address and phone) assuming that the input names match the models fields. This obviously saves superfluous lines of code, since all fields can be updated at once, instead of specifying individually.

The mass assignment vulnerability

So, how might an attacker exploit this?

As may be evident from the code above, the framework is taking all the input fields from the Request variable and updating the model without performing any kind of validation. Therefore, its trusting that all the fields provided are intended to be updateable.

Although the example currently only provides options for updating fields such as name and email, there are usually more columns in the User table which aren’t displayed on the front end. In this case, lets imagine that there is also a field named role , which determines the privilege of the user. The role field wasn’t displayed in the HTML form because the developers didn’t want users changing their own role.

However, with our understanding that the controller is simply trusting all input provided by the request to update the User model, an attacker can inject their own HTML into the page to add a field for role , simply by using built in browser tools. This can also be done by intercepting the request using a proxy and appending the field name and value, or by any other technique that allows client side modification.

This time, when the controller is reached, the user model will be updated with the expected fields (name, email, address, phone) as well as the additional role field provided.  In this case, the vulnerability leads to privilege escalation.

This particular example demonstrates how mass assignment can be exploited to achieve privilege escalation, however it is often possible to bypass other controls using the same technique. For example, an application might prevent a username from being edited when updating profile information, to ensure integrity and accountability across audit trails. Using this attack, a user could perform malicious actions under the guise of one username before switching to another.

Countermeasures

There are several ways to protect against mass assignment attacks. Most frameworks provide defensive techniques such as those discussed in this section.

The general idea is to validate input before updating the model. The safest way to do this is to somewhat fall back to the original and more convoluted process of specifying each field individually. This also has the added benefit of providing the ability to add additional validation to each field beyond ensuring only expected fields are updated.

In Laravel, one way to do this would be as shown below; include some validation such as the maximum number of permissible characters for the name field, and then update the User model with the validated data. As the validate() function lists the exact fields expected, if the role field was appended as demonstrated in our previous sample attack, it would be ignored and have no effect.

An alternative method is to utilize allow lists and deny lists to explicitly state what fields can and cannot be mass assigned. In Laravel, this can be done by setting the $fillable property on the User model to state which fields may be updated in this way. The code below lists the four original fields from the HTML form, so if an attacker tried to append the role field, since its not in the $fillable allow list, it won’t be updated.

Similarly, deny lists can be used to specify which fields cannot be updated via mass assignment. In Laravel, this can be done using the $guarded property in the model instead. Using the following code would have the same effect as the above, since the role parameter has been deny listed.

Mass assignment vulnerabilities are important issues to check for during software development and during penetration tests because they are often not picked up by automated tools, due to them often having a logic component. For example, a tool will not likely have the context to understand if a user has managed to escalate their privilege after a specially crafted request.

They are also often overlooked by developers, partly due to lack of awareness for how certain features can be exploited, but also due to pressure to complete projects since its faster to use mass assignment without performing input validation.

It’s important to understand that mass assignment vulnerabilities exist and can be exploited with high impact. A strong software development lifecycle and associated testing regime will reduce the likelihood of these vulnerabilities appearing in code.

Share This Story, Choose Your Platform!

Related posts.

This Badge is My Badge

API Security

Mass Assignment Vulnerability: How to Test Mass Assignment in APIs using Akto

This blog is about learning mass assignment vulnerability, how to find it manually, how to test for it using Akto and finally how to prevent it.

what is mass assignment security

In 2017, Equifax, an American multinational consumer credit reporting agency, experienced a data breach . Hackers exploited a vulnerability in Equifax's web application that allowed them to access sensitive personal information of millions of customers. The vulnerability was caused by an unpatched version of Apache Struts, a popular open-source framework used for building web applications. The hackers were able to exploit the vulnerability to gain access to sensitive data by modifying the values of certain parameters using a technique called mass assignment . The result was a massive data breach that compromised the personal information of millions of people, causing widespread damage and leading to numerous lawsuits and investigations.

This highlights the importance of properly securing APIs, particularly from mass assignment vulnerabilities, through regular testing and validation of user input, as well as limiting the properties that can be modified through user input. In this blog, we will cover the following:

1. What is Mass Assignment?

2. How to find Mass Assignment Vulnerability?

3. Automation with Akto

4. How to prevent mass assignment?

What is Mass Assignment?

Mass Assignment vulnerability is a security flaw that can occur in API when user input is directly used to modify the properties of an object. This can allow attackers to modify data and perform unauthorized actions on an application. To prevent this vulnerability, it is important to validate and sanitize user input, and to limit the properties that can be modified through user input. Mass Assignment is one of the OWASP Top 10 API vulnerabilities. Therefore, it is crucial to test for it from a security standpoint.

OWASP API Top 10: https://owasp.org/www-project-api-security/

How to find Mass Assignment Vulnerability?

The most effective method to discover mass assignment vulnerabilities in an API endpoint is by analyzing an it’s requests and responses. The recommended tool for this task is a web application scanner, such as BurpSuite.

Steps to find APIs with potential Mass Assignment vulnerability:

1. Turn on the Burp Suite proxy and start visiting every endpoint in a web application. Focus on endpoints that allow a user to create resources into the application such as creating account, updating, creating wallet or inviting a user.

2. Once you have added the target to the scope in BurpSuite, try to interact with the application in a variety of ways. This could include submitting different types of input or performing different actions within the application.

3. If you encounter any parameters or variables in the response that are being assigned to the user, take note of them. These variables can often be manipulated to gain access to sensitive data or functionality. For example, variables like " role:authenticated ", " role:customer ", " balance:0 ", " timestamp:XX ", " user_id:XXX ", etc.

4. Additionally, make sure to explore all of the functionality of the application, including any areas that may not be immediately obvious. This can help you identify additional vulnerabilities that may not be apparent at first glance.

Let's assume that, after account creation, you find a variable in the response such as " role:customer ". The server assigns this "role" variable to identify the user's role and assign privileges accordingly.

How to exploit manually?

To perform this test, follow the steps below:

1. Search for the request that assigns a role to the user on the server-side.

2. Once you have found the request, try modifying the JSON data of the request by changing the value of the variable that assigns the user's role (e.g., "admin").

3. Analyze the response from the server. If the response returns " role:admin ", it means that the variable has been successfully overwritten by the user.

4. Another way to exploit is to attempt various HTTP methods such as POST, PUT, and PATCH, and send the request.

5. To confirm the vulnerability, return to the application and check if there are any additional features or pages that you can now access. For example, you may be able to access a page that previously displayed a 403 error, or access the admin dashboard.

6. If you can access additional features or pages, it is likely that the application is vulnerable to a privilege escalation attack, and further investigation is required.

Test for Mass Assignment using the best proactive API Security product

Our customers love us for our proactive approach and world class API Security test templates. Try Akto's test library yourself in your testing playground. Play with the default test or add your own.

Start Testing

How much time does it take?

Finding and exploiting vulnerabilities in an API endpoint can take hours or even days to complete. The duration depends on the number of API endpoints and their complexity which is too cumbersome.

Automation with Akto

Each step I described above takes time and requires proper analysis of requests and responses. Doing so manually, could take hours or even days, depending on the complexity of the APIs. Just imagine doing this for thousands of APIs! It sounds difficult, right?

Akto can make this task easier for you by scanning thousands of endpoints with just one click!

If you have not yet installed Akto, you can do so from the Akto GitHub page along with the Akto extension in Burp Suite. For demonstration purposes, we will use OWASP Juice Shop .

Akto Burp Extension

There are multiple ways to create an API inventory in Akto that work in both the Community and Professional editions. You can do this by importing a .har file or forwarding traffic from BurpSuite.

Steps to Create API Inventory using Akto Extension:-

1. Run Akto in docker

2. Launch BurpSuite

3. Download Akto Burp extension. Check this out for setup.

4. Turn on burp proxy and browse the target application

what is mass assignment security

While browsing, you will soon notice that the Akto extension captures many requests. To filter the requests you are interested in, simply left-click on the target request and choose "Use Request.path Value as Log Filter". This will automatically add a filter to the filter bar since the extension captures all requests from the proxy tab.

what is mass assignment security

Open the Akto Dashboard, where you will be able to see that an API Inventory is created automatically with a name. The default name of the collection is " burp ," but it can be changed through the "options" menu in the Akto burp extension.

Exploitation: Run Test

what is mass assignment security

Click on "Run Test". A "Configure Test" box will pop up, asking for the vulnerabilities you want to test for. Select and deselect as needed, then run the test. Afterward, move to the "Testing" tab to see the status of the test.

what is mass assignment security

As you can see, I've selected Mass Assignment for my testing and left the other default settings as they are.

Findings: Test Results

Move to the Testing tab to see test results

what is mass assignment security

Below, you can see a list of endpoints that were tested, along with their severity. Since I wanted to test for mass assignment, I selected "Mass Assignment" from the " Issue Category " tab to filter the endpoints that are vulnerable to mass assignment.

Clicking on the first request, I can see three options – “Description, Original, Attempt”.

Description: Information about the found vulnerability.

Original : Intended or normal client request and response.

Attempt : Akto attempt to exploit the vulnerability.

what is mass assignment security

In the original tab request, we can see that the response says "role:customer". Therefore, this is the variable that the server is using to assign roles and privileges. In this case, it's a customer role with fewer privileges.

what is mass assignment security

Now switch to the attempt option, the Akto engine was able to identify the variable used and hence tried assigning " role:admin " by sending a request to the server. The server updated the variable value to "admin," leading to a successful mass assignment exploitation. Now, any normal user can become an admin just by assigning a variable in the client request, which is a critical vulnerability We found it in just seconds.

When to use Burp vs Akto?

Both manual and automated testing are helpful for detecting vulnerabilities in an API endpoint. When you have just deployed a new API inventory, start by testing in Akto to cover all the popular mass assignment vulnerability attacks. After you finish testing, manually explore the critical APIs in Burp to find vulnerabilities you couldn’t find using Akto. This approach can help you save time and focus on critical endpoints.

How to Prevent it?

APIs take input inside the JSON body and set data according to it. Therefore, it is vulnerable to injection attacks. The most important step is input sanitization to prevent such attacks. Also, here are some additional points to keep in mind while writing code.

Limit the properties that can be modified by the user. It can be done by ensuring that the payload meets the defined schema, and rejecting any payload that does not.

Whitelist or blacklist to specify which properties can or cannot be updated by the client. If your system allows it, try making properties read-only using the @read-only annotation.

If possible, use a separate API endpoint for admin functionality instead of using parameters to assign roles to the user in the same API endpoint.

Try to avoid using functions like unserialize() in PHP applications.

When using ASP.NET Core or Apache Structs, automatic binding of request parameters into objects can sometimes cause issues. In such cases, use the [Bind] attribute model to select only bindable attributes.

Provide explicit definitions for all the parameters that the server is expecting, as well as those that it is not expecting.

Getting Started on Mass Assignment

Start your API testing with Akto, You can download it from the GitHub page and follow the instructions for a successful installation. Also, don't forget the BurpSuite Akto extension, which you can download by following steps from here .

Looking forward to hearing from you. Please let us know if you have any ideas that you would like us to include.

Happy API security testing!

Want to ask something?

Our community offers a network of support and resources. You can ask any question there and will get a reply in 24 hours.

Ask community now

Follow us for more updates

Keep reading

PCI DSS Guidelines

PCI DSS Guidelines

PCI DSS includes a set of rules designed to ensure the safety and security of credit and debit card information, protecting it from data breaches.

Akto Introduces New Usage-Based Flexible Pricing Model

Product updates

Akto Introduces New Usage-Based Flexible Pricing Model

You can now upgrade your Akto account to our new usage-based pricing model, offering you greater flexibility and value.

Web Application Firewall Solutions

10 Best WAF Solutions

10 best Web Application Firewall (WAF) solutions that filter and monitor web traffic, blocking malicious hackers before they can attack.

Experience enterprise-grade API Security solution

Book a demo

IMAGES

  1. What is Mass Assignment?

    what is mass assignment security

  2. Mass Assignment

    what is mass assignment security

  3. Exploiting Mass Assignment Vulnerabilities

    what is mass assignment security

  4. Mass Assignment Vulnerability For Application Framework

    what is mass assignment security

  5. Exploiting Mass Assignment Vulnerabilities

    what is mass assignment security

  6. 7 Laravel 7 for beginner

    what is mass assignment security

VIDEO

  1. Individual Assignment Security & Safety Audit

  2. MASS OUTAGES: The Gov And Media Programming Turned Out To Be Predictive!

  3. API Testing Methodology, w/ Dr. Katie Paxton-Fear

  4. Mass Effect 2: Assignment

  5. Exploiting a mass assignment vulnerability

  6. Digital Storytelling

COMMENTS

  1. Mass Assignment Cheat Sheet

    This is called a Mass Assignment vulnerability. Alternative Names¶ Depending on the language/framework in question, this vulnerability can have several alternative names: Mass Assignment: Ruby on Rails, NodeJS. Autobinding: Spring MVC, ASP NET MVC. Object injection: PHP. Example¶ Suppose there is a form for editing a user's account information:

  2. API6:2019

    API6:2019 - Mass Assignment. Exploitation usually requires an understanding of the business logic, objects' relations, and the API structure. Exploitation of mass assignment is easier in APIs, since by design they expose the underlying implementation of the application along with the properties' names. Modern frameworks encourage developers ...

  3. What is mass assignment?

    By exploiting mass assignment vulnerabilities, a malicious actor could create multiple security problems including. Data tampering: Attackers can modify sensitive information in the database, such as password or account balance; Data theft: Attackers can gain access to confidential information stored in the database; Elevation of privilege: Attackers can manipulate the properties of an object ...

  4. Mass Assignment Vulnerability: How It Works & 6 Defensive Measures

    6 Ways to Mitigate the Security Risks of Mass Assignment Here are some of the measures that can be used to prevent mass assignment attacks. 1. Allowlist Allowed Attributes. Define which attributes can be safely exposed to mass assignment. Using an allowlist approach ensures only specified attributes can be updated through user input.

  5. Mass Assignment Vulnerability: Understanding & Mitigating the Risks in

    The "Mass Assignment" vulnerability is a security flaw that occurs when an application assigns user input directly to model attributes without proper validation or sanitization. This can lead to unauthorized access and modification of sensitive data, potentially compromising the security of the application and its users. ...

  6. Mass Assignment · OWASP Cheat Sheet Series

    This is called a Mass Assignment vulnerability. Alternative Names. Depending on the language/framework in question, this vulnerability can have several alternative names: Mass Assignment: Ruby on Rails, NodeJS. Autobinding: Spring MVC, ASP NET MVC. Object injection: PHP. Example. Suppose there is a form for editing a user's account information:

  7. Mass assignment vulnerability

    Mass assignment is a computer vulnerability where an active record pattern in a web application is abused to modify data items that the user should not normally be allowed to access such as password, granted permissions, or administrator status.. Many web application frameworks offer an active record and object-relational mapping features, where external data in serialization formats is ...

  8. What is Mass Assignment? Attacks and Security Tips

    What is a Mass Assignment vulnerability? To make things easier for developers, many frameworks include features that automatically associate the parameters of an HTTP request with variables linked to an object in the application code. A Mass Assignment vulnerability occurs when the server does not correctly filter the data transmitted by the ...

  9. API Security 101: Mass Assignment & Exploitation in the Wild

    A mass assignment without a whitelist of allowed "Key-Value Pairs" could allow an attacker to use arbitrary values to create or update the resources abusing the applications' regular workflow. Privilege escalation is one of the most common vulnerabilities arising from Mass Assignment vulnerability. According to OWASPthis vulnerability ...

  10. Mass Assignment 101

    A mass assignment attack is a type of security vulnerability that occurs when an attacker is able to modify the values of multiple object's properties by passing them in as part of an HTTP request. This is typically done in bulk where multiple objects are changed at once using attack automation tooling. ...

  11. Mass Assignment 101

    A mass assignment attack is a type of security vulnerability that occurs when an attacker is able to modify the values of multiple object's properties by passing them in as part of an HTTP request. This is typically done in bulk where multiple objects are changed at once using attack automation tooling. This can allow the attacker to set the ...

  12. What is a Mass Assignment Vulnerability?

    What is a Mass Assignment Attack? In order to reduce the work for developers, many frameworks provide convenient mass-assignment functionality. This lets developers inject an entire set of user-entered data from a form directly into an object or database. Without it, developers would be forced to tediously add code specifically for each field ...

  13. What is Mass Assignment?

    Understanding Mass Assignment in Web Development. When it comes to web application development, Mass Assignment is a pivotal concept that can either empower users or expose your application to grave security risks. In simple terms, Mass Assignment allows users to submit data that is then used to update the corresponding model attributes with ease.

  14. API-Security/editions/2019/en/0xa6-mass-assignment.md at master

    API6:2019 - Mass Assignment. Exploitation usually requires an understanding of the business logic, objects' relations, and the API structure. Exploitation of mass assignment is easier in APIs, since by design they expose the underlying implementation of the application along with the properties' names.

  15. What is Mass Assignment: How We Can Help

    How to Prevent Mass Assignment . Similar to BOLA, prevention starts with defensive programming techniques, such as enforcing a standardized authorization strategy within all endpoints of your API, taking into account the user authorization level and the authorization requirements of all referenced resources, and rigorously maintaining security policies controlling which fields are editable ...

  16. Secure Coding Guidelines

    Mass Assignment is a vulnerability where API endpoints don't restrict which properties of their associated object can be modified by a user. This vulnerability can occur when making use of a library/framework that allows for the automatic binding of HTTP parameters onto a model that then goes on to be used without any validation. The use of ...

  17. Lab: Exploiting a mass assignment vulnerability

    Attack surface visibility Improve security posture, prioritize manual testing, free up time. CI-driven scanning More proactive security - find and fix vulnerabilities earlier. Application security testing See how our software enables the world to secure the web. DevSecOps Catch critical bugs; ship more secure software, more quickly. Penetration testing Accelerate penetration testing - find ...

  18. What is a mass-assignment attack?

    Mass-assignment, sometimes also referred to as an over-posting attack, is an attack on (web) applications in which an attacker can arbitrarily modify elements of an object. Applications that use model binding in a request in particular can be vulnerable to this attack. ... Due to security reasons we are not able to show or modify cookies from ...

  19. Explaining Mass Assignment Vulnerabilities

    Explaining Mass Assignment Vulnerabilities. Programming frameworks have gained popularity due to their ability to make software development easier than using the underlying language alone. However, when developers don't fully understand how framework functionality can be abused by attackers, vulnerabilities are often introduced.

  20. Mass Assignment Vulnerability

    Mass Assignment vulnerability is a security flaw that can occur in API when user input is directly used to modify the properties of an object. This can allow attackers to modify data and perform unauthorized actions on an application. To prevent this vulnerability, it is important to validate and sanitize user input, and to limit the properties ...

  21. WSTG

    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.

  22. Golf courses

    Golf courses, and in particular Donald Trump's own properties, have long been a source of concern among Secret Service officials tasked with securing the grounds while the commander in chief ...