Home > front end >  Is `std::format` vulnerable to format string attack? How to mitigate it?
Is `std::format` vulnerable to format string attack? How to mitigate it?

Time:12-26

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.

CodePudding user response:

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.

CodePudding user response:

The C functions like printf use variadic arguments, which don't provide any means to detect types and amount of the arguments actually passed. The only way printf can tell is by examining the format string. If this string lies, you have UB.

On the other hand, std::format is a templated function where all the types and amount of the arguments are known at compile time. It does know what each type is and, moreover, it checks at compile time that the string matches the types. Same for std::vformat, which does know the types in the same manner (using the information in its std::format_args parameter), and does check validity of the string, although at runtime.

Thus, attacks of this kind, i.e. with malicious strings, are defied.

CodePudding user response:

std::format, like printf/etc., assumes that the format string is from a trusted source. A malicious format string for std::format can't usually cause the same specific problems as one for printf/etc. (implicit type punning, buffer overruns, etc.), though std::format has some customization support which potentially enables such problems (and others).

If you want to use std::format, then you need to make sure that the format string is OK, either by writing it yourself or by validating that it has the specific form you expect.

  • Related