Linux single user mode
How to Boot into Single User Mode in CentOS/RHEL 7
by Aaron Kili | Published: August 17, 2017 | Last Updated: August 8, 2017
Single User Mode (sometimes known as Maintenance Mode) is a mode in Unix-like operating systems such as Linux operate, where a handful of services are started at system boot for basic functionality to enable a single superuser perform certain critical tasks.
It is runlevel 1 under system SysV init, and runlevel1.target or rescue.target in systemd. Importantly, the services, if any, started at this runlevel/target varies by distribution. It’s generally useful for maintenance or emergency repairs (since it doesn’t offer any network services at all), when a computer is not capable of normal operations.
Some of the low-level repairs include running such as fsck of damaged disk partitions, reset root password if you have lost it, fix “failed to mount /etc/fstab” error – just to mention the most critical of them. And also when the system fails to boot normally.
In this tutorial, we will describe how to boot into single user mode on CentOS 7. Note that practically this will help you enter the emergency mode and access an emergency shell.
How to Boot into Single User Mode
1. First restart your CentOS 7 machine, once boot process starts, wait for the GRUB boot menu to appear as shown in the screen shot below.
CentOS 7 Grub Menu
2. Next, select your Kernel version from the grub menu item and press e key to edit the first boot option. Now use the Down arrow key to find the kernel line (starts with “linux16“), then change the argument ro to rw init=/sysroot/bin/sh as shown in the screen shot below.
Edit Grub Boot Options
3. Once you have finished the task in the previous step, press Ctrl-X or F10 to boot into single user mode (access an emergency shell).
CentOS 7 Emergency Shell
4. Now mount root (/) filesystem using the following command.
At this point, you can perform all the necessary low-level system maintenance tasks. Once you are done, reboot the system using this command.
You may also liked to read following articles.
Lastly, the single user mode or maintenance mode is not password-protected by default, so any one with malicious intend and physical access to your computer can enter the emergency mode and “destroy” your system.
Linux single user mode
Recently I was asked to reset root password on some long forgotten Debian box. It was an easy and straightforward task, but, as there are some interesting pitfalls, I will describe the whole process of acquiring root shell without password using single-user mode and a couple of ways to prevent it.
What is single-user mode?
To access root shell without password you need to have physical access to the machine. Then you can modify kernel parameters to boot system into single-user mode which is just a single superuser maintenance/recovery mode with all services disabled.
How to access single-user mode?
Default Debian configuration will require password before executing single-user mode and this is a standard behavior found in today’s Linux distributions.
To boot into this mode you need to turn on computer, access GRUB menu and select Recovery mode entry.
In case the Recovery mode menu entry is not available, you need to perform five simple steps in order to modify kernel parameters list.
- Turn on computer.
- Access GRUB menu.
- Edit existing menu entry (use e key).
- Add single keyword (alternatively you can use -s or S ) to the Linux kernel parameters list.
- Press CTRL-X or F10 while still in edit mode to continue boot process.
How single-user mode is protected?
It is protected by using sulogin utility which is invoked by init process when system goes into single-user mode. You can verify this behavior manually by opening /etc/inittab file and looking for single-user runlevel definition.
You can change it to shell interpreter if you do not want to enter password.
How to overcome the above protection?
You can modify default behavior and specify your own command run as init process as long as you can define kernel parameters.
So, according to the above statement you can get around this protection mechanism and boot into single-user mode to access root shell without password by specifying init option in the kernel parameters list.
How to protect against such attacks?
Disable boot from external devices and lock boot device to the used one. Password protect BIOS settings. It is a weak protection but an important one, as circumventing it will surely draw an attention.
Disable generation of recovery mode menu entries and lock down boot-loader to require authentication before accessing command line.
This way is suitable only for personal devices but complements the above-mentioned methods with very strong protection. Full disk encryption will surely prevent access to the configuration files.
Use this mode in case of emergency when you need to enter directly single-user mode without executing any other commands or startup scripts.
To start this mode use -b or emergency kernel option in the same way as the above ones.
Please note that emergency shell configuration is hard-coded and will use sulogin utility. Download sysvinit package source code if you want to modify it.
How to Change to Single User Mode
Single user mode, also referred to as maintenance mode and runlevel 1, is a way of running Linux or another Unix-like operating system that uses minimal system resources and provides only minimal functionality.
Single user mode can be useful for checking and repairing operating systems, particularly those that have been damaged and will not allow booting (i.e., starting up) into the default GUI (graphical user interface) or console (i.e., text-only) multi-user mode. For example, it is used for running fsck (which is used to check and repair filesystems) on a /usr partition because this requires that the partition be unmounted (i.e., not logically attached to the system). A partition is a logically independent section of a hard disk drive (HDD).
A runlevel is any of several operating states of a computer, each allowing the operation of a different set of services. By default Linux boots into either runlevel 3 or runlevel 5. The former permits the system to run all services except for a GUI. The latter allows all services including a GUI. The previous and current runlevels can be found at any time by running the runlevel command as follows:
There are several ways to change into single user mode. It is easiest to do while the computer is already in operation. All that is necessary is for the root (i.e., administrative) user to run the init command, which is used to change the runlevel, using the number the letter s or the number 1 as an option as follows:
It will be obvious when single user mode has been entered. This is particularly true in the likely case that the user was working in a GUI, as the GUI will be shut down and the computer will be in console mode. Also, there will typically be a change in the shell from bash (the default on Linux) to sh, which features a small size and minimal functionality, and this will be indicated by a change in the command prompt (i.e., the short text message at the start of each line). A shell is a program that provides a text-only user interface and reads and executes commands that are typed in.
It is also possible to boot directly into single user mode, although this is slightly more complicated. If the GRUB (grand unified boot loader) is used (as is typical on modern versions of Linux), the first step is to wait for the GRUB splash screen (i.e., full-screen image) to appear and then (1) enter the letter p from the keyboard followed by the password if a password has been set for GRUB. This step can be ignored if no password has been set for GRUB (which is not wise for systems which might be physically accessible to unauthorized people, as this creates a serious security hole).
The second step is to (2) select the desired operating system or version of the desired kernel (i.e., the core of the operating system) for booting using the up and down arrow keys and then type the letter e . This results in a choice of lines of text appearing that start with the words root, kernel and initrd.
The third step is to (3) select the line that starts with the word kernel and type e again. This replaces the text with a new line that begins with grub edit>.
The next step is to (4) type a space followed by the word single at the end of the line starting with grub edit> and then press the ENTER key. This causes the previous text to reappear.
The final step is to (5) type the letter b . This causes the system to boot in what looks like a normal booting process. However, booting only continues to a level sufficient for the operation of single user mode.
It is very easy to return to the previous runlevel or continue booting into the default runlevel after the checks and/or repairs have been made. One way is to use the init command again, followed by the runlevel desired, as follows:
Another way is to simultaneously press the CONTROL and d keys. In addition, a computer should return to its former runlevel when rebooted, although this can take substantially more time, which can be an important consideration on enterprise systems.
Created July 13, 2006.
Copyright © 2006 The Linux Information Project. All Rights Reserved.
Single User Mode Secure Boot on Ubuntu & Debian
On Ubuntu and Debian hosts, the single user mode, also referred as the rescue mode, is used to perform critical operations.
The single-user mode can be used to reset the root password or to perform file systems checks and repairs if your system is unable to mount them.
In this tutorial, we are going to see how you can boot on single user mode on Debian and Ubuntu hosts and how to reset the root password.
We are also configure our target units (rescue and emergency) to prompt for a password on single-user mode boot.
Note: in order to boot into rescue or emergency targets, you are need physical access to the machine to interrupt the default GRUB boot process.
Table of Contents
Rescue & Emergency Targets on Debian
On recent Debian distributions, systemd is responsible for booting your Linux host using a default target.
If you want to check the default target run by systemd, you can run the following command
As you can see, my system is set to boot on graphical target by default.
As I don’t own any desktop environment like GNOME or KDE, it is going to boot in a simple shell.
However, the graphical target is not the only target available on Linux, you can boot in the following modes:
- poweroff : used to shutdown your host and power off the system;
- rescue : a mode used to boot your system with a rescue shell;
- emergency : similar to the rescue mode except that no services are launched and no filesystems are mounted;
- multi-user : the default mode on Linux systemd systems, used to boot your host in a non-graphical system (without a desktop environment);
- graphical : includes the multi-user target and a graphical environment such a KDE or GNOME for example;
- reboot : shutdowns the system and reboot it immediately
As their names reflect it, those modes are used in order to perform maintenance operations on a Linux system, but they need to be done securely to avoid any security leaks.
In this article, we are going to focus on the rescue and emergency modes and see how we can securely on them.
We are also going to see how booting in single user mode can be used to change the root password or to perform simple filesystems checks.
Configuring the Root Account on Debian
By default, when entering single user mode, you are going to be given a root prompt with complete privileges.
As a consequence, in order to boot in single-user mode (or rescue mode), your root account needs to be unlocked and it needs to have a password.
Checking Root Account Lock Status
On Ubuntu, root accounts are disabled by default as a security measure, and you can choose to have it disabled on Debian 10 also (if you don’t specify a root password when installing Debian)
In order to check if your root account is locked, run the following command
As you can see, there is an exclamation mark on the space reserved for the password : it means that the root is locked.
Setting a Root Account Password
In order to set a password for the root account, run the following command
If you go back to check the content of your shadow file, you should now see that the content has been modified and that no exclamation mark are presented.
Awesome, now we can start booting into single user mode from the GRUB bootloader screen.
Booting in Rescue Mode from GRUB
In order to boot into single user mode, or rescue mode, you are going to interrupt the default boot process when starting your machine.
Reset your machine and interrupt the boot process by pressing a key arrow in the GNU GRUB menu.
If you are running a Debian based distribution, this is what you should see on your screen
As described in the bottom description panel, press ‘e’ in order to edit the boot commands
You should now see the following window on your screen
Using the directional arrows, navigate to the Linux kernel booting line and put the following string at the end of the line.
You can also simply type “1”, it is equivalent to booting in single user mode on Debian.
As described below the boot script, press F10 to boot into rescue target.
Your Linux Kernel will be loaded and your initial virtual filesystem will be loaded.
Before having the access, you will be prompt with the root password that you just changed before.
Type the password you defined before, and you should now have a root shell directly into your host.
Awesome! Now that you have a root shell into the host, you can start by changing the root password or by checking your filesystems.
Security Recommendations for Single User Mode
When it comes to the single user mode, or the rescue target, it is important that this mode is password-protected on your system.
As you can see, it is the case by default on Debian 10, but you have to make sure on other distributions that it is the case.
If any intruder has physical access to your machine, in a data-center for example, it could be as easy as rebooting the machine, interrupting the boot process and launching a non-protected single user mode.
From there, every file can be deleted, copied or transferred to a non secure server.
Malicious programs can also be installed to track the host activity and to steal personal information.
Sulogin login shell
Luckily for you, standard Debian distributions are configured to ask for the root password when booting in single user mode.
It can be seen by inspecting the rescue and emergency services on your host (located at /usr/lib/systemd/system)
By default, when starting, your system is going to launch the systemd-sulogin-shell in rescue mode, which is safe from unauthorized access.
However, you have to make sure that this file was not altered and that the system is not instructed to launch a simple shell (like /bin/sh for example).
This would result in having an unsafe single user mode, essentially having a major security breach if anyone has physical access to the machine.
In this tutorial, you learnt about the single user mode on Debian-based distributions and how it is related to the rescue and emergency targets on Linux.
You learnt that this mode needs to be password protected as it offers a root shell for users who were to log into it.
You also had a look at how you can instruct the GRUB to boot into this mode, and how it can be used to perform maintenance operations on your system.
If you are curious about Linux system administration, we have a complete section dedicated to it on the website.
Also, make sure to read our most recent post about access control lists on Linux as they define another layer of security on Linux filesystems.
Single user mode по сети
Допустим есть железка, где основная vt недоступна от слова вообще (headless сервер, или одноплатник где UART не распаян и т.п.). Допустим из-за какого-то косяка в файловой системе или настройке сервисов, все вылетело в аварийную консоль. В ней, понятное дело, нет ни сети, ничего.
Задача — достучаться в таком «аварийном» режиме до этой самой аварийной консоли по сети с наименьшим количеством костылей. Есть ли у кого истории успеха?
все вылетело в аварийную консоль. В ней, понятное дело, нет ни сети, ничего.
Задача — достучаться в таком «аварийном» режиме до этой самой аварийной консоли по сети с наименьшим количеством костылей.
В смысле post factum (после того, как всё вылетело), не трогая при этом саму железку? Очевидно, невозможно.
Почему это? ILOM. Хотя это не средствами ОС и есть не везде.
В тегах «debian» и «systemd», а в тексте — речь об одноплатниках. Я так понимаю, здесь речь не об out of band management.
Ну, из очевидного запихивать telnet initramfs/запускать в single user. Его все же хотелось бы наименее костыльного решения.
А, то есть ты хочешь заранее подготовить софт и железку, чтобы потом её можно было спасать. Я не так понял вопрос.
Тогда как-то так:
создаёшь minimal.target , ставишь его в зависимости к emergency.target и rescue.target
добавляешь в зависимости к minimal.target всё что тебе нужно, с явным перечислением всех транзитивных зависимостей и системных юнитов из sysinit.target (а именно: sshd, сетевой менеджер, udev)
проверяешь, что в каждом таком сервисе написано DefaultDependencies=no
для ssh придётся написать отдельный сервис, который копирует имеющийся, но с DefaultDependencies=no (ну или поправить имеющийся, но тогда иметь в виду, что sshd может стартануть до полного монтирования всех ФС, например)
вылетело в аварийную консоль
В смысле вылетело? Single user mode — обычно это означает, что вместо инита (systemd) запустился интерактивный шелл (из initramfs) принудительно или из-за ошибки при старте инита.
Single user mode — обычно это означает, что вместо инита (systemd) запустился интерактивный шелл (из initramfs)
Нет, man rescue.target.
из-за ошибки при старте инита
При «ошибке при старте инита» происходит kernel panic.
Ясно. Своим терминам приписываем термины из sysvinit.
Так бы сразу и написали. Насколько помню по стандарту «runlevel 1» (rescue.target как его аналог) не поднимает сетевые соединения.
При «ошибке при старте инита» происходит kernel panic.
kernel panic — это когда инит (systemd) падает. А вот когда initramfs не может стартовать основной инит по каким-то причинам, то он обычно запускает вместо инита интерактивный шелл.
С initramfs две конфигурации init, ты про какую?