# Buffer overflow 0

<figure><img src="/files/EZXWNu8E0QIB1u6LdOva" alt=""><figcaption></figcaption></figure>

Here's the vulnerable code :

```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) {
  printf("%s\n", flag);
  fflush(stdout);
  exit(1);
}

void vuln(char *input){
  char buf2[16];
  strcpy(buf2, input);
}

int main(int argc, char **argv){
  
  FILE *f = fopen("flag.txt","r");
  if (f == NULL) {
    printf("%s %s", "Please create 'flag.txt' in this directory with your",
                    "own debugging flag.\n");
    exit(0);
  }
  
  fgets(flag,FLAGSIZE_MAX,f);
  signal(SIGSEGV, sigsegv_handler); // Set up signal handler
  
  gid_t gid = getegid();
  setresgid(gid, gid, gid);


  printf("Input: ");
  fflush(stdout);
  char buf1[100];
  gets(buf1); 
  vuln(buf1);
  printf("The program will exit now\n");
  return 0;
}

```

#### Vulnerabilities:

* `gets()` — accepts unlimited input (vulnerable to buffer overflow).
* `strcpy()` in `vuln()` copies data into a small buffer `buf2[16]` without bounds checking.
* A signal handler is registered for `SIGSEGV`, which **prints the flag** when a crash happens.

💡 **Key Insight**: All we need to do is trigger a **segfault** (e.g. buffer overflow), and the handler will print the flag for us.

<figure><img src="/files/tamEF03ihCBqWYmEHs8e" alt=""><figcaption></figcaption></figure>

Bingo we got our flag&#x20;


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gr3edydevel0per.gitbook.io/ctf/picoctf/binary-exploitation/buffer-overflow-0.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
