缺少函数级访问控制¶
ID: cs/web/missing-function-level-access-control
Kind: problem
Security severity: 7.5
Severity: warning
Precision: medium
Tags:
- security
- external/cwe/cwe-285
- external/cwe/cwe-284
- external/cwe/cwe-862
Query suites:
- csharp-security-extended.qls
- csharp-security-and-quality.qls
敏感操作(如编辑或删除内容或访问管理页面)应进行授权检查,以确保恶意行为者无法使用它们。
建议¶
确保对敏感操作进行适当的授权检查。对于 WebForms 应用程序,可以使用 Web.config
XML 文件中的 authorization
标记来实现访问控制。还可以使用 System.Web.UI.Page.User
属性来验证用户的角色。对于 MVC 应用程序,可以使用 Authorize
特性来要求对特定操作方法进行授权。
示例¶
在以下 WebForms 示例中,标记为“错误”的情况没有授权检查,而标记为“正确”的情况使用 User.IsInRole
来检查用户的角色。
class ProfilePage : System.Web.UI.Page {
// BAD: No authorization is used
protected void btn1_Edit_Click(object sender, EventArgs e) {
...
}
// GOOD: `User.IsInRole` checks the current user's role.
protected void btn2_Delete_Click(object sender, EventArgs e) {
if (!User.IsInRole("admin")) {
return;
}
...
}
}
以下 Web.config
文件使用 authorization
标记来拒绝匿名用户访问,并在 location
标记中应用该配置到特定路径。
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<location path="User/Profile">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
</configuration>
在以下 MVC 示例中,标记为“错误”的情况没有授权检查,而标记为“正确”的情况使用了 Authorize
特性。
public class ProfileController : Controller {
// BAD: No authorization is used.
public ActionResult Edit(int id) {
...
}
// GOOD: The `Authorize` attribute is used.
[Authorize]
public ActionResult Delete(int id) {
...
}
}
参考¶
Page.User
属性 - Microsoft Learn。在 ASP.NET 应用程序中控制授权权限 - Microsoft Learn。
ASP.NET Core 中的简单授权 - Microsoft Learn。
常见弱点枚举:CWE-285。
常见弱点枚举:CWE-284。
常见弱点枚举:CWE-862。