A file pointer is defined by the name fp. At this stage, a hacker or malicious user might invoke the symlink function to create a soft link named file1.txt to the file named file2.txt. In this program, file2.txt can be replaced by the password file or some other sensitive file that the malicious user may want to overwrite or destroy.
Because the program is for creating a new file, the program invokes the fopen function to open file1.txt in write-only mode and the opened file will be pointed at by fp, the file pointer. But because file1.txt and file2.txt are linked, file2.txt will be actually opened instead of file1.txt, and in write-only mode, and will be pointed at by the file pointer, fp. The program will terminate if the file cannot be opened in write-only mode or some other error occurs.
The user is prompted to enter lines of text for the file. The lines entered by the user are assigned to the str string. The fputs function is invoked to write the content assigned to the str string into the file pointed at by the file pointer, fp. Consequently, the sensitive file will be overwritten. The user can enter as many lines of text as desired and can enter stop when they are done. So a while loop is set to execute that will keep taking lines of text from the user and will keep writing them into the file until stop is entered. Finally, the file pointed to by the file pointer, fp, is closed.
Let's use GCC to compile the fileproblem.c program as shown in the following screenshot. If you get no errors or warnings, it means the fileproblem.c program has compiled into an executable file: fileproblem.exe. Let's run this file:
The preceding text will not go into the desired file, file1.txt, but will overwrite the sensitive file, file2.txt, deleting its earlier content, if any. If we look at the content of the file2.txt file, we will see the content that was supposed to be written into file1.txt:
Now, let's rewrite the program to remove the file vulnerabilities.