0

Lets say that:

char name[50]="TEST";
printf("%s",name);

Here in the code, the %s just says that the variable is a string. But why when we print out user inputs, the %s suddenly change meaning? What's the difference between the user inputting %s and the program printing out %s? Even if the user inputs "%s", the %s still doesn't have the same meaning. So how did the user input got validated as a command, and it is possible to do the "vulnerability" inside the program? For example, if the user inputs %x, the program will print out information on the stack. Is it possible to do this within the program itself?

1 Answer 1

1

The vulnerability does not exist in the way you've written it. The vulnerability arises if the user input is used as the format string rather than the varg.

char input[50] = "%x %x %x %x";
printf(input);

Unless there is a bug in the implementation of the stdlib, vargs should not be interpreted as format strings.

6
  • Hi, thanks for the reply. So why do format strings exist anyways? When will it be useful to do like printf("%x");? And also, can similar things like SQL injection work, for example, printing out a variable given its name?
    – No Name
    Commented Mar 18, 2022 at 16:31
  • To format the output. For example, printf("I have %d dollars and %d cents.\n", numDollars, numCents); inserts the number of dollars and cents in each %d. The phrase printf("%x"); without a varg (the values after the first comma) to specify what %x should be would likely be a warning at minimum from the compiler.
    – foreverska
    Commented Mar 18, 2022 at 16:38
  • re SQL injection: Not that my C/C++ brain can immediately imagine. Variable names are a human construct in C. They aren't really tracked by the C compiler past a certain point, except for debugging purposes, if that's turned on.
    – foreverska
    Commented Mar 18, 2022 at 16:41
  • @MysteriousShadow If you're familiar with SQLi defenses, then proper use of format strings is akin to using prepared statements.
    – forest
    Commented Mar 18, 2022 at 21:07
  • @foreverska Ok got it. So basically one should never say printf("%x") with a varg. If that's the case, then why is that "feature" there? Like when they designed the language they didn't thought of the vulnerability and why didn't they remove it like the program simply crashes when that happens. I'm just trying to understand the origin of this vulnerability.
    – No Name
    Commented Mar 19, 2022 at 2:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .