Uncontrolled format string¶
ID: cs/uncontrolled-format-stringKind: path-problemSecurity severity: 7.3Severity: errorPrecision: highTags: - security - external/cwe/cwe-134Query suites: - csharp-code-scanning.qls - csharp-security-extended.qls - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Passing untrusted format strings toString.Format can throw exceptions and cause a denial of service. For example, if the format string references a missing argument, or an argument of the wrong type, thenSystem.FormatException is thrown.
Recommendation¶
Use a string literal for the format string to prevent the possibility of data flow from an untrusted source. This also helps to prevent errors where the arguments toString.Format do not match the format string.
If the format string cannot be constant, ensure that it comes from a secure data source or is compiled into the source code.
Example¶
In this example, the format string is read from an HTTP request, which could cause the application to crash.
usingSystem.Web;publicclassHttpHandler:IHttpHandler{stringSurname,Forenames,FormattedName;publicvoidProcessRequest(HttpContextctx){stringformat=ctx.Request.QueryString["nameformat"];// BAD: Uncontrolled format string.FormattedName=string.Format(format,Surname,Forenames);}}
References¶
OWASP:Format string attack.
Microsoft docs:String.Format Method
Common Weakness Enumeration:CWE-134.