CodeQL documentation

Uncontrolled format string

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

Click to see the query in the CodeQL repository

Passing untrusted format strings to String.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, then System.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 to String.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.

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);
    }
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy