Mass Assignment in Aspnet
How Mass Assignment Manifests in Aspnet
Mass assignment vulnerabilities in Aspnet applications occur when model binding automatically populates object properties from HTTP request data without proper filtering. This Aspnet-specific behavior creates attack vectors that developers often overlook.
The most common manifestation appears in Aspnet MVC and Web API controllers where model binding automatically maps request parameters to strongly-typed objects. Consider an Aspnet controller action:
[HttpPost]
public IActionResult CreateUser([FromBody] User user) {
_userService.Create(user);
return Ok();
}The Aspnet model binder automatically populates all public properties of the User class from the JSON request body. An attacker can exploit this by including additional properties:
{
"username": "attacker",
"password": "pass123",
"isAdmin": true,
"accountBalance": 10000
}Since Aspnet's default model binding behavior includes all public properties, the Admin and AccountBalance properties get set without validation. This Aspnet-specific feature becomes dangerous when combined with ORM frameworks like Entity Framework Core.
Entity Framework Core's tracking behavior amplifies this risk. When Aspnet controllers return entities directly or use DbContext.Update(), all properties become updatable:
public IActionResult UpdateUser([FromBody] User user) {
_context.Users.Update(user); // Aspnet + EF Core vulnerability
_context.SaveChanges();
return Ok();
}The Aspnet model binder populates the entire User object, then EF Core tracks all properties as modified. This creates a perfect storm where Aspnet's convenience features enable complete object takeover.
Another Aspnet-specific pattern involves [Bind] attributes and TryUpdateModel. While these provide some protection, they're often misapplied:
public async Task Edit(int id, User user) {
var existing = await _context.Users.FindAsync(id);
if (await TryUpdateModelAsync(
existing,
"user",
u => u.Username, u => u.Email)) {
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(existing);
} Even with property whitelisting, Aspnet's dynamic model binding can still introduce risks through complex object graphs and nested properties.
Aspnet-Specific Detection
Detecting mass assignment vulnerabilities in Aspnet applications requires understanding both Aspnet's model binding mechanics and the application's data flow. middleBrick's Aspnet-specific scanning identifies these issues through black-box testing of unauthenticated endpoints.
The scanner tests Aspnet model binding by sending requests with additional properties that shouldn't be user-modifiable. For instance, when scanning an Aspnet API endpoint like:
POST /api/users HTTP/1.1
Content-Type: application/json
{
"username": "testuser",
"password": "password123",
"role": "admin",
"creditLimit": 50000
}middleBrick analyzes the response and subsequent API behavior to detect if Aspnet successfully bound the extra properties. The scanner checks for Aspnet-specific indicators like:
- Changes in Aspnet's authentication/authorization state
- Database modifications to properties that should be immutable
- Aspnet's model state validation bypass
- Entity Framework Core's change tracking behavior
middleBrick also examines Aspnet's binding conventions by testing various property names and data structures. Aspnet's default binding behavior attempts to match JSON properties to C# class properties by name, so the scanner systematically tests this mapping.
For Aspnet applications using Data Transfer Objects (DTOs), middleBrick analyzes the separation between API models and domain entities. Many Aspnet developers create DTOs but still expose entity classes through API endpoints, creating a false sense of security.
The scanner's Aspnet-specific checks include:
class AspnetMassAssignmentCheck {
async Task TestEndpoint(string url, HttpMethod method) {
var payload = GenerateExploitPayload();
var response = await SendRequest(url, method, payload);
return await AnalyzeResponseForPropertyChanges(response);
}
} middleBrick's continuous monitoring for Aspnet applications can detect when new properties are added to models without corresponding security reviews, alerting developers when Aspnet's default binding behavior might expose new attack surfaces.
Aspnet-Specific Remediation
Securing Aspnet applications against mass assignment requires leveraging Aspnet's built-in security features while understanding the framework's binding mechanics. The most effective approach combines multiple Aspnet-specific techniques.
Start with Aspnet's [Bind] attribute for explicit property whitelisting:
public class UserController : Controller {
[HttpPost]
public IActionResult Create([Bind("Username,Email,Password")] User user) {
if (ModelState.IsValid) {
_userService.Create(user);
return RedirectToAction("Index");
}
return View(user);
}
}This Aspnet-specific attribute tells the model binder to only populate explicitly listed properties, preventing unexpected data from being bound.
For Aspnet applications using Entity Framework Core, implement view models that separate API contracts from database entities:
public class UserCreateModel {
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
public class UserController : Controller {
[HttpPost]
public async Task Create([FromBody] UserCreateModel model) {
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
var user = new User {
Username = model.Username,
Email = model.Email,
PasswordHash = HashPassword(model.Password)
};
await _context.Users.AddAsync(user);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetById), new { id = user.Id }, user);
}
} This Aspnet pattern ensures that only intended properties flow from the API to the database layer.
Aspnet's IModelBinder interface enables custom binding logic for complex scenarios:
public class SecureUserBinder : IModelBinder {
public Task BindModelAsync(ModelBindingContext bindingContext) {
var modelName = bindingContext.ModelName;
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None) {
return Task.CompletedTask;
}
var model = new User();
var json = valueProviderResult.FirstValue;
var jsonObject = JsonSerializer.Deserialize<JsonElement>(json);
if (jsonObject.TryGetProperty("username", out var username)) {
model.Username = username.GetString();
}
// Only bind explicitly allowed properties
if (jsonObject.TryGetProperty("email", out var email)) {
model.Email = email.GetString();
}
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}
}This Aspnet-specific approach gives complete control over the binding process.
For Aspnet applications using AutoMapper, configure mapping profiles to exclude sensitive properties:
public class MappingProfile : Profile {
public MappingProfile() {
CreateMap()
.ForMember(dest => dest.IsAdmin, opt => opt.Ignore())
.ForMember(dest => dest.AccountBalance, opt => opt.Ignore());
}
} These Aspnet-specific remediation techniques, combined with middleBrick's continuous scanning, provide comprehensive protection against mass assignment vulnerabilities.
Related CWEs: propertyAuthorization
| CWE ID | Name | Severity |
|---|---|---|
| CWE-915 | Mass Assignment | HIGH |