Как установить Ubuntu с LVM и LUKS на SSD и использование зашифрованного жесткого диска LUKS для данных на Dell Inspiron 7580

Цель Dell Inspiron 7580 (SSD меньшего размера и HDD большего размера) - установить Ubuntu (LVM / LUKS) на SSD и использовать HDD (LUKS-зашифрованный) для больших файлов (например, видео, Картинки, Скачать, ...). Я искал в Интернете и не мог найти конкретную инструкцию.

задан 14 June 2020 в 17:56

2 ответа

I had to find a lot of information to succeed on this specific task and would like to share it with others, maybe somebody else will find the answer or part of it helpful:

Regarding Ubuntu on Dell Inspiron 7580 I found first a discouraging page:
"Standard images of Ubuntu may not work at all on the system or may not work well, though Canonical and computer manufacturers will try to certify the system with future standard releases of Ubuntu."
This is weird as the special image would work and why would Dell not feed the changes back into the community and Canonical? Why can they not offer the special image to download? But there is hope as I am using now Ubuntu 19.04 without problems.

Some basic comments that I found helpful:
And no need for overprovisioning (leave some of the SSD empty). That's old news periodically regurgitated in some blogs for clickbait (SuperUser Answer).

A lot of users see old info on SSDs. They now are just as reliable (unreliable?) as HDDs. (Source: Ubuntu Forum, HotHardware, Ubuntu Forum)

And see comments to this Ubuntu Ask answer: "Work doesn’t kill solid state drives, but age does, according to Google study."

Therefore no need to transfer the swap partition and var-folder from the SDD to the HDD

Installation and configuration of Ubuntu (19.04) on Dell Inspiron 7580
I used the following answer as stepping stone: Encrypt an Ubuntu 18.04 LTS Installation with TWO Drives: OS on the primary SSD, /home on your secondary HDD

But before you do install Ubuntu, make sure your SSD is recognised during the installation process. At the step of the “installation type”, you can choose “something else” and see whether two drives (SSD + HDD) are shown. For me it was BC501 NVMe ... 128GB and ST2000LM015-2E8174.

  • If both drives are recognised, go back to the “installation type” and you are good to install LVM with encryption (LUKS). It should ask you on which drive you want to install Ubuntu and choose the SSD “NVMe ...”.
  • If only the HDD is shown, follow the steps below to have the SSD recognised.
  1. Install Ubuntu onto your smaller (usually the SSD) and check (i) erase the disk, (ii) encrypt the installation, and (iii) LVM management. This will result in an encrypted SSD, but will not touch the second (usually HDD) drive.

When I wanted to restart the laptop, it seemed to try to start with the SSD but stopped with a squeaking sound, then it starts the HDD (called ubuntu in the UEFI) which then shows a black screen with GRUB command line. If this happens to you, please check the steps below to solve the problem, in my case it was a wrong boot option/sequence

  1. Open gParted (if not yet installed: sudo apt install gparted)
  • navigate to your second HDD (carefully check the /dev/sd?X)
  • delete any & all existing partitions
  • create a new PRIMARY PARTITION using the ext4 file system. You could also label it, but that’s not necessary. Choose "Apply".
    One gParted is finished, close gParted.
  1. Now you're ready to install the LUKS container on the second drive and then format it. In the following commands, replace sd?X with the name of your SECONDARY drive (not your primary drive), for example sda1: sudo cryptsetup -y -v luksFormat /dev/sd?X

  2. Then you’ll need to decrypt the new partition so that you can format it with ext4, the modern Linux file system preferred by Ubuntu.
    sudo cryptsetup luksOpen /dev/sd?X sd?X_crypt
    sudo mkfs.ext4 / dev / mapper / sd? X_crypt

  3. Если вы хотите использовать второй жесткий диск в качестве обычного жесткого диска с часто используемым доступом, есть способ автоматически смонтировать и расшифровать второй диск при запуске, когда ваш компьютер запрашивает Вы для основного пароля расшифровки жесткого диска. За исключением: я использую ту же самую парольную фразу для ОБА моих дисков, так как я вижу больше проблем с двумя разными парольными фразами.
    Сначала вам нужно создать ключевой файл, который будет действовать как пароль для вашего дополнительного диска, и вам не нужно будет вводить каждый раз при запуске (например, ваш основной пароль шифрования жесткого диска).
    sudo dd if = / dev / urandom of = / root / .keyfile bs = 1024 count = 4
    sudo chmod 0400 /root/.keyfile
    sudo cryptsetup luksAddKey / dev / sd? X /root/.keyfile
    Once the keyfile has been created, add the following lines to /etc/crypttab using nano
    sudo nano /etc/crypttab
    Add this line, save & close the file (/etc/crypttab).
    sd?X_crypt UUID= /root/.keyfile luks,discard
    For me: sda1_crypt UUID=7e0edaa0-69f9-425d-ba9d-3f5fdff14cd5 /root/.keyfile luks,discard
    To get your parition’s UUID to enter into the /etc/crypttab file, use this command (you need to use sudo it so that all of your partitions show up):
    sudo blkid
    The value you want is the UUID of /dev/sd?X, not dev/mapper/sd?X_crypt. Also make sure to copy the UUID, not the PARTUUID.
    Close & save /etc/crypttab file.

  4. Add this line to /etc/fstab to actually mount the partition on startup. (Be careful with this file as it can quite easily cause your system not to boot, see AskUbuntu answer)
    /dev/mapper/sd?X_crypt / ext4 defaults 0 2
    For me: /dev/mapper/sda1_crypt /media/Storage ext4 defaults,discard 0 2

  5. Then restart (entering your primary drive decryption password) and it should decrypt BOTH your primary and secondary drives.
    If you find yourself unable to create files in the new partition, it’s probably still owned by root and needs to be chowned to your user. Run this command:
    sudo chown : / -R
    Reboot and check to see if this (daisy-chain decrypt) is in fact is the case. If the secondary drive is automatically decrypted, when you choose “Other Locations” the second drive should show up in the list and have a lock icon on it, but the icon should be unlocked.

