views:

78

answers:

2

I am starting to use boost/format.

When coding with boost/format, what should I pay attention to with regard to security?

Can I do the following without being concerned about security?

std::cout << boost::format("Hello %2%! Do you want to %1%?") 
    % user_supplied_str1 % user_supplied_str2 << std::endl;

What are situations where security would be an issue while using boost/format?

+1  A: 

If you mean security in terms of printf equivalents with incorrect type specifiers or possible buffer overflows then boost/format is perfectly fine -- even with a user supplied format string, I think. But you do have to keep in mind that it might throw an exception. Check the documentation about when and what exceptions are thrown.

sellibitze
+3  A: 

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.:

  1. %n allows writing to arbitrary memory locations.
  2. varargs doesn't allow argument counting, so a string can print out the entire heap.
  3. 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.

larsmans