#include<stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<sys/types.h>#include<wchar.h>#include<locale.h>#define BUFSIZE 32#define FLAGSIZE 64#define CANARY_SIZE 4voidwin(){charbuf[FLAGSIZE];FILE*f=fopen("flag.txt","r");if(f==NULL){printf("Flag File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");exit(0);}fgets(buf,FLAGSIZE,f);puts(buf);fflush(stdout);}charglobal_canary[CANARY_SIZE];voidread_canary(){FILE*f=fopen("canary.txt","r");if(f==NULL){printf("Canary is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");exit(0);}fread(global_canary,sizeof(char),CANARY_SIZE,f);fclose(f);}voidvuln(){charcanary[CANARY_SIZE];charbuf[BUFSIZE];charlength[BUFSIZE];intcount;intx=0;memcpy(canary,global_canary,CANARY_SIZE);printf("How Many Bytes will You Write Into the Buffer?\n> ");while(x<BUFSIZE){read(0,length+x,1);if(length[x]=='\n')break;x++;}sscanf(length,"%d",&count);printf("Input> ");read(0,buf,count);if(memcmp(canary,global_canary,CANARY_SIZE)){printf("*** Stack Smashing Detected *** : Canary Value Corrupt!\n");exit(-1);}printf("Ok... Now Where's the Flag?\n");fflush(stdout);}intmain(intargc,char**argv){setvbuf(stdout,NULL,_IONBF,0);// Set the gid to the effective gid// this prevents /bin/sh from dropping the privilegesinti;gid_tgid=getegid();setresgid(gid,gid,gid);read_canary();vuln();return0;}
Answer
In the source code below, the canary is load from a text file and is only four bytes, #define CANARY_SIZE 4.
So, we can bruteforce it. The good way to do it, it's by bruteforcing the canary one byte at a time.
Example
padding + 'a' : Stack Smashing Detected -> The canary is NOT starting by the letter 'a'.
padding + 'b' : Stack Smashing Detected -> The canary is NOT starting by the letter 'b'.
...
padding + 'o' : Ok... Now Where'''s the Flag? -> The canary is starting by the letter 'o'.
Then, you go on with : 'oa', 'ob', 'oc', ... until you get the four bytes.
Once you retrieve the whole canary, you now can jump to the win function.
Let's make a python script with pwntools to flag this challenge :