1

I came across an article about format string vulnerability in C and didn't understand how the format string %7$llx works.

Here is the code from that article:

#include <stdio.h>
#include <unistd.h>

int main() {
    int secret_num = 0x8badf00d;

    char name[64] = {0};
    read(0, name, 64);
    printf("Hello ");
    printf(name);
    printf("! You'll never get my secret!\n");
    return 0;
}

Command line input and output is this:

./fmt_string
%7$llx
Hello 8badf00d3ea43eef
! You'll never get my secret!

Article link here

So, I want to find out what happens in stack when printf is given that format string. As article states:

Due to how GCC decided to lay out the stack, secret_num is actually at a lower address on the stack than name, so we only have to go to the 7th "argument" in printf to leak the secret

What does the author mean when saying: "so we only have to go to the 7th argument in printf"? BTW, I understand memory layout and how stack works, it is just the printf and it's %7$llx format I don't understand in this particular piece of code.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
PIRIQITI
  • 149
  • 7
  • 1
    Both the [man page](https://man7.org/linux/man-pages/man3/printf.3.html) and [cppreference.com](https://en.cppreference.com/w/c/io/fprintf) are _**anything but**_ vague, and they both mention the `%n$` specifier format — it’s a POSIX requirement. – Dúthomhas Feb 01 '23 at 20:46
  • 2
    So given the answer to the duplicate, it looks like your understanding of `%7` isn't correct. It is used to "reach deeper" into the stack, where the seventh parameter of `printf` would be expected. – Eugene Sh. Feb 01 '23 at 20:48
  • 1
    @user3386109 It's not GCC, it's [POSIX](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html). – Andrew Henle Feb 01 '23 at 20:58
  • @EugeneSh. that is exactly what I was trying to find out, thanks. – PIRIQITI Feb 01 '23 at 21:17
  • @PIRIQITI, For clarity, the `"$"` in the specifier `"%7$llx"` results in _undefined behavior_ ("If a conversion specification is invalid, the behavior is undefined") in standard C. It is some extension to the format allowed by "Lowercase letters may be added to the conversion specifiers and length modifiers in fprintf and fscanf. Other characters may be used in extensions." – chux - Reinstate Monica Feb 01 '23 at 21:18

0 Answers0