为 grub 引导菜单添加密码,防止他人修改启动参数,以 debian 13 为例。

生成密码 #

root@debian:~# grub-mkpasswd-pbkdf2
Enter password:
Reenter password:
PBKDF2 hash of your password is grub.pbkdf2.sha512.10000.xxx

修改 GRUB 脚本 #

/etc/grub.d/40_custom最后添加:

set superusers="root"
password_pbkdf2 root grub.pbkdf2.sha512.10000.xxx

这将为启动菜单增加密码保护,任何对引导条目的编辑 (e) 和 GRUB 命令行 (c) 的访问都需要输入密码才行。

默认情况下,也需要输入密码才能正常启动系统,可以添加--unrestricted选项,这样无需密码就能启动默认菜单,但仍然阻止他人编辑。

编辑/etc/grub.d/10_linux找到以下行:

echo "menuentry '$(echo "$os" | grub_quote)' ${CLASS} \$menuentry_id_option 'gnulinux-simple-$boot_device_id' {" | sed "s/^/$submenu_indentation/"

添加--unrestricted选项:

echo "menuentry '$(echo "$os" | grub_quote)' ${CLASS} --unrestricted \$menuentry_id_option 'gnulinux-simple-$boot_device_id' {" | sed "s/^/$submenu_indentation/"

使更改生效 #

## 备份旧配置
cp /boot/grub/grub.cfg /boot/grub/grub.cfg.bak

## 更新菜单
update-grub2

检查配置:

root@debian:~# git diff /boot/grub/grub.cfg.bak /boot/grub/grub.cfg
diff --git a/boot/grub/grub.cfg.bak b/boot/grub/grub.cfg
index 25f1841..cdf657b 100644
--- a/boot/grub/grub.cfg.bak
+++ b/boot/grub/grub.cfg
@@ -103,7 +103,7 @@ function gfxmode {
 }
 set linux_gfx_mode=
 export linux_gfx_mode
-menuentry 'Debian GNU/Linux' --class debian --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-b5d82a9d-3224-4e20-9f64-d70c3658ea84' {
+menuentry 'Debian GNU/Linux' --class debian --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-simple-b5d82a9d-3224-4e20-9f64-d70c3658ea84' {
        load_video
        insmod gzio
        if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
@@ -186,6 +186,9 @@ fi
 # This file provides an easy way to add custom menu entries.  Simply type the
 # menu entries you want to add after this comment.  Be careful not to change
 # the 'exec tail' line above.
+
+set superusers="root"
+password_pbkdf2 root grub.pbkdf2.sha512.10000.xxx
 ### END /etc/grub.d/40_custom ###

后续升级 grub2 软件包之后,可能需要重复以上操作。