如何从 ASPX 查询字符串修复 aspx.cs 页面中反射的 XSS 特定客户端?

问题描述 投票:0回答:1

我下面的 C# 代码如下所示:

Control c1 = (Control)LoadControl(System.Web.HttpContext.Current.Request.QueryString["UserControl"]);

Checkmarx 扫描后,我收到以下漏洞错误描述:

说明

这种不受信任的数据未经适当的清理或编码就嵌入到输出中,使攻击者能够将恶意代码注入生成的网页。攻击者只需在 Page_Init 方法读取的用户输入 QueryString 中提供修改后的数据,即可更改返回的网页。该输入然后通过代码直接流向输出网页,没有经过清理。这可以启用反射跨站点脚本 (XSS) 攻击。

c# asp.net query-string xss checkmarx
1个回答
0
投票

要修复特定的反射 XSS 漏洞,您需要在页面输出中使用之前正确验证和编码用户输入。以下是您可以遵循的步骤:

  1. 验证输入:检查
    "UserControl"
    查询字符串参数的值,以确保它是一个可以加载的有效控件。这可以包括检查参数是否不为空,是否仅包含有效字符,以及控件是否存在于允许列表(已知的有效控件列表)中。
  2. 对输出进行编码:验证输入后,在将其用于页面输出之前对其进行正确编码。根据它在输出中的使用方式,您可以使用
    HtmlEncode
    JavaScriptEncode
    函数对输入值进行编码。

以下是如何修改代码以修复漏洞的示例:


string userControl = System.Web.HttpContext.Current.Request.QueryString["UserControl"];

if (!string.IsNullOrEmpty(userControl))
{
    // Validate the input
    List<string> validControls = new List<string> { "Control1.ascx", "Control2.ascx", "Control3.ascx" };
    if (validControls.Contains(userControl))
    {
        // Encode the output
        Control c1 = (Control)LoadControl(Server.HtmlEncode(userControl));
        this.Controls.Add(c1);
    }
    else
    {
        // Handle invalid input
        // For example, redirect to an error page or display a friendly error message
    }
}
else
{
    // Handle missing input
    // For example, redirect to an error page or display a friendly error message
}

本例首先检查“UserControl”的输入值,确保其不为空。然后,检查有效控件名称列表以确保输入值对应于已知且有效的控件。最后,输入值在 LoadControl 方法中使用之前使用 HtmlEncode 函数进行编码。

© www.soinside.com 2019 - 2024. All rights reserved.