From: Theodore Ts'o Date: Mon, 26 May 2025 14:09:59 +0000 (-0400) Subject: libe2p: avoid potential integer overflow in interate_on_dir() X-Git-Tag: v1.47.3-rc1~17 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=3a4bbc5cd5baff73d85306f6c4f18cf36d85636d;p=thirdparty%2Fe2fsprogs.git libe2p: avoid potential integer overflow in interate_on_dir() Overflows won't happen if the OS's implementation of pathconf() returns reasonable values, but we can make it a bit more hardened against maliciou implementations. Addresses-Coverity-Bug: 1633758 Signed-off-by: Theodore Ts'o --- diff --git a/lib/e2p/iod.c b/lib/e2p/iod.c index 6a030dd4..5e076544 100644 --- a/lib/e2p/iod.c +++ b/lib/e2p/iod.c @@ -24,30 +24,32 @@ #include #include +#define max_long(a,b) ((((long) (a)) > ((long) (b))) ? (a) : (b)) + int iterate_on_dir (const char * dir_name, int (*func) (const char *, struct dirent *, void *), void * private) { DIR * dir; struct dirent *de, *dep; - int max_len = -1, len, ret = 0; + long name_max = -1; + int max_len, len, ret = 0; #if HAVE_PATHCONF && defined(_PC_NAME_MAX) - max_len = pathconf(dir_name, _PC_NAME_MAX); + name_max = pathconf(dir_name, _PC_NAME_MAX); #endif - if (max_len == -1) { #ifdef _POSIX_NAME_MAX - max_len = _POSIX_NAME_MAX; -#else + name_max = max_long(name_max, _POSIX_NAME_MAX); +#endif #ifdef NAME_MAX - max_len = NAME_MAX; -#else - max_len = 256; -#endif /* NAME_MAX */ -#endif /* _POSIX_NAME_MAX */ - } - max_len += sizeof(struct dirent); + name_max = max_long(name_max, NAME_MAX); +#endif + name_max = max_long(name_max, 256); + /* clamp name_max in case the OS returns something crazy */ + if (name_max > 65536) + name_max = 65536; + max_len = name_max + sizeof(struct dirent); de = malloc(max_len+1); if (!de) return -1;