How to prevent unprivileged users from viewing dmesg command output on Linux

Iwant to restrict both normal users and root user inside LXD container “hypervisor” from viewing and using dmesg command output. How do I prevent non-root (unprivileged) Linux users from viewing the Linux kernel’s log buffer?

One can use dmesg command see or control the kernel ring buffer. To display all messages from the kernel ring buffer just type the dmesg command:
$ dmesg
OR
$ sudo dmesg
Sample outputs:

Fig.01: dmesg command displaying the Linux kernel ring buffer
Fig.01: dmesg command displaying the Linux kernel ring buffer
It is possible to see more human readable output with the following command:
$ sudo dmesg -H --color

How do I restrict unprivileged access to kernel syslog?

Run the following sysctl command as root user:
$ sudo sysctl -w kernel.dmesg_restrict=1

To view value, run:
$ sysctl kernel.dmesg_restrict
From the Linux kernel docs:
This toggle indicates whether unprivileged users are prevented from using dmesg(8) to view messages from the kernel’s log buffer. When dmesg_restrict is set to (0) there are no restrictions. When dmesg_restrict is set set to (1), users must have CAP_SYSLOG to use dmesg(8). The kernel config option CONFIG_SECURITY_DMESG_RESTRICT sets the default value of dmesg_restrict.
Now unprivileged users will be greeted with the following error message when they run
$ dmesg
Sample outputs:

Why restrict access to to kernel syslog?

From the lwn mailing list:
The kernel syslog contains debugging information that is often useful during exploitation of other vulnerabilities, such as kernel heap addresses. Rather than futilely attempt to sanitize hundreds (or thousands) of printk statements and simultaneously cripple useful debugging functionality, it is far simpler to create an option that prevents unprivileged users from reading the syslog.
This patch, loosely based on grsecurity’s GRKERNSEC_DMESG, creates the dmesg_restrict sysctl. When set to “0”, the default, no restrictions are enforced. When set to “1”, only users with CAP_SYS_ADMIN can read the kernel syslog via dmesg(8) or other mechanisms.

How do I clear the ring buffer?

Type the following command:
$ sudo dmesg --clear
You can also clear the ring buffer after first printing its contents on screen:
$ sudo dmesg --read-clear

How can I disable the printing of messages to the console?

For security reason or to avoid too much message on the console, run:
$ sudo dmesg --console-off
To turn it on again pass the --console-on option:
$ sudo dmesg --console-on

How do I show kernel messages only?

$ sudo dmesg --kernel
To just display userspace messages, run:
$ sudo dmesg --userspace
I suggest you read dmesg man page or type the following command:
$ dmesg -h

Trả lời

Close Menu