不受控制的格式字符串¶
ID: cs/uncontrolled-format-string
Kind: path-problem
Security severity: 9.3
Severity: error
Precision: high
Tags:
- security
- external/cwe/cwe-134
Query suites:
- csharp-code-scanning.qls
- csharp-security-extended.qls
- csharp-security-and-quality.qls
将不受信任的格式字符串传递给 String.Format
可能会引发异常并导致拒绝服务。例如,如果格式字符串引用了缺少的参数或类型错误的参数,则会引发 System.FormatException
。
建议¶
对格式字符串使用字符串字面量,以防止数据从不受信任的源流入。这还有助于防止 String.Format
的参数与格式字符串不匹配的错误。
如果格式字符串不能为常量,请确保它来自安全的数据源或已编译到源代码中。
示例¶
在此示例中,格式字符串是从 HTTP 请求中读取的,这可能会导致应用程序崩溃。
using System.Web;
public class HttpHandler : IHttpHandler
{
string Surname, Forenames, FormattedName;
public void ProcessRequest(HttpContext ctx)
{
string format = ctx.Request.QueryString["nameformat"];
// BAD: Uncontrolled format string.
FormattedName = string.Format(format, Surname, Forenames);
}
}
参考¶
OWASP:格式字符串攻击。
Microsoft 文档:String.Format 方法
常见弱点枚举:CWE-134。