ASP.NET MVC UpdateModel vulnerable to hacking?

前端 未结 5 1563
不知归路
不知归路 2020-12-15 13:51

I have an ASP.NET MVC application that is calendar-like. As per the NerdDinner example, I\'m updating the results of my edit page using UpdateMethod()

In my app, cer

相关标签:
5条回答
  • 2020-12-15 14:22

    It's perfectly possible for someone enterprising / malicious to map the fields to any of the properties on your model. There are a few ways around this

    The most simple is to use the exclude / include properties overloads of UpdateModel as has been mentioned before. The downside of this is that the method only accepts a string array which can sometimes mean your code gets out of sync if you do any renaming.

    Another way is to use a simple DTO which holds the bound fields, you can then take the DTO and do what you want with your event object, this obviously adds another class and is much more manual but gives you a lot more control

    public ActionResult(int id, EditForm form) {
        MyEvent event = _eventRepository.GetMyEvent(id);
        event.Name = form.Name; //etc;
        if (User.IsInRole("Organiser")) {
            event.Date = form.Date;
        }
        return ...
    }
    

    Another way could be via a customer model binder for your MyEvent class which only binds your desired field, probably overkill though.

    0 讨论(0)
  • 2020-12-15 14:23

    You can mark fields on your model that should be ignored by update or pass a list of included/excluded fields using one of the other UpdateModel overloads.

    0 讨论(0)
  • 2020-12-15 14:34

    Your fears are right. This is called mass assignment. You can protect your code by marking your class with BindAttribute and setting Exclude / Include properties.

    0 讨论(0)
  • 2020-12-15 14:40

    You're missing the section on "Model Binding Security". You should always include a whitelist of properties that can be updated by any of your user input methods.

    For example, from NerdDinner:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create( [Bind(Include="Title, Address")] Dinner dinner)
    {
    
    }
    

    or if you're calling UpdateModel, you can create a string array of allowed properties, and do

    UpdateModel(myObject, allowedProperties);
    

    You can lock down the classes themselves so that only certain properties are updateable as well.

    [Bind(Include="MyProp1,MyProp2,MyProp3")]
    public partial class MyEntity { }
    
    0 讨论(0)
  • 2020-12-15 14:48

    There are overloads of UpdateModel that take an array of strings naming properties to update. These overloads will only update the named properties.

    There may be other easier / more declarative ways to accomplish this, I'm not an expert on MVC data binding.

    0 讨论(0)
提交回复
热议问题