• 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
  • 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
  • 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]

  • 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.

We'd really appreciate it if you could take a minute to rate how valuable this lesson was for you and provide feedback to help us improve! Also, make sure to check out our lessons on other common vulnerabilities.

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?

Denial of service, double free, excessive agency.

VAADATA – Ethical Hacking Services

What is Mass Assignment? Attacks and Security Tips

What is a mass assignment vulnerability.

what is mass assignment

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

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

what is mass assignment

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

Server response:

what is mass assignment

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

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

Full request:

what is mass assignment

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

Modifying java serialized objects as easily as json, what is a dos attack types, exploitations and security tips, antivirus and edr bypass techniques.

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 " ".

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.

what is mass assignment

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 loves us

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.

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 Security Check
  • 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

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.

what is mass assignment

Popular with:

Application security, 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).

Abhay Bhargav

Teams that train together, work together

what is mass assignment

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

what is mass assignment

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

Threatx security xchange: terence runge, ciso, announcing new threatx api protection capabilities, account takeover (ato): types, detection, prevention and protection, join our newsletter.

Cobalt PtaaS + DAST combines manual pentests and automated scanning for comprehensive application security.

  • Application Pentest
  • Secure Code Review
  • Threat Modeling
  • 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

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.

Pacman Attack Example

How Low Severity Vulns Become Critical: PACMAN Attack Example

Common Network Security Vulnerabilities cover image

Common Network Security Vulnerabilities

A Pentester’s Guide to SQL Injection (SQLi) cover image

A Pentester’s Guide to SQL Injection (SQLi)

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

blog post image

Andrew Lock | .NET Escapades Andrew Lock

  • ASP.NET Core

Preventing mass assignment or over posting in ASP.NET Core

Mass assignment, also known as over-posting, is an attack used on websites that involve some sort of model-binding to a request. It is used to set values on the server that a developer did not expect to be set. This is a well known attack now, and has been discussed many times before , (it was a famous attack used against GitHub some years ago ), but I wanted to go over some of the ways to prevent falling victim to it in your ASP.NET Core applications.

How does it work?

Mass assignment typically occurs during model binding as part of MVC. A simple example would be where you have a form on your website in which you are editing some data. You also have some properties on your model which are not editable as part of the form, but instead are used to control the display of the form, or may not be used at all.

For example, consider this simple model:

It has two properties, but we only actually going to allow the user to edit the Name property - the IsAdmin property is just used to control the markup they see:

So the idea here is that you only render a single input tag to the markup, but you post this to a method that uses the same model as you used for rendering:

This might seem OK - in the normal browser flow, a user can only edit the Name field. When they submit the form, only the Name field will be sent to the server. When model binding occurs on the model parameter, the IsAdmin field will be unset, and the Name will have the correct value:

Normal post

However, with a simple bit of HTML manipulation, or by using Postman/Fiddler , a malicious user can set the IsAdmin field to true . The model binder will dutifully bind the value, and you have just fallen victim to mass assignment/over posting:

Malicious post with overposting

Defending against the attack

So how can you prevent this attack? Luckily there's a whole host of different ways, and they are generally the same as the approaches you could use in the previous version of ASP.NET. I'll run through a number of your options here.

1. Use BindAttribute on the action method

Seeing as the vulnerability is due to model binding, our first option is to use the BindAttribute :

The BindAttribute lets you whitelist only those properties which should be bound from the incoming request. In our case, we have specified just Name , so even if a user provides a value for IsAdmin , it will not be bound. This approach works, but is not particularly elegant, as it requires you specify all the properties that you want to bind.

2. Use [Editable] or [BindNever] on the model

Instead of applying binding directives in the action method, you could use DataAnnotations on the model instead. DataAnnotations are often used to provide additional metadata on a model for both generating appropriate markup and for validation.

For example, our UserModel might actually be already decorated with some data annotations for the Name property:

Notice that as well as the Name attributes, I have also added an EditableAttribute . This will be respected by the model binder when the post is made, so an attempt to post to IsAdmin will be ignored.

