Your example is safe. In fact, it was safe with printf
. Like printf
, Boost.Format only parses its format string once, so there's no chance to insert extra format specifiers. Passing an incomplete format
object to boost::format
throws an exception.
I guess what you're afraid of are format string exploits. Those are, I think, impossible using Boost.Format. The reasons why printf
is vulnerable are summarized by Cowan et al.:
%n
allows writing to arbitrary memory locations.
varargs
doesn't allow argument counting, so a string can print out the entire heap.
varargs
isn't type-safe.
Ad (1), %n
has been omitted from Boost.Format "because it does not fit in this context." Ad (2), Boost.Format doesn't use varargs
and throws an exception when the number of arguments doesn't fit the format string. Ad (3), this is solved because the arguments to operator%
are checked at compile time.
(I just tried to get Boost.Format to print the address of a C string in memory using a custom format string, and it won't let me.)
Further, the buffer overflow in sprintf
is avoided because strings are allocated dynamically.
If you want to be on the safe side, don't use format strings from untrusted sources.