Binary Exploitation

OverFlow 0

picoCTF 2019

30 January 2020

Points: 100

Problem :lock:

This should be easy. Overflow the correct buffer in this program and get a flag.

// relevant code
void sigsegv_handler(int sig) {
  fprintf(stderr, "%s\n", flag);
  fflush(stderr);
  exit(1);
}

void vuln(char *input){
  char buf[128];
  strcpy(buf, input);
}

int main(int argc, char **argv){
  
  FILE *f = fopen("flag.txt","r");
  ...
  signal(SIGSEGV, sigsegv_handler);
  ...
  if (argc > 1) {
    vuln(argv[1]);
    printf("You entered: %s", argv[1]);
  }
  else
    printf("Please enter an argument next time\n");
  return 0;
}
Full code

Download vuln.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

#define FLAGSIZE_MAX 64

char flag[FLAGSIZE_MAX];

void sigsegv_handler(int sig) {
  fprintf(stderr, "%s\n", flag);
  fflush(stderr);
  exit(1);
}

void vuln(char *input){
  char buf[128];
  strcpy(buf, input);
}

int main(int argc, char **argv){
  
  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(flag,FLAGSIZE_MAX,f);
  signal(SIGSEGV, sigsegv_handler);
  
  gid_t gid = getegid();
  setresgid(gid, gid, gid);
  
  if (argc > 1) {
    vuln(argv[1]);
    printf("You entered: %s", argv[1]);
  }
  else
    printf("Please enter an argument next time\n");
  return 0;
}

Hint :bulb:

Find a way to trigger the flag to print

If you try to do the math by hand, maybe try and add a few more characters. Sometimes there are things you aren’t expecting.

Solution :key:

Looking at the source, we see the buf[128] variable, this will be the variable that we overflow. So we run the program with an argv[1] bigger than 128. Here I used nested command with python to print 150 a chars to be used as the argument in running the vuln executable.

./vuln $(python -c "print 'a'*150")

Then the program will run along a little like this:

  1. signal() function will watch for SIGSEGV, if that happens, sigsegv_handler() will be called
  2. vuln() function will be called with argv[1] as parameter
  3. strcpy() is going to run and raise SIGSEGV because it can’t copy a string of 150 chars into the buf[128] variable that can only hold 127 chars
  4. sigsegv_handler() will be called and the flag will be printed into stderr
  5. program exits with exit code 1

Flag :checkered_flag:

picoCTF{3asY_P3a5y0a131490}