• 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

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

Navigation Menu

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

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

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

HackerWhite

Point of Contact

  • Vulnerability 101

Mass Assignment Vulnerability: Understanding & Mitigating the Risks in API

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

Introduction:

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

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

Understanding the "Mass Assignment" Vulnerability:

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

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

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

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

Common Examples of "Mass Assignment":

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

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

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

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

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

Risks and Consequences:

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

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

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

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

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

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

Best Practices for Mitigating the "Mass Assignment" Vulnerability:

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

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

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

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

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

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

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

Tools and Resources:

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

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

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

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

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

The Role of Security Testing and Auditing:

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

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

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

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

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

Conclusion:

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

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

Need Help? Hire us part-time

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

Secured High Growth Companies Worldwide

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

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

  • Mass Assignment

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?

Overreliance on llms, insecure plugins for llms, snyk apprisk pro - using application analytics (tenant->analytics->applications).

mass assignment vulnerability java

Common vulnerabilities in Java and how to fix them

30 vulnerabilities to look out for in java applications: arbitrary file writes, directory traversal, deserialization, and more….

Vickie Li

ShiftLeft Blog

Securing applications is not the easiest thing to do. An application has many components: server-side logic, client-side logic, data storage, data transportation, API, and more. With all these components to secure, building a secure application can seem really daunting.

Thankfully, most real-life vulnerabilities share the same root causes. And by studying these common vulnerability types and why they happen, you can learn to prevent them and secure your application.

The use of every language, framework, or environment exposes the application to a unique set of vulnerabilities. The first step to fixing vulnerabilities in your application is to know what to look for. Today, let’s take a look at 30 of the most common vulnerabilities that affect Java applications, and how you can find and prevent them.

Let’s secure your Java application! The vulnerabilities I will cover in this post are:

  • XML external entity attacks (XXE)
  • Insecure deserialization
  • Remote code execution (RCE)
  • SQL injection
  • NoSQL injection

LDAP Injection

  • Log injection
  • Mail injection
  • Template injection (SSTI)
  • Expression language injection
  • Regex injection
  • XPath injection
  • Header injection
  • Session injection and insecure cookies
  • Host header poisoning
  • Sensitive data leaks or information leaks
  • Authentication bypass
  • Improper access control
  • Directory traversal or path traversal
  • Arbitrary file writes
  • Denial of service attacks (DoS)
  • Encryption vulnerabilities
  • Insecure TLS configuration and improper certificate validation
  • Mass assignment
  • Open redirects
  • Cross-site request forgery (CSRF)
  • Server-side request forgery (SSRF)
  • Trust boundary violations

XML External Entity Attacks

XML external entity attacks , or XXE, are when attackers exploit an XML parser to read arbitrary files on your server. Using an XXE, attackers might also be able to retrieve user information, configuration files, or other sensitive information like AWS credentials.

Java applications are particularly prone to XXE because most Java XML parsers have the requirements for XXE enabled by default. To prevent XXE attacks in a Java application, you need to explicitly disable these functionalities. You can read in detail about how to prevent XXE here .

Take me back to the top.

Insecure Deserialization

Serialization is a process during which an object in a programming language (say, a Java object) is converted into a format that can be saved to the database or transferred over a network. Whereas deserialization refers to the opposite: it’s when the serialized object is read from a file or the network and converted back into an object. Many programming languages support the serialization and deserialization of objects, including Java, PHP, Python, and Ruby.

Insecure deserialization is a type of vulnerability that arises when an attacker can manipulate the serialized object and cause unintended consequences in the program’s flow. Insecure deserialization bugs are often very critical vulnerabilities: an insecure deserialization bug will often result in authentication bypass, denial of service, or even arbitrary code execution. Learn how attackers can exploit insecure deserialization .

To prevent insecure deserialization, you need to first keep an eye out for patches and keep dependencies up to date. Many insecure deserialization vulnerabilities are introduced via dependencies, so make sure that your third-party code is secure. It also helps to avoid using serialized objects and utilize simple data types instead, like strings and arrays. Finally, you can learn how to deserialization objects safely to prevent insecure deserialization .

Remote Code Execution

Remote code execution vulnerabilities, or RCE, are a class of vulnerabilities that happen when attackers can execute their code on your machine. One of the ways this can happen is through command injection vulnerabilities. They are a type of remote code execution that happens when user input is concatenated directly into a system command. The application cannot distinguish between where the user input is and where the system command is, so the application executes the user input as code. The attacker will be able to execute arbitrary commands on the machine.

One of the easiest ways to prevent command injection is to implement robust input validation in the form of an allowlist. Read about how to implement allowlists to prevent RCE here .

Command injection is also a type of injection issue. Injection happens when an application cannot properly distinguish between untrusted user data and code. When injection happens in system OS commands, it leads to command injection. But injection vulnerabilities manifest in other ways too.

SQL Injection

In an SQL injection attack, for example, the attacker injects data to manipulate SQL commands. When the application does not validate user input properly, attackers can insert characters special to the SQL language to mess with the query’s logic, thereby executing arbitrary SQL code. Learn more about how these SQL injection attacks work here .

SQL injections allow attacker code to change the structure of your application’s SQL queries to steal data, modify data, or potentially execute arbitrary commands in the underlying operating system. The best way to prevent SQL injections is to use parameterized statements, which makes SQL injection virtually impossible. Learn about how to use parameterized statements in Java in this article.

NoSQL Injection

Databases don’t always use SQL. NoSQL databases, or Not Only SQL databases, are those that don’t use the SQL language. NoSQL injection refers to attacks that inject data into the logic of these database languages. NoSQL injections can be just as serious as SQL injections: they can lead to authentication bypass and remote code execution.

Modern NoSQL databases, such as MongoDB, Couchbase, Cassandra and HBase, are all vulnerable to injection attacks. NoSQL query syntax is database-specific, and queries are often written in the programming language of the application. For the same reason, methods of preventing NoSQL injection in each database are also database-specific. You can learn how to prevent NoSQL injection in MongoDB, Couchbase, Cassandra and HBase here .

The Lightweight Directory Access Protocol (LDAP) is a way of querying a directory service about the system’s users and devices. For instance, it’s used to query Microsoft’s Active Directory. When an application uses untrusted input in LDAP queries, attackers can submit crafted inputs that causes malicious effects. Using LDAP injection, attackers can bypass authentication and mess with the data stored in the directory. You can use parameterized queries to prevent LDAP injection. Find out how LDAP injections work and how to prevent them .

Log Injection

You probably conduct system logging to monitor for malicious activities going on in your network. But have you ever considered that your log file entries could be lying to you? Log files, like other system files, could be tampered with by malicious actors. Attackers often modify log files to cover up their tracks during an attack. Log injection is one of the ways attackers can change your log files. It happens when the attacker tricks the application into writing fake entries in your log files.

In Java, log injection often happens when the application does not sanitize new line characters “\n” in input written to logs. Attackers can make use of the new line character to insert new entries into application logs. Another way attackers can exploit user input in logs is that they can inject malicious HTML into log entries to attempt to trigger an XSS on the browser of the admin who views the logs.

