Main Content

ISO/IEC TS 17961 [libmod]

Modifying the string returned by getenv, localeconv, setlocale, and strerror

Description

Rule Definition

Modifying the string returned by getenv, localeconv, setlocale, and strerror.1

Polyspace Implementation

This checker checks for Modification of internal buffer returned from nonreentrant standard function.

Examples

expand all

Issue

Modification of internal buffer returned from nonreentrant standard function occurs when the following happens:

  • A nonreentrant standard function returns a pointer.

  • You attempt to write to the memory location that the pointer points to.

Nonreentrant standard functions that return a non const-qualified pointer to an internal buffer include getenv, getlogin, crypt, setlocale, localeconv, strerror and others.

Risk

Modifying the internal buffer that a nonreentrant standard function returns can cause the following issues:

  • It is possible that the modification does not succeed or alters other internal data.

    For instance, getenv returns a pointer to an environment variable value. If you modify this value, you alter the environment of the process and corrupt other internal data.

  • Even if the modification succeeds, it is possible that a subsequent call to the same standard function does not return your modified value.

    For instance, you modify the environment variable value that getenv returns. If another process, thread, or signal handler calls setenv, the modified value is overwritten. Therefore, a subsequent call to getenv does not return your modified value.

Fix

Avoid modifying the internal buffer using the pointer returned from the function.

Example - Modification of getenv Return Value
#include <stdlib.h>
#include <string.h>

void printstr(const char*);

void func() {
    char* env = getenv("LANGUAGE");
    if (env != NULL) {
        strncpy(env, "C", 1);
        printstr(env);
    }
}

In this example, the first argument of strncpy is the return value from a nonreentrant standard function getenv. The behavior can be undefined because strncpy modifies this argument.

Correction - Copy Return Value of getenv and Modify Copy

One possible solution is to copy the return value of getenv and pass the copy to the strncpy function.

#include <stdlib.h>
#include <string.h>
enum {
    SIZE20 = 20
};

void printstr(const char*);

void func() {
    char* env = getenv("LANGUAGE");
    if (env != NULL) {
        char env_cp[SIZE20];
        strncpy(env_cp, env, SIZE20);  
        strncpy(env_cp, "C", 1);        
        printstr(env_cp);
    }
}

Check Information

Decidability: Undecidable

Version History

Introduced in R2019a


1 Extracts from the standard "ISO/IEC TS 17961 Technical Specification - 2013-11-15" are reproduced with the agreement of AFNOR. Only the original and complete text of the standard, as published by AFNOR Editions - accessible via the website www.boutique.afnor.org - has normative value.