Main Content

CWE Rule 374

Passing Mutable Objects to an Untrusted Method

Since R2023b

Description

Rule Description

The product sends non-cloned mutable data as an argument to a method or function.

Polyspace Implementation

The rule checker checks for the issue Passing private data members to external functions by non-const reference.

Examples

expand all

Issue

This issue occurs when you pass private data members of a class to external functions that take them by non-const reference. External functions include all functions that are not methods of the class.

Risk

Private data members of a class are supposed to be accessed only through class methods. If you pass them to external functions that take them by non-const reference, you leave open the chance that these functions might modify them. Following the function call, the data member values might have changed. Any subsequent code that relies on those data values being unchanged would become incorrect.

Fix

If an external function that takes arguments by non-const reference needs to read private members of a class, instead of passing the members themselves, pass a copy of the members.

Example — Passing Private Members to External Function by Non-const Reference

In this example, the method books::addToInventory() takes its second argument by non-const reference. A private data member aBook of class bookKeeper is passed to this method. After the method is invoked, the private member can no longer be expected to be in the same state as before the invocation.

class book { /* ... */ };

class books
{
public:
    void addToInventory(int, book&);
};

class bookKeeper
{
private:
    int serialNo;
    book aBook;
    books bookSet;
public:
    book getABook();
    void updateBookSet()
    {
        aBook = getABook();
        serialNo++;
        bookSet.addToInventory(serialNo, aBook); //Noncompliant
    }
};

void main()
{
    bookKeeper B;
    B.updateBookSet();
}
Correction — Make Copies of Private Members Before Passing to External Functions

If you need to read a private data member using an external function, pass a copy of this member to the function. In the following corrected example, instead of passing the data member aBook to the external method books::addToInventory(), a local copy copyOfABook is passed.

class book { /* ... */ };

class books
{
public:
    void addToInventory(int, book&);
};

class bookKeeper
{
private:
    int serialNo;
    book aBook;
    books bookSet;
public:
    book getABook();
    void updateBookSet()
    {
        aBook = getABook();
        book copyOfABook = aBook;
        serialNo++;
        bookSet.addToInventory(serialNo, copyOfABook);        
    }
};

void main()
{
    bookKeeper B;
    B.updateBookSet();
}

Check Information

Category: State Issues

Version History

Introduced in R2023b

expand all