Skip to content

[Code scan] Validate cube read success before copying charge data #7563

Description

@njzjz

This issue is a result of a Codex global repository scan.

read_cube() returns bool, but read_cube.cpp ignores that result and assumes dimensions and data are valid. A malformed or truncated cube file can leave invalid dimensions or an undersized data_read vector, after which the caller copies/interpolates from data_read.data().

Caller ignoring the result:

// we've already checked the file existence, so we don't need the returned value here
ModuleIO::read_cube(fn, comment, natom, origin, nx_read, ny_read, nz_read,
dx, dy, dz, atom_type, atom_charge, atom_pos, data_read);
// if mismatch, trilinear interpolate
if (nx == nx_read && ny == ny_read && nz == nz_read)
{
std::memcpy(data_xyz_full.data(), data_read.data(), nxyz * sizeof(double));
}
else
{
trilinear_interpolate(data_read.data(), nx_read, ny_read, nz_read, nx, ny, nz, data_xyz_full.data());

Parser reads dimensions/data without checking each extraction:

ifs >> natom;
origin.resize(3);
for (auto& cp : origin)
{
ifs >> cp;
}
dx.resize(3);
dy.resize(3);
dz.resize(3);
ifs >> nx >> dx[0] >> dx[1] >> dx[2];
ifs >> ny >> dy[0] >> dy[1] >> dy[2];
ifs >> nz >> dz[0] >> dz[1] >> dz[2];
atom_type.resize(natom);
atom_charge.resize(natom);
atom_pos.resize(natom, std::vector<double>(3));
for (int i = 0;i < natom;++i)
{
ifs >> atom_type[i] >> atom_charge[i] >> atom_pos[i][0] >> atom_pos[i][1] >> atom_pos[i][2];
}
const int nxyz = nx * ny * nz;
data.resize(nxyz);
for (int i = 0;i < nxyz;++i)
{
ifs >> data[i];

Relevant code:

ModuleIO::read_cube(fn, comment, natom, origin, nx_read, ny_read, nz_read, 
    dx, dy, dz, atom_type, atom_charge, atom_pos, data_read);

if (nx == nx_read && ny == ny_read && nz == nz_read)
{
    std::memcpy(data_xyz_full.data(), data_read.data(), nxyz * sizeof(double));
}
else
{
    trilinear_interpolate(data_read.data(), nx_read, ny_read, nz_read, nx, ny, nz, data_xyz_full.data());
}

Suggested fix:

Check the read_cube() return value and validate positive dimensions, nonnegative atom count, nx * ny * nz overflow, and that all expected data values were read before copying or interpolating.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    Status
    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions