Main Content

Misuse of a FILE object

Use of copy of FILE object

Description

This defect occurs when:

  • You dereference a pointer to a FILE object, including indirect dereference by using memcmp().

  • You modify an entire FILE object or one of its components through its pointer.

  • You take the address of FILE object that was not returned from a call to an fopen-family function. No defect is raised if a macro defines the pointer as the address of a built-in FILE object, such as #define ptr (&__stdout).

Risk

In some implementations, the address of the pointer to a FILE object used to control a stream is significant. A pointer to a copy of a FILE object is interpreted differently than a pointer to the original object, and can potentially result in operations on the wrong stream. Therefore, the use of a copy of a FILE object can cause the software to stop responding, which an attacker might exploit in denial-of-service attacks.

Fix

Do not make a copy of a FILE object. Do not use the address of a FILE object that was not returned from a successful call to an fopen-family function.

Examples

expand all

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

void fatal_error(void);

int func(void)
{
	/*'stdout' dereferenced and contents
        copied to 'my_stdout'. */
    FILE my_stdout = *stdout;  
	
	/* Address of 'my_stdout' may not point to correct stream. */
    if (fputs("Hello, World!\n", &my_stdout) == EOF)  
    {
        /* Handler error */
        fatal_error();
    }
    return 0;
}
        
      

In this example, FILE object stdout is dereferenced and its contents are copied to my_stdout. The contents of stdout might not be significant. fputs() is then called with the address of my_stdout as an argument. Because no call to fopen() or a similar function was made, the address of my_stdout might not point to the correct stream.

Correction — Copy the FILE Object Pointer

Declare my_stdout to point to the same address as stdout to ensure that you write to the correct stream when you call fputs().

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

void fatal_error(void);

int func(void)
{
	/* 'my_stdout' and 'stdout' point to the same object. */
    FILE *my_stdout = stdout;  
    if (fputs("Hello, World!\n", my_stdout) == EOF)
    {
        /* Handler error */
        fatal_error();
    }
    return 0;
} 

Result Information

Group: Programming
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: FILE_OBJECT_MISUSE
Impact: Low

Version History

Introduced in R2017b