Skip to content

Potential buffer-overflow from string operations in function array_from_pyobj of fortranobject.c #19000

@awen-li

Description

@awen-li

Reproducing code example:

Snippet:

    char mess[200];
    if ((intent & F2PY_INTENT_HIDE)
        || ((intent & F2PY_INTENT_CACHE) && (obj==Py_None))
        || ((intent & F2PY_OPTIONAL) && (obj==Py_None))
        ) {
        /* intent(cache), optional, intent(hide) */
        if (count_negative_dimensions(rank,dims) > 0) {
            int i;
            strcpy(mess, "failed to create intent(cache|hide)|optional array"
                   "-- must have defined dimensions but got (");  ----> 91 chars copied into mess
            for(i=0;i<rank;++i)
                sprintf(mess+strlen(mess),"%" NPY_INTP_FMT ",",dims[i]);  ----> max of rank is F2PY_MAX_DIMS (40), and all values of dims could be -1. Given the format "%d," ("-1,"), max length of this part could be 40*3=120 + 91 > 200
            strcat(mess, ")");
            PyErr_SetString(PyExc_ValueError,mess);
            return NULL;
        }
        arr = (PyArrayObject *)
            PyArray_New(&PyArray_Type, rank, dims, type_num,
                        NULL,NULL,1,
                        !(intent&F2PY_INTENT_C),
                        NULL);
        if (arr==NULL) return NULL;
        if (!(intent & F2PY_INTENT_CACHE))
            PyArray_FILLWBYTE(arr, 0);
        return arr;
    }

Error message:

File: numpy/f2py/src/fortranobject.c
Function: array_from_pyobj (line 724 : 733)
Optional call-path: External -> fortran_setattr -> array_from_pyobj
Details in description

When we run our analysis tool on NumPy, a few Inappropriate string operations are reported at call sites of function strcpy, sprintf, and strcat in array_from_pyobj. There are no boundary checks at these points despite "mess" seems large enough to ensure the operations safe except for the point shown above.
As a suggestion, it is better to replace these functions with strncpy, strncat, and snprintf.

NumPy/Python version information:

the main branch of NumPy

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions