user-util: add asserts for buffer allocation overflow safety

Coverity flags ALIGN(sizeof(struct passwd/group)) + bufsize as
potential overflows in the getpw/getgr helpers. Add asserts to
make the bounds explicit for static analyzers.

CID#1548047
CID#1548049
CID#1548069
CID#1548070

Follow-up for 75673cd8ae
This commit is contained in:
Luca Boccassi
2026-03-28 21:12:31 +00:00
parent 55354d5930
commit 02f848b375

View File

@@ -1113,6 +1113,8 @@ int getpwnam_malloc(const char *name, struct passwd **ret) {
for (;;) {
_cleanup_free_ void *buf = NULL;
/* Silence static analyzers */
assert(bufsize <= SIZE_MAX - ALIGN(sizeof(struct passwd)));
buf = malloc0(ALIGN(sizeof(struct passwd)) + bufsize);
if (!buf)
return -ENOMEM;
@@ -1154,6 +1156,8 @@ int getpwuid_malloc(uid_t uid, struct passwd **ret) {
for (;;) {
_cleanup_free_ void *buf = NULL;
/* Silence static analyzers */
assert(bufsize <= SIZE_MAX - ALIGN(sizeof(struct passwd)));
buf = malloc0(ALIGN(sizeof(struct passwd)) + bufsize);
if (!buf)
return -ENOMEM;
@@ -1198,6 +1202,8 @@ int getgrnam_malloc(const char *name, struct group **ret) {
for (;;) {
_cleanup_free_ void *buf = NULL;
/* Silence static analyzers */
assert(bufsize <= SIZE_MAX - ALIGN(sizeof(struct group)));
buf = malloc0(ALIGN(sizeof(struct group)) + bufsize);
if (!buf)
return -ENOMEM;
@@ -1237,6 +1243,8 @@ int getgrgid_malloc(gid_t gid, struct group **ret) {
for (;;) {
_cleanup_free_ void *buf = NULL;
/* Silence static analyzers */
assert(bufsize <= SIZE_MAX - ALIGN(sizeof(struct group)));
buf = malloc0(ALIGN(sizeof(struct group)) + bufsize);
if (!buf)
return -ENOMEM;