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

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

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.

What is the solution for Mass Assignment: Insecure Binder Configuration Vulnerability?

I have this Controller in Java:

When I scan my code in Fortify, the object comunicationWithAspRequest causes the Mass Assignment: Insecure Binder Configuration Vulnerability. Is possible to control which HTTP request parameters will be used in the binding process and which ones will be ignored?

Brayan Reyes's user avatar

2 Answers 2

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.

SimpleController.java

Ben Cheng's user avatar

  • I was searching solution for same fortify mass assignment issue, whitelisting and black listing is a tedious task for my application.Is there any other way to fix this other than spring @InitBinder ? –  Shibina EC Jun 14, 2018 at 10:17
  • In my project, i just use a dirty way to solve this issue. ie. @JsonIgnore –  Ben Cheng Jun 15, 2018 at 2:22
  • I tried JsonView which works for my project more than JsonIgnore since the objects are used for more than 1 endpoint. Yet Fortify doesn't seem to recognize it –  bourne2program Jan 18, 2019 at 16:32
  • 1 One more finding is that, Fortify is actually just to do scan to pop you warning. Some issue may not is solved, you just need to accept it with reason. –  Ben Cheng Jan 19, 2019 at 7:25
  • In my project, I have used something like @JsonIgnoreProperties(ignoreUnknown=true) –  viveknaskar Jul 10, 2019 at 9:08

By adding @JsonIgnoreProperties(ignoreUnknown = true) annotation on the class level the issue can be resolve in case we don't know what to ignore.

lbndvs's user avatar

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 .

Not the answer you're looking for? Browse other questions tagged java fortify or ask your own question .

  • The Overflow Blog
  • Introducing Staging Ground: The private space to get feedback on questions...
  • How to prevent your new chatbot from giving away company secrets
  • Featured on Meta
  • The [tax] tag is being burninated
  • The return of Staging Ground to Stack Overflow
  • The 2024 Developer Survey Is Live
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • G string becomes out of tune in F shape barre chords
  • What's the maximum amount of material that a puzzle with unique solution can have?
  • How often does systemd journal collect/read logs from sources
  • Is obeying the parallelogram law of vector addition sufficient to make a physical quantity qualify as a vector?
  • When was the ‘mathematics department’ first established in universities?
  • Why do airplanes sometimes turn more than 180 degrees after takeoff?
  • What’s the history behind Rogue’s ability to touch others directly without harmful effects in the comics?
  • Moving after copying in assignment of conditional operator result
  • How to remind myself of important matters in the heat of running the game?
  • is it correct to say "push the table by its far edge"?
  • My vehicle shut off in traffic and will not turn on
  • Has ever a country by its own volition refused to join United Nations, or those which havent joined it's because they aren't recognized as such by UN?
  • An application of the (100/e)% rule applied to postdocs: moving on from an academic career, perhaps
  • Effects if a human was shot by a femtosecond laser
  • Could a 200m diameter asteroid be put into a graveyard orbit and not be noticed by people on the ground?
  • Matter currents
  • How to create an enumerate environment with Case 1, Case 2,
  • Handling cases of "potential" ChatGPT-generated reviews in non-anonymous program committees (as a PC member)
  • How do I get rid of the artifacts on this sphere?
  • Book recommendation introduction to model theory
  • In Catholicism, is it OK to join a church in a different neighborhood if I don't like the local one?
  • StreamPlot does not give me the streamlines I ask for
  • How to lock the view to stay in camera view?
  • Understanding the Amanda Knox, Guilty Verdict for Slander

java mass assignment example

Navigation Menu

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

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

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

java mass assignment example

What is and how to prevent Mass Assignment Vulnerabilities

  • luisfontes19
  • Jun 13, 2021

First time I heard about mass assignment vulnerabilities was a long time ago, when I started learning Ruby & Rails. In fact I learnt a lot, security related back then, as Rails is a quite complex and secure framework, and to properly work with it you should understand the underlying mechanisms.

At that time Rails had just introduced a security feature called “Strong Parameters” to help protect against mass assignment attacks and I was curious about what it was for so I spent some time going through the docs.

Mass Assignment Vulnerabilities Explained

The concept referes to when you inject a set of values directly into an object, thus the name mass assignment, which without proper validation can cause serious problems to the application logic.

Lets see a Java example with Spring:

(value = "/users", method = RequestMethod.POST) public void create(User user) { userService.add(user); }

What can go wrong with the snippet above? If the User object has fields like “isAdmin” an attacker can easily create an admin user because the endpoint blindly accepts all fields from the User class.

A more complex example

Mass assignment is basically this, but you can have some complex and interesting attack vectors, so lets see another case, this time in Node:

app.post("/posts", async (req: Request, res: Response) => { const p: Post = req.body; const post = await Post.create(p).save(); res.send(post); }); ... @Entity("posts") export class Post extends BaseEntity { ... @ManyToOne(type => Author, author => author.posts, { cascade: true }) @JoinColumn({ name: "author_id" }) author?: Author; } @Entity("authors") export class Author extends BaseEntity { ... @Column({ name: "is_admin" }) isAdmin?: number; @OneToMany(type => Post, post => post.author) posts?: Post[]; }

This example uses Express and TypeORM with the ActiveRecord pattern.

The endpoint receives a “Post” object in the request’s body and blindly creates a post in the database with the data received.

In this case, an attacker can send in the payload a user object, as its part of the Post structure, and this user will get created at the same time than the post. Again, you have the isAdmin field that can be used to create a privileged account, but this time from a Post. Neat.

This is the request content that can trigger this flow:

"title": "Some Post", "author": {"name": "Me", "isAdmin": true, ...}, ...}

Careful with NoSQL Databases

You can also have Mass Assignment vulnerabilities with NoSQL databases that can cause NoSQL Injection Let’s take into consideration MongoDB. MongoDB works with unstructured documents, so 10 user objects can have completely different fields in the database and an attacker can take advantage of this

But most important: NoSQL Injection attacks. Mongo query language (MQL) resembles javascript objects so if you use user input to do a query a lot of things can go wrong.

Imagine you have a line like:

.post("/search", async (req: Request, res: Response) => { const users = await User.find(req.body.name) res.send(users); });

And this is how an attacker could exploit this:

"name": {"$ne": "-"}}

Notice that instead of a string, an object was sent, that will be injected in the find query, searching for all users where name is not equal to “-”.

Now that we have a fair understanding of what’s Mass Assignment lets move to how to prevent/fix it.

The first tip for that, and should be a rule of thumb for every project is: Know the technologies you’re using. This is actually really important, not only for Mass Assignment but for everything… In the second example above, the attack to create a new user was only possible because the cascade property (in the many to one reference) was set to true, otherwise TypeORM wouldn’t do it by default. Mass Assignment would still be possible for the Post object.

Another example: Rails implements “Strong Parameters” so if you want to mass assign something you need to explicitly whitelist the parameters that you want to allow for Mass Assignment, but thats for models that inherit from ActiveRecord, so this isn’t a “global” protection although it should work for most of cases.

Knowing the frameworks/libs you’re working with can help a lot. I usually start by spending some good time reading security and/or best practices from the official docs of the technologies I’m using.

Data Transfer Objects

Also known as DTOs, the idea behind this approach is that you create objects specifically to be in transit, and most important, with user supplied data. So you only have the fields needed for the required operations.

To fix the first snippet you could create a CreateUserDTO class that didn’t have the isAdmin field. Then there’s a routine that converts that into a User object (being the default isAdmin option false). You can create other DTOs for sending users that have the isAdmin field if needed.

This is a common practice, but personally I don’t like it as adds a lot of overhead, multiple DTOs, the conversions, etc. Personally I like to have simple code so this is not a best fit for me.

Filter Fields

This is usually my go to. Specify which fields can be sent (whitelisting, never blacklisting), and change them for specific operations if needed. Again, this is the logic of Rails' strong parameters. If you’re using an ORM also remember to check the type of a field, because if you get an object where you were expecting a string, the ORM may resolve that and save the foreign object as well. I’ve seen a lot of “fixes” online to use for example underscore ’s pick method, but if you allow a user field, and the user field is an object, you still have a problem there. So be careful on how you implement this.

You can easily create a method to filter the fields that you want to accept, like this:

const filter = (object: any, fields: any) => { const cleanObject: any = {} Object.keys(fields).forEach(k => { const fieldType = fields[k] if (typeof fieldType === "object") cleanObject[k] = filter(object[k], fieldType) else if (typeof object[k] === fieldType) cleanObject[k] = object[k] }) return cleanObject } const userSuppliedObject = { group: { name: "My Group", public: true, owner: { username: "NEW USER", isAdmin: true } } } const allowedFields = { group: { name: "string", owner: { username: "string" } } }; const cleanObject = filter(userSuppliedObject, allowedFields)
  • 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 output handling in llms, overreliance on llms, insecure plugins for llms.

LRQA Nettitude Labs Logo

LRQA Nettitude Command & Control Framework - Free and Open Source

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

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

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

Implementing mass assignment

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

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

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

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

The mass assignment vulnerability

So, how might an attacker exploit this?

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

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

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

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

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

Countermeasures

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

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

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

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

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

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

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

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

Share This Story, Choose Your Platform!

Related posts.

Emulation with Qiling

Discord logo.

Join Our Community on Discord

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

java mass assignment example

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)

java mass assignment example

Injection - XSS

java mass assignment example

Injection - Path Traversal

java mass assignment example

Using Components with Known Vulnerabilities

java mass assignment example

Insufficient Logging and Monitoring

java mass assignment example

Security misconfiguration - XXE detailed

java mass assignment example

Security Misconfiguration

java mass assignment example

Server-Side Request Forgery

java mass assignment example

Password Storage

java mass assignment example

Authentication and Authorization

java mass assignment example

File Upload

Injection 101, sql injection.

java mass assignment example

Command Injection

Secure Code Warrior Learning Platform

Discover the Secure Code Warrior Learning Platform

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

websights

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

java mass assignment example

Mass Assignment 101

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

What is a Mass Assignment attack?

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

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

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

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

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

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

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

Why you need to know about Mass Assignment

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

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

How to prevent mass assignment attacks

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

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

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

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

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

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

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

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

See why security teams love us

  • 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
  • Solve Coding Problems
  • Share Your Experience
  • Java Tutorial

Overview of Java

  • Introduction to Java
  • The Complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works - JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted Output in Java using printf()
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples

Java Assignment Operators with Examples

  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • 'this' reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Singleton Method Design Pattern in Java
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Java Try Catch Block
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • Regex Tutorial - How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

JDBC - Java Database Connectivity

  • Introduction to JDBC (Java Database Connectivity)
  • JDBC Drivers
  • Establishing JDBC Connection in Java
  • Types of Statements in JDBC
  • JDBC Tutorial
  • Java 8 Features - Complete Tutorial
  • Java Backend Development Course

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
  • OpenAI launches ChatGPT Edu for universities: Here is what it is and how it works
  • NVIDIA Launches AI Assistants With GeForce RTX AI PCs
  • How to Download WhatsApp Status in iPhone
  • 10 Best ChatGPT Prompts for Increasing Productivity in 2024
  • 10 Best Free Reverse Phone Number Lookup

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Knowledge Base
  • Pentest services

Application Penetration Testing

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

API Mass Assignment Vulnerability

  • Web Server TRACE Enabled

AWS Pentesting

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

DevOps Security

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

Network Penetration Testing

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

Pentesting Fundamentals

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

Windows Hardening

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

Home » API Mass Assignment Vulnerability

Table of Contents

  • 1. API Mass Assignment

API Mass Assignment

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • Application

CWE

Common Weakness Enumeration

A community-developed list of SW & HW weaknesses that can become vulnerabilities

New to CWE? click here!

> > CWE- Individual Dictionary Definition (4.14)  
  • 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

java mass assignment example

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: .
NatureTypeIDName
ChildOf 913
ParentOf 1321
PeerOf 502
NatureTypeIDName
MemberOf 399
PhaseNote
Architecture and Design
Implementation

Ruby (Undetermined Prevalence)

ASP.NET (Undetermined Prevalence)

PHP (Undetermined Prevalence)

Python (Undetermined Prevalence)

Class: Not Language-Specific (Undetermined Prevalence)

ScopeImpactLikelihood
Integrity

