Tags: programming secure-coding
Rating:
# PWN
In one of the previous challenges, we leveraged a buffer overflow to attack a program. Now, we're going to modify a program to be resistant to buffer overflows.
This is the vulnerable program:
```c
#include <stdio.h>
#include <stdlib.h>
void echo()
{
printf("%s", "Enter a word to be echoed:\n");
char buf[128];
gets(buf);
printf("%s\n", buf);
}
int main()
{
echo();
}
```
The reason that this program is vulnerable is because it uses `gets()`. We should instead be using `fgets()`. `fgets()` behaves a bit differently than `gets()`. In addition to specifying the buffer user input will go to, we also need to specify how large the user input can be in bytes, and from where will we read input. The user input will be, at max, the size of the buffer. We will read input from standard input.
The secure program is:
```c
#include <stdio.h>
#include <stdlib.h>
void echo()
{
printf("%s", "Enter a word to be echoed:\n");
char buf[128];
fgets(buf, sizeof buf, stdin);
printf("%s\n", buf);
}
int main()
{
echo();
}
```
After that, we just need to fork the repository, add our secure program to it, commit, and push it to be tested.
![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-TAMU/images/PWN-1.png)