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

Double free, excessive agency, prompt injection.

HatchJS Logo

HatchJS.com

Cracking the Shell of Mystery

Mass Assignment: How to Protect Your Application from Insecure Binder Configuration

Avatar

Mass Assignment: An Insecure Binder Configuration

In software development, mass assignment is the act of sending a large number of parameters to a function or method. This can be a useful technique for quickly creating new objects or updating existing ones. However, if not done correctly, mass assignment can also lead to security vulnerabilities .

One common way to implement mass assignment is to use a binder . A binder is a type of object that maps between a set of input parameters and a set of properties on an object. When mass assignment is used with a binder, the binder will automatically set the properties on the object to the corresponding values from the input parameters.

This can be a convenient way to create or update objects, but it can also be dangerous if the binder is not configured correctly. If a binder allows untrusted input, an attacker could use it to inject malicious code into an application. This could lead to a variety of security problems, such as cross-site scripting (XSS) , SQL injection , and remote code execution (RCE) .

In this article, we will discuss the risks of mass assignment and how to secure binder configurations. We will also provide some examples of how attackers can exploit insecure binder configurations.

By the end of this article, you will be able to:

  • Identify the risks of mass assignment
  • Understand how to secure binder configurations
  • Recognize the signs of an insecure binder configuration

| Column | Data | |—|—| | Name | Description | | Example | Vulnerability | | Mitigation | How to fix | |—|—|—| | `allow_all_fields` | Whether or not to allow all fields to be mass assigned. | `allow_all_fields = true` | This is a very insecure setting and should never be used. | Set `allow_all_fields = false`. | | `whitelist` | A list of fields that are allowed to be mass assigned. | `whitelist = [“name”, “email”]` | This is a more secure setting than `allow_all_fields = true`, but it is still possible to mass assign fields that are not in the whitelist. | Make sure the whitelist is as comprehensive as possible. | | `blacklist` | A list of fields that are not allowed to be mass assigned. | `blacklist = [“password”]` | This is the most secure setting, as it prevents all fields from being mass assigned except for those that are explicitly allowed. | Make sure the blacklist is as comprehensive as possible. |

Mass assignment is a vulnerability that allows an attacker to send a single request to a web application and modify multiple rows of data in a database. This can be done by sending a request with a list of values for each field of a table, or by sending a single value that is used to update multiple rows of data.

Mass assignment is a serious vulnerability because it can allow an attacker to take control of a web application or to steal sensitive data. In this blog post, we will discuss what mass assignment is, how it works, and how to prevent it.

  • What is mass assignment?

Mass assignment is a vulnerability that occurs when a web application allows an attacker to send a single request to update multiple rows of data in a database. This can be done by sending a request with a list of values for each field of a table, or by sending a single value that is used to update multiple rows of data.

For example, consider a web application that allows users to create and manage accounts. If the application is not properly configured, an attacker could send a request to create a new account with a list of usernames and passwords. This would allow the attacker to create multiple accounts with the same username and password, which could then be used to access the application.

Another example would be a web application that allows users to create and manage products. If the application is not properly configured, an attacker could send a request to update the price of all products in the database. This would allow the attacker to change the prices of all products, which could lead to financial loss for the company.

How does insecure binder configuration lead to mass assignment?

In order to prevent mass assignment, web applications typically use a binder to sanitize user input before it is used to update a database. The binder checks the input to make sure that it is in the correct format and that it does not contain any malicious code.

If the binder is not configured correctly, it may allow user input to be passed directly to the database. This could allow an attacker to send a request with a list of values for each field of a table, or with a single value that is used to update multiple rows of data.

How to prevent mass assignment

There are a number of ways to prevent mass assignment. Here are some tips:

  • Use a binder to sanitize user input. A binder is a security mechanism that can be used to prevent mass assignment. The binder checks the input to make sure that it is in the correct format and that it does not contain any malicious code.
  • Limit the number of rows that can be updated in a single request. This will help to prevent an attacker from sending a request to update multiple rows of data.
  • Use role-based access control. This will help to ensure that users only have access to the data that they need to access.
  • Monitor your web application for suspicious activity. This will help you to identify and respond to mass assignment attacks.

Mass assignment is a serious vulnerability that can allow an attacker to take control of a web application or to steal sensitive data. By following the tips in this blog post, you can help to prevent mass assignment and protect your web application from attack.

Additional resources

  • [OWASP Top 10: A1 – Injection](https://owasp.org/www-project-top-ten/2017/A1_Injection)
  • [Preventing Mass Assignment Attacks](https://www.owasp.org/index.php/Preventing_Mass_Assignment_Attacks)
  • [Mass Assignment Attacks: How to Prevent and Mitigate](https://www.cisa.gov/uscert/ncas/tips/ST16-008)

3. What are the risks of insecure binder configuration?

Insecure binder configuration is a serious security vulnerability that can allow attackers to bypass access controls and modify data in a database. This can lead to a variety of serious consequences, including data loss, data corruption, denial of service, and identity theft.

An attacker can use mass assignment to delete data from a database by sending a malicious request that contains a list of record IDs. The binder will then attempt to update each record with the data provided in the request, which could include a delete operation. If the binder is not configured correctly, it may not properly validate the request data and could delete records that the user does not have permission to delete.

Data corruption

An attacker can use mass assignment to modify data in a database by sending a malicious request that contains a list of record IDs and new data values. The binder will then attempt to update each record with the data provided in the request, which could include invalid or malicious data. If the binder is not configured correctly, it may not properly validate the request data and could update records with data that could corrupt the database.

Denial of service

An attacker can use mass assignment to make a web application unavailable by sending a malicious request that contains a large number of record IDs. The binder will then attempt to update each record with the data provided in the request, which could consume a significant amount of resources and slow down or crash the web application.

Identity theft

An attacker can use mass assignment to steal sensitive data, such as usernames, passwords, and credit card numbers, by sending a malicious request that contains a list of record IDs and the data values that they want to steal. The binder will then attempt to update each record with the data provided in the request, which could include the attacker’s own data values. If the binder is not configured correctly, it may not properly validate the request data and could update records with the attacker’s data values, which could then be used to steal the victim’s identity.

4. How can you prevent insecure binder configuration?

There are a number of steps that you can take to prevent insecure binder configuration, including:

  • Use a secure binder library. There are a number of secure binder libraries available that can help you to prevent insecure binder configuration. These libraries typically include features such as input validation, parameter binding, and type checking.
  • Configure the binder correctly. When you configure the binder, you should make sure to set the appropriate security options. For example, you should make sure that the binder only allows trusted users to update data in the database.
  • Sanitize user input before it is used to update a database. Even if you use a secure binder library and configure it correctly, you should still sanitize user input before it is used to update a database. This will help to protect your application from attacks that exploit vulnerabilities in the binder library.
  • Monitor your web application for signs of mass assignment attacks. You should monitor your web application for signs of mass assignment attacks. This can be done by using a security monitoring tool or by manually reviewing your application logs. If you detect any suspicious activity, you should investigate it immediately and take steps to mitigate the threat.

By following these steps, you can help to prevent insecure binder configuration and protect your web application from a variety of serious security vulnerabilities.

Q: What is mass assignment?

A: Mass assignment is a security vulnerability that occurs when an application allows an attacker to send a single request that sets multiple properties of an object. This can be exploited to create new users, modify existing users, or delete users.

Q: What is an insecure binder configuration?

A: An insecure binder configuration is a configuration that allows mass assignment to occur. This can happen when a developer forgets to add the `attr` or `only` parameters to a `Form::model()` or `Form::create()` call.

Q: What are the risks of mass assignment?

A: Mass assignment can allow an attacker to do the following:

  • Create new users with administrator privileges
  • Modify existing user accounts
  • Delete user accounts
  • Read sensitive data from user accounts

Q: How can I protect my application from mass assignment?

There are a few things you can do to protect your application from mass assignment:

  • Use the `attr` or `only` parameters to restrict the properties that can be mass assigned.
  • Use the `csrf_field()` helper to protect against cross-site request forgery (CSRF) attacks.
  • Use a framework that has built-in protection against mass assignment.

Q: What are some additional resources on mass assignment?

  • [Laravel’s documentation on mass assignment](https://laravel.com/docs/8.x/securitymass-assignment)
  • [The PHP Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/PHP_Security_Cheat_Sheet.html)
  • [OWASP’s Top 10 Most Critical Web Application Security Risks](https://owasp.org/www-project-top-ten/)

In this blog post, we discussed the security risks of mass assignment and how to secure your application against it. We covered the following topics:

  • How does mass assignment work?
  • What are the security risks of mass assignment?
  • How to secure your application against mass assignment

We hope that this blog post has helped you to understand the security risks of mass assignment and how to secure your application against it. If you have any questions or feedback, please feel free to contact us.

Key takeaways:

  • Mass assignment is a vulnerability that allows an attacker to send arbitrary data to a server-side application.
  • Mass assignment can be exploited to inject malicious code into a server-side application, which can lead to a variety of security breaches.
  • To secure your application against mass assignment, you should use a whitelist of allowed fields and use input validation to ensure that all data is properly sanitized.

Author Profile

Marcus Greenwood

Latest entries

  • December 26, 2023 Error Fixing User: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
  • December 26, 2023 How To Guides Valid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
  • December 26, 2023 Error Fixing How to Fix the The Root Filesystem Requires a Manual fsck Error
  • December 26, 2023 Troubleshooting How to Fix the `sed unterminated s` Command

Similar Posts

Power automate desktop: how to use multiple conditions.

Power Automate Desktop: Multiple Conditions Power Automate Desktop is a powerful tool that can help you automate tasks on your PC. One of the things you can do with Power Automate Desktop is create multiple conditions. This allows you to perform different actions depending on the values of different variables. For example, you could create…

How to Delete a Pokmon Black Save File | A Step-by-Step Guide

How to Delete a Pokmon Black Save Pokmon Black is a popular Nintendo DS game that allows players to catch, train, and battle Pokmon. However, if you ever need to delete your save file for any reason, there are a few simple steps you can follow. In this article, we will walk you through the…

How to Use Continuity to Evaluate a Limit

How to Use Continuity to Evaluate a Limit In mathematics, a limit is a value that a function approaches as its input approaches a particular value. Continuity is a property of functions that means that they can be drawn without lifting the pen from the paper. If a function is continuous at a point, then…

How to Show Durability in Minecraft | Minecraft Guides

How to Show Durability in Minecraft Minecraft is a popular sandbox game that allows players to build, explore, and survive in a blocky world. One of the important aspects of Minecraft is managing your resources, including your tools and weapons. As you use your tools, they will lose durability and eventually break. This can be…

How to Copy a Block in Minecraft | Minecraft Guide

Have you ever wanted to copy a block in Minecraft? Maybe you want to duplicate a valuable item, or create a symmetrical build. Whatever your reason, there are a few different ways to copy blocks in Minecraft. In this article, we’ll show you how to copy blocks using both the traditional method and a more…

How to Make Text Bold in Android Studio

Bold Text in Android Studio Android Studio is a powerful IDE for developing Android apps. It comes with a variety of features to help you create beautiful and engaging user interfaces, including the ability to easily bold text. In this article, we’ll show you how to bold text in Android Studio. We’ll cover the basics…

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

Mass Assignment

Learn about the pros and cons of mass assignment.

What is mass assignment?

Protecting your application.

Mass assignment is an incredibly useful tool. When used properly, it can speed up development time. But it can cause severe damage if used improperly. This functionality is usually included as part of an Object Relational Mapper (ORM) or Object Document Mapper (ODM). ORMs aren’t as popular in Node as they are in other languages, but they come up occasionally. ODMs are popular if you use MongoDB, CouchDB, or another schema-less document database.

In the examples below, we’ll use Mongoose . Mongoose is a MongoDB object modeling tool for Node.js


Let’s say you have a User model that needs to be updated with several changes. You could update each field individually, or you could pass all of the changes from a form and update it in one go.

Your form might look like this:

Then you have back end code to process and save the form submission. That might look like this:

Quick and easy, right? But what if a malicious user modifies the form, giving themselves administrator permissions?

That same code would now change this user’s permissions erroneously.

Many developers and sites have fallen victim to this problem. A recent, well-known exploit of this vulnerability occured when a user exposed Ruby on Rails.

  • Egor Homakov initially reported to the Rails team that new Rails installs were insecure. His bug report was rejected.
  • The core team thought it was a minor concern that would be easier for new developers to leave enabled by default.
  • Homakov hilariously “hacked” the Rails GitHub account (GitHub is built on Rails) to give himself administrative rights to their repositories.

Needless to say, this proved his point, and now Rails, and GitHub, are protected from this attack by default.

How do you protect your application against this? The exact implementation details depend on the framework or codebase you’re using, but you have a few options:

  • Turn off mass assignment completely; in Mongoose this is accomplished by using strict mode.
  • Whitelist the fields that are safe to be mass assigned, iterate over your body params, and only save the whitelisted fields.
  • Blacklist the fields that are not safe to be mass assigned, iterate over your body params, and only save the fields that are not blacklisted.

There is also a plugin for Mongoose specifically, Mongoose Mass Assign , that will assist with this.

Depending on your implementation, some of these may be used simultaneously. A simple whitelist implementation looks like this:

Get hands-on with 1200+ tech skills courses.

blog post image

Andrew Lock | .NET Escapades Andrew Lock

  • ASP.NET Core
  • Razor Pages

Preventing mass assignment or over posting with Razor Pages in ASP.NET Core

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

This post is an updated version of one I wrote several years ago , talking about over posting attacks in ASP.NET Core MVC controllers. The basic premise is exactly the same, though Razor Pages makes it much easier to do the "right" thing.

What is mass assignment?

Mass assignment occurs during the model binding phase of a Razor Pages request. It happens when a user sends data in a request that you weren't expecting to be there, and that data is used to modify state on the server.

It's easier to understand with an example. Lets imagine you have a form on your website where a user can edit their name. On the same form, you also want to display some details about the user that they shouldn't be able to edit - whether they're an admin user.

Lets imagine you have the following very simple domain model of a user:

It has three properties, but you only actually allow the user to edit the Name property - the IsAdmin property is just used to control the markup they see, by adding an "Admin" badge to the markup.

This gives a form that looks something like this:

View of the generated HTML

In the above Razor Page, the CurrentUser property exposes the AppUser instance that we use to display the form correctly. The vulnerability in the Razor Page is because we're directly model-binding a domain model AppUser instance to the incoming request and using that data to update the database:

Don't use the code below, it's riddled with issues!

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

Normal post

However, with a simple bit of HTML manipulation, or by using Postman/Fiddler for example, a malicious user can set the IsAdmin field to true , even though you didn't render a form field for it. The model binder will dutifully bind the value to the request:

Malicious post with overposting

If you update your database/state with the provided IsAdmin value (as the previous Razor Page does) then you have just fallen victim to mass assignment/over posting!

There's a very simple way to solve this with Razor Pages, and thankfully, it's pretty much the default approach for Razor Pages.

Using a dedicated InputModel to prevent over posting

The solution to this problem is actually very commonly known, and comes down to this: use a dedicated InputModel .

Instead of model-binding to the domain model AppUser class that contains the IsAdmin property, create a dedicated InputModel that contains only the properties that you want to bind in your form. This is commonly defined as a nested class in the Razor Page where it's used.

With this approach, we can update the Razor Page as follows:

We then update the Razor Page slightly, so that the form inputs bind to the Input property, instead of CurrentUser :

There's a few things to note with this solution:

  • In the example above, we still have access to the same AppUser object in the view as we did before, so we can achieve exactly the same functionality (i.e. display the IsAdmin badge).
  • Only the Input property is model bound, so malicious users can only set properties that exist on the InputModel
  • We have to "re-populate" values in the OnPost that weren't model bound. In practical terms this was required for correctness previously too, I just ignored it

  • To set values on our "domain" AppUser object, we rely on "manual" left-right copying from the InputModel to the AppUser before you save it.

Overall, there's essentially no down-sides to this approach. The only additional work you have to do is define the nested class InputModel , and also copy the values from the input to the domain object, but I'd argue they're not really downsides.

First, the nested InputModel isn't strictly necessary. In this very simple example, it's pretty much redundant, as it only has a single property, which could be set directly on the PageModel instead. If you prefer, you could do this:

In practice though, your InputModel will likely contain many properties, potentially with multiple data annotation attributes for validation etc. I really like having all that encapsulated in a nested class. It also simplifies the PageModel overall and makes all your pages consistent, as every page has just a single bound property called Input of type PAGENAME.InputModel . Also, being a nested class, I don't have to jump around in the file system, so there's no real overhead there either.

The final point, having to copy values back and forth between your InputModel and your domain object ( AppUser ) is a bit annoying. But there's not really anything you can do about that. Code like that has to exist somewhere in your application, and you already know it can't be in the model binder! You can potentially use tools like AutoMapper to automate some of this.

Another approach, which keeps separate Input and Output models is using a mediator . With this approach, the request is directly model-bound to a "command" which is dispatched to a mediator for handling. This command is the "input" model. The response from the mediator serves as the output model.

Using a separate InputModel like this really is the canonical way to avoid over-posting in Razor Pages, but I think it's interesting to consider why this approach didn't seem to be as prevalent with MVC.

Defending against over posting in MVC

In my previous post on over posting in ASP.NET Core MVC , I described multiple different ways to protect yourself from this sort of attack, many of which used extra features of the model binder to "ignore" the IsAdmin property. This typically involves adding extra attributes, like [Bind] , [BindNever] , or [ModelMetadataType] to convince the model binder to ignore the IsAdmin field.

The simplest option, and the best in my ( and others ) opinion, is simply to use separate input and output models for MVC too. The "Output" model would contain the IsAdmin and Name properties, so can render the view as before. The "Input" model would only contain the Name property, so isn't vulnerable to over posting, just as for Razor Pages.

So if the answer is as simple as that, why isn't in more popular?

To be clear, it is very popular, especially if you're using the Mediator pattern with something like MediatR . I really mean why isn't it the default in all sample code for example?

As far as I can tell, the reason that separate Input/Output models wasn't more popular stems from several things:

  • The C# convention of a separate file per class . Even the small overhead of creating another file can be enough to discourage good practices!
  • The "default" MVC layout . Storing Controller, View, and Models files separately in a project, means lots of jumping around the file system. Coupled with the separate-file convention, that's just more overhead. Feature slices are designed to avoid this problem.
  • Properties on the Output model must be model-bound to the equivalent properties on the Input model . That means properties on the Input model must be named exactly the same as those on the Output model that are used to render the view. Similarly, validation metadata must be kept in-sync between the models.
  • The perceived additional left-right copying between models required . I say perceived, because once you close the over-posting vulnerability you realistically have to have some left-right copying somewhere, it just wasn't always as obvious!

These minor annoyances all add up in MVC which seems to discourage the "separate input/output" model best practice. So why didn't that happen for Razor Pages?

Razor Pages inherently tackles the first 2 points, by co-locating handlers, models, and views. It's hard to overstate just how beneficial this is compared to separate MVC views and controllers, but you really have to try it to believe it!

Point 3 above could be tackled in MVC either by using inheritance , by using separate "metadata" classes , or by using composition . Razor Pages favours the composition approach, where the InputModel is composed with the other properties required to render the view on the PageModel ( CurrentUser in my previous example). This neatly side-steps many of the issues with using composition, and just fits really well into the Razor Pages model.

Point 4 is still there for Razor Pages, but as I mentioned, it's pretty much a fact of life. The only way around that is to bind directly to domain models, which you should never do, even if the ASP.NET Core getting started code does it !đŸ˜±

Bonus: over posting protection != authorization

Before we finish, I just want to address a point that always seems to come up when discussing over posting:

You could edit the id parameter to update the name for a different user. How does separate-models protect against that?

The short answer: it doesn't. But it's not trying to.

The Razor Page I described above allows anyone to edit the name of any AppUser - you just need to provide a valid ID in the URL. We can't easily remove the ID from the URL, or prevent users from sending it, as we need to know which user to edit the name for. There's only really 3 feasible approaches:

  • Store the ID in state on the server-side. Now you've got a whole different set of problems to manage!
  • Encrypt the ID and echo it back in the request. Again, way more complex than you need, and if done incorrectly can be a security hole, or not offer the protection you think it does.
  • Verify a user is authorized to edit the name. There are well-established patterns for resource-based authorization .

The final point there is clearly the correct approach to take. Before you accept a POST request that edits the name of a user, verify that the authenticated user is authorized to make that change! There's no need for some sort of custom approach - ASP.NET Core has support for imperative resource-based authorization out of the box . I also have a (rather old now) post on creating custom authorization handlers , and the source code for this post includes a basic example.

In this post I discussed mass assignment attacks, and how they work on a Razor Pages application. I then showed how to avoid the attack, by creating a nested InputModel in your Razor Page, and only using BindProperty on this single type. This keeps your vulnerable surface-area very explicit, while not exposing other values that you might need to display the Razor view correctly (i.e. IsAdmin ).

This approach is pretty standard for Razor Pages, but it wasn't as easy to fall into the pit of success for MVC. The overall design of Razor Pages helps to counteract the impediments, so if you haven't already, I strongly suggest trying them out.

Finally I discussed an issue that comes up a lot that conflates over-posting with more general authorization. These are two very different topics - you can still be vulnerable to over-posting even if you have authorization, and vice-versa. In general, resource-based authorization is a good approach for tackling this side-issue.

Whatever you do, don't bind directly to your EntityFramework domain models . Pretty please.

Popular Tags

js mass assignment

Stay up to the date with the latest posts!

Team Research blog

Hacked freeCodeCamp Certification

Hunting For Mass Assignment Vulnerabilities Using GitHub CodeSearch and grep.app

This post discusses the process of searching top GitHub projects for mass assignment vulnerabilities. This led to a fun finding in the #1 most starred GitHub project, freeCodeCamp , where I was able to acquire every coding certification – supposedly representing over 6000 hours of study – in a single request.

Searching GitHub For Vulnerabilities

With more than 200 million repositories, GitHub is by far the largest code host. While the vast majority of repositories contain boilerplate code, forks, or abandoned side projects, GitHub also hosts some of the most important open source projects. To some extent Linus’s law – “given enough eyeballs, all bugs are shallow” – has been empirically shown on GitHub, as projects with more stars also had more bug fixes. We might therefore expect the top repositories to have a lower number of security vulnerabilities, especially given the incentives to find vulnerabilities such as bug bounties and CVE fame.

Undeterred by Linus’s law, I wanted to see how quickly I could find a vulnerability in a popular GitHub project. The normal approach would be to dig into the code of an individual project, and learn the specific conventions and security assumptions behind it. Combine with a strong understanding of a particular vulnerability class, such as Java deserialization, and use of code analysis tools to map the attack surface, and we have the ingredients to find fantastic exploits which everyone else missed such as Alvaro Munoz’s attacks on Apache Dubbo .

However, to try and find something fast, I wanted to investigate a “wide” rather than a “deep” approach of vuln-hunting. This was motivated by the beta release of GitHub’s new CodeSearch tool . The idea was to find vulnerabilities through querying for specific antipatterns across the GitHub project corpus.

The vulnerability class I chose to focus on was mass assignment, I’ll describe why just after a quick refresher.

Mass Assignment

A mass assignment vulnerability can occur when an API takes data that a user provides, and stores it without filtering for allow-listed properties. This can enable an attacker to modify attributes that the user should not be allowed to access.

A simple example is when a User model contains a “role” property which specifies whether a user has admin permissions; consider the following User model:

And a user registration function which saves all attributes specified in the request body to a new user instance:

A typical request from a frontend to this endpoint might look like:

However, by modifying the request to add the “role” property, a low-privileged attacker can cause its value to be saved. The attacker’s new account will gain administrator privileges in the application:

The mass assignment bug class is #6 on the OWASP API Security Top 10 . One of the most notorious vulnerability disclosures, back in 2012, was when researcher Egar Homakov used a mass assignment exploit against GitHub to add his own public key to the Ruby on Rails repository and commit a message directly to the master branch.

Why Mass Assignment?

This seemed like a good vulnerability class to focus on, for several reasons:

  • In the webapp assessments we do, we often find mass assignments, possibly because developers are less aware of this type of vuln compared to e.g. SQL injection.
  • They can be highly impactful, enabling privilege escalation and therefore full control over an application.
  • The huge variety of web frameworks have different ways of preventing/addressing mass assignment.
  • As in the above example, mass assignment vulns often occur on a single, simple line of code, making them easier to search for.

Mass Assignment in Node.js

Mass assignment is well known in some webdev communities, particularly Ruby On Rails. Since Rails 4 query parameters must be explicitly allow-listed before they can be used in mass assignments. Additionally, the Brakeman static analysis scanner has rules to catch any potentially dangerous attributes that have been accidentally allow-listed.

Therefore, it seemed worthwhile to narrow the scope to the current web technologies du jour, Node.js apps, frameworks, and object-relational mappers (ORMs). Among these, there’s a variety of ways that mass assignment vulnerabilities can manifest, and less documentation and awareness of them in the community.

To give examples of different ways mass assignment can show up, in the Mongoose ORM , the findOneAndUpdate () method could facilitate a mass assignment vulnerability if taking attributes directly from the user:

In the sophisticated Loopback framework , model access is defined in ACLs, where an ACL like the following on a user model would allow a user to modify all their own attributes:

In the Adonis.js framework , any of the following methods could be used to assign multiple attributes to an object:

The next step was to put together a shortlist of potentially-vulnerable code patterns like these, figure out how to search for them on GitHub, then filter down to those instances which actually accept user-supplied input.

Limitations of GitHub Search

GitHub’s search feature has often been criticized , and does not feel like it lives up to its potential. There are two major problems for our intended use-case:

  • Global code searches of GitHub turns up an abundance of starter/boilerplate projects that have been abandoned years ago, which aren’t relevant. There is a “stars” operator to only return popular projects, e.g. stars:>1000 , but it only works when searching metadata such as repository names and descriptions, not when searching through code .
  • The following characters are ignored in GitHub search: .,:;/\`'"=*!?#$&+^|~<>(){}[]@ . As key syntactical characters in most languages, it’s a major limitation that they can’t be searched for.

The first two results when searching for “ user.update(req.body) ” illustrate this:

js mass assignment

The first result looks like it might be vulnerable, but is a project with zero stars that has had no commits in years. The second result is semantically different than what we searched. Going through all 6000+ results when 99% of the results are like this is tedious.

These restrictions previously led some security researchers to use Google BigQuery to run complex queries against the 3 terabyte GitHub dataset that was released in 2016. While this can produce good results , it doesn’t appear that the dataset has been updated recently. Further, running queries on such a large amount of data quickly becomes prohibitively expensive.

GitHub CodeSearch

GitHub’s new CodeSearch tool is currently available at https://cs.github.com/ for those who have been admitted to the technology preview. The improvements include exact string search, an increased number of filters and boolean operators, and better search indexing. The CodeSearch index right now includes 7 million public repositories, chosen due to popularity and recent activity.

Trying the same query as before, the results load a lot faster and look more promising too:

js mass assignment

The repositories showing up first actually have stars, however they all have less than 10. Unfortunately only 100 results are currently returned from a query, and once again, none of the repositories that showed up in my searches were particularly relevant. I looked for a way to sort by stars, but that doesn’t exist . So for our purposes, CodeSearch solves one of the problems with GitHub search, and is likely great for searching individual codebases, but is not yet suitable for making speculative searches across a large number of projects.

Looking for a better solution, I stumbled across a third-party service called grep.app . It allows exact match and regex searches, and has only indexed 0.5 million GitHub repositories, therefore excluding a lot of the noise that has clogged up the results so far.

Trying the naĂŻve mass assignment search once again:

js mass assignment

Only 22 results are returned, but they are high-quality results! The first repo shown has over 800 stars. I was excited – finally, here was a search engine which could make the task efficient, especially with regex searches.

With the search space limited to top GitHub projects, I could now search for method names and get a small enough selection of results to scan through manually. This was important as “ req.body ” or other user input usually gets assigned to another variable before being used in a database query. To my knowledge there is no way to express these data flows in searches. CodeQL is great for tracking malicious input (taint tracking) over a small number of projects, but it can’t be used to make a “wide” query across GitHub.

Mass Assignment In FreeCodeCamp

Searching for “ user.updateAttributes( “, the first match was for freeCodeCamp, the #1 most starred GitHub project, with over 350k stars:

js mass assignment

Looking at the code in the first result, we appeared to have a classic mass assignment vulnerability:

Acquiring All Certifications on freeCodeCamp

The next step was to ensure that this function could be reached from a public-facing route within the application, and it turned out to be as simple as a PUT call to /update-user-flag : a route originally added in order that you could change your theme on the site.

I created an account on freeCodeCamp’s dev environment, and also looked at the user model in the codebase to find what attributes I could maliciously modify . Although freeCodeCamp did not have roles or administrative users, all the certificate information was stored in the user model.

Therefore, the exploit simply involved making the following request:

After sending the request, a bunch of signed certifications showed up on my profile, each one supposedly requiring 300 hours of work.

js mass assignment

Some aspiring developers use freeCodeCamp certifications as evidence of their coding skills and education, so anything that calls into question the integrity of those certifications is bad for the platform. There are certainly other ways to cheat, but those require more effort than sending a single request.

I reported this to freeCodeCamp, and they promptly fixed the vulnerability and released a GitHub security advisory .

Overall, it turned out that a third-party service, grep.app, is much better than both GitHub’s old and new search for querying across a large number of popular GitHub projects. The fact that we were able to use it to so quickly discover a vuln in a top repository suggests there’s a lot more good stuff to find. The key was to be highly selective so as to not get overwhelmed by results.

I expect that GitHub CodeSearch will continue to improve, and hope they will offer a “stars” qualifier by the time the feature reaches general availability.

Share this:

Leave a reply cancel reply, discover more from include security research blog.

Subscribe now to keep reading and get access to the full archive.

Type your email


Continue reading

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Assignment (=)

The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:

  • Initializers of var , let , and const declarations
  • Default values of destructuring
  • Default parameters
  • Initializers of class fields

All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Simple assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators in the JS guide
  • Destructuring assignment
  • Misconfigured Database
  • Misconfigured SMTP SSL
  • Non Async Task Null
  • NoSQL Injection
  • Open Redirect
  • Overwrite Collection Element
  • Part Creation Policy Not Export
  • Password Lockout Disabled
  • Property Accessor
  • Recursive Type Inheritance
  • Regular Expression Injection
  • Right Shift Not Number
  • SQL Injection
  • Safe Handle
  • Serialization Constructor
  • Serialization Event Implement
  • Server Side Request Forgery (SSRF)
  • Session Fixation
  • Shared Instance
  • Shared Object Lock
  • SQL Keyword Delimit
  • SSL Verification Disabled
  • Template Injection
  • Thread Suspend Resume
  • Unsafe Buffer Allocation
  • Unsafe HTTP Method
  • Unsafe runInContext
  • Use of document.domain
  • Use of document.write.md
  • Use of FindDOMNode and Refs
  • Use of msapp.execunsafelocalfunction
  • Use of SCE bypass
  • Use of Unsafe HTML
  • Use of unsafe innerHTML
  • View State Mac Disabled
  • Weak Cipher Mode
  • Weak Crypto Key Length
  • Weak Hashing Configuration
  • Weak Password Configuration
  • Weak SSL/TLS
  • Weak Symmetric Algorithm
  • XPath Injection
  • XML External Entity (XXE) Processing

Mass Assignment

What does this mean .

Mass Assignment is the act of constructing an object with a parameters hash. such as assigning multiple values to attributes via a single assignment operator.

What can happen ?

An attacker exploiting mass assignment vulnerabilities can update object properties that they should not have access to allowing them to escalate privileges, tamper with data, and bypass security mechanisms

Recommendation

Disable and specify exact keys using params.permit

Sample Code

Vulnerable : public class User { public string Login { get ; set ; } public string Password { get ; set ; } public string Role { get ; set ; } } // /Create?Login=username&Password=pwd public IActionResult Create ( User user ) { _context . Update ( user ); return View ( user ); }

Non Vulnerable : public class User { public string Login { get ; set ; } public string Password { get ; set ; } [Editable(false)] public string Role { get ; set ; } }

Vulnerable : class AssetUploadParameters { String root = Constants . ASSETS_ROOT ; String name ; String data ; }

Non Vulnerable : class AssetUploadParameters { transient String root = Constants . ASSETS_ROOT ; String name ; String data ; }

Vulnerable : class RegisterController extends Controller { public function save () { $user = new User ( request () -> all ()); } }

Non Vulnerable : class User extends Register { protected $fillable = [ 'name' , 'email' , 'password' , ]; }

Vulnerable : app . post ( '/register' , function ( req , res ) { const { username } = req . body ; usersCollection . countDocuments ({ username }, function ( err , count ) { if ( count === 0 ) { const newUser = req . body ; usersCollection . insert ( newUser ); res . status ( 201 ); } else { res . status ( 409 ); } }); });

Non Vulnerable : const { username , password } = req . body ; usersCollection . insert ({ username , password });

Vulnerable : def register @user = User . new ( params . permit ( :name , :password , :first_name , :last_name , :is_admin )) end

Non Vulnerable : User . new ( params . permit! )

  • https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html
  • 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]

Mass Assignment in NodeJS

Using mongodb, vulnerable example.

This Express.js route allows for an application to be signed up to. The logic checks whether a user already exists with the specified username; otherwise, it creates the new user by passing the whole User object passed from the request to the insert function:

Assuming an HTTP form is like this:

And assuming that the web application uses an is_admin field to implement a rudimentary access control mechanism, an attacker could craft a request adding the is_admin POST field with value 1 .

MongoDB does not provide any specific facility to prevent Mass Assignment; it is up to the developer to create the object to be inserted by only using a subset of all the fields that might be present in the request:

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

OWASP - Mass Assignment Cheat Sheet

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript assignment, javascript assignment operators.

Assignment operators assign values to JavaScript variables.

Shift Assignment Operators

Bitwise assignment operators, logical assignment operators, the = operator.

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

The Exponentiation Assignment Operator raises a variable to the power of the operand.

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example

The >>>= operator.

The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

Unsigned Right Shift Assignment Example

The &= operator.

The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

Bitwise AND Assignment Example

The |= operator.

The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.

Bitwise OR Assignment Example

The ^= operator.

The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

Use the correct assignment operator that will result in x being 15 (same as x = x + y ).

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

js mass assignment

Node.js Vulnerability Cheatsheet

  • February 17, 2022

js mass assignment

Newsletter Sign Up

Stay informed of the latest news and critical events in AppSec space:

  • Leadership Team

Platform Overview

  • Integrations
  • Code Property Graph

Platform Components

  • Intelligent SCA
  • Press & News
  • Privacy Policy
  • Terms of Service

© 2024 Qwiet. All rights reserved.

Firefox is no longer supported on Windows 8.1 and below.

Please download Firefox ESR (Extended Support Release) to use Firefox.

Download Firefox ESR 64-bit

Download Firefox ESR 32-bit

Firefox is no longer supported on macOS 10.14 and below.

Mozilla Foundation Security Advisory 2024-18

Security vulnerabilities fixed in firefox 125.

  • Firefox 125

# CVE-2024-3852: GetBoundName in the JIT returned the wrong object

Description.

GetBoundName could return the wrong version of an object when JIT optimizations were applied.

  • Bug 1883542

# CVE-2024-3853: Use-after-free if garbage collection runs during realm initialization

A use-after-free could result if a JavaScript realm was in the process of being initialized when a garbage collection started.

  • Bug 1884427

# CVE-2024-3854: Out-of-bounds-read after mis-optimized switch statement

In some code patterns the JIT incorrectly optimized switch statements and generated code with out-of-bounds-reads.

  • Bug 1884552

# CVE-2024-3855: Incorrect JIT optimization of MSubstr leads to out-of-bounds reads

In certain cases the JIT incorrectly optimized MSubstr operations, which led to out-of-bounds reads.

  • Bug 1885828

# CVE-2024-3856: Use-after-free in WASM garbage collection

A use-after-free could occur during WASM execution if garbage collection ran during the creation of an array.

  • Bug 1885829

# CVE-2024-3857: Incorrect JITting of arguments led to use-after-free during garbage collection

The JIT created incorrect code for arguments in certain cases. This led to potential use-after-free crashes during garbage collection.

  • Bug 1886683

# CVE-2024-3858: Corrupt pointer dereference in js::CheckTracedThing<js::Shape>

It was possible to mutate a JavaScript object so that the JIT could crash while tracing it.

  • Bug 1888892

# CVE-2024-3859: Integer-overflow led to out-of-bounds-read in the OpenType sanitizer

On 32-bit versions there were integer-overflows that led to an out-of-bounds-read that potentially could be triggered by a malformed OpenType font.

  • Bug 1874489

# CVE-2024-3860: Crash when tracing empty shape lists

An out-of-memory condition during object initialization could result in an empty shape list. If the JIT subsequently traced the object it would crash.

  • Bug 1881417

# CVE-2024-3861: Potential use-after-free due to AlignedBuffer self-move

If an AlignedBuffer were assigned to itself, the subsequent self-move could result in an incorrect reference count and later use-after-free.

  • Bug 1883158

# CVE-2024-3862: Potential use of uninitialized memory in MarkStack assignment operator on self-assignment

The MarkStack assignment operator, part of the JavaScript engine, could access uninitialized memory if it were used in a self-assignment.

  • Bug 1884457

# CVE-2024-3863: Download Protections were bypassed by .xrm-ms files on Windows

The executable file warning was not presented when downloading .xrm-ms files. Note: This issue only affected Windows operating systems. Other operating systems are unaffected.

  • Bug 1885855

# CVE-2024-3302: Denial of Service using HTTP/2 CONTINUATION frames

There was no limit to the number of HTTP/2 CONTINUATION frames that would be processed. A server could abuse this to create an Out of Memory condition in the browser.

  • Bug 1881183
  • VU#421644 - HTTP/2 CONTINUATION frames can be utilized for DoS attacks

# CVE-2024-3864: Memory safety bug fixed in Firefox 125, Firefox ESR 115.10, and Thunderbird 115.10

Memory safety bug present in Firefox 124, Firefox ESR 115.9, and Thunderbird 115.9. This bug showed evidence of memory corruption and we presume that with enough effort this could have been exploited to run arbitrary code.

  • Memory safety bug fixed in Firefox 125, Firefox ESR 115.10, and Thunderbird 115.10

# CVE-2024-3865: Memory safety bugs fixed in Firefox 125

Memory safety bugs present in Firefox 124. Some of these bugs showed evidence of memory corruption and we presume that with enough effort some of these could have been exploited to run arbitrary code.

  • Memory safety bugs fixed in Firefox 125

Red Sox roster: Lefty reliever DFA’d to make room for 31-year-old rookie

  • Updated: Apr. 19, 2024, 4:26 p.m. |
  • Published: Apr. 19, 2024, 4:10 p.m.

Joe Jacques

Joe Jacques was cut loose by the Red Sox one day after making his season debut. (AP Photo/Steven Senne) AP

PITTSBURGH — To make room for the addition of one left-handed reliever, the Red Sox are cutting another southpaw loose.

With 31-year-old rookie Cam Booser joining the Red Sox for their series against the Pirates beginning Friday, Boston designated lefty reliever Joe Jacques for assignment to clear a spot on the 40-man roster. Jacques, who has made 24 appearances over the last two seasons, was optioned to Triple-A following Thursday’s loss; he’s now in limbo and could find himself heading to another team in the coming days.

js mass assignment

If you purchase a product or register for an account through a link on our site, we may receive compensation. By using this site, you consent to our User Agreement and agree that your clicks, interactions, and personal information may be collected, recorded, and/or stored by us and social media and other third-party partners in accordance with our Privacy Policy.

IMAGES

  1. Laravel mass assignment and fillable vs guarded

    js mass assignment

  2. JavaScript Assignment Operators

    js mass assignment

  3. Broken user auth attack scenario

    js mass assignment

  4. What is Mass Assignment? Attacks and Security Tips

    js mass assignment

  5. How to Test Mass Assignment in APIs using Akto

    js mass assignment

  6. Mass assignment and learning new things

    js mass assignment

VIDEO

  1. Daily Mass

  2. March 18, 2024

  3. EASTER SUNDAY HOLY MASS IN TELUGU

  4. Process utilities and mechanical operations Assignment questions set 6

  5. Easter Vigil

  6. Law of conservation of Mass chemistry# #chemicalproperties#physics@gabaeducator&wellness

COMMENTS

  1. Mass Assignment

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

  2. Mass-assign to multiple Javascript objects

    Neither of these seems better than the three assignment statements. What you are trying to do is to destructure into an object (in this case, one that you can assign to this. Various syntaxes have been proposed for this, such as. Object.assign(this, { [name, age, is_male] = ['John Doe', 22, true] }); and

  3. What is mass assignment?

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

  4. Mass Assignment: How to Protect Your Application from Insecure Binder

    Mass Assignment: An Insecure Binder Configuration. In software development, mass assignment is the act of sending a large number of parameters to a function or method. This can be a useful technique for quickly creating new objects or updating existing ones. However, if not done correctly, mass assignment can also lead to security vulnerabilities.

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

  6. Avoiding mass assignment vulnerabilities in Node.js

    An attacker can use a mass assignment vulnerability to take complete control of a system or steal sensitive data, making it essential to defend against this kind of attack. This article will demonstrate a mass assignment vulnerability in a Node.js project, how an attacker can exploit it, and ways to protect a web application against it.

  7. Mass Assignment

    The exact implementation details depend on the framework or codebase you're using, but you have a few options: Turn off mass assignment completely; in Mongoose this is accomplished by using strict mode. Whitelist the fields that are safe to be mass assigned, iterate over your body params, and only save the whitelisted fields. Blacklist the ...

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

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

  9. OWASP API #6: Mass Assignment

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

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

  11. Hunting For Mass Assignment Vulnerabilities Using GitHub CodeSearch and

    Mass Assignment in Node.js. Mass assignment is well known in some webdev communities, particularly Ruby On Rails. Since Rails 4 query parameters must be explicitly allow-listed before they can be used in mass assignments. Additionally, the Brakeman static analysis scanner has rules to catch any potentially dangerous attributes that have been ...

  12. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...

  13. Mass Assignment

    Mass Assignment is the act of constructing an object with a parameters hash. such as assigning multiple values to attributes via a single assignment operator. What can happen ? An attacker exploiting mass assignment vulnerabilities can update object properties that they should not have access to allowing them to escalate privileges, tamper with ...

  14. What is a Mass Assignment Vulnerability?

    Mass Assignment What is a Mass Assignment Attack? In order to reduce the work for developers, many frameworks provide convenient mass-assignment functionality. This lets developers inject an entire set of user-entered data from a form directly into an object or database.

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

    Mass assignment vulnerabilities are often the result of an attacker adding unexpected fields to an object to manipulate the logic of a program. This was the cause of a famous GitHub authentication vulnerability , where mass assignment functionality in Ruby on Rails allowed an attacker to add their public key to the rails GitHub organization and ...

  16. Mass Assignment in NodeJS

    This Express.js route allows for an application to be signed up to. The logic checks whether a user already exists with the specified username; otherwise, it creates the new user by passing the whole User object passed from the request to the insert function: app.post('/signup', function (req, res) { const {username} = req.body; usersCollection ...

  17. JavaScript Assignment

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  18. Mass Assignment, Rails, and You

    Mass Assignment, Rails, and You. Early in 2012, a developer, named Egor Homakov, took advantage of a security hole at Github (a Rails app) to gain commit access to the Rails project. His intent was mostly to point out a common security issue with many Rails apps that results from a feature, known as mass assignment (and did so rather loudly).

  19. Node.js Vulnerability Cheatsheet

    Mass assignment; Open redirects; Cross-site request forgery (CSRF) Server-side request forgery (SSRF) Trust boundary violations; Prototype Pollution. JavaScript is a unique language with many idiosyncrasies. One of these characteristics that set it apart from other mainstream languages is how objects are created in Javascript.

  20. node.js

    3. A Mongoose model, Thing, has two fields, only one of which (safe) should be settable through mass assignment: safe: { type: String }, // settable through mass assignment. unsafe: { type: String } // not settable through mass assignment. A controller sets up Thing by passing parameters: var thing = new Thing(req.body);

  21. Security Vulnerabilities fixed in Firefox 125

    The MarkStack assignment operator, part of the JavaScript engine, could access uninitialized memory if it were used in a self-assignment. References. Bug 1884457 # CVE-2024-3863: Download Protections were bypassed by .xrm-ms files on Windows Reporter Eduardo Braun Prado working with Trend Micro Zero Day Initiative

  22. Red Sox roster: Lefty reliever DFA'd to make room for 31-year-old

    With 31-year-old rookie Cam Booser joining the Red Sox for their series against the Pirates beginning Friday, Boston designated lefty reliever Joe Jacques for assignment to clear a spot on the 40 ...

  23. Rails mass assignment and Backbone.js

    I want my controller clean, how to use mass assignment with Backbone.js? ruby-on-rails; backbone.js; Share. Improve this question. Follow asked Jan 23, 2011 at 12:12. Yury Kaspiarovich Yury Kaspiarovich. 2,036 2 2 gold badges 19 19 silver badges 26 26 bronze badges. 2.