The problem with this one is that although applying the EditableAttribute to the IsAdmin produces the correct output, it may not be semantically correct in general. What if you can edit the IsAdmin property in some cases? Things can just get a little messy sometimes.

As pointed out by Hamid in the comments, the [BindNever] attribute is a better fit here. Using [BindNever] in place of [Editable(false)] will prevent binding without additional implications.

3. Use two different models

Instead of trying to retrofit safety to our models, often the better approach is conceptually a more simple one. That is to say that our binding/input model contains different data to our view/output model. Yes, they both have a Name property, but they are encapsulating different parts of the system so it could be argued they should be two different classes:

Here our BindingModel is the model actually provided to the action method during model binding, while the UserModel is the model used by the View during HTML generation:

Even if the IsAdmin property is posted, it will not be bound as there is no IsAdmin property on BindingModel . The obvious disadvantage to this simplistic approach is the duplication this brings, especially when it comes to the data annotations used for validation and input generation. Any time you need to, for example, update the max string length, you need to remember to do it in two different places.

This brings us on to a variant of this approach:

4. Use a base class

Where you have common properties like this, an obvious choice would be to make one of the models inherit from the other, like so:

This approach keeps your models safe from mass assignment attacks by using different models for model binding and for View generation. But compared to the previous approach, you keep your validation logic DRY .

There is also a variation of this approach which keeps your models completely separate, but allows you to avoid duplicating all your data annotation attributes by using the ModelMetadataTypeAttribute .

5. Use ModelMetadataTypeAttribute

The purpose of this attribute is to allow you defer all the data annotations and additional metadata about you model to a different class. If you want to keep your BindingModel and UserModel hierarchically distinct, but also son't want to duplicate all the [MaxLength(200)] attributes etc, you can use this approach:

Note that only the UserModel contains any metadata attributes, and that there is no class hierarchy between the models. However the MVC model binder will use the metadata of the equivalent properties in the UserModel when binding or validating the BindingModel .

The main thing to be aware of here is that there is an implicit contract between the two models now - if you were to rename Name on the UserModel , the BindingModel would no longer have a matching contract. There wouldn't be an error, but the validation attributes would no longer be applied to BindingModel .

This was a very quick run down of some of the options available to you to prevent mass assignment. Which approach you take is up to you, though I would definitely suggest using one of the latter 2-model approaches. There are other options too, such as doing explicit binding via TryUpdateModelAsync<> but the options I've shown represent some of the most common approaches. Whatever you do, don't just blindly bind your view models if you have properties that should not be edited by a user, or you could be in for a nasty surprise.

And whatever you do, don't bind directly to your EntityFramework models. Pretty please.

Popular Tags

what is mass assignment

Stay up to the date with the latest posts!

what is mass assignment

How Do Mass Assignment Vulnerabilities Impact My Business?

what is mass assignment

Web application security is a never-ending process. A web application has different components based on its complexity. It’s needless to say that attackers will leave no stone unturned and will try to attack every piece of the application. Hence, it’s important to secure all parts of the application. One of the first things any application owner should do to secure their application is to identify known vulnerabilities and fix them. In this post, we’ll discuss one such vulnerability: mass assignment vulnerability.

Mass assignment vulnerabilities are less common. But they pose great risks to applications and organizations. A mass assignment vulnerability could lead to less critical exploitations such as changing the price of a product to buy it at a cheaper price. But it could also lead to an attacker taking complete control over the application. It depends on how the application is built.

By the end of the post, you’ll understand what mass assignment is and how it leads to a vulnerability. We’ll also look at some examples and understand its impact on business.

what is mass assignment

What Is Mass Assignment?

Modern applications are pretty advanced and complex. But one of the basic functions of most applications is taking user input and storing it in a database. All the way from signing up for the application to adding personal details, the user inputs data. And all that data has to be stored somewhere.

Traditionally, developers had to add code to store each piece of data. In most cases, doing this would just be copying and pasting code and changing some attributes or using a loop. But it’s still something developers could save time on. Additionally, with this approach developers had redundant code in their codebase.

So, to save developers some time on user inputs, most frameworks provided functionality for easy mapping. Mass assignment is one such functionality. Mass assignment lets developers bind user-side data into data objects using a single line of code. This sounds cool, but it can lead to mass assignment vulnerability. So, how does that happen?

