DEV Community

TurfSixNine
TurfSixNine

Posted on

Buffer Overflow Vulnerability C Code

Hi folks,

I have this c code:

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

int ssp(char * str)
{
    char buffer[100];
    strcpy(buffer,str);

    return 1;
}

int main(int argc, char **argv)
{
    char str[400];
    FILE * afile;

    afile = fopen("afile", "r");
           fread(str, sizeof(char), 400, afile);
    ssp(str);

    printf("Returned Properly\n");  

    return 1;
}
Enter fullscreen mode Exit fullscreen mode

The program provided reads the contents of a file called "afile" into a character array called str, which can hold up to 400 characters. It then calls the ssp function and passes str as an argument.

The ssp function copies the contents of the str character array into a local character array called buffer. The strcpy function used to copy the string data does not perform any bounds checking, which can lead to buffer overflow vulnerabilities if the input string is longer than the buffer size.

However, the lack of bounds checking in the strcpy function in the ssp function can potentially lead to buffer overflow vulnerabilities if used in a larger program or in an environment with untrusted input data.

Could anyone please assist with a shellcode at the end of "afile" and then store the shellcode on the stack to run? Please...

Top comments (1)

Collapse
 
manojlingala profile image
manojlingala

Ages ago I worked on C .

Hopefully this pseduo code gives a safer programming practices to avoid the overflow issue.

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

#define MAX_STR_LEN 400
#define MAX_BUFFER_LEN 100

int ssp(const char *str, char *buffer, size_t buffer_len)
{
    if(strlen(str) >= buffer_len) {
        return 0; // Error: buffer overflow potential
    }

    strcpy(buffer, str);

    return 1;
}

int main(int argc, char **argv)
{
    char str[MAX_STR_LEN];
    char buffer[MAX_BUFFER_LEN];

    FILE *afile;
    afile = fopen("afile", "r");

    if (afile == NULL) {
        perror("Error opening file");
        return 1;
    }

    size_t bytes_read = fread(str, sizeof(char), MAX_STR_LEN - 1, afile);
    str[bytes_read] = '\0'; // null-terminate string

    fclose(afile);

    if(ssp(str, buffer, MAX_BUFFER_LEN)) {
        printf("Returned Properly\n");  
    } else {
        printf("Error: potential buffer overflow\n");
    }

    return 0;
}

Enter fullscreen mode Exit fullscreen mode