Take the 2-minute tour ×
Information Security Stack Exchange is a question and answer site for Information security professionals. It's 100% free, no registration required.

Here's the statement: fprintf(stderr, "Some random string\n").

Is it okay not to have a format specifier, such as %s, even though the statement doesn't take any user input? Is it still potentially exploitable? It seems like it should still at least be considered a best practice to include a format specifier. I'd appreciate some clarity on the matter. Thanks.

share|improve this question

1 Answer 1

The statement, as you show it, is not vulnerable to anything. However, fprintf() is indeed an interpreter in its own right: what it takes as format string is not just a sequence of characters; it is source code for a specific language with directives beginning with a '%' sign.

When you use your fprintf() function like that, sooner or later, some developer will go all generic and righteous and fanatic of internationalization, and will insist on rewriting it that way:

/* in some .h file */
#define MSG_EN_42   "Some random string\n"

#if LANGUAGE_IS_ENGLISH
#define MSG_42   MSG_EN_42
#endif

/* in another .c file */
fprintf(stderr, MSG_42);

Then, some weeks/months/years later, another developer, with little grasp of C but remarkable knowledge of German/Thaï/Klingon, will change the .h to look like this:

/* in some .h file */
#define MSG_EN_42   "Some random string\n"
#define MSG_KG_42   "fs'k5 f%n59 #$dsai!\n"

#if LANGUAGE_IS_ENGLISH
#define MSG_42   MSG_EN_42
#endif
#if LANGUAGE_IS_KLINGON
#define MSG_42   MSG_KG_42
#endif

And then trouble ensues.

(Not an actual Klingon example, by the way; using true Klingon words on the unsuspecting reader would be kind of rude. But you get the idea.)

To void these issues, use a format string when a format string is due. This would lead to:

fprintf(stderr, "%s", "Some random string\n");

or, as a simpler solution:

fputs("Some random string\n", stderr);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.