修正 bash 5.3rc2 tmpfile.c 的安全問題

日期: 分類: «shell» 作者: ols3
標籤: ,

Bash 5.3rc2 lib/sh/tmpfile.c 使用了不安全的 mktemp 函式,這個會有 race condition 的問題。

這裡我把它改用 mkstemp,修改如下:

--- lib/sh/tmpfile.c    2025-07-03 13:30:00.000000000 +0800
+++ lib/sh/tmpfile.c    2025-07-03 13:35:00.000000000 +0800
@@ -170,11 +170,17 @@
   if (flags & MT_TEMPLATE)
     strcpy (filename, nameroot);
   else
     snprintf (filename, PATH_MAX, "%s/%s.XXXXXX", tdir, lroot);
-  if (mktemp (filename) == 0)
+  /* Use mkstemp instead of mktemp for security */
+  int fd = mkstemp (filename);
+  if (fd < 0)
     {
       free (filename);
       filename = NULL;
     }
+  else
+    {
+      close (fd);  /* Close the file descriptor since we only need the name */
+    }
 #else  /* !USE_MKTEMP */
 #ifndef USE_URANDOM32
   sh_seedrand ();