How to do it...

We will start by assuming that some important file by the name of file2.txt already exists on your computer and contains some sensitive information. Here are the steps that a malicious user or hacker can use in your program to create a file to overwrite file2.txt:

  1. A file pointer is defined.
  2. The hacker might create a soft link and attach a sensitive file to the file that we want to create.
  3. Open the file to which we want to write the content. But in reality, the sensitive file that is attached to our file will be opened in write-only mode.
  4. Prompt the user to enter the lines of text to be written into the file.
  5. Write the lines entered by the user into the file.
  6. Repeat steps 4 and 5 until the user enters stop.
  7. Close the file pointed to by the file pointer, fp.

Following is the program that a malicious user can use to link some important file to the file that you want to create, and hence can overwrite and destroy that important file on your system:

//fileproblem.c

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

#define BUFFSIZE 255

void main(int argc, char * argv[]) {
FILE * fp;
char str[BUFFSIZE];
if (symlink("file2.txt", "file1.txt") != 0) {
perror("symlink() error");
unlink("file2.txt");
exit(1);
} else {
fp = fopen("file1.txt", "w");
if (fp == NULL) {
perror("An error occurred in creating the file\n");
exit(1);
}
printf("Enter content for the file\n");
gets(str);
while (strcmp(str, "stop") != 0) {
fputs(str, fp);
gets(str);
}
}
fclose(fp);
}

Now, let's go behind the scenes to understand the code better.