I followed some tips to make the Ubuntu installer recognize the SSD
Only when I changed the SATA mode from RST(RAID) to AHCI in the UEFI it worked (be careful if you want to have dual boot with Windows). Some other possibly helpful steps:

The second installation went well, I could choose on which harddisk I wanted to install Ubuntu 19.04 (LVM+LUKS).

Black screen, wrong boot option
When I wanted to restart the laptop, it seemed to try to start with the SSD but stopped with a squeaking sound, then it starts the HDD (called ubuntu in the UEFI) which then shows a black screen with GRUB command line. If this happens to you, please check the steps below to solve it. After the start of the USB installer I would see a quick error: Couldn't get size:0x800000000000000e.
The error is probably not related to the SSD:
https://ubuntuforums.org/showthread.php?t=2424000&highlight=couldn%27t+size Following https://www.howtogeek.com/196740/how-to-fix-an-ubuntu-system-when-it-wont-boot/ respectively https://www.howtogeek.com/114884/how-to-repair-grub2-when-ubuntu-wont-boot/, I ran the Boot repair but it could not help.

But I also found another thread which seemed to me it could be helpful: I followed the answer, not thinking of an USB-drive but of my SSD. The only difference was that I had to choose FS1: (FSO: did not work, it booted the Grub probably from the HDD)

  1. When the Dell logo appears, hit F2 to enter the BIOS setup.
  2. Go on Boot Sequence, you need to ensure the BIOS is set to UEFI, disable Legacy option ROMS and check that secure boot is enabled on the Secure Boot Enable line.
  3. Now the most important operation... come back to Boot Sequence (General menu on the left) • click on Add Boot Option. The Add Boot Option window will pop up. Type a name in the Boot Option Name text area ("Ubuntu", for example).
    • Click the button to the left of the File Name text area. The EFI Boot Selection window will pop up.
    • In the File System drop down menu choose FS1 (or FS0) and EFI. Then using the directories section, navigate until you can choose SHIMx64.EFI (for Ubuntu only - for other distros use grubx64.efi or grubx.efi if your PC is not amd64, anyway it will be named grubxxxxx.efi) in the Files section.
  4. A new boot option will now appear on the top and in the boot menu. Save and exit
  5. The computer should now restart without problems.

Symlink to folders (Music, Pictures, … on other folder)
ln (link) -s (symbolic link), see “man ln” in the terminal
How to: https://askubuntu.com/a/56340/30631 ln -s /path/to/file /path/to/symboliclink

Delete current Videos folder (empty it first!): rm -rf ~/Videos
ln -s /media/Storage/Videos ~/Videos
ln -s /media/Storage/Pictures ~/Pictures
ln -s /media/Storage/Public ~/Public
ln -s /media/Storage/Music ~/Music
ln -s /media/Storage/Downloads ~/Downloads
ln -s /media/Storage/Online-Storage ~/Online-Storage
ln -s /media/Storage/Apps-n-Backup ~/Apps-n-Backup
ln -s /media/Storage/E-Books+Articles ~/E-Books+Articles
Can I change personal folder locations? nautilus Is there a difference between a symbolic link via terminal or right-click make link?

