Skip to content

Possibility for buffer overreads: strncpy drops a null terminator if a target buffer has no trailing space for it #94536

Closed as not planned
@arhadthedev

Description

@arhadthedev

Ubuntu runners give a bunch of warnings:

‘__builtin_strncpy’ specified bound 16 equals destination size [-Wstringop-truncation]

Ivaigult in his answer to gcc-8 -Wstringop-truncation what is the good practice? points out that they're from GCC static analyzer when strncpy target is not terminated manually. A reason is given in https://en.cppreference.com/w/c/string/byte/strncpy:

If count is reached before the entire array src was copied, the resulting character array is not null-terminated.

As a result, every call to strncpy with large enough dynamic source strings causes buffer overread later.

A list of strncpy callers that need to be further analyzed:

C:\Users\oleg\Documents\dev\notmine\cpython>git grep "strncpy("
Modules/_ctypes/darwin/dlfcn_simple.c:        strncpy(errstr, "dlcompat: ", ERR_STR_LEN);
Modules/getpath.c:                    strncpy(modPath, path, MAXPATHLEN);
Modules/socketmodule.c:        strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
Modules/socketmodule.c:                strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
Modules/socketmodule.c:                strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
Modules/socketmodule.c:                strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
Modules/socketmodule.c:                strncpy(info.ctl_name, PyBytes_AS_STRING(ctl_name),
Modules/socketmodule.c:        strncpy((char *)sa->salg_type, type, sizeof(sa->salg_type));
Modules/socketmodule.c:        strncpy((char *)sa->salg_name, name, sizeof(sa->salg_name));
Modules/timemodule.c:    strncpy(zone, p->tm_zone ? p->tm_zone : "   ", n);
Objects/stringlib/find.h:    strncpy(format + len, function_name, FORMAT_BUFFER_SIZE - len - 1);
PC/_msi.c:        strncpy(pccab->szCab, PyBytes_AsString(result), sizeof(pccab->szCab));
Parser/pegen.c:        strncpy(tag, start, len);
Python/getargs.c:            strncpy(msgbuf, "is not retrievable", bufsize);
Python/pystrtod.c:            strncpy(p, float_strings[OFS_INF], 3);
Python/pystrtod.c:            strncpy(p, float_strings[OFS_NAN], 3);
Python/pystrtod.c:        strncpy(p, digits, decpt-0);
Python/pystrtod.c:        strncpy(p, digits+decpt, digits_len-decpt);
Python/pystrtod.c:        strncpy(p, digits, digits_len);

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions