c++printfc++20format-stringfmt

Is `std::format` vulnerable to format string attack? How to mitigate it?


I would like to refactor C style code using printf, fprintf, etc... to C++. Is std::format vulnerable to format string attack, as the aforementioned C functions?

If I search for format string attacks, all I find is stdio format string vulnerabilities. I would like to know more about if std::format is vulnerable, and how to mitigate it, even if I have to format user provided strings.


Solution

  • I would like to know more about if std::format is vulnerable, and how to mitigate it, even if I have to format user provided strings.

    Even if you use std::vformat (which accepts a run-time string), the input is verified against the types of the other arguments and std::format_error is raised upon mismatch (while std::format verifies this at the call site during compile time).

    So a malicious user cannot sneak in a format specifier for an argument you did not provide. And since the formatter that is used for an argument must be based on its static type (and so also provided by you), an attacker cannot try punning.

    All in all, that vector of attack seems blocked.