Not really helpful in this setting better with symlinks gnome - Change default user folders path?
gedit ~/.config/user-dirs.dirs

Trim and noatime for LVM volumes
12.04 - How to check if TRIM is working for an encrypted volume? - Ask Ubuntu

A lot of users see old info on SSDs. They now are just as reliable (unreliable?) as HDDs. So writes are not really an issue. But I do change SSD partitions to use noatime parameter. https://ubuntuforums.org/showthread.php?t=2424263&p=13878959#post13878959

Add discard parameter to the cryptdevice options in /etc/crypttab to make LUKS accept the discard behavior of the LVM partition.

/etc/fstab: /dev/mapper/ubuntu--vg-root / ext4 errors=remount-ro,discard,noatime 0 1

The whole fstab looks like this:

# <file system> <mount point>   <type>  <options>       <dump>  <pass>  
/dev/mapper/ubuntu--vg-root /               ext4    errors=remount-ro,discard,noatime 0       1  
# /boot was on /dev/nvme0n1p2 during installation  
UUID=eb0d2e85-12cf-446e-9594-92ca1005b5cd /boot           ext4    defaults        0       2  
# /boot/efi was on /dev/nvme0n1p1 during installation  
UUID=5295-E16A  /boot/efi       vfat    umask=0077      0       1  
/dev/mapper/ubuntu--vg-swap_1 none            swap    sw,discard              0       0  
#mount HDD  
/dev/mapper/sda1_crypt  /media/Storage   ext4    defaults,discard        0       2  

To check whether TRIM is active (after restart):
The SDD itself is trimmed automatically, handled by systemd, you can check this with: sudo systemctl status fstrim.timer (see comment https://askubuntu.com/a/19480/30631 and https://wiki.archlinux.org/index.php/Systemd/Timers )

LVM: sudo dmsetup table /dev/mapper/sda1_crypt --showkeys You are all set, if the last command shows a result: 1 allow_discards at the end.

Notice: enabling TRIM on an encrypted partition reduces the security of the encryption because it reveals which parts of the partition contain data and which don't. This can aid in some types of analysis. To put this in perspective this does not immediately make your data visible but it would be a similar security trade-off to using a sparse file as the encrypted block, or of setting up an encrypted partition but not initialising the free space with random data, as is usually recommended. См. Комментарий https://askubuntu.com/a/122007/30631

ответ дан 19 June 2020 в 21:24

Извините за мой плохой английский. Во-первых, о локальном для хранения больших файлов есть выбор. Один из вариантов — установить /home как раздел на жестком диске. Вы можете сделать это в расширенном методе разбиения. Преимущество в том, что он будет работать для всех пользователей, но недостаток в том, что некоторые данные приложения (в основном файлы конфигурации) также будут перемещены на жесткий диск. Таким образом, другой вариант — переместить только папки, такие как «Документы», «Видео», «Изображение» и т. Д., На жесткий диск. Я не согласен с предыдущим ответом на данный момент: правильный способ перемещения этих папок - это редактирование файла ~/.config/user-dirs.dirs и изменение значений переменных среды, таких как XDG_DOCUMENTS_DIR, вместо создания символических ссылок, поэтому переменные среды для эти папки будут действительным путем к папкам. Значки и ярлыки для этих папок будут работать нормально.

Во-вторых, вы захотите смонтировать раздел жесткого диска при загрузке, чтобы вы могли лучше использовать это, потому что пути к жесткому диску всегда будут действительными. Вы можете установить систему на ssd в обычном режиме, а затем создать раздел luks на жестком диске с помощью утилиты gnome-disks. Затем вы можете ввести пароль при загрузке или просто использовать ключевой файл, что, я думаю, является лучшим вариантом, если ваш ssd также зашифрован.

Учебник с запросом пароля https://averagelinuxuser.com/auto-mount-encrypted-partitions-at-boot/ Учебник с ключевым файлом https://www.golinuxcloud.com/mount-luks-encrypted-disk-partition-linux/

Просто совет: монтирование раздела в /media сделает этот носитель более заметным, появится в «других местах» в nautilus, но также будет неразборным в nautilus и всегда будет показывать значок в тире ubuntu точно так же, как флешка (вы можете изменить это в gnome-tweaks, но он также будет скрывать значки флешки). Я предпочитаю монтировать в /mnt (например, /mnt/hdd) или просто в новый каталог /, например /data. Вы можете увидеть свободное место на этом носителе в nautilus, просто открыв этот каталог, щелкнув правой кнопкой мыши, свойства, и вы можете добавить закладку в эту папку.

ответ дан 25 June 2020 в 14:27

Другие вопросы по тегам:

Похожие вопросы: