# Linux Buffer Overflow With Command Injection

```c
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int bo(char *name, char *cmd){
        char c[40], n[40];
        printf("Name is at %p; command is at %p\n", n, c);
        strcpy(c, cmd);
        strcpy(n, name);
        printf("Goodbye, %s!\n", n);
        printf("Executing command: %s\n", c);
        fflush(stdout);
        system(c);
}

int main(){
        char name[200];
        printf("What is your name?\n");
        scanf("%s", name);
        bo(name, "date");
}
```

This program inputs a name from the user and prints out a "Goodbye" message. It then calls system() to print out the date. It uses two buffers in a subroutine to do that in an unsafe manner, allowing the name buffer to overflow into the command buffer.

![](https://3889206050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M6DIEHtstePxj4NCmCC%2F-M6fW8xbwpD6X09K39Ww%2F-M6gMKGYx1nTRadQyRF7%2Fimage.png?alt=media\&token=a689e150-f860-469c-9579-c7550d8a6b04)

When we execute the program we can see that it prints out the location of the `name` buffer and the `cmd` buffer, says "Goodbye", and executes the command "date", as shown above. We can also notice that the `cmd` buffer is stored at a higher memory address.

Now let's try to overflow the program and cause a crash.

![](https://3889206050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M6DIEHtstePxj4NCmCC%2F-M6fW8xbwpD6X09K39Ww%2F-M6gNcg6lDJvFf-KCj59%2Fimage.png?alt=media\&token=67f4af43-1b44-4949-9922-3583785f3a5e)

By typping 42 A characters, we can see that the program tries to execute "AA" as shown above. This tells us that after the 40th character there is a **code injection point**. So now we can try to inject a command to be executed instead of `date`.

![](https://3889206050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M6DIEHtstePxj4NCmCC%2F-M6fW8xbwpD6X09K39Ww%2F-M6gOU8UQ7vsH6oPsYn0%2Fimage.png?alt=media\&token=c0407060-8c0f-49fb-980c-1dbc65e29ec7)

If we want to execute a command that needs a space in between, like for example `ls -la` we need to use one of the many methods to escape spaces, since the space will be interpreted as the end of a string. Some of these methods are:

* Adding a backslash character, `\`, before the space
* Enclosing the whole string in quotation marks
* Using the Inter-Frame Spacing methacharacter, `$IFS`, instead of a space