Integrity

Other
Integrity

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.

ReferenceDescription

Phase: Implementation

Phases: Architecture and Design; Implementation

Phase: Implementation

Phases: Implementation; Architecture and Design

OrdinalityDescription

Automated Static Analysis

NatureTypeIDName
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 DateSubmitterOrganization
2013-01-26
(CWE 2.4, 2013-02-21)
CWE Content TeamMITRE
Contributions
Contribution DateContributorOrganization
2013-01-26Dan Amodio, Dave WichersAspect Security
Suggested adding mass assignment, provided references, and clarified relationship with AutoBinding.
Modifications
Modification DateModifierOrganization
2013-07-17CWE Content TeamMITRE
updated References
2017-05-03CWE Content TeamMITRE
updated Potential_Mitigations
2017-11-08CWE Content TeamMITRE
updated References
2019-06-20CWE Content TeamMITRE
updated Relationships
2020-02-24CWE Content TeamMITRE
updated Relationships
2020-06-25CWE Content TeamMITRE
updated Alternate_Terms, Potential_Mitigations
2020-12-10CWE Content TeamMITRE
updated Relationships
2021-10-28CWE Content TeamMITRE
updated Relationships
2023-01-31CWE Content TeamMITRE
updated Description, Observed_Examples
2023-04-27CWE Content TeamMITRE
updated Detection_Factors, References, Relationships
2023-06-29CWE Content TeamMITRE
updated Mapping_Notes
2024-02-29
(CWE 4.14, 2024-02-29)
CWE Content TeamMITRE
updated Demonstrative_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.

IMAGES

  1. Broken user auth attack scenario

    java mass assignment example

  2. Java Programming

    java mass assignment example

  3. Laravel mass assignment and fillable vs guarded

    java mass assignment example

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

    java mass assignment example

  5. Java GUI Body Mass Index

    java mass assignment example

  6. Java Assignment Operators with Examples

    java mass assignment example

VIDEO

  1. Portswigger: Exploiting a mass assignment vulnerability

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

  3. [API-08] Mass Assignment Attacks

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

  5. API PENETRATION TESTING: THE MASS ASSIGNMENT VULNERABILITY

  6. Массивы в Java

COMMENTS

  1. Mass Assignment

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

  2. Mass Assignment · OWASP Cheat Sheet Series

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

  3. Mass_Assignment_Cheat_Sheet.md

    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.

  4. java

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

  5. 0xa6-mass-assignment.md

    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.

  6. Mass Assignment in Java

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

  7. What is and how to prevent Mass Assignment Vulnerabilities

    Mass Assignment Vulnerabilities Explained. The concept referes to when you inject a set of values directly into an object, thus the name mass assignment, which without proper validation can cause serious problems to the application logic. Lets see a Java example with Spring:

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

  9. OWASP API #6: Mass Assignment

    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.

  10. Hibernate Mass Assignment: Risks and Solutions

    Mass Assignment and Understanding Mass Assignment Mass Assignment is a concept in web application development where multiple attributes of an object are set at once, typically from user input.

  11. Explaining Mass Assignment Vulnerabilities

    This particular example demonstrates how mass assignment can be exploited to achieve privilege escalation, however it is often possible to bypass other controls using the same technique. For example, an application might prevent a username from being edited when updating profile information, to ensure integrity and accountability across audit ...

  12. WSTG

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

  13. Secure Coding Guidelines

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

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

  15. Mass Assignment

    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

  16. What is a Mass Assignment Vulnerability?

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

  17. Mass Assignment 101

    For example, if an application allows users to submit an HTTP request with a JSON or XML payload that includes all of the properties of an object, an attacker may be able to manipulate the values of these properties in order to gain unauthorized access or permissions. ... Here's an example of an API vulnerable to Mass Assignment attack: @app ...

  18. Java Assignment Operators with Examples

    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.

  19. API Mass Assignment Vulnerability

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

  20. CWE

    Example: educators, technical writers, and project/program managers. ... such as mass assignment, autobinding, or object injection. Alternate Terms. Mass Assignment: ... Media library allows deserialization of objects by untrusted Java applets, leading to arbitrary code execution. Potential Mitigations.