The following issues were found

numpy/random/_examples/cffi/extending.py
4 issues
Attempted relative import beyond top-level package
Error

Line: 7 Column: 1

              import os
import numpy as np
import cffi
from .parse import parse_distributions_h
ffi = cffi.FFI()

inc_dir = os.path.join(np.get_include(), 'numpy')

# Basic numpy types

            

Reported by Pylint.

Access to a protected member _generator of a client class
Error

Line: 21 Column: 18

              
parse_distributions_h(ffi, inc_dir)

lib = ffi.dlopen(np.random._generator.__file__)

# Compare the distributions.h random_standard_normal_fill to
# Generator.standard_random
bit_gen = np.random.PCG64()
rng = np.random.Generator(bit_gen)

            

Reported by Pylint.

Constant name "n" doesn't conform to UPPER_CASE naming style
Error

Line: 30 Column: 1

              state = bit_gen.state

interface = rng.bit_generator.cffi
n = 100
vals_cffi = ffi.new('double[%d]' % n)
lib.random_standard_normal_fill(interface.bit_generator, n, vals_cffi)

# reset the state
bit_gen.state = state

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 40
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              vals = rng.standard_normal(n)

for i in range(n):
    assert vals[i] == vals_cffi[i]

            

Reported by Bandit.

numpy/ma/setup.py
4 issues
Redefining name 'config' from outer scope (line 11)
Error

Line: 4 Column: 5

              #!/usr/bin/env python3
