我下面的 C# 代码如下所示:
Control c1 = (Control)LoadControl(System.Web.HttpContext.Current.Request.QueryString["UserControl"]);
Checkmarx 扫描后,我收到以下漏洞错误描述:
说明
这种不受信任的数据未经适当的清理或编码就嵌入到输出中,使攻击者能够将恶意代码注入生成的网页。攻击者只需在 Page_Init 方法读取的用户输入 QueryString 中提供修改后的数据,即可更改返回的网页。该输入然后通过代码直接流向输出网页,没有经过清理。这可以启用反射跨站点脚本 (XSS) 攻击。
要修复特定的反射 XSS 漏洞,您需要在页面输出中使用之前正确验证和编码用户输入。以下是您可以遵循的步骤:
"UserControl"
查询字符串参数的值,以确保它是一个可以加载的有效控件。这可以包括检查参数是否不为空,是否仅包含有效字符,以及控件是否存在于允许列表(已知的有效控件列表)中。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 函数进行编码。