- How to encrypt root partition and entire file system using LUKS in Linux
- Lab Environment
- Install Cryptsetup in Linux
- Encrypt alternate partition /dev/sdb1 with LUKS
- Create Encrypted Physical Volume
- Encrypt Volume Group
- Encrypt root partition with LUKS
- Update encrypted LUKS device details in GRUB2 and /etc/crypttab
- Related Posts
- 5 thoughts on “How to encrypt root partition and entire file system using LUKS in Linux”
- How to Encrypt Root Filesystem in Linux
- Steps to Encrypt Filesystem
- Ubuntu Documentation
- Prerequisites
- Boot the Installer
- Boot Modes
- Selecting UEFI boot mode
- Detecting UEFI boot mode
- First Boot Screen
- GRUB (UEFI mode)
- Syslinux (BIOS mode)
- Welcome Options
- Live Desktop
- Pre-Prepare Encrypted Partitions
- Identify Installation Target Device
- Partitioning
- LUKS Encrypt
- LUKS unlock
- Format File-systems
- LVM (Logical Volume Management)
- Install Ubuntu
- Manual Partitioning
- Enable Encrypted GRUB
- Post-Installation Steps
- ReBoot
How to encrypt root partition and entire file system using LUKS in Linux
Table of Contents
During scratch installation of Red Hat or CentOS, you can select the checkbox to encrypt all the available disks but it is also possible to encrypt root partition and other volumes once OS is installed. We will encrypt volume group and underlying physical volume and root partition with LUKS online using cryptsetup .
Below are some more articles on LUKS based Disk Encryption
Lab Environment
I have a Virtual machine with CentOS 8 Linux running on Oracle VirtualBox installed on my Linux Server . There are two disks attached to this VM.
First Disk → Size: 15GB → /dev/sda3 → The node is installed on this disk which is un-encrypted.
Second Disk → Size: 20GB → /dev/sdb1 → We will use this disk to move the all the available file system from /dev/sda3 which will be encrypted with LUKS
These are the steps to replace an existing un-encrypted PV ( /dev/sda3 ) with an encrypted Physical Volume ( /dev/sdb1 ) in a running/active system for root volume:
Install Cryptsetup in Linux
To encrypt root partition and our physical volume in Linux we need cryptsetup rpm
Encrypt alternate partition /dev/sdb1 with LUKS
Open the encrypted LUKS device using a mapping. Here I am mapping my LUKS device to /dev/mapper/secret . After this step you should see /dev/mapper/secret encrypted file system on your LInux system
Create Encrypted Physical Volume
Now we will start with the steps to encrypt root partition. The first steps would be to create physical volume using our LUKS Mapping /dev/mapper/secret .
List the available physical devices. Currently as you see we have one encrypted physical volume /dev/mapper/secret available on /dev/sdb1 and one un-encrypted physical volume /dev/sda3
Encrypt Volume Group
Next extend the volume group by adding the newly created physical volume. With this we are one step closer to encrypt volume group in our Linux system.
List the available Volume Groups. As you see our VG has two physical volumes wherein one of the PV /dev/mapper/secret is LUKS encrypted.
List the available Physical Volumes. As you see in the encrypted Physical Volume we have 19GB free while un-encrypted PV ( /dev/sda3 ) has content of 14.5GB so we can easily migrate the content to encrypted physical volume.
Encrypt root partition with LUKS
Our root and swap partition are logical volume in rhel volume group. Now since we have added encrypted physical volume to our existing volume group. We will move the content of PV1 ( /dev/sda3 ) to PV2 ( /dev/mapper/secret ) using pvmove
As you see now our encrypted physical volume has all the content from PV1 /dev/sda3 and PV1 is empty.
Similar using vgs we see our VG have 2 physical volumes
To encrypt volume group, since we have migrated our data to encrypted physical volume, we can remove the un-encrypted physical volume from the rhel VG.
Once done also remove the un-encrypted physical volume to completely encrypt volume group as we do not have any more un-encrypted physical volume.
Update encrypted LUKS device details in GRUB2 and /etc/crypttab
Now since we have migrated all the data to encrypted LUKS device to encrypt root partition, we must also configure our GRUB2 to handle the reboot. Update LUKS device details in /etc/crypttab and grub.cfg
We will update /etc/crypttab with the key details of our LUKS device.
This command will generate UUID of our LUKS device and append the same to /etc/crypttab
Below is my crypttab file content
Next update /etc/sysconfig/grub by adding rd.luks.uuid= of the LUKS device as highlighted . This UUID should be the same as we added in /etc/crypttab
Next rebuild your GRUB2 configuration using grub2-mkconfig
Now you can reboot your Linux node. Since we encrypt root partition the boot up screen will prompt you for the LUKS passphrase before coming UP.
In our next article I will explain all about Network Based Disc Encryption (NBDE) wherein you can configure a tang server to get the key so that the system with encrypt root partition will automatically fetch the key from the tang server and continue to boot .
Lastly I hope the steps from the article to encrypt root partition, encrypt volume group and have an encrypted physical volume using LUKS in Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Posts
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!!
5 thoughts on “How to encrypt root partition and entire file system using LUKS in Linux”
How can I do this on a debian system when my root/boot partition isn’t created with LVM2, therefore, the PV move step won’t work. The only way to write to the lv is by mounting it to a dir in /mnt. I was eventually going to use dropbear to access the box during boot and unlock the luks container, but given the additional step needed to access the files after unlocking then mounting, I’m not sure this will work. Thanks for your time.
In such case an entire backup and restore may be performed but this is all theoretical as I have never tried this. If you do manage to get a working procedure kindly share here.
This howto ignores what happens with the original harddisk after removing it from the LVM.
Therefore I’d recommend a slightly lengthier approach:
* Don’t encrypt sdb1 but add it to the VG without encryption.
* Use “pvmove sda2” to move content to sdb1, then “pvremove sda2”.
* Encrypt sda2.
* Use “pvmove sdb1” to move content to the crypted sda2, then “pvremove sdb1”.
* You can then remove the temporary harddisk sdb from your system (see necessary steps to cleanly remove a disk from Linux in other howtos).
Thanks Andreas, This is also actually a good suggestion. This way we can utilize the existing disk and use additional disk just for the backup and restore purpose
I will try to test this and update the article with detailed steps using both methods
I found one problem with this approach. While trying to restore my data on sda2 , I got following error:
This is because my sdb1 was 15GB while sda2 was 14.5GB. So to follow your steps, the size of both the disks should be “EXACTLY” the same size or else the operation would fail.
In such case I would prefer to stick with what is written in the tutorial and end user can decide what they want to do with sda2
Источник
How to Encrypt Root Filesystem in Linux
An understanding of how your computer boots is required, because unlocking an encrypted root filesystem is integral to the bootstrap process. The current, stable kernel series, 2.6, optionally uses initramfs to help boot, Initramfs is a cpio archive that the kernel now knows how to unpack into a RAM-based disk. This unpacked filesystem contains a script that traditionally loads kernel modules needed to mount the root filesystem. In our case, this script also unlocks the encrypted root filesystem.
Several filesystem encryption interfaces are available for Linux. Several cryptoloop variations that provide an encrypted loopback device also exist. This article focuses on the dm-crypt interface provided by the recent 2.6 Linux kernels. This interface currently is preferred by the Fedora Project, and dm-crypt modules are provided by Fedora’s kernel packages. Also required is a statically linked cryptsetup. This utility simplifies the management of dm-crypt devices. Finally, parted and hfsutils are used to manage the boot filesystem. Now similar interface are ported to new CentOS/RHEL 6 2.6 kernel by default, I will show you after this traditional episode that describes the method used by Fedora based modules.
Before an encrypted filesystem is set up, you should randomize the partition it will occupy. This eliminates a potential leak of information about the disk’s contents. A partition is randomized by overwriting its contents with random data, for ex:if the partition is /dev/hda1
This process can take a long time, because creating random data is somewhat difficult.
Steps to Encrypt Filesystem
There are steps to be followed for encryption
1) Ensure that the aes, dm-mod and dm-crypt modules have been loaded into the kernel.
2) Unmount the partition that will host the encrypted root filesystem, /dev/hda4, from /home
3) Create a random 256-bit encryption key and store it at /etc/root-key
This key will be copied to the Flash disk later.
4) Create a dm-crypt device, encrypted using the key you just generated
Accessing ‘/dev/mapper/root’ now provides an encrypted layer on top of /dev/hda4. By default, cryptsetup creates an AES-encrypted dm-crypt device and assumes a keyspace of 256 bits.
5) Create an ext3 filesystem on ‘/dev/mapper/root’
6) Mount the new filesystem
7) Now that you have an encrypted filesystem, you must populate it with the contents of /dev/hda5 (the original root filesystem)
8) Finally, create an entry in ‘/mnt/encroot/etc/crypttab’ so that various utilities know how the filesystem was configured
Now we have our encrypted filesystem ready.
A similar and rather an easy perspective can be found in new RHEL6 where we have the concept of LUKS (volume encryption) whose looks are really killing ( Linux Unified Key Setup) and also ecryptfs , a «pseudo-file system» which provides data and filename encryption on a per-file basis. The term «pseudo-file system» refers to the fact that eCryptfs does not have an on-disk format; rather, it is a file system layer that resides on top of an actual file system. The eCryptfs layer provides encryption capabilities.
eCryptfs works like a bind mount, as it intercepts file operations that write to the underlying (i.e. encrypted) file system. The eCryptfs layer adds a header to the metadata of files in the underlying file system. This metadata describes the encryption for that file, and eCryptfs encrypts file data before it is passed to the encrypted file system. Optionally, eCryptfs can also encrypt filenames.
eCryptfs is not an on-disk file system; as such, there is no need to create it via tools such asmkfs. Instead, eCryptfs is initiated by issuing a special mount command. To manage file systems protected by eCryptfs, the ecryptfs-utils package must be installed first.
Diving deep in such topics will require another article and is out of scope fo this tutorial as of now. If you have any questions or feedback, feel free to leave a comment.
Источник
Ubuntu Documentation
Further support may be available from the official Ubuntu support community IRC channel #ubuntu on Libera (irc.libera.chat). This page is an up-to-date guide to comprehensive LUKS encryption, including GRUB, covering 18.04 LTS and later releases.
It is focused on modifying the Ubuntu Desktop installer process in the minimum possible way to allow it to install with an encrypted /boot/ and root file-system. It requires 36 commands be performed in a terminal, all of which are shown in this guide and most can be copy and pasted.
It is also a useful overview on the manual steps required for storage-at-rest encryption.
It is intended to replace the current (hopelessly out-of-date and inadequate) FullDiskEncryptionHowto page.
Almost Full Disk Encryption (FDE)
I’m (Tj) being deliberately pedantic in calling this almost Full Disk Encryption since the entire disk is never encrypted. What is encrypted are the operating system partition and the boot-loader second-stage file-system which includes the Linux kernel and initial RAM disk.
However, this is much better than the Ubuntu installer Encrypt Disk option which only supports encrypting the operating system partition but leaves the boot-loader second stage file-system unencrypted and therefore vulnerable to tampering of the GRUB configuration, Linux kernel or more likely, the initial RAM file-system ( initrd.img).
In both cases the first-stage GRUB boot-loader files are not (and cannot) be encrypted or protected through cryptographic signatures in BIOS boot mode.
It is possible, in UEFI Secure Boot mode, to have every stage cryptographically signed, in which case any tampering can be detected and boot aborted. Unfortunately, Canonical (who control the building of the packaged signed GRUB UEFI boot-loader) did not include the encryption modules in their signed GRUB EFI images until the release of 19.04 Disco. See bug #1565950.
Illustrations (screen-captures) are taken from the Ubuntu 19.04 ‘Disco’ Desktop Installer. Other flavours have their own installers and themes and may not look identical.
Prerequisites
Desktop installer ISO image from http://releases.ubuntu.com/ copied to installation media (usually a USB Flash device but may be a DVD or the ISO file attached to a virtual machine hypervisor).
Boot the Installer
Even before starting the installer it is critical to select the correct boot mode. Ubuntu (and flavours like Kubuntu, Lubuntu, Xubuntu, etc.) uses hybrid bootable images that have two alternate boot-loaders:
- GRUB (GRand Unified Bootloader)
- Syslinux
The ISO images can boot in several possible combinations of mode and partitioning:
- ISO-9660 El-Torito (the CD/DVD optical media boot mechanism — uses Syslinux)
- GPT + EFI-SP (GUID Partition Table and EFI System Partition — uses GRUB)
- MBR + EFI-SP (Master Boot Record and EFI System Partition — uses GRUB)
- GPT + PC (GUID Partition Table and BIOS boot — uses Syslinux)
- MBR + PC (Master Boot Record and BIOS boot — uses Syslinux)
Boot Modes
PCs have two boot modes: BIOS (Basic Input Output System) and UEFI (Unified Extensible Firmware Interface). BIOS was installed in IBM PCs and compatibles from the 1980s. UEFI mode has become prevalent since Microsoft introduced it in Windows 7 and later began requiring it on new PCs to meet the Windows Logo License Agreement requirements. Most PCs since 2010 have UEFI.
Apple Macintosh/iMac devices have their own EFI (Extensible Firmware Interface) which is almost, but not quite, the same as UEFI but do not have a BIOS equivalent. This guide doesn’t (currently) address installation on Apple devices.
BIOS is also known as Legacy or CSM (Compatibility Support Module) when part of UEFI.
If the target system is BIOS-only you can disregard the rest of this section.
Selecting UEFI boot mode
In order to support UEFI Secure Boot, or to install alongside another operating system that uses UEFI boot mode (e.g. Windows 10), the system motherboard’s firmware boot-manager has to be told to start the Ubuntu installer in UEFI mode.
Unfortunately there is no consistency between different PC manufacturers on how motherboard firmware boot-managers should indicate boot-mode so we, as users, have to figure it out from what clues we can see when the PC’s boot menu is displayed and lists boot devices.
Let’s assume we’re using a USB Flash device. The boot menu may list that device twice (once for UEFI mode, and again for BIOS/CSM/Legacy mode). It may make it explicit that one is «UEFI» and the other not, or it may use some hard-to-spot code such as a single letter abbreviation (e.g. «U» vs «B»).
If we want to guarantee UEFI mode and avoid BIOS/CSM/Legacy mode then by entering firmware Setup at power-on we should be able to find an option to disable CSM/Legacy mode.
After doing that we can be sure the installer will boot in UEFI mode.
There is a quick way to confirm the installer has started in UEFI mode — it will be using GRUB, so see the following section First Boot Screen > GRUB (UEFI mode) for what it will look like.
Detecting UEFI boot mode
Once Linux has started it is possible to check. The presence of the efivarfs file-system means the system booted in UEFI mode:
First Boot Screen
The options displayed will look different depending on which boot-loader is used.
GRUB (UEFI mode)
Choose Try Ubuntu without installing from the GRUB boot-loader menu:
Syslinux (BIOS mode)
The display will briefly pause for selection of the input language:
If you interrupt at this stage to choose a language Syslinux will display a menu where you can make various advanced changes to the boot options. At this point you should choose the Try Ubuntu without installing menu option.
Welcome Options
If the boot hasn’t been interrupted to choose a language the Welcome dialog with start-up options will be displayed. Choose Try Ubuntu.
Live Desktop
Once the Live Desktop environment has started we need to use a Terminal shell command-line to issue a series of commands to pre-prepare the target device before executing the Installer itself.
On Ubuntu (Gnome) press the Show Applications button at lower-left corner
In the subsequent text search field type «Term» until just the Terminal icon is shown
Press the icon to launch Terminal.
Instead of these steps you can just press Ctrl+Alt+T hot-key combination.
Pre-Prepare Encrypted Partitions
You might find maximising the Terminal window is helpful for working with the command-line.
As much as is possible these manual steps will keep to the same installation layout and naming as the installer uses.
For these commands you’ll need elevated privileges so switch to root user (the $ prefix indicates a regular user and # indicates root user):
A couple of later commands rely on Bourne-Again Ash Shell (BASH) specific functionally so always switch from the default shell to bash:
If at any time you wish to check which shell is in use do:
You will something like one of these:
Identify Installation Target Device
Here the installation target device is sda but yours may vary so examine the SIZE to ensure you choose the correct target. (in this example target is a 9GiB virtual machine disk image file).
We’ll set an environment variable we can re-use in all future commands. Doing this will allow you to copy and paste these instructions directly into your terminal (note: do not copy and paste the «#» prefix). In this example I’m installing to /dev/sda:
On systems with NVME storage devices the naming scheme is /dev/nvme$
Finally we’ll set an environment variable for the encrypted device-mapper naming that omits the leading path «/dev/» part:
And we have to cope with NVME devices needing a ‘p’ for partition suffix:
Partitioning
We’ll now create a disk label and add four partitions. We’ll be creating a GPT (GUID Partition Table) so it is compatible with both UEFI and BIOS mode installations. We’ll also create partitions for both modes in addition to the partitions for the encrypted /boot/ and / (root) file-systems.
We’ll be using the sgdisk tool. To understand its options please read man 8 sgdisk
First check for any existing partitions on the device and if some are found consider if you wish to keep them or not. If you wish to keep them DO NOT USE sgdisk —zap-all command detailed next. Instead, consider if you need to free up disk space by shrinking or deleting individual existing partitions.
If you do need to manipulate the existing partitions use the Show Applications menu to search for GPartEd which is the graphical user interface partitioning tool (see the GPartEd manual for how to use it)
If it is safe to delete everything on this device you should wipe out the existing partitioning metadata — DO NOT DO THIS if you are installing alongside existing partitions!
Now we’ll create the partitions. A small bios_boot (2MB) partition for BIOS-mode GRUB’s core image, an 128MB EFI System Partition, a 768MB /boot/ and a final partition for the remaining space for the operating system.
: : where start and end can be relative values and when zero (0) adopt the lowest or highest possible value respectively.
Partition 4 is not created. The reason is the Ubuntu Installer would only create partitions 1 and 5. Here we create those and in addition the two boot-loader alternatives.
LUKS Encrypt
The default LUKS (Linux Unified Key Setup) format (version) used by the cryptsetup tool has changed since the release of 18.04 Bionic. 18.04 used version 1 («luks1«) but more recent Ubuntu releases default to version 2 («luks2«). GRUB only supports opening version 1 so we have to explicitly set luks1 in the commands we use or else GRUB will not be able to install to, or unlock, the encrypted device.
In summary, the LUKS container for /boot/ must currently use LUKS version 1 whereas the container for the operating system’s root file-system can use the default LUKS version 2.
For more information see the man-pages for 18.04 Bionic or 18.10 Cosmic onwards.
First the /boot/ partition:
Now the operating system partition:
LUKS unlock
Now open the encrypted devices:
After the Ubuntu installation is finished we will be adding key-files to both of these devices so that you’ll only have to type the pass-phrase once for GRUB and thereafter the operating system will use embedded key-files to unlock without user intervention.
Format File-systems
IMPORTANT this step must be done otherwise the Installer’s partitioner will disable the ability to write a file-system to this device without it having a partition table (Man-page for mkfs.ext4):
Format the EFI-SP as FAT16 (Man-page for mkfs.vfat):
LVM (Logical Volume Management)
We’ll now create the operating system LVM Volume Group (VG) and a Logical Volume (LV) for the root file-system.
LVM has a wonderful facility of being able to increase the size of an LV whilst it is active. To provide for this we will only allocate 80% of the free space in the VG to the LV initially. Later, if you need space for other file-systems, or snapshots, the installed system will be ready and able to support those requirements without struggling to free up space.
I am also creating a 4GiB LV device for swap which, as well as being used to provide additional memory pages when free RAM space is low, is used to store a hibernation image of memory so the system can be completely powered off and can resume all applications where they left off. The size of the swap space to support hibernation should be equal to the amount of RAM the PC has now or is is expected to have in the future.
Install Ubuntu
Now minimise the Terminal window and start the Installer:
Choose the installation language and keyboard and then the software installation choices:
In the Installation Type options choose Something Else:
Manual Partitioning
The manual partitioner will start:
Select the root file-system device for formatting ( /dev/mapper/ubuntu—vg-root), press the Change button, choose Use As Ext4. and Mount point /:
Select the swap device ( /dev/mapper/ubuntu—vg-swap_1), press the Change button, choose Use as swap area:
Select the Boot file-system device for formatting ( /dev/mapper/LUKS_BOOT), press the Change button. choose Use as Ext4. and Mount point /boot:
Select the boot-loader device ( /dev/sda in my example). Boot-loader device should always be a raw disk not a partition or device-mapper node:
Press the Install Now button to write the changes to the disk and press the Continue button:
The installation process will continue in the background whilst you fill in the Where Are You? and Who Are You? forms:
Enable Encrypted GRUB
As soon as you have completed those forms switch to the Terminal to configure GRUB. These commands wait until the installer has created the GRUB directories and then adds a drop-in file telling GRUB to use an encrypted file-system. The command will not return to the shell prompt until the target directory has been created by the installer. In most cases that will have been done before this command is executed so it should instantly return:
This has to be done before the installer reaches the Install Bootloader stage at the end of the installation process.
If installation is successful choose the Continue Testing option:
Post-Installation Steps
Return to the Terminal and create a change-root environment to work in the newly installed OS (Man-pages for mount chroot):
Within the chroot install and configure the cryptsetup-initramfs package. This may already be installed. Note: this package is not available in 18.04 Bionic because the files are included in the main cryptsetup package.
This allows the encrypted volumes to be automatically unlocked at boot-time. The key-file and supporting scripts are added to the /boot/initrd.img-$VERSION files.
This is safe because these files are themselves stored in the encrypted /boot/ which is unlocked by the GRUB boot-loader (which asks you to type the pass-phrase) which then loads the kernel and initrd.img into RAM before handing execution over to the kernel. (Man-page for initramfs.conf):
Create a randomised key-file of 4096 bits (512 bytes), secure it, and add it to the LUKS volumes (Man-pages for dd chmod):
Add the keys to the crypttab (Man-pages for crypttab blkid):
Finally update the initialramfs files to add the cryptsetup unlocking scripts and the key-file:
If everything has gone well the system is now ready to reboot.
ReBoot
Reboot the system, not forgetting to remove the installation media (otherwise it’ll boot again!).
You should get a GRUB pass-phrase prompt:
Full_Disk_Encryption_Howto_2019 (последним исправлял пользователь tj 2021-09-04 12:41:49)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Источник