What Is Mass Assignment Vulnerability?

Mass assignment simplifies handling user input. But if you don’t take care of security, this functionality can allow attackers to modify user requests and map data that they’re not supposed to. This is known as mass assignment vulnerability. Now, let’s try to understand how this works.

Let’s say your application uses a form for a user to sign up for your application. The form would collect basic information such as name, email address, password, etc. The data entered in the form comes to the server from the user’s browser in the form of a request. Then the server would insert the data into the database. This is how the signup process is designed to work.

The application can have normal users or users with special privileges referred to as admin users by the application. And the application could use a boolean value to mark a user as an admin or not. You wouldn’t want just any user signing up as an admin. So, by default, the value for this boolean value will be false (e.g., isAdmin = False ). Let’s assume that this value is coded as a hidden element on the webpage and the request to the server is designed to have isAdmin = False by default.

Now, when a user signs up, the browser sends a request with the following data:

“name”:”Tony”,”email”:”[email protected]”,”password”:”secret”,”isAdmin”:false

Then, the server inserts this data into the database. This could lead to a mass assignment vulnerability exploitation.

what is mass assignment

Malicious Request

Looking at requests is pretty easy using tools like Burpsuite. Attackers can intercept the request and see what attributes and values the browser sends to the server. If the attackers discover the isAdmin field, they could modify the request and set it to true . And by doing this, the server would add the attacker’s email address as an admin.

This is how attackers can exploit mass assignment functionality.

Examples of Mass Assignment Vulnerability

Now that you understand mass assignment and how it can lead to vulnerabilities, let’s move from theory to seeing things in action. We’ll discuss two types of mass assignment vulnerabilities:

  • API request with hidden field
  • application configured default values at database level

API Request With Hidden Field

The first example we’ll look at is when the isAdmin field is hidden. The HTML for signup is as follows:

<form action=”http://127.0.0.1:5000/signup” method=”POST”>

<h1>Sign Up</h1>

<p>Welcome to This Application! Please sign up to continue.</p>

Name*: <input type=”text” placeholder=”Enter Name” name=”name” required><br/><br/>

Email*: <input type=”text” placeholder=”Enter Email” name=”email” required><br/><br/>

Password* : <input type=”password” placeholder=”Enter Password” name=”pass” required><br/><br/>

<input type=”hidden”name=”isAdmin” value=false required>

<a href=”#” style=”color:blue”>Terms & Conditions</a><br/>

<button type=”button” class=”cancelbtn”>Cancel</button>

<button type=”submit” class=”signupbtn”>Sign Up</button>

</form>

I’m on a Kali machine and will be using the Apache2 server that comes with the OS installation. To start the Apache2 server, I run the command service apache2 start. Then, I’ll place the HTML file with the above script in the /var/www/html directory. I can open the webpage now by visiting localhost on my browser.

what is mass assignment

Python API Server

I’ll use a Python Flask API server on the back end. This API server will take the values from the form and display them on the terminal. To keep it simple, I’m not inserting the data into a database. The Python 3 script for the API server is as follows:

from flask import Flask, json, request, jsonify 

import os 

from flask_cors import CORS

api = Flask(__name__) 

api.config[‘SECRET_KEY’] = ‘the quick brown fox jumps over the lazy dog’ 

api.config[‘CORS_HEADERS’] = ‘Content-Type’ 

cors = CORS(api)

@api.route(‘/signup’, methods=[‘POST’]) 

def data_insert(): 

    data = {}

    data.update(request.form.to_dict(flat=True))

    print(data) 

    return (“Data Inserted”)

if __name__ == ‘__main__’: 

    api.run()

You need to install the Flask library using the command pip3 install flask . Save the above script in a Python extension file, (e.g., api.py ) and start the API server by running python3 <filename>.py . If all goes well, you should see something like this:

what is mass assignment

Now let’s enter some values and see how this works. When I click the signup button, the browser will send a request to my server. And because I’ve programmed the server to just print the values, I’ll see the data entered in the terminal.

what is mass assignment

As you can see, along with the name, email, and password, I also see the isAdmin , which is by default set to false. Now let’s see how an attacker can exploit this.

Because the data for isAdmin is present in the HTML that’s available on the browser, I can change the value using the browser without any additional tools. To do this, I’ll right-click on the browser and click the Inspect button. Next, I’ll find the hidden element and change the value of isAdmin from false to true. 

what is mass assignment

Application Configured Default Values at Database Level

In the previous example, we saw that the admin flag was present in HTML and was being sent in the request. But such cases are very rare. In most cases, these fields aren’t passed from the browser. Instead, the database itself is configured to set a default value. In such cases, you can’t modify the value from the browser and you’ll need additional tools.

For this example, I’ll use Burpsuite, which comes preinstalled in Kali. To intercept the request, you’ll have to configure Burpsuite and the browser . When you configure Burp proxy, Burpsuite doesn’t capture traffic to the localhost. Instead, you’ll have to use your LAN IP. Similarly, you’ll also have to replace 127.0.0.1 in the HTML file with the LAN IP.

what is mass assignment

Now, when I enter data and sign up, Burpsuite should intercept my traffic. By default, the isAdmin won’t be a part of the request.

what is mass assignment

So, I will add it myself.

what is mass assignment

Now my server clearly shows the modified value, and the server will add Tony as an admin. This is how attackers can leverage mass assignment vulnerabilities.

Impact of Mass Assignment Vulnerabilities

As we’ve seen in the examples, mass assignment vulnerabilities can lead to critical privilege escalation. If an attacker gets admin privileges to an application, they can steal or modify data or even bring the whole application down.

But this vulnerability doesn’t always need to be used to get privilege access. Attackers can also use it to access certain features or bypass certain checks. For example, if the application tracks whether a user’s email is verified or not using an isVerified flag, the user can modify this value and bypass email verification.

Another example could be bypassing two-factor authentication used in many organizations. An organization could be using a third-party two-factor authentication tool as an extra level of authentication and APIs for verification from the tool. Using mass assignment, an attacker could manipulate the field that indicates whether two-factor authentication was successful and could bypass the second factor of authentication even by entering wrong values. Such vulnerabilities can result in unimaginable harm.

Real-World Example: GitHub Breach

One good real-world example that clearly illustrates the impact of mass assignment vulnerability on your business is when GitHub had a security breach in 2012. A GitHub member was able to use mass assignment to gain access to repositories with super-user privileges. The member was able to do so by exploiting the public key update functionality that was vulnerable to mass assignment. Imagining an attacker getting super-user privileges to your codebase is scary. They could delete your code, bring your whole application down, or try to create more vulnerabilities for later exploitation.

When an application is a crucial element of your business, an attacker compromising it would majorly affect your business. You might end up losing all your data, lose your codebase, or even end up paying heavy fines or getting sued due to data leakage . Even bringing the system down for some time could result in a huge loss of revenue.

what is mass assignment

Mass assignment is an under-discussed security threat, but it poses a great danger to applications and businesses. We’ve seen examples of how attackers can exploit mass assignment vulnerabilities and how it can impact your business.

An application is only as secure as its least secure component. A lot of organizations focus mostly on server-side security, authentication, and authorization, which is undoubtedly crucial. But they also overestimate their API security and don’t focus much on improving it.

The Price of Hubris ebook has addressed an attacker’s way to hack APIs and what happens when organizations overestimate their API security. Finally, what we should take from this is that API security is as important as securing any other components of the application.

This post was written by Omkar Hiremath. Omkar is a cybersecurity team lead who is enthusiastic about cybersecurity, ethical hacking, and Python. He is keenly interested in bug bounty hunting and vulnerability analysis.

See product

Meet with sales.

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.

Test mass assignment vulnerability

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

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

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

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

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

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

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

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!

Follow us for more updates

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

Table of contents

Keep reading.

March Newsletter

March Product News: 98 New Tests, Dynamic wordlists, and more

This edition of Akto’s newsletter is packed with new features and tests that will greatly decrease your API Security testing time and increase targeted testing.

swagger and postman file import error

Product updates

Detailed Errors on Postman and Swagger File Import

