https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fprintf-s-fprintf-s-l-fwprintf-s-fwprintf-s-l?view=msvc-170
int fprintf_s(
FILE *stream,
const char *format [,
argument_list ]
);
format Format-control string.
fprintf_s (stdout, "%s", "Hello" );
Important Ensure that format is not a user-defined string.
What does it mean? Do not do like that:
char user_defined_str [100] = "%s";
fprintf_s (stdout, user_defined_str, "Hello");
? If "yes" - why? What is the problem?
I tried to read and expected "yes", but don't understand why this should be avoided.
The relevant term here is "format string attack".
Let's take your code and change it a bit
char user_defined_str [100];
fgets(user_defined_str, sizeof(user_defined_str), stdin);
fprintf_s (stdout, user_defined_str, "Hello");
Now suppose what happes if the user supplies the format string %s %s? There's no further argument passed to fprintf_s, but the function doesn't know this. So it will just attempt to print a string from where that pointer on the argument would be, but in this case it's going to be some garbage value.
This might be used to expose data from within the process, like cryptographic keys, that are not supposed to be exposed. But things are even worse than that. Suppose it's not fprintf_s that's getting a user defined format string, but snprintf_s. Then by supplying a sufficiently crafted format string it'd be possible to clobber parts of the process, thereby injecting code into it. Consider this is happening in a tool that's processing data coming in from the Internet: That's how security vulnerabilities happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With