Swift Uncontrolled Format String

Swift uncontrolled format string

Description

Using user input as the format string for String(format:), NSString(format:), or NSLog lets format specifiers be interpreted, potentially causing exceptions, information disclosure, or log manipulation.

Potential impact

  • Exceptions or application crashes
  • Log manipulation
  • Unintended formatting of data

Remediation

  1. Keep format strings as static constants.
  2. Pass user values only as format arguments; do not concatenate or interpolate them into the format string.
  3. Use structured logging and an appropriate redaction policy.

Examples

Before

swift
let message = String(format: userControlledFormat)

After

swift
let message = String(format: "Hello %@", username)

Explanation:

  • Before: User input is interpreted as a format string.
  • After: The format string is fixed, and the user value is supplied as an argument.

References