def configuration(parent_package='',top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('ma', parent_package, top_path)
    config.add_subpackage('tests')
    config.add_data_files('*.pyi')
    return config

if __name__ == "__main__":

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3
def configuration(parent_package='',top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('ma', parent_package, top_path)
    config.add_subpackage('tests')
    config.add_data_files('*.pyi')
    return config

if __name__ == "__main__":

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 2 Column: 1

              #!/usr/bin/env python3
def configuration(parent_package='',top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('ma', parent_package, top_path)
    config.add_subpackage('tests')
    config.add_data_files('*.pyi')
    return config

if __name__ == "__main__":

            

Reported by Pylint.

Import outside toplevel (numpy.distutils.misc_util.Configuration)
Error

Line: 3 Column: 5

              #!/usr/bin/env python3
def configuration(parent_package='',top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('ma', parent_package, top_path)
    config.add_subpackage('tests')
    config.add_data_files('*.pyi')
    return config

if __name__ == "__main__":

            

Reported by Pylint.

numpy/core/src/multiarray/array_method.c
4 issues
strcpy - Does not check for buffer overflows when copying to destination [MS-banned]
Security

Line: 443 Column: 5 CWE codes: 120
Suggestion: Consider using snprintf, strcpy_s, or strlcpy (warning: strncpy easily misused)

                      PyErr_NoMemory();
        return NULL;
    }
    strcpy(res->method->name, spec->name);

    return res;
}



            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 640 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                  PyArray_Descr *out_descrs[NPY_MAXARGS];
    Py_ssize_t length = -1;
    int aligned = 1;
    char *args[NPY_MAXARGS];
    npy_intp strides[NPY_MAXARGS];
    int nin = self->method->nin;
    int nout = self->method->nout;

    if (!PyTuple_CheckExact(arr_tuple) ||

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 802 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  NpyAuxData *strided_loop_auxdata = auxdata->unmasked_auxdata;

    char **dataptrs = auxdata->dataptrs;
    memcpy(dataptrs, data, nargs * sizeof(char *));
    char *mask = data[nargs];
    npy_intp mask_stride = strides[nargs];

    npy_intp N = dimensions[0];
    /* Process the data as runs of unmasked values */

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 436 Column: 25 CWE codes: 126

                      return NULL;
    }

    Py_ssize_t length = strlen(spec->name);
    res->method->name = PyMem_Malloc(length + 1);
    if (res->method->name == NULL) {
        Py_DECREF(res);
        PyErr_NoMemory();
        return NULL;

            

Reported by FlawFinder.

tools/ci/push_docs_to_repo.py
4 issues
Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3

import argparse
import subprocess
import tempfile
import os
import sys
import shutil


            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

Line: 4
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess

              #!/usr/bin/env python3

import argparse
import subprocess
import tempfile
import os
import sys
import shutil


            

Reported by Bandit.

Missing function or method docstring
Error

Line: 35 Column: 1

                  sys.exit(1)


def run(cmd, stdout=True):
    pipe = None if stdout else subprocess.DEVNULL
    try:
        subprocess.check_call(cmd, stdout=pipe, stderr=pipe)
    except subprocess.CalledProcessError:
        print("\n! Error executing: `%s;` aborting" % ' '.join(cmd))

            

Reported by Pylint.

subprocess call - check for execution of untrusted input.
Security injection

Line: 38
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html

              def run(cmd, stdout=True):
    pipe = None if stdout else subprocess.DEVNULL
    try:
        subprocess.check_call(cmd, stdout=pipe, stderr=pipe)
    except subprocess.CalledProcessError:
        print("\n! Error executing: `%s;` aborting" % ' '.join(cmd))
        sys.exit(1)



            

Reported by Bandit.

numpy/typing/tests/data/fail/array_like.py
4 issues
Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
from numpy.typing import ArrayLike


class A:
    pass


x1: ArrayLike = (i for i in range(10))  # E: Incompatible types in assignment

            

Reported by Pylint.

Missing class docstring
Error

Line: 5 Column: 1

              from numpy.typing import ArrayLike


class A:
    pass


x1: ArrayLike = (i for i in range(10))  # E: Incompatible types in assignment
x2: ArrayLike = A()  # E: Incompatible types in assignment

            

Reported by Pylint.

Class name "A" doesn't conform to PascalCase naming style
Error

Line: 5 Column: 1

              from numpy.typing import ArrayLike


class A:
    pass


x1: ArrayLike = (i for i in range(10))  # E: Incompatible types in assignment
x2: ArrayLike = A()  # E: Incompatible types in assignment

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 5 Column: 1

              from numpy.typing import ArrayLike


class A:
    pass


x1: ArrayLike = (i for i in range(10))  # E: Incompatible types in assignment
x2: ArrayLike = A()  # E: Incompatible types in assignment

            

Reported by Pylint.

numpy/core/src/multiarray/datetime_strings.c
4 issues
_snprintf - If format strings can be influenced by an attacker, they can be exploited, and note that sprintf variations do not always \0-terminate
Security

Line: 1012 Column: 14 CWE codes: 134
Suggestion: Use a constant for the format specification

                   * to have data all the way to the end of the buffer.
     */
#ifdef _WIN32
    tmplen = _snprintf(substr, sublen, "%04" NPY_INT64_FMT, dts->year);
#else
    tmplen = snprintf(substr, sublen, "%04" NPY_INT64_FMT, dts->year);
#endif
    /* If it ran out of space or there isn't space for the NULL terminator */
    if (tmplen < 0 || tmplen > sublen) {

            

Reported by FlawFinder.

snprintf - If format strings can be influenced by an attacker, they can be exploited, and note that sprintf variations do not always \0-terminate
Security

Line: 1014 Column: 14 CWE codes: 134
Suggestion: Use a constant for the format specification

              #ifdef _WIN32
    tmplen = _snprintf(substr, sublen, "%04" NPY_INT64_FMT, dts->year);
#else
    tmplen = snprintf(substr, sublen, "%04" NPY_INT64_FMT, dts->year);
#endif
    /* If it ran out of space or there isn't space for the NULL terminator */
    if (tmplen < 0 || tmplen > sublen) {
        goto string_too_short;
    }

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 96 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      func_name = "localtime";
        goto fail;
    }
    memcpy(tms, tms_tmp, sizeof(struct tm));
 #endif
#else
    if (localtime_r(ts, tms) == NULL) {
        func_name = "localtime_r";
        goto fail;

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 1565 Column: 47 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                          /* Zero the destination string completely */
            memset(dataptr[1], 0, strsize);
            /* Convert that into a string */
            if (make_iso_8601_datetime(&dts, (char *)dataptr[1], strsize,
                                local, utc, unit, tzoffset, casting) < 0) {
                goto fail;
            }
        } while(iternext(iter));
    }

            

Reported by FlawFinder.

numpy/core/tests/data/generate_umath_validation_data.cpp
4 issues
random - This function is not sufficiently random for security-related functions such as key and nonce creation
Security

Line: 6 Column: 10 CWE codes: 327
Suggestion: Use a more secure technique for acquiring random values

              #include<iostream>
#include<algorithm>
#include<vector>
#include<random>
#include<fstream>
#include<time.h>

struct ufunc {
    std::string name;

            

Reported by FlawFinder.

random - This function is not sufficiently random for security-related functions such as key and nonce creation
Security

Line: 22 Column: 11 CWE codes: 327
Suggestion: Use a more secure technique for acquiring random values

              T RandomFloat(T a, T b) {
    T random = ((T) rand()) / (T) RAND_MAX;
    T diff = b - a;
    T r = random * diff;
    return a + r;
}

template<typename T>
void append_random_array(std::vector<T>& arr, T min, T max, size_t N)

            

Reported by FlawFinder.

srand - This function is not sufficiently random for security-related functions such as key and nonce creation
Security

Line: 102 Column: 5 CWE codes: 327
Suggestion: Use a more secure technique for acquiring random values

              }

int main() {
    srand (42);
    std::vector<struct ufunc> umathfunc = {
        {"sin",sin,sin,2.37,3.3},
        {"cos",cos,cos,2.36,3.38},
        {"tan",tan,tan,3.91,3.93},
        {"arcsin",asin,asin,3.12,2.55},

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 131 Column: 20 CWE codes: 362

                      if ((umathfunc[ii].name != "sin") && (umathfunc[ii].name != "cos")) {
            std::string fileName = "umath-validation-set-" + umathfunc[ii].name + ".csv";
            std::ofstream txtOut;
            txtOut.open (fileName, std::ofstream::trunc);
            txtOut << "dtype,input,output,ulperrortol" << std::endl;

            // Single Precision
            auto f32in = generate_input_vector<float>(umathfunc[ii].name);
            auto f32out = computeTrueVal<float, double>(f32in, umathfunc[ii].f32func);

            

Reported by FlawFinder.

numpy/core/tests/_locales.py
4 issues
Unable to import 'pytest'
Error

Line: 7 Column: 1

              import sys
import locale

import pytest

__ALL__ = ['CommaDecimalPointLocale']


def find_comma_decimal_point_locale():

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 73 Column: 24

                          pytest.skip("No French locale available")
        locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)

    def __exit__(self, type, value, traceback):
        locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 60 Column: 5

                  """
    (cur_locale, tst_locale) = find_comma_decimal_point_locale()

    def setup(self):
        if self.tst_locale is None:
            pytest.skip("No French locale available")
        locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)

    def teardown(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 65 Column: 5

                          pytest.skip("No French locale available")
        locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)

    def teardown(self):
        locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)

    def __enter__(self):
        if self.tst_locale is None:
            pytest.skip("No French locale available")

            

Reported by Pylint.

numpy/core/src/umath/umathmodule.c
4 issues
strcpy - Does not check for buffer overflows when copying to destination [MS-banned]
Security

Line: 205 Column: 5 CWE codes: 120
Suggestion: Consider using snprintf, strcpy_s, or strlcpy (warning: strncpy easily misused)

                      Py_DECREF(tmp);
        return PyErr_NoMemory();
    }
    strcpy(newdocstr, docstr);
    ufunc->doc = newdocstr;

    Py_DECREF(tmp);
    Py_RETURN_NONE;
}

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 145 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      types[i] = NPY_OBJECT;
    }
    str = types + offset[1];
    memcpy(str, fname, fname_len);
    memcpy(str+fname_len, " (vectorized)", 14);
    Py_XDECREF(pyname);

    /* Do a better job someday */
    doc = "dynamic ufunc based on a python function";

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 146 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  }
    str = types + offset[1];
    memcpy(str, fname, fname_len);
    memcpy(str+fname_len, " (vectorized)", 14);
    Py_XDECREF(pyname);

    /* Do a better job someday */
    doc = "dynamic ufunc based on a python function";


            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 200 Column: 30 CWE codes: 126

                   * this should not be a problem since the user would have to
     * repeatedly create, document, and throw away ufuncs.
     */
    char *newdocstr = malloc(strlen(docstr) + 1);
    if (!newdocstr) {
        Py_DECREF(tmp);
        return PyErr_NoMemory();
    }
    strcpy(newdocstr, docstr);

            

Reported by FlawFinder.

numpy/matrixlib/setup.py
4 issues
Redefining name 'config' from outer scope (line 11)
Error

Line: 4 Column: 5

              #!/usr/bin/env python3
def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('matrixlib', parent_package, top_path)
    config.add_subpackage('tests')
    config.add_data_files('*.pyi')
    return config

if __name__ == "__main__":

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3
def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('matrixlib', parent_package, top_path)
    config.add_subpackage('tests')
    config.add_data_files('*.pyi')
    return config

if __name__ == "__main__":

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 2 Column: 1

              #!/usr/bin/env python3
def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('matrixlib', parent_package, top_path)
    config.add_subpackage('tests')
    config.add_data_files('*.pyi')
    return config

if __name__ == "__main__":

            

Reported by Pylint.

Import outside toplevel (numpy.distutils.misc_util.Configuration)
Error

Line: 3 Column: 5

              #!/usr/bin/env python3
def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('matrixlib', parent_package, top_path)
    config.add_subpackage('tests')
    config.add_data_files('*.pyi')
    return config

if __name__ == "__main__":

            

Reported by Pylint.