- General Solutions
- Ruby On Rails
- Jackson (JSON Object Mapper)
- GSON (JSON Object Mapper)
- JSON-Lib (JSON Object Mapper)
- Flexjson (JSON Object Mapper)
- References and future reading
- Microservices Security
- Microservices based Security Arch Doc
- Mobile Application Security
- Multifactor Authentication
- NPM Security
- Network Segmentation
- NodeJS Docker
- Nodejs Security
- OS Command Injection Defense
- PHP Configuration
- Password Storage
- Prototype Pollution Prevention
- Query Parameterization
- REST Assessment
- REST Security
- Ruby on Rails
- SAML Security
- SQL Injection Prevention
- Secrets Management
- Secure Cloud Architecture
- Secure Product Design
- Securing Cascading Style Sheets
- Server Side Request Forgery Prevention
- Session Management
- Software Supply Chain Security.md
- TLS Cipher String
- Third Party Javascript Management
- Threat Modeling
- Transaction Authorization
- Transport Layer Protection
- Transport Layer Security
- Unvalidated Redirects and Forwards
- User Privacy Protection
- Virtual Patching
- Vulnerability Disclosure
- Vulnerable Dependency Management
- Web Service Security
- XML External Entity Prevention
- XML Security
- XSS Filter Evasion
Mass Assignment Cheat Sheet ¶
Introduction ¶, definition ¶.
Software frameworks sometime allow developers to automatically bind HTTP request parameters into program code variables or objects to make using that framework easier on developers. This can sometimes cause harm.
Attackers can sometimes use this methodology to create new parameters that the developer never intended which in turn creates or overwrites new variable or objects in program code that was not intended.
This is called a Mass Assignment vulnerability.
Alternative Names ¶
Depending on the language/framework in question, this vulnerability can have several alternative names :
- Mass Assignment: Ruby on Rails, NodeJS.
- Autobinding: Spring MVC, ASP NET MVC.
- Object injection: PHP.
Example ¶
Suppose there is a form for editing a user's account information:
Here is the object that the form is binding to:
Here is the controller handling the request:
Here is the typical request:
And here is the exploit in which we set the value of the attribute isAdmin of the instance of the class User :
Exploitability ¶
This functionality becomes exploitable when:
- Attacker can guess common sensitive fields.
- Attacker has access to source code and can review the models for sensitive fields.
- AND the object with sensitive fields has an empty constructor.
GitHub case study ¶
In 2012, GitHub was hacked using mass assignment. A user was able to upload his public key to any organization and thus make any subsequent changes in their repositories. GitHub's Blog Post .
Solutions ¶
- Allow-list the bindable, non-sensitive fields.
- Block-list the non-bindable, sensitive fields.
- Use Data Transfer Objects (DTOs).
General Solutions ¶
An architectural approach is to create Data Transfer Objects and avoid binding input directly to domain objects. Only the fields that are meant to be editable by the user are included in the DTO.
Language & Framework specific solutions ¶
Spring mvc ¶, allow-listing ¶.
Take a look here for the documentation.
Block-listing ¶
Nodejs + mongoose ¶, ruby on rails ¶, django ¶, asp net ¶, php laravel + eloquent ¶, grails ¶, play ¶, jackson (json object mapper) ¶.
Take a look here and here for the documentation.
GSON (JSON Object Mapper) ¶
Take a look here and here for the document.
JSON-Lib (JSON Object Mapper) ¶
Flexjson (json object mapper) ¶, references and future reading ¶.
- Mass Assignment, Rails and You
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 " ".
HatchJS.com
Cracking the Shell of Mystery
Mass Assignment: How to Protect Your Application from Insecure Binder Configuration
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
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
How to clone a salesforce flow | step-by-step guide.
Cloning a flow in Salesforce is a quick and easy way to create a copy of an existing flow. This can be useful for making changes to a flow without affecting the original, or for creating a new flow based on an existing one. In this article, we will show you how to clone a…
BigQuery: How to Get the Current Timestamp Minus 1 Hour
BigQuery Current Timestamp Minus 1 Hour: A Powerful Tool for Data Analysis The BigQuery current timestamp minus 1 hour function is a powerful tool for data analysis. It allows you to compare data from the current hour to data from the previous hour, which can help you identify trends and patterns. For example, you could…
How to Turn Off Drum Sounds in OSU!
Are you tired of the drum sounds in osu! cluttering up your gameplay? Do you want to be able to focus on the music and your own performance? If so, then you’ve come to the right place! In this article, I will show you how to turn off drum sounds in osu! in just a…
Do not use BuildContexts across async gaps: Why it’s a bad idea and how to avoid it
Do Not Use BuildContexts Across Async Gaps In Flutter, a BuildContext is a critical object that provides access to the widget tree and other information about the current state of the application. However, it’s important to be aware of the limitations of BuildContexts, and one of the most important is that you should never use…
How to Repair a Mr. Handy in Fallout Shelter
How to Repair a Mr. Handy in Fallout Shelter In Fallout Shelter, Mr. Handys are essential for keeping your vault running smoothly. They can perform a variety of tasks, from collecting resources to defending your vault from raiders. However, Mr. Handys can also break down, and when they do, it can be a major inconvenience….
How to Mark All Emails as Read in Yahoo Mail
How to Mark All Emails as Read in Yahoo Do you have a lot of unread emails in your Yahoo inbox? If so, you may be wondering how to mark all of them as read at once. This can be a helpful way to clear out your inbox and make it easier to find the…
- 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?
Insecure default variable initialization, uncaught exception, insufficient encapsulation.
What is Mass Assignment? Attacks and Security Tips
What is a mass assignment vulnerability.
To make things easier for developers, many frameworks include features that automatically associate the parameters of an HTTP request with variables linked to an object in the application code.
A Mass Assignment vulnerability occurs when the server does not correctly filter the data transmitted by the user and associates it directly with an object without verification.
In this way, an attacker can add new parameters to the HTTP request, which will create or replace variables in the application code although this was not initially intended.
Depending on the framework, these are also known as “autobinding” or “object injection” vulnerabilities.
Impact of a Mass Assignment vulnerability
The main impact of a Mass Assignment vulnerability is linked to modifying or creating variables. Depending on the variables or objects affected, the impact can be more or less significant, ranging from the simple modification of a value with no impact to a privilege escalation.
Indeed, when the vulnerability is present in a feature linked to the creation or modification of users, it is not uncommon to be able to escalate privileges.
This was the case, for example, on the Github platform in 2012, when a Mass Assignment vulnerability enabled users to upload their SSH public key to any organisation, potentially resulting in a massive data leak.
Such a vulnerability is not to be taken lightly, as it can have a severe impact.
How to identify this type of vulnerability?
As an attacker or pentester does not necessarily have a list of all the variables and values associated with the modified object on the server side, identifying a Mass Assignment vulnerability can be complex.
Depending on the technical conditions of the pentest, here are a few ways of identifying this type of security flaw:
- In white box, i.e. with access to the source code, it is possible to refer to the data models to identify sensitive fields that would not be transmitted by default in HTTP requests.
- Without access to the source code, this is more complex. One technique is to test known or probable parameters. This involves fuzzing the parameters. For example, adding a “role” field to the user creation request with standard values such as “admin” or “root” can lead to a privilege escalation in the event of Mass Assignment.
- In some cases, using the API documentation, it is possible to identify parameters that are not used by default. For example, with access to the introspection of a GraphQL API, i.e. to the list of fields associated with an entity, it is possible to try to add a variable in certain queries or mutations in the hope that this will be taken into account.
- Another technique is to observe the server responses. If additional fields are returned, it may be useful to reuse them in requests to detect Mass Assignment. Let’s imagine, for example, that we have access to the list of users. If you access the API route used to list users, you can see a “role” field associated with each user in the server response. It may therefore be useful to add this role parameter with a valid value in the request used to modify the profile information or the request used to create a user.
What are the common exploits of Mass Assignment vulnerabilities?
Mass assignment and privilege escalation.
During a grey box pentest , we had access to an application with several levels of user privileges. We had a user access (not admin), but which nevertheless allowed us to create other users with the same level of privileges.
Using the graphic interface, the request to add a user looked like this:
The content of the server response in JSON was as follows:
As we can see, a “Profiles” field is returned in the JSON object corresponding to the new user we have just created. It seems to correspond to the user’s rights. This field has been added automatically. In particular, we can see that the newly created user has a profile of type “customer” associated with ID 5. This profile has certain roles.
The fact that this “Profiles” field is present in the response even though it was not initially filled in should immediately alert us. We can now try to replay the creation of a user by adding a “Profiles” field.
Here, we know that profile ID 5 corresponds to a “customer” type user. Let’s try this with ID 1. We’ve left the other fields empty because we didn’t know the existing values:
Server response:
The Mass Assignment attack has been taken into account. The profile ID “1” has been associated with the user we have just created. The response tells us that we have successfully created an administrator type user.
This means that on the server side, the entire JSON object sent by the attacker is used to link the transmitted fields to the user object created. This is done without checking what data is being transmitted and by accepting an unexpected field.
We can now connect with the new user. Our privileges have been escalated and we can perform all the actions restricted to administrators.
Mass Assignment on a GraphQL API and privilege escalation
During a pentest on an application running with a GraphQL API, a mutation was used to update the user’s profile. By default and using the graphical interface, the mutation transmitted was as follows:
At first glance, there’s nothing particularly interesting about this mutation. It allows a user to change his/her surname, first name and telephone number.
However, we had access to GraphQL introspection (the equivalent of the documentation for a classic API) and we were able to see that the GraphQL “User” object also had a “role” field.
By modifying the previous mutation, we were able to change the role of our user due to a Mass Assignment. This enabled us to escalate our privileges:
Full request:
Following this request, our user became an administrator because the mutation took into account the role field even though it was not sent by default.
How to prevent Mass Assignment vulnerabilities?
Fortunately, preventing or correcting this type of vulnerability is fairly straightforward.
It involves setting up a white list of fields that are authorised to be used on the server side to create or modify an object. In addition, only non-sensitive fields should be authorised. And if other fields are present in the request received, they must not be taken into account by the server.
Frameworks often allow this type of whitelist to be configured simply. A list of potential existing solutions by framework can be found on the OWASP website.
If we go back to the previous examples, in the first case, the white list must not include the “profiles” field. If a user tries to send a value for this field, the value transmitted should not be taken into account when creating the user.
In the second case, the mutation used to modify the profile must not accept the “role” value. It must be limited to the “first_name”, “last_name” and “language” parameters only.
Author : Yoan MONTOYA – Pentester @Vaadata
Related Posts
Introduction to nuclei, an open source vulnerability scanner, what is prototype pollution exploitations and security tips, account takeover techniques and security best practices.
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
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)
Injection - XSS
Injection - Path Traversal
Using Components with Known Vulnerabilities
Insufficient Logging and Monitoring
Security misconfiguration - XXE detailed
Security Misconfiguration
Server-Side Request Forgery
Password Storage
Authentication and Authorization
File Upload
Injection 101, sql injection.
Command Injection
Discover the Secure Code Warrior Learning Platform
We secure software through developer-driven security at the start of the software development lifecycle.
DEV Community
Posted on Apr 19, 2020
How to avoid Insecure Binder Configuration in JAVA
What is api abuse 😥.
An API is a contract between a caller and a callee. The most common forms of API abuse are caused by the caller failing to honor its end of this contract. For example, if a program fails to call chdir() after calling chroot(), it violates the contract that specifies how to change the active root directory in a secure fashion. Another good example of library abuse is expecting the callee to return trustworthy DNS information to the caller. In this case, the caller abuses the callee API by making certain assumptions about its behavior (that the return value can be used for authentication purposes). One can also violate the caller-callee contract from the other side. For example, if a coder subclasses SecureRandom and returns a non-random value, the contract is violated.
The framework binder used for binding the HTTP request parameters to the model class has not been explicitly configured to allow, or disallow certain attributes
Explanation 🤓
To ease development and increase productivity, most modern frameworks allow an object to be automatically instantiated and populated with the HTTP request parameters whose names match an attribute of the class to be bound. Automatic instantiation and population of objects speeds up development, but can lead to serious problems if implemented without caution.
Any attribute in the bound classes, or nested classes, will be automatically bound to the HTTP request parameters. Therefore, malicious users will be able to assign a value to any attribute in bound or nested classes, even if they are not exposed to the client through web forms or API contracts.
The vulnerability 😩
The solution 😊.
Jackson provides an annotation that can be used on class level (JsonIgnoreProperties).
So simple, just add @JsonIgnoreProperties(ignoreUnknown = true) before the class.
Add the following to the top of your class (not to individual methods):
Top comments (1)
Templates let you quickly answer FAQs or store snippets for re-use.
- Joined Jan 28, 2022
Hi Marcos, if the model class is used in both POST and PUT calls, how can I avoid certain fields from SET only in case of PUT operation. Thanks,Vinay
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .
Hide child comments as well
For further actions, you may consider blocking this person and/or reporting abuse
Building a Secure PDF Chat AI Application with Langchain, Next.js, arcjet, and Pinecone DB
Nikos Benakis - Jul 15
Efficient Algorithms for Finding Prime Numbers
Paul Ngugi - Jul 15
Finding the Closest Pair of Points Using Divide-and-Conquer
Top 10 Application Security Vulnerabilities in 2024
ByteHide - Jul 15
We're a place where coders share, stay up-to-date and grow their careers.
Mass Assignment
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 the client request including fields that are not intended to be freely altered.
Active record and object-relational mapping are common features in many web application frameworks as they allow for serialized external data to be automatically converted upon input into internal objects and, subsequently, into the database records field. Depending on the framework, developers are sometimes allowed to automatically bind HTTP request parameters into program code variables or objects for ease of use. However, if the conversion interface for the framework is overly permissive and developers haven’t marked specific fields as immutable, the potential for exploitation is open.
Malicious attackers can leverage Mass Assignment vulnerabilities to manipulate the internal state of the application and potentially compromise its confidentiality, integrity, and availability. By overwriting the value of certain fields, an attacker may be able to modify an admin permission flag, thus effecting an authorization bypass which, depending on the level of authorization, could lead to full server access.
In 2012, none other than Github, the world’s code repository, was shown to be harbouring a potentially catastrophic Mass Assignment vulnerability that ended up being exposed by a security researcher in a fairly public stoush. The issue was fortunately resolved with no loss of data; but the security researcher in question was able to upload his public key to any organisation and thus potentially make malicious changes in their repositories.
The following exemplifies a Mass Assignment attack within a web application that stores users in a NoSQL database and implements access control by simply keeping one boolean flag is_admin for each user.
Upon sign up, some fields need to be used to create the new user. If the web application uses the whole POST data to build a new User object, a malicious actor could add the is_admin=1 field to the post data to overwrite the default value and gain administrative privileges on the application.
Developers must avoid using functions that bind client input into variables or internal objects automatically. Additionally, developers must explicitly define all payloads and parameters that the server is expecting.
Depending on the application framework, it may be possible to only allow fields that are determined safe to be fetched from the client request. If the application does not allow for this process, developers must ensure they manually determine which fields are allowed to be extracted from the request and used in downstream contexts.
Verify that frameworks protect against mass parameter assignment attacks, or that the application has countermeasures to protect against unsafe parameter assignment, such as marking fields private or similar.
- OWASP ASVS : 5.1.2
- OWASP Testing Guide : Test Business Logic Data Validation , Test Ability to Forge Requests , Test Integrity Checks
Table of contents
- Mass Assignment in .NET
- Mass Assignment in Java
- Mass Assignment in NodeJS
- Mass Assignment in PHP
- Mass Assignment in Python
- Mass Assignment in Ruby
- 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]
Common Weakness Enumeration
A community-developed list of SW & HW weaknesses that can become vulnerabilities
> > CWE- Individual Dictionary Definition (4.15) |
- About ▼ About New to CWE User Stories History Documents FAQs Glossary Compatibility
- CWE List ▼ Latest Version Downloads Reports Visualizations Archive
- Mapping ▼ Root Cause Mapping Guidance Root Cause Mapping Quick Tips Root Cause Mapping Examples
- Top-N Lists ▼ Top 25 Software Top Hardware Top 10 KEV Weaknesses
- Community ▼ Community Working Groups & Special Interest Groups Board Board Meeting Minutes CWE Discussion List CWE Discussion Archives Contribute Weakness Content to CWE
CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes
: ALLOWEDThis CWE ID may be used to map to real-world vulnerabilities Abstraction: BaseBase - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource. |
Edit Custom Filter
If the object contains attributes that were only intended for internal use, then their unexpected modification could lead to a vulnerability.
This weakness is sometimes known by the language-specific mechanisms that make it possible, such as mass assignment, autobinding, or object injection.
Mass Assignment: | |
---|---|
AutoBinding: | |
PHP Object Injection: | . |
Scope | Impact | Likelihood |
---|---|---|
Integrity | ||
Integrity | ||
Other Integrity |
Phase: Implementation
|
Phases: Architecture and Design; Implementation |
Phase: Implementation |
Phases: Implementation; Architecture and Design |
Nature | Type | ID | Name |
---|---|---|---|
ChildOf | 913 | ||
ParentOf | 1321 | ||
PeerOf | 502 |
Nature | Type | ID | Name |
---|---|---|---|
MemberOf | 399 |
Phase | Note |
---|---|
Architecture and Design | |
Implementation |
Ruby (Undetermined Prevalence)
ASP.NET (Undetermined Prevalence)
PHP (Undetermined Prevalence)
Python (Undetermined Prevalence)
Class: Not Language-Specific (Undetermined Prevalence)
This function sets object attributes based on a dot-separated path.
This function does not check if the attribute resolves to the object prototype. These codes can be used to add "isAdmin: true" to the object prototype.
By using a denylist of dangerous attributes, this weakness can be eliminated.
Reference | Description |
---|---|
Ordinality | Description |
---|---|
Automated Static Analysis |
Nature | Type | ID | Name |
---|---|---|---|
MemberOf | 1340 | ||
MemberOf | 1354 | ||
MemberOf | 1415 |
Usage: ALLOWED |
Reason: Acceptable-Use |
Rationale: This CWE entry is at the Base level of abstraction, which is a preferred level of abstraction for mapping to the root causes of vulnerabilities. |
Comments: Carefully read both the name and description to ensure that this mapping is an appropriate fit. Do not try to 'force' a mapping to a lower-level Base/Variant simply to comply with this preferred level of abstraction. |
Maintenance
>. . |
>. . |
>. . |
>. . |
>. . |
>. . |
>. . |
>. . |
>. . |
>. . |
>. . |
>. . |
Submissions | ||
---|---|---|
Submission Date | Submitter | Organization |
2013-01-26 (CWE 2.4, 2013-02-21) | CWE Content Team | MITRE |
Contributions | ||
Contribution Date | Contributor | Organization |
2013-01-26 | Dan Amodio, Dave Wichers | Aspect Security |
Suggested adding mass assignment, provided references, and clarified relationship with AutoBinding. | ||
Modifications | ||
Modification Date | Modifier | Organization |
2013-07-17 | CWE Content Team | MITRE |
updated References | ||
2017-05-03 | CWE Content Team | MITRE |
updated Potential_Mitigations | ||
2017-11-08 | CWE Content Team | MITRE |
updated References | ||
2019-06-20 | CWE Content Team | MITRE |
updated Relationships | ||
2020-02-24 | CWE Content Team | MITRE |
updated Relationships | ||
2020-06-25 | CWE Content Team | MITRE |
updated Alternate_Terms, Potential_Mitigations | ||
2020-12-10 | CWE Content Team | MITRE |
updated Relationships | ||
2021-10-28 | CWE Content Team | MITRE |
updated Relationships | ||
2023-01-31 | CWE Content Team | MITRE |
updated Description, Observed_Examples | ||
2023-04-27 | CWE Content Team | MITRE |
updated Detection_Factors, References, Relationships | ||
2023-06-29 | CWE Content Team | MITRE |
updated Mapping_Notes | ||
2024-02-29 (CWE 4.14, 2024-02-29) | CWE Content Team | MITRE |
updated Demonstrative_Examples | ||
2024-07-16 (CWE 4.15, 2024-07-16) | CWE Content Team | MITRE |
updated Observed_Examples |
| | | | | | Use of the Common Weakness Enumeration (CWE™) and the associated references from this website are subject to the . CWE is sponsored by the (DHS) (CISA) and managed by the (HSSEDI) which is operated by (MITRE). Copyright © 2006–2024, The MITRE Corporation. CWE, CWSS, CWRAF, and the CWE logo are trademarks of The MITRE Corporation. |
- Java Course
- Java Arrays
- Java Strings
- Java Collection
- Java 8 Tutorial
- Java Multithreading
- Java Exception Handling
- Java Programs
- Java Project
- Java Collections Interview
- Java Interview Questions
- Spring Boot
Java Assignment Operators with Examples
Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide.
Types of Operators:
- Arithmetic Operators
- Unary Operators
- Assignment Operator
- Relational Operators
- Logical Operators
- Ternary Operator
- Bitwise Operators
- Shift Operators
This article explains all that one needs to know regarding Assignment Operators.
Assignment Operators
These operators are used to assign values to a variable. The left side operand of the assignment operator is a variable, and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. This means that the assignment operators have right to left associativity, i.e., the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side value must be declared before using it or should be a constant. The general format of the assignment operator is,
Types of Assignment Operators in Java
The Assignment Operator is generally of two types. They are:
1. Simple Assignment Operator: The Simple Assignment Operator is used with the “=” sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.
2. Compound Assignment Operator: The Compound Operator is used where +,-,*, and / is used along with the = operator.
Let’s look at each of the assignment operators and how they operate:
1. (=) operator:
This is the most straightforward assignment operator, which is used to assign the value on the right to the variable on the left. This is the basic definition of an assignment operator and how it functions.
Syntax:
Example:
2. (+=) operator:
This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left.
Note: The compound assignment operator in Java performs implicit type casting. Let’s consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5 Method 2: x += 4.5 As per the previous example, you might think both of them are equal. But in reality, Method 1 will throw a runtime error stating the “i ncompatible types: possible lossy conversion from double to int “, Method 2 will run without any error and prints 9 as output.
Reason for the Above Calculation
Method 1 will result in a runtime error stating “incompatible types: possible lossy conversion from double to int.” The reason is that the addition of an int and a double results in a double value. Assigning this double value back to the int variable x requires an explicit type casting because it may result in a loss of precision. Without the explicit cast, the compiler throws an error. Method 2 will run without any error and print the value 9 as output. The compound assignment operator += performs an implicit type conversion, also known as an automatic narrowing primitive conversion from double to int . It is equivalent to x = (int) (x + 4.5) , where the result of the addition is explicitly cast to an int . The fractional part of the double value is truncated, and the resulting int value is assigned back to x . It is advisable to use Method 2 ( x += 4.5 ) to avoid runtime errors and to obtain the desired output.
Same automatic narrowing primitive conversion is applicable for other compound assignment operators as well, including -= , *= , /= , and %= .
3. (-=) operator:
This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting the variable’s value on the right from the current value of the variable on the left and then assigning the result to the operand on the left.
4. (*=) operator:
This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left.
5. (/=) operator:
This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the quotient to the operand on the left.
6. (%=) operator:
This operator is a compound of ‘%’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the remainder to the operand on the left.
Please Login to comment...
Similar reads.
- Java-Operators
- How to Get a Free SSL Certificate
- Best SSL Certificates Provider in India
- Elon Musk's xAI releases Grok-2 AI assistant
- What is OpenAI SearchGPT? How it works and How to Get it?
- Full Stack Developer Roadmap [2024 Updated]
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
is this example of mass assignment and should we throws exception for this?
I have read the following article on Mass assignment https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html
but still have some unknown, e.g.
Here is the controller handling the request:
here is the request with more parameter than class User has (isAdmin=true)
As the class User has NO isAdmin property,
- is the class User still has Mass Assignment security problem for this request?
- should we throws exception if request parameter is more than the expected binding input parameter class?
- related to question 2, if we ignore the extra parameter and returns response 200 (ok), is this right? As in a security check, our program is complained by return 200 for similar case.
As I see the article, the solution has NOT said to throws error or exception for this case.
- mass-assignment
- Please summarize the relevant part of what you linked to, point out how it relates to your question. – Yunnosch Commented Jun 15, 2023 at 5:06
- the linked article talk about Mass Assignment and give an example, in the example the User class has property isAdmin, but it has not mentioned the case that if the Class User has no this property but the request still has isAdmin property. – user1169587 Commented Jun 15, 2023 at 6:22
- Please edit to add information to the question, instead of providing them in comments. – Yunnosch Commented Jun 15, 2023 at 6:27
Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .
Your answer.
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Sign up or log in
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
Browse other questions tagged java mass-assignment or ask your own question .
- The Overflow Blog
- From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
- Featured on Meta
- We've made changes to our Terms of Service & Privacy Policy - July 2024
- Bringing clarity to status tag usage on meta sites
- Feedback requested: How do you use tag hover descriptions for curating and do...
- What does a new user need in a homepage experience on Stack Overflow?
Hot Network Questions
- Why if gravity were higher, designing a fully reusable rocket would be impossible?
- Hotspot vs home internet
- "Authorized ESTA After Incorrectly Answering Criminal Offense Question: What Should I Do?"
- Will fire still burn well in my atmosphere?: concentration vs partial pressure
- How to make a ParametricPlot3D into solid shape
- There are at least 3 versions of a quote, with 2 having different attributions. What is the original, who said it, and what does the quote mean?
- Why do we reduce a body to its center of mass when calculating gain/loss of gravitational potential energy?
- Curry a C function pointer
- Help Identify SMD Part Marking ATPJ
- Should I GFCI-protect a bathroom light and fan?
- Movie or series involving a red-headed female scientist who invented a device that permits travel to other time periods or parts of the world
- Immutability across programming languages
- Distribute realized geometry based on field values
- Did US troops insist on segregation in British pubs?
- Why is not it generally accepted that tyranids are the strongest most adaptable race in w40k?
- Using ExplSyntax with tasks to create a custom \item command - Making \item backwards compatible
- Do we need to be translating the Hebrew form and meaning of the word hate in Romans 9:13?
- Meaning of “ ’thwart” in a 19th century poem
- When was this photo taken?
- Cannot remove old solder
- What does "close" mean in the phrase: "close a tooth pick between the jamb and the door"?
- Rashi's opinion on the child of a gentile father
- Perpendicularity problem about squares drawn externally on a triangle
- Which game is "that 651"?
IMAGES
COMMENTS
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:
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. ...
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:
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.
API #6: Mass Assignment. This week, we are going to talk about 'Mass Assignment', which if not working with incoming data transfer objects or models, is often left unattended. This can cause ...
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 ...
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.
What is a Mass Assignment vulnerability? To make things easier for developers, many frameworks include features that automatically associate the parameters of an HTTP request with variables linked to an object in the application code. A Mass Assignment vulnerability occurs when the server does not correctly filter the data transmitted by the ...
The impact of a mass assignment can vary depending on the context therefore, for each test input attempted in the previous phase, analyze the result and determine if it represents a vulnerability that has a realistic impact on the web application's security. ... Java. Spring MVC allows to automatically bind user input into object. Identify ...
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 ...
Mass assignment is a computer vulnerability where an active record pattern in a web application is abused to modify data items that the user should not normally be allowed to access such as password, granted permissions, or administrator status.. Many web application frameworks offer an active record and object-relational mapping features, where external data in serialization formats is ...
The solution 😊. Jackson provides an annotation that can be used on class level (JsonIgnoreProperties). So simple, just add @JsonIgnoreProperties(ignoreUnknown = true) before the class. Add the following to the top of your class (not to individual methods): @JsonIgnoreProperties(ignoreUnknown = true) public class MyClasss implements ...
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 ...
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 the client ...
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 ...
This weakness is sometimes known by the language-specific mechanisms that make it possible, such as mass assignment, autobinding, or object injection. Alternate Terms. ... Media library allows deserialization of objects by untrusted Java applets, leading to arbitrary code execution. Weakness Ordinalities. Ordinality Description; Primary
Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.
InspSecretEntity.java:23(Mass Assignment: Request Parameters Bound into Persisted Objects) ...
the linked article talk about Mass Assignment and give an example, in the example the User class has property isAdmin, but it has not mentioned the case that if the Class User has no this property but the request still has isAdmin property.