logo

Database

C Sharp User Input Generate Improper Output

Description

Detects potential Cross-Site Scripting (XSS) vulnerabilities in ASP.NET Core applications where unvalidated user input is directly assigned to HtmlString objects in ViewBag. This creates a security risk since HtmlString content bypasses ASP.NET Core's automatic HTML encoding, allowing potential injection of malicious scripts.

Weakness:

008 - Reflected cross-site scripting (XSS)

Category: Unexpected Injection

Detection Strategy

    Checks if Microsoft.AspNetCore.Html namespace is imported in the code

    Identifies HtmlString object instantiations that are assigned to ViewBag properties

    Verifies if the HtmlString constructor receives user-provided input (e.g. from request parameters, form data)

    Reports a vulnerability when user input flows directly into HtmlString objects without proper encoding or sanitization

Vulnerable code example

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;

public IActionResult DisplayUserInput(HttpRequest request)
{
    ViewBag.Data = new HtmlString(request.Params["name"]); // Vulnerable: Directly renders user input as HTML without sanitization
    return View();
}

✅ Secure code example

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;
using System.Web;

public IActionResult DisplayUserInput(HttpRequest request)
{
    // Encode user input before wrapping in HtmlString to prevent XSS
    ViewBag.Data = new HtmlString(HttpUtility.HtmlEncode(request.Params["name"]));...