1

正如我在你能发现对 ASP.NET MVC 3.0+ 模型绑定器的小改动的安全隐患/漏洞吗?CartModelBinder 类的一个版本(如下所示)允许通过 MVC ModelBinding 漏洞(也称为 OverPosting)进行利用

你能看出是哪一个吗?

理想情况下,您应该使用 UnitTests 提供您的答案/结果/证明:)

版本 1:使用 DefaultModelBinder 和 CreateModel

public class CartModelBinder : DefaultModelBinder
{
    private const string sessionKey = "Cart";

    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        // get the Cart from the session
        Cart cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
        // create the Cart if there wasn't one in the session data
        if (cart == null)
        {
            cart = new Cart();
            controllerContext.HttpContext.Session[sessionKey] = cart;
        }
        // return the cart
        return cart;
    }
}

版本 2:使用 IModelBinder 和 BindModel

public class CartModelBinder : IModelBinder
{
    private const string sessionKey = "Cart";

    public object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)
    {

        // get the Cart from the session
        Cart cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
        // create the Cart if there wasn't one in the session data
        if (cart == null)
        {
            cart = new Cart();
            controllerContext.HttpContext.Session[sessionKey] = cart;
        }
        // return the cart
        return cart;
    }
}

控制器示例:

public RedirectToRouteResult AddToCart(Cart cart, int productId, string returnUrl)
{
    Product product = repository.Products
        .FirstOrDefault(p => p.ProductID == productId);

    if (product != null)
    {
        cart.AddItem(product, 1);
    }
    return RedirectToAction("Index", new { returnUrl });
}
4

1 回答 1

1

您当前的设计很容易像您建议的那样被滥用。更好的解决方案是最初获取购物车并使用该实例。

  public class CartController : Controller
  {
        private IProductRepository repository;
        private IOrderProcessor orderProcessor;
        private cart;
        public CartController(IProductRepository repo, IOrderProcessor proc)
        {
            repository = repo;
            orderProcessor = proc;
            cart = Session["Cart"]; // or Cart.Current
        }

        public RedirectToRouteResult AddToCart(int productId, string returnUrl)
        {
            Product product = repository.Products
                .FirstOrDefault(p => p.ProductID == productId);

            if (product != null)
            {
                cart.AddItem(product, 1);
            }
            return RedirectToAction("Index", new { returnUrl });
        }

  }
于 2013-07-18T19:12:20.533 回答