To prevent log injection attacks, you need a way to distinguish between real log entries, and fake log entries injected by the attacker. One way to do this is by prefixing each log entry with extra meta-data like a timestamp, process ID, and hostname. You should also treat the contents of log files as untrusted input and validate it before accessing or operating on it.

Mail Injection

Many web applications send emails to users based on their actions. For instance, if you subscribed to a feed on a news outlet, the website might send you a confirmation with the name of the feed.

Mail injection happens when the application employs user input to determine which addresses to send emails to. This can allow spammers to use your server to send bulk emails to users or enable scammers to conduct social engineering campaigns via your email address. Learn how attackers can achieve mail injection and how you can prevent it here .

Template Injection

Template engines are a type of software used to determine the appearance of a web page. These web templates, written in template languages such as Jinja, provide developers with a way to specify how a page should be rendered by combining application data with web templates. Together, web templates and template engines allow developers to separate server-side application logic from client-side presentation code during web development.

Template injection refers to injection into web templates. Depending on the permissions of the compromised application, attackers might be able to use the template injection vulnerability to read sensitive files, execute code, or escalate their privileges on the system. Learn how template injection work and how to prevent them in this post .

Expression Language Injection

Expression language (EL) refers to program expressions written into Java Server Pages (JSP) that is executed as code. When untrusted user input is passed into these expressions, attackers might be able to insert malicious code which is then executed by the expression language interpreter. This leads to remote code execution. Learn about how this attack works here .

To prevent EL injection , you should avoid passing untrusted user input into expressions evaluated by the EL interpreter. If you do need to pass data into EL expressions, validate the data using an allowlist, or encode the data to make sure that it is not interpreted as code.

Regex Injection

A regular expression, or regex, is a special string that describes a search pattern in text. Sometimes, applications let users provide their own regex patterns for the server to execute or build a regex with user input. A regex injection attack, or a regular expression denial of service attack (ReDoS), happens when an attacker provides a regex engine with a pattern that takes a long time to evaluate. You can find examples of these patterns in my post here .

Thankfully, regex injection can be reliably prevented by not generating regex patterns from user input, and by constructing well-designed regex patterns whose required computing time does not grow exponentially as the text string grows. You can find some examples of these preemptive measures here .

XPath Injection

XPATH is a query language used for XML documents. Think SQL for XML. XPATH is used to query and perform operations on data stored in XML documents. For example, XPATH can be used to retrieve salary information of employees stored in an XML document. It can also be used to perform numeric operations or comparisons on that data.

XPATH injection is an attack that injects into XPATH expressions in order to alter the outcome of the query. Like SQL injection, it can be used to bypass business logic, escalate user privilege, and leak sensitive data. Since applications often use XML to communicate sensitive data across systems and web services, these are the places that are the most vulnerable to XPATH injections. Similar to SQL injection, you can prevent XPATh injection by using parameterized queries .

Header Injection

Header injection happens when HTTP response headers are dynamically constructed from untrusted input. Depending on which response header the vulnerability affects, header injection can lead to cross-site scripting, open redirect, and session fixation.

For instance, if the Location header can be controlled by a URL parameter, attackers can cause an open redirect by specifying their malicious site in the parameter. Attackers might even be able to execute malicious scripts on the victim’s browser, or force victims to download malware by sending completely controlled HTTP responses to the victim via header injection. More about how these attacks work here .

You can prevent header injections by avoiding writing user input into response headers, stripping new-line characters from user input (new line characters are used to create new HTTP response headers), and using a allowlist to validate header values.

Session Injection and Insecure Cookies

Session injection is a type of header injection. If an attacker can manipulate the contents of their session cookie, or steal someone else’s cookies, they can trick the application into thinking that they are someone else. There are three main ways that an attacker can obtain someone else’s session: session hijacking, session tampering, and session spoofing.

Session hijacking refers to the attacker stealing someone else session cookie and use it as their own. Attackers often steal session cookies with XSS or MITM (man-in-the-middle) attacks . Session tampering refer to when attackers can change their session cookie to change how the server interprets their identity. This happens when session state is communicated in the cookie and the cookie is not properly signed or encrypted. Finally, attackers can “spoof” sessions when session IDs are predictable. If that’s the case, attackers can forge valid session cookies and log in as someone else. Preventing these session management pitfalls requires multiple layers of defense .

Host Header Poisoning

Web servers often host multiple different websites on the same IP address. After an HTTP request arrives at an IP address, the server will forward the request to the host specified in the Host header. Although Host headers are typically set by a user’s browser, it’s still user-provided input and thus should not be trusted.

If a web application does not validate the Host header before using it to construct addresses, attackers can launch a range of attacks, like XSS, server-side request forgery ( SSRF), and web cache poisoning attacks via the Host header. For instance, if the application uses the Host header to determine the location of scripts, the attacker could submit a malicious Host header to make the application execute a malicious script:

Learn more about how Host header attacks work here .

Sensitive Data Leaks

Sensitive data leak occurs when an application fails to properly protect sensitive information, giving users access to information they shouldn’t have available to them. This sensitive information can include technical details that aid an attack, like software version numbers, internal IP addresses, sensitive filenames, and file paths. It could also include source code that allows attackers to conduct a source code review on the application. Sometimes, the application leaks private information of users, such as their bank account numbers, email addresses, and mailing addresses.

Some common ways that an application can leak sensitive technical details are through descriptive response headers, descriptive error messages with stack traces or database error messages, open directory listings on the system’s file system, and revealing comments in HTML and template files. You can learn how to prevent data leaks in Java here .

Authentication Bypass

Authentication refers to proving one’s identity before executing sensitive actions or accessing sensitive data. If authentication is not implemented correctly on an application, attackers can exploit these misconfigurations to gain access to functionalities they should not be able to. For more details about how you can configure authentication properly in Java, read this tutorial .

Improper Access Control

Authentication bypass issues are essentially improper access control. Improper access control occurs anytime when access control in an application is improperly implemented and can be bypassed by an attacker. However, access control comprises of more than authentication. While authentication asks a user to prove their identity: “Who are you?”, authorization asks the application “What is this user allowed to do?”. Proper authentication and authorization together ensures that users cannot access functionalities outside of their permissions.

There are several ways of configuring authorization for users: role-based access control, ownership-based access control, access control lists, and more. A good post to reference for implementing access control is here .

Directory Traversal

Directory traversal vulnerabilities are another type of improper access control. They happen when attackers can view, modify, or execute files they shouldn’t have access to by manipulating file paths in user-input fields. This process involves manipulating file path variables the application uses to reference files by adding the ../ characters or other special characters to the file path. The ../ sequence refers to the parent directory of the current directory in Unix systems, so by adding it to a file path, you can often reach system files outside the web directory.

Attackers can often use directory traversals to access sensitive files like configuration files, log files, and source code. To prevent directory traversals, you should validate user input that are inserted into file paths, or avoid direct references to file names and use indirect identifiers instead, read this tutorial for more information.

Arbitrary File Writes

Arbitrary file write vulnerabilities work similarly to directory traversals. If an application writes files to the underlying machine, and determines the output file name via user input, attackers might be able to create arbitrary files on any path they want, or overwrite existing system files. Attackers might be able to alter critical system files like password files or log files, or add their own executables into script directories.

