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?
Your example is safe. In fact, it was safe with
printf. Likeprintf, Boost.Format only parses its format string once, so there’s no chance to insert extra format specifiers. Passing an incompleteformatobject toboost::formatthrows an exception.I guess what you’re afraid of are format string exploits. Those are, I think, impossible using Boost.Format. The reasons why
printfis vulnerable are summarized by Cowan et al.:%nallows writing to arbitrary memory locations.varargsdoesn’t allow argument counting, so a string can print out the entire heap.varargsisn’t type-safe.Ad (1),
%nhas been omitted from Boost.Format “because it does not fit in this context.” Ad (2), Boost.Format doesn’t usevarargsand throws an exception when the number of arguments doesn’t fit the format string. Ad (3), this is solved because the arguments tooperator%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
sprintfis avoided because strings are allocated dynamically.If you want to be on the safe side, don’t use format strings from untrusted sources.