Here are the steps to understand how a vulnerability occurs while copying a string:
- Define a structure consisting of two members, name and orderid.
- Define a variable of the structure type defined in step 1.
- Assign any integer value to the orderid member of the structure.
- Invoke the strcpy function to assign text to the name member of the structure. In order to generate a buffer overflow, assign a larger text to it.
- Display data assigned to the orderid and name members of the structure to confirm if the ambiguous output is generated, which verifies that a buffer overflow has occurred.
The program that shows a vulnerability when copying a string is as follows:
//strcpyproblem.c
#include <stdio.h>
#include <string.h>
struct users {
char name[10];
int orderid;
};
int main(void) {
struct users user1;
char userid[] = "administrator";
user1.orderid = 101;
strcpy(user1.name, userid);
printf("Information of the user - Name %s, Order number %d\n",
user1.name, user1.orderid);
}
Now, let's go behind the scenes to understand the code better.