Linux blacklist kernel module

Как занести в черный список модули ядра?

Как отключить загрузку ненужных модулей ядра. Ядро 3.2.4

5 ответов

Примечание: внесение в черный список не будет работать для модулей, которые встроены в образ ядра (т.е. не загружаются через отдельный .ko файл. Единственный способ отключить такие модули — через параметр ядра (если есть) или перекомпиляцию ядра.

Просто открой свой /etc/modprobe.d/blacklist файл и добавить drivername, используя следующий синтаксис:

РЕДАКТИРОВАТЬ: В более поздних версиях с 12.10 (12.04?) Файл /etc/modprobe.d/blacklist.conf

Перезагрузите ваш компьютер и используйте команду lsmod, чтобы показать состояние модулей в ядре Linux.

Примечание: здесь driver-name имя желаемого драйвера черного списка. Например, если вы хотите отключить драйвер сетевой карты, вы можете найти имя драйвера ядра для вашей сетевой карты, используя команду lspci -v команда в терминале.
Например, мой вывод был:

Здесь я вижу драйвер tg3 , так что вам нужно написать tg3 (или ваш водитель) вместо driver-name ,

Много информации можно найти здесь.

Вы также можете временно поместить их в черный список в командной строке grub (linux line) при загрузке с синтаксисом

Другой способ занести в черный список модули как минимум в Ubuntu 16.04 LTS — добавить следующую строку в командную строку ядра:

Использование системы /etc/modprobe — лучший способ, но это альтернатива, которая может быть использована в крайнем случае путем редактирования командной строки GRUB при загрузке.

Это также можно сделать постоянным, отредактировав /etc/default/grub и добавив в GRUB_CMDLINE_LINUX_DEFAULT переменная. Например, в моем /etc/default/grub у меня есть:

Тогда я бегу update-grub2 , затем update-initramfs -u , После перезагрузки вы будете свободны от модуля, если после загрузки ничего не загружается.

Этот метод также работает в вариантах EL (RHEL, CentOS, SciLinux), но вам придется использовать методы этого дистрибутива для обновления grub и initrd.

Источник

Kernel module

Kernel modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system.

To create a kernel module, you can read The Linux Kernel Module Programming Guide. A module can be configured as built-in or loadable. To dynamically load or remove a module, it has to be configured as a loadable module in the kernel configuration (the line related to the module will therefore display the letter M ).

Contents

Obtaining information

Modules are stored in /usr/lib/modules/kernel_release . You can use the command uname -r to get your current kernel release version.

To show what kernel modules are currently loaded:

To show information about a module:

To list the options that are set for a loaded module:

To display the comprehensive configuration of all the modules:

To display the configuration of a particular module:

List the dependencies of a module (or alias), including the module itself:

Automatic module loading with systemd

Today, all necessary modules loading is handled automatically by udev, so if you do not need to use any out-of-tree kernel modules, there is no need to put modules that should be loaded at boot in any configuration file. However, there are cases where you might want to load an extra module during the boot process, or blacklist another one for your computer to function properly.

Kernel modules can be explicitly listed in files under /etc/modules-load.d/ for systemd to load them during boot. Each configuration file is named in the style of /etc/modules-load.d/program.conf . Configuration files simply contain a list of kernel modules names to load, separated by newlines. Empty lines and lines whose first non-whitespace character is # or ; are ignored.

See modules-load.d(5) for more details.

Manual module handling

Kernel modules are handled by tools provided by kmod package. You can use these tools manually.

Читайте также:  Astra linux доменный пользователь не входит

To load a module:

To load a module by filename (i.e. one that is not installed in /usr/lib/modules/$(uname -r)/ ):

To unload a module:

Setting module options

To pass a parameter to a kernel module, you can pass them manually with modprobe or assure certain parameters are always applied using a modprobe configuration file or by using the kernel command line.

Manually at load time using modprobe

The basic way to pass parameters to a module is using the modprobe command. Parameters are specified on command line using simple key=value assignments:

Using files in /etc/modprobe.d/

Files in /etc/modprobe.d/ directory can be used to pass module settings to udev, which will use modprobe to manage the loading of the modules during system boot. Configuration files in this directory can have any name, given that they end with the .conf extension. The syntax is:

Using kernel command line

If the module is built into the kernel, you can also pass options to the module using the kernel command line. For all common bootloaders, the following syntax is correct:

Simply add this to your bootloader’s kernel-line, as described in Kernel Parameters.

Aliasing

Aliases are alternate names for a module. For example: alias my-mod really_long_modulename means you can use modprobe my-mod instead of modprobe really_long_modulename . You can also use shell-style wildcards, so alias my-mod* really_long_modulename means that modprobe my-mod-something has the same effect. Create an alias:

Some modules have aliases which are used to automatically load them when they are needed by an application. Disabling these aliases can prevent automatic loading but will still allow the modules to be manually loaded.

Blacklisting

Blacklisting, in the context of kernel modules, is a mechanism to prevent the kernel module from loading. This could be useful if, for example, the associated hardware is not needed, or if loading that module causes problems: for instance there may be two kernel modules that try to control the same piece of hardware, and loading them together would result in a conflict.

Some modules are loaded as part of the initramfs. mkinitcpio -M will print out all automatically detected modules: to prevent the initramfs from loading some of those modules, blacklist them in a .conf file under /etc/modprobe.d and it shall be added in by the modconf hook during image generation. Running mkinitcpio -v will list all modules pulled in by the various hooks (e.g. filesystems hook, block hook, etc.). Remember to add that .conf file to the FILES array in /etc/mkinitcpio.conf if you do not have the modconf hook in your HOOKS array (e.g. you have deviated from the default configuration), and once you have blacklisted the modules regenerate the initramfs, and reboot afterwards.

Using files in /etc/modprobe.d/

Create a .conf file inside /etc/modprobe.d/ and append a line for each module you want to blacklist, using the blacklist keyword. If for example you want to prevent the pcspkr module from loading:

However, there is a workaround for this behaviour; the install command instructs modprobe to run a custom command instead of inserting the module in the kernel as normal, so you can force the module to always fail loading with:

This will effectively blacklist that module and any other that depends on it.

Using kernel command line

You can also blacklist modules from the bootloader.

Simply add module_blacklist=modname1,modname2,modname3 to your bootloader’s kernel line, as described in Kernel parameters.

Troubleshooting

Modules do not load

In case a specific module does not load and the boot log (accessible by running journalctl -b as root) says that the module is blacklisted, but the directory /etc/modprobe.d/ does not show a corresponding entry, check another modprobe source folder at /usr/lib/modprobe.d/ for blacklisting entries.

A module will not be loaded if the «vermagic» string contained within the kernel module does not match the value of the currently running kernel. If it is known that the module is compatible with the current running kernel the «vermagic» check can be ignored with modprobe —force-vermagic .

Источник

Kernel hardening: Disable and blacklist Linux modules

Disable and black Linux kernel modules

The Linux kernel is modular, which makes it more flexible than monolithic kernels. New functionality can be easily added to a run kernel, by loading the related module. While that is great, it can also be misused. You can think of loading malicious modules (e.g. rootkits), or unauthorized access to the server and copy data via a USB port. In our previous article about kernel modules, we looked at how to prevent loading any module. In this case, we specifically disallow the ones we don’t want.

Читайте также:  Наилучший архиватор для mac os

Blacklisting modules

Blacklisting modules is one way to disallow them. This defines which modules should no longer be loaded. However, it will only limit the loading of modules during the boot process. You can still load a module manually after booting.

Blacklisting a module is simple. Create a file in the /etc/modprobe.d directory and give it a proper name (e.g. blacklist-module.conf).

Blacklisting firewire

Let’s say we want to blacklist firewire. We first have to determine what modules are available. By using find, we can quickly determine the related kernel drivers:

Now we know there are multiple modules, most part of the drivers and one in the sound section. If we want to disable all these modules, we could simply blacklist them all. Or block the generic category.

Gathering module information

By using modinfo, we can gather the details about a particular module. In this case, we have a look at the snd-firewire-lib module and see what it does:

modinfo shows on which a module depends

We can see it depends on firewire-core. Let’s have a look at the firewire-core module itself:

Details of firewire core module

The details of the firewire-core module show that is responsible for firewire itself. It is the core unit itself and doing the transaction logic within the IEEE1394 protocol specifications. We can see it is depending on the CRC-ITU-T standard.

By blacklisting the firewire-core, we effectively disable any module depending on it. In this case, we don’t blacklist the crc-itu-t module, to prevent other modules from properly functioning.

The related snippet to blacklist would be:

/etc/modprobe.d/blacklist-firewire.conf

See blacklisted modules

To see what modules are currently blacklisted, we can use the modprobe command:

This will show all modules which are blacklisted.

Disable modules

The next level of blacklisting modules is to actually disable them. This way they won’t be loaded unintentionally.

To disable a module, we have to redirect a module via the install option. Modprobe will try to load the related file. By defining a module as /bin/true, it won’t be loaded.

Using the install option we can avoid loading modules

To see what modules are currently disabled via install, we can use modprobe as well:

Note: the root user can still override settings, by using the –ignore-install parameter. In that case, the module can still be loaded.

Besides the install routine, there is also an alias option. This might be used to redirect a module to /dev/null for example.

Conclusion

By using the right combination of blacklist, install and alias, we can disallow the loading of Linux kernel modules. They form the first level of defense against unintentional and unauthorized module loading. By using the kernel setting kernel.modules_disabled and set its value to 1, we can make sure things are really tightened. Even the root user can not load any modules anymore.

Useful commands

When working with kernel modules, here are some of the most common commands:

  • Blacklisted and disabled modules
    • modprobe –showconfig | egrep “^(blacklist|install)”
  • Find modules
    • find /lib/modules/`uname -r` -print
  • Show loaded modules
    • lsmod
  • Load module
    • modprobe module
  • Unload module
    • modprobe -r module
  • Module details
    • modinfo module

Questions or other tips? Share it in the comments.

Keep learning

So you are interested in Linux security? Join the Linux Security Expert training program, a practical and lab-based training ground. For those who want to become (or stay) a Linux security expert.

Run automated security scans and increase your defenses. Lynis is an open source security tool to perform in-depth audits. It helps with system hardening, vulnerability discovery, and compliance.

Источник

5 easy steps to blacklist kernel module in CentOS RHEL 7 8

Table of Contents

In this article I will shares the steps to disable kernel module and also blacklist kernel module in RHEL/CentOS 7 and 8 Linux. You can disable kernel module runtime using » modprobe -r » and to blacklist kernel module you can use /etc/modprobe.d/local-blacklist.conf

We will analyse both the options to blacklist kernel module in detail, in this example we will blacklist btrfs module from our RHEL/CentOS 7 and 8 Linux node.

Check if module is loaded in kernel

Before you choose to blacklist kernel module, check if the respective module is loaded in the kernel.
You can use lsmod to list all the loaded modules and try to grep for your module name.

Читайте также:  Накопительное обновление для windows 10 version 1507

Alternatively you can also use modinfo to query a kernel module

In my case the btrfs module is loaded which I can also verify using /var/log/messages

Step 1: Disable kernel module run time

To unload kernel module run time we can use modprobe —remove

In this example modprobe has unload btrfs and all dependency modules . But this will disable kernel module only for the current session, after reboot it is possible that btrfs may load again.

Step 2: Blacklist kernel module

Next to blacklist kernel module btrfs , we will create a new file btrfs-blacklist.conf under /etc/modprobe.d/

  • The name of the blacklist file is not important, and you can use any name based on your requirement.
  • The install line simply causes /bin/false to be run instead of installing a module.
  • This change will take effect the next time that the module is attempted to load. (A node reboot is not required at this stage)
  • There may be unexpected side effects if a module is blacklisted that is required for other specific hardware.

Below is the content of my btrfs-blacklist.conf

These steps may work most of the time to blacklist kernel module in Linux but in some sporadic scenarios, it is possible that some kernel modules will still attempt to load optional modules on demand.

Hence we must properly blacklist kernel module for permanent change, so that the module is not loaded even as part of some depepdedncy

Step 3: Take a backup copy of initramfs

It is recommended but not mandatory to make a backup copy of your initramfs . So you have a initramfs backup to fallback if something breaks.

Step 4: Rebuild initramfs

Next you must omit the respective kernel module and rebuild your initramfs

You can also provide a list of drivers in the same command using dracut —omit-drivers «module1 module2 module3» -f

If you want to have a verbose output then you can also add » -v » to the above command

Step 5: Update GRUB2 to blacklist kernel module

To properly blacklist kernel module we must also inform dracut and GRUB2. The steps to update GRUB2 varies between Red Hat/CentOS 7 and 8 Linux.

Follow the respective chapter based on your environment :

Disable kernel module using GRUB2 in RHEL/CentOS 7

Next we must also update GRUB2 configuration to make sure kernel module is not loaded at boot up stage. You can manually update /etc/sysconfig/grub by using any editor as shown below.

Append .blacklist to the kernel cmdline. We give it an invalid parameter of blacklist and set it to 1 as a way to preclude the kernel from loading it.
Here we also set rd.driver.blacklist as another method of preventing it from being loaded.

Alternatively, you can also use below sed command to append kernel module in grub file

Rebuild your GRUB2 configuration file

Disable kernel module using GRUB2 in RHEL/CentOS 8

The procedure to update GRUB2 in RHEL/CentOS 8 is different compared to RHEL/CentOS 7. I have written a separate article with the steps to update GRUB2 in RHEL 8 using 3 different tools.

In this example I will update GRUB2 using grub2-mkconfig .
Append .blacklist=1 and rd.driver.blacklist= to GRUB_CMDLINE_LINUX in /etc/sysconfig/grub

Next list the existing values of kernelopts

Next unset the existing values of kernelopts

Rebuild the GRUB2 configuration file

Verify the updated list of kernelopts

Next reboot your Linux server to activate the changes.

Verify the changes

Post reboot check if your module is still loaded

We should get a blank output for lsmod when grepped for respective module.

Try to call the kernel module using modprobe

As expected now after we disable kernel module btrfs , modprobe is not allowed to run or install this module.

You can disable any other kernel module in Linux using this method.

Lastly I hope the steps from the article to properly and permanently disable kernel module on RHEL/CentOS 7 and 8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Оцените статью