Akto now replays APIs to automatically get data during an import of Postman and Swagger files and transparently displays reasons why each specific API couldn't be replayed in the case of an error.

Added 98 Tests

Added 98 New API Security Tests across 5 OWASP categories

Akto has introduced new tests across several categories including BOLA, Broken Authentication, Unrestricted Resource Consumption, BFLA, and SSRF that you can explore with Akto’s Test Editor.

Texas substitute teacher suspended over 'disturbing' class assignment

by STEPHANIE BECERRA | KEYE Staff

Texas substitute teacher suspended over 'disturbing' class assignment (KEYE)

HAYS COUNTY, Texas (KEYE) — A Texas substitute theater arts teacher is under investigation and was suspended Friday over concerns about a class assignment.

Hays CISD says the sub reportedly assigned Johnson High School students to perform a puppet show in which one of the puppets had to be murdered. They added that one group of students said the performance would have involved a mass shooting.

Hays CISD apologized to the students and parents and called the teacher's conduct "disturbing and unacceptable."

The teacher was hired by Hays CISD in January 2024.

An investigation remains underway and it's still unclear if that was the specific assignment.

what is mass assignment

Heroes of Rockford deadly mass stabbing honored for life-saving actions

what is mass assignment

A Winnebago County sheriff's deputy and a good Samaritan were recognized Thursday for their life-saving actions during a deadly mass stabbing in Rockford that claimed the lives of four people and injured several more.

Sheriff Gary Caruana and County Board Chairman Joe Chiarelli presented Deputy Michael Gambino and Rockford resident Keith Fahrney awards for their bravery in helping to put an end to a killing spree.

Fahrney was driving through his southeast side neighborhood on March 27 when he saw a man attacking and stabbing a woman in a front yard. Fahrney got out of his vehicle and fought the man off of the woman, getting attacked himself in the process.

"I always believed you've got to help other people," Fahrney said Thursday at the Winnebago County Board meeting where he and Gambino were honored.

More: Rockford man lauded as a hero, good Samaritan for his actions during mass stabbing

Gambino was one of the first law enforcement officers on the scene. He chased after the alleged assailant, later identified as 22-year-old Christian Soto, through the neighborhood before finally subduing him and bringing him into custody.

The victims of the March 27 attacks were killed within blocks of each other. Mother and son, Romona Schupbach and Jacob Schupbach, stabbed to death their home, U.S. Postal Service letter carrier Jay Larson was stabbed and run over with a truck while on his route and 15-year-old Jenna Newcomb was beaten to death in her home.

Soto faces multiple counts of first-degree murder among other charges.

Also at Thursday night's county board meeting, Cassidy Davenport, a senior at Hononegah High School was honored for saving a choking child at the Machesney Park Target store.

Chris Green is a Rockford Register Star general assignment reporter. He can be reached at 815-987-1241, via email at  [email protected]  and X  @chrisfgreen

IMAGES

  1. What is Mass Assignment?

    what is mass assignment

  2. Hunting for Mass Assignment

    what is mass assignment

  3. Mass Assignment Attacks Explained

    what is mass assignment

  4. Mass Assignment vulnerability and prevention

    what is mass assignment

  5. What is Mass Assignment? Attacks and Security Tips

    what is mass assignment

  6. 7 Laravel 7 for beginner

    what is mass assignment

VIDEO

  1. Mass Com Assignment

  2. mass comm digital storytelling assignment

  3. Mass Effect: Assignment (Fan Film)

  4. WHAT IS MASS...? #metamind #physics #iit #neet

  5. Portswigger: Exploiting a mass assignment vulnerability

  6. API Testing Portswigger :Lab Exploiting a mass assignment vulnerability 100% Working Cyber security