The best way to mitigate this risk is by not creating file names based on any user input, including session information, HTTP input, or anything that the user controls. You should control the file name, path, and extension for every created file. For instance, you can generate a random alphanumeric filename every time the user needs to generate a unique file. You can also strip user input of special characters before creating the file. Learn about these techniques in this post .

Denial of Service Attacks

Denial of service attacks, or DoS attacks, disrupts the target machine so that legitimate users cannot access its services. Attackers can launch DoS attacks by exhausting all the server’s resources, crashing processes, or making too many time-consuming HTTP requests at once.

Denial of service attacks are hard to defend against. But there are ways to minimize your risk by making it as difficult as possible for attackers. For instance, you can deploy a firewall that offers DoS protection, and prevent logic-based DoS attacks by setting limits on file sizes and disallowing certain file types. You can find more detailed steps on preventing denial of service attacks here .

Encryption Vulnerabilities

Encryption issues are probably one of the most severe vulnerabilities that can happen in an application. Encryption vulnerabilities refers to when encryption and hashing are not properly implemented. This can lead to wide-spread data leaks and authentication bypass through session spoofing.

Some common mistakes developers make when implementing encryption on a site are:

  • Using weak algorithms
  • Using the wrong algorithm for the purpose
  • Creating custom algorithms
  • Generating weak random numbers
  • Mistaking encoding for encryption

A guide to encryption security can be found here .

Insecure TLS Configuration and Improper Certificate Validation

Besides encrypting the information in your data stores properly, you should also make sure that your application in transmitting data properly. A good way of making sure that you are communicating over the Internet securely is to use HTTPS with a modern version of transport layer security (TLS) and a secure cipher suite .

During this process, you need to ensure that you are communicating with a trusted machine, and not a malicious third-party. TLS uses digital certificates as the basis of its public key encryption, and you need to validate these certificates before establishing the connection with the third-party. You should verify that the server you are trying to connect to has a certificate that is issued by a trusted certificate authority (CA) and that none of the certificates in the certificate chain are expired.

Mass Assignment

“ Mass assignment ” refers to the practice of assigning values to multiple variables or object properties all at once. Mass assignment vulnerabilities happen when the application automatically assigns user input to multiple program variables or objects. This is a feature in many application frameworks designed to simplify application development.

However, this feature sometimes allows attackers to overwrite, modify, or create new program variables or object properties at will. This can lead to authentication bypass, and manipulation of program logic . To prevent mass assignments, you can disable the mass assignment feature with the framework you are using, or use a whitelist to only allow assignment on certain properties or variables .

Open Redirects

Websites often need to automatically redirect their users. For example, this scenario happens when unauthenticated users try to access a page that requires logging in. The website will usually redirect those users to the login page, and then return them to their original location after they are authenticated.

During an open-redirect attack, an attacker tricks the user into visiting an external site by providing them with a URL from the legitimate site that redirects somewhere else. This can lead users to believe that they are still on the original site, and help scammers build a more believable phishing campaign.

To prevent open redirects, you need to make sure the application doesn’t redirect users to malicious locations. For instance, you can disallow offsite redirects completely by validating redirect URLs . There are many other ways of preventing open redirects, like checking the referrer of requests, or using page indexes for redirects. But because it’s difficult to validate URLs , open redirects remain a prevalent issue in modern web applications.

Cross-Site Request Forgery

Cross-site request forgery (CSRF) is a client-side technique used to attack other users of a web application. Using CSRF, attackers can send HTTP requests that pretend to come from the victim, carrying out unwanted actions on a victim’s behalf. For example, an attacker could change your password or transfer money from your bank account without your permission.

Unlike open redirects, there is a surefire way of preventing CSRF: using a combination of CSRF tokens and SameSite cookies , and avoid using GET requests for state-changing actions.

Server-Side Request Forgery

SSRF, or Server Side Request Forgery , is a vulnerability that happens when an attacker is able to send requests on behalf of a server. It allows attackers to “forge” the request signatures of the vulnerable server, therefore assuming a privileged position on a network, bypassing firewall controls and gaining access to internal services.

Depending on the permissions given to the vulnerable server, an attacker might be able to read sensitive files, make internal API calls, and access internal services like hidden admin panels. The easiest way to prevent SSRF vulnerabilities is to never make outbound requests based on user input. But if you do need to make outbound requests based on user input, you’ll need to validate those addresses before initiating the request.

Trust Boundary Violations

“Trust boundaries” refer to where untrusted user input enter a controlled environment. For instance, an HTTP request is considered untrusted input until it has been validated by the server.

There should be a clear distinction between how you store, transport, and process trusted and untrusted input. Trust boundary violations happen when this distinction is not respected, and trusted and untrusted data are confused with each other. For instance, if trusted and untrusted data are stored in the same data structure or database, the application will start confusing the two. In this case, untrusted data might be mistakenly seen as validated.

A good way to prevent trust boundary violation is to never write untrusted input into session stores until it is verified. See an example of this mitigation implemented in Java here .

What other security concepts do you want to learn about? I’d love to know. Feel free to connect on Twitter @vickieli7 .

Now that you know how to fix these vulnerabilities, secure your Java application by scanning for these vulnerabilities! ShiftLeft CORE ( https://www.shiftleft.io/shiftleft-core/ ) can find these vulnerabilities in your application and protect you from Java security issues.

Vickie Li

Written by Vickie Li

Professional investigator of nerdy stuff. Hacks and secures. Creates god awful infographics. https://twitter.com/vickieli7

More from Vickie Li and ShiftLeft Blog

How to find more IDORs

How to find more IDORs

And maximize their impact while hunting for bugs..

API Security 101: Injection

API Security 101: Injection

How sql injection and command injection happen in apis.

5 Application Security Standards You Should Know

The ShiftLeft Team

5 Application Security Standards You Should Know

Here is your compliance shortlist (yay).

Hacking JSON Web Tokens (JWTs)

The Startup

Hacking JSON Web Tokens (JWTs)

And how attackers forge tokens and log in as someone else., recommended from medium.

What is LFI (Local File Inclusion) Vulnerability ?

Errorfiathck

What is LFI (Local File Inclusion) Vulnerability ?

Local file inclusion is an attack technique in which attackers trick a web application into executing or exposing files on a web server….

API Testing — Portswigger Labs (Part 1)

Prince Varghese

API Testing — Portswigger Labs (Part 1)

Hey friends..

mass assignment vulnerability java

General Coding Knowledge

mass assignment vulnerability java

Stories to Help You Grow as a Software Developer

An illustration of two women standing in front of a climbing wall, having a discussion about the climb they are about to do.

Coding & Development

Broken Object Level Authorization — BOLA (ex crAPI)

Ammar Ahmed

Broken Object Level Authorization — BOLA (ex crAPI)

One of the main components of security is authorization and today we will have a look at an authorization vulnerability called bola. but….

IDOR in APIs

Yasmeena Rezk

IDOR in APIs

Java Lambdas and Streams in under 5 minutes!

Harshitha Khandelwal

Java Lambdas and Streams in under 5 minutes!

Want to become efficient while writing java codes use streams to optimize your codes and increase productivity.

My first Web Cache Poisoning bug

Bikram kharal

InfoSec Write-ups

My first Web Cache Poisoning bug

Web cache poisoning is an advanced technique where by an attacker exploits the behavior of a web server and cache so that a harmful http….

Text to speech

Discord logo.

Join Our Community on Discord

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

mass assignment vulnerability java

Mass Assignment

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

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

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

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

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

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

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

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

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

Mitigation strategies.

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

Avoid re-using data models for request models

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

Be explicit in your mappings

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

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

Further Examples

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

C# - insecure

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

C# - secure

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

C# - alternative - excludes parameters

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

Java - insecure

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

‍ Java - secure

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

Javascript - insecure

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

Javascript - secure

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

Python - Insecure

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

Python - Secure

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

mass assignment vulnerability java

Injection - XSS

mass assignment vulnerability java

Injection - Path Traversal

mass assignment vulnerability java

Using Components with Known Vulnerabilities

mass assignment vulnerability java

Insufficient Logging and Monitoring

mass assignment vulnerability java

Security misconfiguration - XXE detailed

mass assignment vulnerability java

Security Misconfiguration

mass assignment vulnerability java

Server-Side Request Forgery

mass assignment vulnerability java

Password Storage

mass assignment vulnerability java

Authentication and Authorization

mass assignment vulnerability java

File Upload

Injection 101, sql injection.

mass assignment vulnerability java

Command Injection

Secure Code Warrior Learning Platform

Discover the Secure Code Warrior Learning Platform

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

websights

Preprint Version

Mining REST APIs for Potential Mass Assignment Vulnerabilities

REST APIs have a pivotal role in accessing protected resources. Despite the availability of security testing tools, mass assignment vulnerabilities are common in REST APIs, leading to unauthorized manipulation of sensitive data. We propose a lightweight approach to mine the REST API specifications and identify operations and attributes that are prone to mass assignment. We conducted a preliminary study on 100 APIs and found 25 prone to this vulnerability. We confirmed nine real vulnerable operations in six APIs.

1. Introduction

REST APIs enable seamless data exchange and functionality integration across different systems. The pivotal role of these APIs in today’s software industry has made them an attractive target for attackers. For instance, a recent API vulnerability disclosed 1.8 million user accounts from an insurance company   (Beeferman, 2022 ) . Additionally, a security breach in the AWS S3 bucket of a digital scheduling platform exposed the personally identifiable information (PII) of 3.7 million user accounts  (Greig, 2022 ) . Furthermore, a major social media platform reported a breach in its API from late 2021 into 2022, revealing the PII of 5.4 million user accounts. The vulnerability originated from an API designed to help users in finding others  (Keary, 2022 ) .

Mass assignment is a critical but overlooked vulnerability in REST APIs. It occurs when REST APIs allow the unintended modification of attributes, leading to unauthorized manipulation of sensitive data. This vulnerability arises due to an incorrect configuration of widely used REST API frameworks that typically facilitate automatic binding between input data fields and the internal data representation, such as database columns.

The support for identifying mass assignment vulnerabilities in REST APIs is limited. Akto  (Team, 2023a ) and RestTestGen  (Team, 2023b ) are two examples of tools for detecting mass assignment vulnerabilities in REST APIs. RestTestGen is an automated black-box testing tool, and Akto is semi-automated. Nonetheless, existing tools mostly evaluate a running API, support to uncover mass assignment vulnerabilities in earlier development stages is limited.

We present LightMass, a tool for mining API endpoints and attributes prone to mass assignment vulnerabilities in REST APIs. Unlike existing tools that interact with a running API, LightMass merely relies on the API specification; therefore, it draws developers’ attention to potential mass assignment vulnerabilities as early as the API’s specification is known. In particular, LightMass inspects operations that handle similar sets of attributes (assuming they handle the same data model), and compares the attributes that a GET operation read and those that a POST , PUT , or PATCH operation writes to. When a GET operation has more attributes than the other operation (i.e., POST , PUT , or PATCH ), the attributes that are only present in the GET operation are considered to be read-only , and therefore, these attributes are candidates for mass assignment vulnerabilities.

We conducted a preliminary study on 100 APIs and found 25 candidate APIs (115 endpoints and 133 operations) prone to mass assignment vulnerabilities. We examined potential vulnerabilities in six APIs for which we could access the source code and confirmed the presence of nine vulnerable operations.

In summary, LightMass identifies operations that fulfill the necessary conditions for mass assignment vulnerabilities for later in-depth analysis. The fast and simple nature of its approach is helpful in several scenarios, such as (i) steering code reviewers’ focus on potential issues; (ii) enabling tools such as Akto to perform automated testing of mass assignment vulnerabilities; and (iii) mining API specifications at large and estimating the potential for mass assignment vulnerabilities in the wild. LightMass is open-source and publicly available on GitHub. 1 1 1 https://github.com/arash-mazidi/LightMass

The rest of this paper is organized as follows. We provide background information about RESTful APIs and the mass assignment vulnerability in Section  2 . We introduce our approach to identify potential mass assignment vulnerabilities in Section  3 . We present our evaluation in Section  4 . We present related work in Section  5 , and conclude the paper in Section  6 .

2. Background

This section introduces REST APIs and the OpenAPI standard for writing API specifications. Subsequently, we introduce the mass assignment vulnerability.

2.1. REST APIs and OpenAPI specifications

REST APIs are web APIs that adhere to the REST (REpresentational State Transfer) architectural style. They offer a consistent interface for creating, reading, updating, and deleting resources. HTTP URIs identify resources, and operations on resources are typically associated with HTTP methods such as POST , GET , PUT (or PATCH ), and DELETE to, respectively, create , read , update or delete resources.

Developers usually follow the OpenAPI standard to describe the API’s structure and behavior. In particular, the OpenAPI specification file, typically structured in JSON or YAML format, describes the endpoints, operations and their attributes, as well as the request and response schemas.

Listing  1 presents a snippet of the OpenAPI specification for a Task Management API. Following an initial header specifying versions, licenses, and the API’s base URL, this specification features an array of paths representing the available URI endpoints in the API. In this example, the HTTP URI leading to a task resource is /tasks (line 12), and the HTTP operations GET and POST (lines 13 and 28) are utilized to retrieve the list of existing tasks and create a new task in the system, respectively. These operations have common attributes such as title (lines 22 and 35) and assignee (lines 24 and 37), which delineate the task’s title and the person responsible for it.

2.2. Mass Assignment Vulnerability

Developers usually rely on frameworks to build REST APIs. These frameworks, such as Spring for Java, Flask for Python, Express.js for JavaScript, and Laravel for PHP, offer a suite of reusable components and features to facilitate REST API development. One of the features typically provided by these frameworks is called auto-binding , a mechanism that adopts naming conventions to automatically map input data in HTTP requests (i.e., parameters) to the backend data objects (e.g., database columns) when they share the same name. This feature is typically enabled by default for all attributes. A mass assignment vulnerability , also known as “object injection” or “auto-binding vulnerability”, occurs when developers neglect to disable this feature for attributes that are meant to be read-only. Therefore, an attacker can add an extra attribute to an HTTP request (one that was not intended to be changed), and the auto-binding feature would automatically link that attribute to its corresponding internal representation, for example, a database column. In principle, this attribute is neither part of the API specification nor the API documentation, and it should have not been processed. Nevertheless, the attacker who exploits this feature, will be able to manipulate and alter data in the database, posing a significant security risk.

For instance, consider the specification of the Task Management API shown in Listing  1 . Suppose the JSON task object within an HTTP request maps to the tasks table in the database, which includes a (supposedly) read-only boolean column named status and two modifiable columns, namely title and assignee . If the REST framework lacks a proper configuration, it may automatically link an additional status attribute in a “create task” request to the corresponding status column in the tasks table. That is, an attacker could manipulate a request body of the POST /tasks operation by introducing an extra status attribute not specified in the OpenAPI specification. The framework would then automatically associate this additional attribute with the status column in the tasks table, allowing the attacker to overwrite the legitimate value in the database with the manipulated HTTP attribute value.

To prevent mass assignment, developers should blacklist read-only attributes from being auto-bound to the internal data representation of the API.

3. LightMass

We developed LightMass, a tool that takes an OpenAPI specification file as input and identifies candidate operations and attributes prone to mass assignment vulnerabilities. Figure  1 illustrates the LightMass workflow, and Listing  2 shows the corresponding procedure.

Refer to caption

LightMass parses the API specification to identify existing endpoints, operations, and attributes. It relies on the Jackson library to parse the content. Subsequently, it resolves all the cross references (i.e., $ref ), 2 2 2 In OpenAPI, one can define a component at one location in the specification document and reference (reuse) it in other places, reducing redundancy and making the document more maintainable. ensuring that they are replaced with their actual definitions. Then, it navigates through the specification to access information about paths and operations (Listing  2 , lines 9-11). The paths object contains details about each endpoint, and under each path, the supported HTTP operations, e.g., GET , POST , PUT , and PATCH are listed. LightMass extracts all attributes for each operation, which are found within both the request and response bodies, as well as other locations such as path, query, and header (lines 14 and 16). This phase is pivotal since mass assignment vulnerabilities often revolve around the manipulation of input attributes.

LightMass identifies similar operations based on similar attributes. Firstly, to facilitate a uniform comparison, Porter’s stemming algorithm  (Porter, 1980 ) is employed to standardize attribute names, i.e., reducing attribute names to their core or root forms. Secondly, it utilizes the Jaccard coefficient to identify similar operations:

Therefore, the similarity measure is the ratio of the number of shared (similar) attributes between two operations to the total number of their distinct attributes (line 20). Specifically, O ⁢ P . R ⁢ E ⁢ Q formulae-sequence 𝑂 𝑃 𝑅 𝐸 𝑄 OP.REQ italic_O italic_P . italic_R italic_E italic_Q comprises the attributes in the request body of a POST , PUT , or PATCH operation, and G ⁢ E ⁢ T . R ⁢ E ⁢ S formulae-sequence 𝐺 𝐸 𝑇 𝑅 𝐸 𝑆 GET.RES italic_G italic_E italic_T . italic_R italic_E italic_S is the set of attributes in the response body of a GET operation.

LightMass reports a potential vulnerability when (i) the similarity between two operations is at least 50%, 3 3 3 In practice, a vulnerability can exist even with just one extra attribute, but in our experience, a 50% threshold was practical to uncover actual vulnerabilities and avoid false positives. Nonetheless, it is possible to adjust the similarity threshold in each run if needed. and (ii) the number of attributes in the response of a GET operation exceeds the number of attributes in the request of the other operation ( POST , PUT , or PATCH ). The additional attributes in the GET operation are supposed to be read-only, making them potential candidates for mass assignment vulnerabilities. In the end, LightMass provides a structured list of candidate endpoints, operations, and attributes prone to mass assignment vulnerabilities.

For instance, consider the API specification in Listing  1 . With two attributes ( title and assignee at lines 35 and 37) in the request body of the POST operation (line 28) and three attributes ( title , assignee , and status at lines 22, 24, and 26) in the response body of the GET operation (line 13), the Jaccard similarity score is 0.66. The number of attributes in the GET operation exceeds that of the POST operation. Therefore, the status attribute in the response body, which is absent in the request body, is a candidate for mass assignment vulnerability.

It is noteworthy that an actual vulnerability exists only if enough protection measures are not in place. Therefore, LightMass’ report serves as a guide for security analysts, developers, and testers in conducting further investigations. For example, they could verify that they have properly disabled the auto-binding feature for the attributes flagged as potentially vulnerable.

4. Evaluation

We applied LightMass to 100 APIs that we randomly collected from previous work  (Corradini et al . , 2023 ) , GitHub, the Google APIs, APIs Guru, 4 4 4 https://apis.guru/ and EMB. 5 5 5 https://github.com/EMResearch/EMB

Mining the OpenAPI specifications of these APIs uncovered 25 potentially vulnerable APIs listed in Table  1 . Specifically, LightMass reported 495 candidate attributes for mass assignment distributed across 115 endpoints and 133 operations in 25 APIs.

Unfortunately, there is no golden dataset for mass assignment vulnerabilities in REST APIs. To evaluate whether these APIs are actually vulnerable, we should either test the APIs or examine their code. It is unethical to test APIs in production due to the potential risk of launching a successful attack. Hence, we compared LightMass and existing tools against six open-source APIs that we could set up and run locally. These APIs are listed in Table  2 .

To identify existing tools for mass assignment detection and compare them with LightMass, we searched the literature and Google with a combination of keywords such as mass assignment and detection, scanner, or analyzer . We also extended our search to GitHub with keywords such as mass assignment , object injection , and autobinding . Upon obtaining a list of potential tools, we paid close attention to the repository descriptions, README files, and any available documentation to determine the relevance of every search result.

We identified a total of nine (semi-)automated tools. We eliminated two since they had not been updated since 2010, suggesting potential obsolescence. We scrutinized the remaining tools and discovered that five are designed for mass assignment detection in web applications. The two remaining tools, namely RestTestGen  (Team, 2023b ) and Akto  (Team, 2023a ) , supported mass assignment detection in REST APIs.

Akto cannot automatically identify mass assignment vulnerabilities, so we had to manually input the potential vulnerable endpoints and attributes. 6 6 6 We provided Akto with the output from LightMass and checked whether Akto flags them for mass assignment vulnerability or not. Therefore, we applied RestTestGen to the six APIs in Table  2 to build our ground truth for mass assignment vulnerabilities.

Table  3 lists the vulnerability reports by each tool. Akto and RestTestGen provided the same results, whereas LightMass flagged one more attribute prone to mass assignment vulnerability in the VAmPI API. We looked at the source code of VAmPI to learn about the extra attribute (named owner ) that LightMass had flagged. Upon inspection, we found that the book model in the VAmPI API had predefined fields allowed to be set while creating a new book instance, namely book_title , secret_content , and user_id . These were the only permissible fields for setting while creating a new book. Any attempt to include an additional field in the request, such as owner , would be unsuccessful due to a server-side restriction and input validation. Therefore, the extra field that LightMass flagged for VAmPI API was a false positive.

It is important to note that the obtained results for these six case studies cannot be generalized to the remaining 19 (unverified) APIs.

In summary, the preliminary evaluation results are promising. Nonetheless, relying on LightMass as a standalone tool requires future studies. Particularly, how it performs in terms of false positives against APIs that are not vulnerable remains for a future work investigation. It is noteworthy that an actual vulnerability exists only if enough protection measures are not in place. Hence, relying merely on the specification is not enough, and false positives are expected. Nonetheless, there is no tool support for early development stages in this domain, and we believe that LightMass draws developers’ attention to this overlooked problem. In addition, as we experimented, LightMass enables Akto to act as a fully automated testing tool for mass assignment vulnerabilities. Akto is a popular and comprehensive API testing tool that does not support automated testing for mass assignment. It requires human interventions and input for suspected operations and attributes. Hence, LightMass in its current state enables the community to apply Akto as a fully automated tool to uncover true mass assignment vulnerabilities.

5. Related Work

Gadient et al.  (Gadient et al . , 2020 ) mined 9,714 Web APIs from 3,376 mobile apps, and found that in 500 apps, these APIs transmit embedded code (e.g., SQL and JavaScrip commands), exposing the app users and web servers to code injection attacks. In a follow-up study  (Gadient et al . , 2021 ) , they also discovered that API servers are usually misconfigured. They observed that on average every second server suffers from version information leaks, and worryingly, servers are typically set up once and then left untouched for up to fourteen months, yielding severe security risks.

Atlidakis et al.  (Atlidakis et al . , 2019 ) presented RESTler, a stateful REST API fuzzer that examines the OpenAPI specification. RESTler statically analyzes OpenAPI specification and creates and executes tests by deducing dependencies and examining the responses from previous test runs. They also demonstrated an extension of RESTler with active property checkers, which enables automatic testing and identification of breaches in adherence to these rules  (Atlidakis et al . , 2020 ) . Godefroid et al.  (Godefroid et al . , 2020a ) conducted a study on the intelligent generation of data payloads within REST API requests, leveraging the OpenAPI specification. They showed that they can detect data-processing vulnerabilities in cloud services. They  (Godefroid et al . , 2020b ) also presented a method for automated differential regression testing of REST APIs aimed at identifying breaking changes between API versions by comparing the responses of various versions when given the same inputs to identify discrepancies and identifying regressions in these observed differences. Mirabella et al.  (Mirabella et al . , 2021 ) presented a deep learning model to predict the validity of test inputs in an API request before making the API call.

Mai et al.  (Mai et al . , 2019 ) introduced a tool designed to automatically create executable security test cases from misuse case specifications written in natural language. Reddy et al.  (Reddy and Rudra, 2022 ) introduced an approach centered around sequence models and transformers to discern whether an API request is prone to injection attacks. Barabanov et al.  (Barabanov et al . , 2022 ) introduced an automated technique for identifying vulnerable endpoints to Insecure Direct Object Reference (IDOR) and Broken Object Level Authorization (BOLA) vulnerabilities which are related to the improper handling of object references, particularly in the context of authorization. This method involves establishing a mapping between attack methodologies and the properties in endpoints found within OpenAPI specifications.

The number of studies on mass assignment vulnerability is limited. Corradini et al.  (Corradini et al . , 2023 ) developed an automated black-box testing approach to find mass assignment vulnerabilities in RESTful APIs. The approach, built on top of the RestTestGen framework  (Corradini et al . , 2022 ) , uses EM clustering to group operations within the endpoints. Subsequently, abstract testing templates are instantiated to automatically generate interaction sequences, to exploit potential vulnerabilities. This tool requires the API to be in a running status for interaction with HTTP operations.

Park et al. (Kim et al . , 2022 ) introduced an automated tool for generating exploits targeting PHP object injection vulnerabilities named FUGIO. Koutroumpouchos et al.  (Koutroumpouchos et al . , 2019 ) introduced ObjectMap, a customizable solution that identifies deserialization and object injection vulnerabilities in web applications using Java and PHP. Shcherbakov et al.  (Shcherbakov and Balliu, 2021 ) introduced SerialDetector, a taint-driven dataflow analysis technique to identify Object Injection Vulnerabilities (OIVs) patterns within .NET assemblies.

6. Conclusion

Mass assignment is a critical vulnerability in REST APIs. However, there is a lack of support for developers to identify this security risk in the early stages of API development. We introduced LightMass, a tool that mines REST API specifications for potential mass assignment vulnerabilities. It identifies operations and attributes that fulfill the necessary conditions for mass assignment vulnerabilities. LightMass is not dependent on an active API, and it can alert developers as soon as the API’s specification is known. It also enables Akto, the popular open-source API testing tool, to execute fully automated API testing for mass assignment vulnerabilities.

  • Atlidakis et al . (2019) Vaggelis Atlidakis, Patrice Godefroid, and Marina Polishchuk. 2019. Restler: Stateful rest api fuzzing. In 2019 IEEE/ACM 41st International Conference on Software Engineering (ICSE) , 748–758.
  • Atlidakis et al . (2020) Vaggelis Atlidakis, Patrice Godefroid, and Marina Polishchuk. 2020. Checking security properties of cloud service REST APIs. In 2020 IEEE 13th International Conference on Software Testing, Validation and Verification (ICST) , 387–397.
  • Barabanov et al . (2022) Alexander Barabanov, Denis Dergunov, Denis Makrushin, and Aleksey Teplov. 2022. Automatic detection of access control vulnerabilities via API specification processing. arXiv preprint arXiv:2201.10833 .
  • Beeferman (2022) Jason Beeferman. 2022. Attack to Insurance APIs . https://www.texastribune.org/2022/05/16/texas-insurance-data-breach/
  • Bookstore (2022) Bookstore. 2022. Bookstore . https://github.com/todo/Bookstore
  • Corradini et al . (2023) Davide Corradini, Michele Pasqua, and Mariano Ceccato. 2023. Automated Black-box Testing of Mass Assignment Vulnerabilities in RESTful APIs. 2023 IEEE/ACM 45th International Conference on Software Engineering (ICSE) .
  • Corradini et al . (2022) Davide Corradini, Amedeo Zampieri, Michele Pasqua, and Mariano Ceccato. 2022. RestTestGen: An Extensible Framework for Automated Black-box Testing of RESTful APIs. In 2022 IEEE International Conference on Software Maintenance and Evolution (ICSME) . IEEE, 504–508.
  • CRUD (2023) CRUD. 2023. CRUD . https://github.com/lucianopereira86/CRUD-NodeJS-Sequelize-Swagger-MySQL
  • Gadient et al . (2020) Pascal Gadient, Mohammad Ghafari, Marc-Andrea Tarnutzer, and Oscar Nierstrasz. 2020. Web APIs in Android through the Lens of Security. In 2020 IEEE 27th International Conference on Software Analysis, Evolution and Reengineering (SANER) . 13–22. https://doi.org/10.1109/SANER48275.2020.9054850
  • Gadient et al . (2021) Pascal Gadient, Marc-Andrea Tarnutzer, Oscar Nierstrasz, and Mohammad Ghafari. 2021. Security Smells Pervade Mobile App Servers. In Proceedings of the 15th ACM / IEEE International Symposium on Empirical Software Engineering and Measurement (ESEM) (Bari, Italy) (ESEM ’21) . https://doi.org/10.1145/3475716.3475780
  • Godefroid et al . (2020a) Patrice Godefroid, Bo-Yuan Huang, and Marina Polishchuk. 2020a. Intelligent REST API data fuzzing. In Proceedings of the 28th ACM Joint Meeting on European Software Engineering Conference and Symposium on the Foundations of Software Engineering , 725–736.
  • Godefroid et al . (2020b) Patrice Godefroid, Daniel Lehmann, and Marina Polishchuk. 2020b. Differential regression testing for REST APIs. In Proceedings of the 29th ACM SIGSOFT International Symposium on Software Testing and Analysis , 312–323.
  • Greig (2022) Jonathan Greig. 2022. Attack to digital scheduling platform . https://www.zdnet.com/article/flexbooker-apologizes-for-breach-of-3-7-million-user-records-credit-card-information/
  • Keary (2022) Tim Keary. 2022. Attack to social media platform . https://venturebeat.com/security/twitter-breach-api-attack/
  • Kim et al . (2022) Sunnyeo Park Daejun Kim, Suman Jana, and Sooel Son. 2022. FUGIO: Automatic Exploit Generation for PHP Object Injection Vulnerabilities. In 31st USENIX Security Symposium (USENIX Security 22) , 197–214.
  • Koutroumpouchos et al . (2019) Nikolaos Koutroumpouchos, Georgios Lavdanis, Eleni Veroni, Christoforos Ntantogian, and Christos Xenakis. 2019. ObjectMap: Detecting insecure object deserialization. In Proceedings of the 23rd Pan-Hellenic Conference on Informatics , 67–72.
  • Mai et al . (2019) Phu X Mai, Fabrizio Pastore, Arda Goknil, and Lionel C. Briand. 2019. MCP: A security testing tool driven by requirements. In 2019 IEEE/ACM 41st International Conference on Software Engineering: Companion Proceedings (ICSE-Companion) , 55–58.
  • Mirabella et al . (2021) A. Giuliano Mirabella, Alberto Martin-Lopez, Sergio Segura, Luis Valencia-Cabrera, , and Antonio Ruiz-Cortés. 2021. Deep learning-based prediction of test input validity for restful apis. In 2021 IEEE/ACM Third International Workshop on Deep Learning for Testing and Testing for Deep Learning (DeepTest) , 9–16.
  • OWASP (2023) OWASP. 2023. OWASP . https://github.com/mattiasanti99/vulnerabilityOWASPproject
  • Porter (1980) Martin F Porter. 1980. An algorithm for suffix stripping. Program 14, 3 (1980), 130–137.
  • Reddy and Rudra (2022) A. Sujan Reddy and Bhawana Rudra. 2022. Detection of injections in API requests using recurrent neural networks and transformers. International Journal of Electronic Security and Digital Forensics , 638–658.
  • Shcherbakov and Balliu (2021) Mikhail Shcherbakov and Musard Balliu. 2021. Serialdetector: Principled and practical exploration of object injection vulnerabilities for the web. In Network and Distributed Systems Security (NDSS) Symposium .
  • StudentAPI (2023) StudentAPI. 2023. StudentAPI . https://github.com/arash-mazidi/StudentAPI
  • Team (2023a) The AKTO Team. 2023a. Instant, Open source API security → API discovery, automated business logic testing and runtime detection . https://github.com/akto-api-security/akto
  • Team (2023b) The RESTTESTGEN Team. 2023b. RestTestGen: A tool and framework for automated black-box testing of RESTful APIs . https://github.com/SeUniVr/RestTestGen
  • Toggle (2023) Toggle. 2023. Toggle . https://github.com/pdonatilio/ToggleAPI
  • VAmPI (2023) VAmPI. 2023. vampi . https://github.com/erev0s/VAmPI
  • Knowledge Base
  • Pentest services

Application Penetration Testing

  • Tale of a Wormable Twitter XSS
  • URL Redirection – Attack and Defense
  • Manipulating Numeric Parameters
  • wkhtmltopdf File Inclusion Vulnerability
  • Preventing Cross-site Scripting In PHP
  • Pentesting User Interfaces: How to Phish Any Chrome, Outlook, or Thunderbird User
  • Cross-domain Referer Leakage
  • Pentesting Basic Authentication
  • Username Enumeration
  • iOS Frida Objection Pentesting Cheat Sheet
  • Jailbreaking iOS 13 with unc0ver
  • X-Runtime Header Timing Attacks

API Mass Assignment Vulnerability

  • Web Server TRACE Enabled

AWS Pentesting

  • HTTP Request Smuggling (AWS)
  • Create an AWS Read-Only Access Token
  • ScoutSuite Quickstart
  • Protecting S3 buckets using IAM and KMS
  • Misconfigured S3 Bucket
  • S3 Storage Does Not Require Authentication

DevOps Security

  • Securing Travis CI
  • SSH Weak Key Exchange Algorithms Enabled
  • SSH Weak MAC Algorithms Enabled
  • TLS 1.0 Initialization Vector Implementation Information Disclosure Vulnerability
  • OpenSSL ‘ChangeCipherSpec’ (CCS) MiTM Vulnerability
  • Null Ciphers Supported
  • ‘Export Ciphers’ Enabled

Network Penetration Testing

  • F5 BIG-IP Cookie Remote Information Disclosure
  • DNS Server Dynamic Update Record Injection
  • rlogin Service Enabled
  • Unauthenticated MongoDB – Attack and Defense
  • SNMP ‘GETBULK’ Denial of Service
  • Responder / MultiRelay Pentesting Cheatsheet
  • NTP Mode 6 Vulnerabilities
  • Cisco Information Disclosure (CVE-2014-3398 – CSCuq65542)
  • SSH Tunneling for Pentesters
  • .NET Handler Enumeration
  • TLS_FALLBACK_SCSV Not Supported
  • PHP Easter Eggs Enabled
  • MySQL Multiple Vulnerabilities
  • Debian Predictable Random Number Generator Weakness
  • Cisco IKE Fragmentation Vulnerability

Pentesting Fundamentals

  • GET vs POST
  • Cache Controls Explained
  • Cookie Security Attributes
  • Essential Wireshark Skills for Pentesting
  • Testing Cookie Based Session Management

Windows Hardening

  • Resolving “Windows NetBIOS / SMB Remote Host Information Disclosure” (2020)

Home » API Mass Assignment Vulnerability

Table of Contents

  • 1. API Mass Assignment

API Mass Assignment

Mass assignment vulnerabilites occur when a user is able to initialize or overwrite server-side variables for which are not intended by the application. By manually crafting a request to include additional parameters in a request, a malicious user may adversely affect application functionality.

Common root causes of mass assignment vulnerabilities may include the following:

Framework-level “autobinding” features. Spring and .NET MVC are two of many frameworks that allow HTTP parameters to be directly mapped to model objects. While this feature is useful to easily set server-side values, it does not prevent arbitrary parameters from being injected.

  • https://agrrrdog.blogspot.com/2017/03/autobinding-vulns-and-spring-mvc.html

Parsing a request body as an object. Although copying an object is easier than selecting numerous individual values within that object, this practice should be avoided. When using data formats such as JSON, developers should only extract values that are intended to be modified by users.

Below shows a common example of this vulnerability in a user registration endpoint: POST /api/register HTTP/1.1 [..] {“email”:”[email protected]”}

HTTP/1.1 200 OK [..] {”userid”:”112345”,“email”:”[email protected]”,”email_verified”:false}

A malicious user may want to bypass email verification for a number of reasons. To attack this endpoint, a value is inserted into the request body:

POST /api/register HTTP/1.1 [..] {“email”:”[email protected]”,”email_verified”:true}

HTTP/1.1 200 OK [..] {”userid”:”112346”,“email”:”[email protected]”,”email_verified”:true}

Developers should also ensure that values do not include nested objects or arrays which may undermine application logic. Below shows another style of attack leveraging JSON arrays:

POST /api/register HTTP/1.1 [..] {“email”:[”[email protected]”,”[email protected]”]}

HTTP/1.1 200 OK [..] {”userid”:”112347”,“email”:[”[email protected]”,”[email protected]”],”email_verified”:false}

In the above example an array is provided where a single string value was expected. This would likely have significant security implications for account access and associations.

  • Application

Mass Assignment in .NET

ASP.NET Core MVC allows automatic model binding of request parameters into objects which may introduce Mass Assignment vulnerabilities.

Vulnerable Example

In this snippet, the unprotected User model accepts dynamic user input, which could allow an attacker to POST a new User with an administrative Role to then become administrator.

One way to prevent binding of unwanted properties is to use [BindNever] or the [Editable(false)] attribute model.

CWE - CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes

OWASP - Mass Assignment Cheat Sheet

IMAGES

  1. Mass Assignment Vulnerability For Application Framework

    mass assignment vulnerability java

  2. Mass Assignment vulnerability and prevention

    mass assignment vulnerability java

  3. Exploiting Mass Assignment Vulnerabilities

    mass assignment vulnerability java

  4. Mass Assignment Vulnerabilities and Validati...

    mass assignment vulnerability java

  5. Mass Assignment Vulnerability

    mass assignment vulnerability java

  6. Broken user auth attack scenario

    mass assignment vulnerability java

VIDEO

  1. Mass communication assignment process of communication barriers to communication Comparison of media

  2. [API-08] Mass Assignment Attacks

  3. Portswigger: Exploiting a mass assignment vulnerability

  4. Unveiling Drought Vulnerability on Cropland in Java

  5. USING VULNERABILITY SCANNERS

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

    You may refer to the problem Prevent mass assignment in Spring MVC with Roo.. In your case, you can use @InitBinder provided by Spring MVC.@InitBinder would specify the white list for json and bean mapping.. In my experience, I used @RequestBody for auto-binding. I need to add @JsonIgnore to specify the property that would not include for the mapping. ...

  3. Mass Assignment · OWASP Cheat Sheet Series

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

  4. CheatSheetSeries/cheatsheets/Mass_Assignment_Cheat_Sheet.md at ...

    The OWASP Cheat Sheet Series was created to provide a concise collection of high value information on specific application security topics. - OWASP/CheatSheetSeries

  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. Mass Assignment in Java

    When these intermediate Java objects are also used to hold internal fields, it is easy to forget to implement proper validation mechanisms that prevent a malicious user to mass-assign an internal field. Imagine having the following class: class AssetUploadParameters { String root = Constants.ASSETS_ROOT; // Some /path/to/assets String name ...

  7. Mass assignment vulnerability

    Mass assignment is a computer vulnerability where an active record pattern in a web application is abused to modify data items that the user should not normally be ... and Java Play framework. In 2012 mass assignment on Ruby on Rails allowed bypassing of mapping restrictions and resulted in proof of concept injection of unauthorized SSH ...

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

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

  9. What is a Mass Assignment Vulnerability?

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

  10. WSTG

    WSTG - Latest is a comprehensive guide for web application security testing, covering various topics and techniques. One of them is testing for mass assignment, a common vulnerability that allows attackers to modify or create arbitrary objects by manipulating the request parameters. Learn how to identify and prevent this risk with OWASP's best practices and tools.

  11. Testing for Mass Assignment (WSTG-INPV-20)

    Gray-Box Testing. When the analysis is performed with a gray-box testing approach, it is possible to follow the same methodology to verify the issue. However, the greater knowledge on the application allows to more easily identify frameworks and handlers subject to mass assignment vulnerability. In particular, when the source code is available ...

  12. What is mass assignment?

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

  13. Mass Assignment Vulnerability

    Description. Mass Assignment is a vulnerability wherein an active record pattern is manipulated into modifying data items that should normally restrict user functions such as passwords, granted permissions, or admin access. They arise when objects on the backend e.g. database records, are created by using the object representation received with ...

  14. Common vulnerabilities in Java and how to fix them

    30 vulnerabilities to look out for in Java applications: Arbitrary file writes, directory traversal, deserialization, and more…. Securing applications is not the easiest thing to do. An application has many components: server-side logic, client-side logic, data storage, data transportation, API, and more.

  15. Secure Coding Guidelines

    Right now, we're going to go through Mass Assignment vulnerabilities and what they look like, along with a few ways to avoid them. First, a quick recap: Mass Assignment is a vulnerability where API endpoints don't restrict which properties of their associated object can be modified by a user. This vulnerability can occur when making use of a library/framework that allows for the automatic ...

  16. Mining REST APIs for Potential Mass Assignment Vulnerabilities

    The support for identifying mass assignment vulnerabilities in REST APIs is limited. Akto (Team, 2023a) and RestTestGen (Team, 2023b) are two examples of tools for detecting mass assignment vulnerabilities in REST APIs. RestTestGen is an automated black-box testing tool, and Akto is semi-automated.

  17. API Mass Assignment Vulnerability

    API Mass Assignment Mass assignment vulnerabilites occur when a user is able to initialize or overwrite server-side variables for which are not intended by the application. By manually crafting a request to include additional parameters in a request, a malicious user may adversely affect application functionality. Common root causes of mass assignment vulnerabilities may include […]

  18. CWE 915: Mass Assignment Vulnerability

    Flaw. CWE 915: Improperly Controlled Modification of Dynamically-Determined Object Attributes, also known as overpost or mass-assignment, is a flaw in which an application accepts input data and does not properly control which elements are allowed to be modified. In ASP.NET MVC model binding simplifies the mapping of incoming (untrusted) data ...

  19. Prevent mass assignment in Spring MVC with Roo

    There are actually two security issues here: mass assignment (MA) and CSRF. AFAIK JSF, for all standard components, always protects against MA. It matches IDs of submitted components against IDs that were rendered, by simply executing the exact same algo at the postback as it does for rendering. Additionally select components explicitly check ...

  20. Mass Assignment in .NET

    ASP.NET Core MVC allows automatic model binding of request parameters into objects which may introduce Mass Assignment vulnerabilities. Vulnerable Example In this snippet, the unprotected User model accepts dynamic user input, which could allow an attacker to POST a new User with an administrative Role to then become administrator.