kmodloader: fix TOCTOU problem with scan_builtin_modules
authorChristian Marangi <ansuelsmth@gmail.com>
Mon, 22 Jan 2024 00:13:11 +0000 (01:13 +0100)
committerChristian Marangi <ansuelsmth@gmail.com>
Mon, 22 Jan 2024 00:20:57 +0000 (01:20 +0100)
Fix TOCTOU problem with scan_builtin_modules by opening the file pointer
only once in module_folders scan.

Fix Coverity Report CID 1586645:  Security best practices violations
(TOCTOU).

Signed-off-by: Christian Marangi <ansuelsmth@gmail.com>
kmodloader.c

index 43105b38adea37a86df77caf55c65b385466ec13..373694278217411186387f558431c37a060446ea 100644 (file)
@@ -502,11 +502,16 @@ static int scan_builtin_modules(void)
                return -1;
        for (p = module_folders; *p; p++) {
                snprintf(path, sizeof(path), "%s%s", *p, MOD_BUILTIN);
-               if (!stat(path, &st) && S_ISREG(st.st_mode)) {
-                       fp = fopen(path, "r");
-                       if (fp)
-                               break;
-               }
+               fp = fopen(path, "r");
+               if (!fp)
+                       continue;
+
+               if (!fstat(fileno(fp), &st) && S_ISREG(st.st_mode))
+                       break;
+
+               /* Not regular file, close it and check next */
+               fclose(fp);
+               fp = NULL;
        }
        if (!fp)
                return 0;       /* OK if modules.builtin unavailable */