COMMENTS

  1. Mass Assignment

    Mass Assignment Cheat Sheet is a concise guide to help developers prevent and mitigate the risks of mass assignment vulnerabilities in web applications. It covers the definition, impact, detection, and prevention of this common security flaw. Learn how to protect your data from unauthorized manipulation with OWASP best practices.

  2. 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.

  3. What is a Mass Assignment Vulnerability?

    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 ...

  4. What is mass assignment?

    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.

  5. 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 ...

  6. 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 ...

  7. Mass Assignment · OWASP Cheat Sheet Series

    Mass Assignment is a common vulnerability that occurs when a web application assigns user-supplied data to properties of an object without proper validation. This cheat sheet provides guidance on how to prevent and mitigate mass assignment attacks in different frameworks and languages. Learn how to use whitelists, blacklists, annotations, and other techniques to protect your web application ...

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

    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.

  9. Mass Assignment 101

    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.

  10. Lab: Exploiting a mass assignment vulnerability

    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.

  11. 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 ...

  12. What is Mass Assignment?

    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. ‍.

  13. Preventing mass assignment or over posting with Razor Pages in ...

    Mass assignment, also known as over-posting, is an attack used on websites that use model-binding. It is used to set values on the server that a developer did not expect to be set. This is a well known attack now, and has been discussed many times before, (it was a famous attack used against GitHub some years ago ).

  14. What is Mass Assignment: How We Can Help

    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 ...

  15. 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 ...

  16. OWASP API #6: Mass Assignment

    Mass Assignment, occurs when an application is implemented in such way, that it actually accepts broader modifications than those intended and described in the documentation.

  17. Preventing mass assignment or over posting in ASP.NET Core

    Mass assignment, also known as over-posting, is an attack used on websites that involve some sort of model-binding to a request. It is used to set values on the server that a developer did not expect to be set. This is a well known attack now, and has been discussed many times before, (it was a famous attack used against GitHub some years ago ...

  18. How Do Mass Assignment Vulnerabilities Impact My Business?

    A mass assignment vulnerability could lead to less critical exploitations such as changing the price of a product to buy it at a cheaper price. But it could also lead to an attacker taking complete control over the application. It depends on how the application is built. By the end of the post, you'll understand what mass assignment is and ...

  19. The dangers of setattr: Avoiding Mass Assignment vulnerabilities in

    Mass assignment, also known as autobinding or object injection, is a category of vulnerabilities that occur when user input is bound to variables or objects within a program. Mass assignment vulnerabilities are often the result of an attacker adding unexpected fields to an object to manipulate the logic of a program.

  20. What is a Mass Assignment Vulnerability?

    Mass Assignment Vulnerability. is a type of API vulnerability that occurs due to an input validation flaw. This vulnerability allows an attacker to perform sensitive actions on a server or leak confidential client information by manipulating input data sent to the API. The vulnerability arises when an API endpoint allows the creation or update ...

  21. What is Mass Assignment?

    Mass Assignment is a powerful Authorization Vulnerability that has been used by researchers and attackers to compromise popular sites like Github in the past...

  22. 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 ...

  23. What does "Mass Assignment" mean in Laravel?

    39. Mass assignment is a process of sending an array of data that will be saved to the specified model at once. In general, you don't need to save data on your model on one by one basis, but rather in a single process. Mass assignment is good, but there are certain security problems behind it.

  24. Mass Shooting Theater Assignment Leads to Teacher's Suspension

    News coming out of Texas today that a theatre teacher has been suspended following reports of a controversial assignment where a mass shooting would be staged using puppets. Hays CISD told local news that the Johnson High School theater arts teacher is a long-term substitute and that they've been suspended pending an investigation by the ...

  25. Students reportedly told to perform murder in puppet show assignment

    Additionally, one group of students reports that their performance would have involved a mass shooting, though it is not clear if that was the specific assignment or a scene created to meet the ...

  26. TX school: 'Disturbing' assignment gets substitute suspended

    A high school substitute teacher was suspended following a "disturbing" puppet show assignment, a Texas school district says. The Hays Consolidated Independent School District said the ...

  27. Texas substitute teacher suspended over 'disturbing' class assignment

    They added that one group of students said the performance would have involved a mass shooting. ... An investigation remains underway and it's still unclear if that was the specific assignment ...

  28. Heroes of Rockford deadly mass stabbing attack recognized for bravery

    Heroes of Rockford deadly mass stabbing honored for life-saving actions. Chris Green. Rockford Register Star. ... Chris Green is a Rockford Register Star general assignment reporter.