How to enable Secure Boot on MSI. About interfaces for setting Secureboot

After turning on, Secure Boot ceased to turn on PC

The Gigabyte Z490M Gaming X motherboard, included in the BIOS Secure Boot, rebooted and after that it does not turn on, does not react to the keyboard, there is no image, I tried to get the BIOS battery for half an hour, it did not help.

UEFI has always been the strangest that I can’t even go to BIOS now

enable, secure, boot, setting

By the way, what a crap with UEFI? If I switch, then only by taking out the vidyakha, replacing it with antiquity, t.to. no building, and back, the picture appears.

No, a few seconds are not always enough. Often in the chip strapping there are capacitors that can give a charge for a long time to power the chip, and the bios does not need much. Rather, the author also needed to receive bios with a closure of contacts for reset, if they are

Recently, I also turned it on and stopped responding to a computer to something after turning on, threw BIOS through a jamper on a motherboard, but this helped. If there is a flash drive and a button for flashing the BIOS, then you can download the Last version of the BIOS and this option to try. And some point thought that everything, GGVP

Yesterday on B450 Aorus Pro included Secure Boot. It also started up somehow strangely. The dark screen was, the power supply was helped by the circuit breaker on the BP. Then she started up.

Aurus Elites, this is not a motherboard at all, but the circus of freaks is evil, I own it myself, and the first month it was not sweetly given.

At first I took the elite, but I had to hand it over, my system did not start on it. I took a pro-version in return. So far, it works. But there was a strange plug on the inclusion of Secure Boot. I even don’t know. Either GB has become so fed like this, or for normal work, you need to buy a motherboard from 20K.

When you turn on the computer, after 5 seconds, when clicking on Caps Lock, it lights up?

This can be if the video card does not support the GOP UEFI or supports but the BIOS is very old, on the first boards with the GOP UEFI they were glitties. You need to reset the BIOS via Clear CMOS on MP (pre.turn off the PC out of the outlet, you can turn off the network filter), and after that, do not turn on the Secure Boot, just turn off CSM so that the W11 reports on compatibility, the Mycrosoft is in vain in vain.

What is secure boot (safe loading) and when it may need to be disconnected?

Secure Boot is one of the innovations introduced during the implementation of UEFI. This is, in turn, the receiver of the BIOS. He, respectively, is responsible for the preparation and loading of the OS. BIOS can be considered a very simple utility with a primitive design that is stitched in the motherboard. UEFI performs the same functions, but this is already a very beautiful and advanced program. For example, with perseverance using UEFI, you can even view the contents of the connected drives, which would be considered an incredible innovation for BIOS.

Not only aesthetic motives were guided by UEFI creators. One of the important goals during development was to detect and limit the influence of malicious. It was assumed that the technology would interfere with its loading along with the operating system (OS), as well as execution on the level of the OS nucleus after its launch. Honor to execute this important mission fell on the secure boot protocol. The technical implementation was this: a cryptographic circuit with open and closed signatures (electronic digital signatures, EDS) was used. In general, the goals were achieved, but in practice this required certain and correct actions not only from users, but also from manufacturers of computer equipment. The description of the whole process will take a lot of time, so we dwell on key features:

  • The software components (drivers, OS boots) have special EDSs, they are also in the firmware of the motherboard, but the characteristics of these EDS are different;
  • When using computer resources, the components must be proved using the EDS that they are not viruses;
  • The key security factor is a closed key, which ideally should be unique for each PC.

Security boot fail. Acer. BIOS 100% способ решения проблемы.Помогло? Подпишись на канал)

The difficulties with technology began at the implementation stage, when Microsoft said that using the protocol would limit the installation of other OS on computers with a pre.installed Windows. Then they abandoned such plans under the onslaught of the public, but the sediment remained. Today, the main difficulty is that the manufacturers of motherboard use the same closed keys for all their products or for individual lines. In any case, good intentions led to a dead end.

In the vast majority of cases, disconnecting Secure Boot is worth solving two problems:

Secure boot itself does not load the system in any way, since it works at a lower software level. The disconnection of the protocol will definitely not improve the responsiveness of the system and will not increase the speed of the processor.

How to disable Secure Boot protection in Bios?

Note that some users mistakenly think that the Secure Boot protocol is disconnected in BIOS. This rather primitive firmware has no, it was not, and there can be no support for securbut. This security protocol works exclusively on UEFI and the disconnection must be made there precisely. The nature of this error is quite simple. For many years, users are used to the fact that everything that occurs on the screen before loading OS is BIOS. In fact, the times of this software superstructure are leaving and it is already obsolete in any way.

It is important that this security protocol is supported only in Windows 8 and later versions. Therefore, if the Secure Boot is included in your motherboard firmware, but Windows 7 is installed on the PC, then you need to turn off anything. The option of safe loading still does not work, and possible problems with the launch of the OS must be sought in other places.

How to disable Secure Boot and UEFI on Acer Aspire laptop?

There are many models of laptops of this manufacturer, but the specificity is such that first it is required to create your own password. The general algorithm of action is as follows:

  • Go to BIOS-UEFI by pressing the F2 or Delete key;
  • Go to the “Security” tab, select the “Set Supervisor Password” option;
  • In a special window, enter the password 2 times. Do not sophisticate, use a simple combination;
  • Success will be confirmed by the message “Changs Have Been Saved”;
  • Go to the “boot” tab and in the “boot mode” line indicate the value of “legacy”;
  • press F10 and make a recording of the modifications of installations;
  • With subsequent overload, enter UEFI again;
  • Go to the “Security” tab, select the “Set Supervisor Password” option, enter the previously specified password;
  • Go to the “Boot” tab and in the “Secure Boot” line indicate the value of “Disabled”;
  • Save changes again.

Secure boot disconnect on Pavilion laptops and other HP models?

  • To enter BIOS, press on ESC or ESC = F10 before starting Windows.
  • Go to the System Configuration tab, and find the line “Boot Options” in it.
  • Set the “Secure Boot” criterion “Disabled”, and “legacy support”. “Enabled” for the criterion.
  • The system will ask whether you are really ready to change the settings. confirm this by pressing the “Yes”.
  • At the end, you need to save the changes made by pressing F10 and confirmation of “Yes”.

With subsequent rebooting, be careful. The system will be rebuilt and turn on the “protection from the fool”. You need to look at what goes after the inscription “Operating System Boot Mode Change (021)”. there will be a digital sequence. Take it and click Enter. If you just need to disable Secure Boot, then you don’t need to do anything further. If everything was initially done for the sake of the opportunity to load from the USB carrier, then immediately after passing “Protection from the fool”, click the ESC, and then F9. Set the required flash drive the maximum priority so that it is loaded first on a hard drive.

On Dell laptops

  • F12 immediately after turning on the computer and before the start of the OS.
  • Go to the Boot tab in the top panel and go to UEFI Boot subsection.
  • Install the “Secure Boot” criterion “Disabled” option.
  • Save changes (F10 = “Yes”) and reboot the laptop.

Secure Boot on Lenovo and Toshiba laptops

To enter UEFI on these devices, you need to press F12, and then perform the following actions:

  • Go to the “Security” tab;
  • Set the “Secure Boot” criterion option “Disabled”;
  • Go to the Advanced tab, and go to the System Configuration menu in it;
  • Install for the criterion “Boot Mode (OS Mode Selection)” option “CSM Boot (CMS OS), (UEFI and LeGacy OS)”;
  • Save everything by pressing F10 = “Yes”.

How to check if safe load is enabled?

The inability to be updated from 10-ki to Windows 11 may be associated with several reasons. Therefore, at first it would not hurt to make sure whether the safe load is disabled on the computer. For this:

one

Another way is to use the free program Whynotwin11, which is designed to determine the compatibility of the computer with Windows 11:

Now that we have found that the reason for the impossibility of updating to Windows 11 lies in the disconnected secure boot function, you can start turning it on.

Turn on safe loading from under Windows 10

To begin with, open the “Parameters” window with a combination of “Win ​​I” keys (or clicking on the “Parameters” icon with the image of the gear in the Start menu). Next, open the “Restoration” tab in this window, then in the right side of it in the “Special load options” block, click on the “Reload now” button:

Further actions will be performed after rebooting the computer:

How to enable Secure Boot back

To protect the computer from malicious and unauthorized software, you can activate the safe loading mode back. Next, consider how to turn off Secure Boot in BIOS. It is done in the same way as when disconnecting, but before from the computer it is necessary to remove all unsigned products: operating systems, drivers for equipment. Sometimes you even have to drop the BIOS/UEFI settings to factory.

After removing the non.signed operating system, drivers and extracting equipment that does not have a digital signature, reboot the computer and go to the BIOS settings. Open the section of the motherboard configuration and click the load.

Visit Windows 8 Configuration.

Go to Secure Boot from it.

The value of the Secure Boot option switch to the inclusive position.

Leave the UEFI settings menu while maintaining changes.

Solution with Secure Boot problems

There are several nuances when working with safe loading.

  • In BIOS, you need to enable UEFI settings. the Legacy Boot Mode mode is disabled.
  • For UEFI, the drive must have GPT, MBR is used by old BIOS versions.

To verify the format of the data placement table:

Open the task manager via Win X

Expand the branch of disk devices and open the properties of a hard drive.

In the Tom tab, click on the button to fill in and pay attention to the line of the sections style.

To change the MBR to GPT, you need to copy all the data to another drive, format the current in GPT and drop the files back.

Some firmware managers support the reset of keys to factory. The option is mainly in the same BIOS Setup section as Secure Boot. If your UEFI supports this opportunity, restore the keys and reboot the computer while maintaining a new configuration.

Windows 11 guides 11

Official system requirements are indicated on the website Microsoft:

  • Processor: 64-bit dual-core with a clock frequency of at least 1 GHz;
  • RAM: 4 gigabytes;
  • Drummer: 64 gigabytes;
  • With support for DirectX 12 or later version and WDDM 2 driver.0;
  • display: at least 9 inches;
  • Other: TPM 2 module.0 and support secure boot.

Despite the rather modest requirements for the processor, the company introduced a list of officially supported CPU. It does not include the fairly common first.generation AMD Ryzen (with Zen architecture) and Intel processors to the eighth generation (Coffee Lake). But you should not panic, most likely, these are just official recommendations of the company, and not an exhaustive list. A full list of processors can be found by links: Intel and AMD.

Nevertheless, the PC Health Check program, which is designed to verify the compatibility of your system with Windows 11, is unlikely to give green light officially illegitimate processors. The author of this article never managed to “get permission” on the Ryzen 1600 processor.

Activate the TPM software module

TPM is a cryptographic module for data encryption and hacking protection. It is a separate chip on the motherboard. Most models selling in such a module do not have the necessary certification of such equipment. But there may be a special slot for its connection. Also, many motherboards support TPM software implementation.

enable, secure, boot, setting

Please note that the system requirements of Windows 11 are indicated by TPM version 2.0. Recall that earlier the company stated that there would be enough older version 1.2.

To check the presence of a module, press the combination of the Win R keys and execute the tpm command.MSC. The window “Management of the trusted platform module on the local computer” will open. If a warning is displayed “it is not possible to find a compatible trusted platform module”, then the module is not active.

Consider the activation of the module on the example of the ASUS motherboard with logic from AMD. First you need to get into the BIOS (when loading, click DEL or F2). Then click F7 to move on to extended settings. Switch to the Advanced tab and select AMD FTPM Configuration. Next, activate the AMD FTPM Switch line. Read more about the activation of the TPM module on other motherboards in our guide “How to configure TPM 2.0 for installing Windows 11 “.

In addition, the network has already learned how to bypass the Windows 11 requirement on TPM by replacing the Appraiserres file.DLL that can be taken from the image of Windows 10.

I can’t enable the safe loading mode for installing Winows 11

Good afternoon. In connection with the release of Windows 11, I decided to personally look out of curiosity at the new version of OC from Microsoft. Unfortunately, I faced a very unpleasant problem during the implementation of the requirement to install a new version of OC, the essence of which was not included in the safety mode of safe loading on my computer. Initially, the Windows 11 installer informed me that my device is not supported due to the safe load turned off on my PC. With grief in half, I was able to include this function in UEFI of my mother:

After that, to my surprise, the following picture awaited me in the information about the system:

I have not yet found a solution to my problem on the Internet, so I want to contact here for help with its solution. Suddenly, here someone also came across a similar situation and knows how to solve it.

Change the marking of the system disc with MBR to GPT (YouTube and Google to help, I did through the Aomei utility), turn off CSM in the bios and turn on the safe loading. Everything is quite simple and quickly done.

Same. You need to turn the disk from MBR to GPT.

Will not help.He has a system installed in Legacy mode and turning off the compatibility mode will simply not allow the system to load.You need to demolish everything.The same problem, only I put on update.Data is more important.

There is a converter in GPT, no need to demolish everything

Tried to convert the system disk? I read about it, but they say that the system may not start after this.

I personally tried it. I turned on the old BIOS Legacy. First converted a disk from MBR to GPT from Windows via CMD for UEFI/Secure Boot for Windows 11. It seems to have converted, but I could not turn on UEFI instead of BIOS, since there was no stupid choice of UEFI. Then I rebooted the PC again, I go into information about the system and see that the BIOS mode has changed to UEFI. Looks like a disk conversion from MBR to GPT helped and he himself systematically switched.

What commands for conversion used? I know only the one that cleans the data on the disk.

Check that conversion is possible. We launch a command line with admin rights and write in it MBR2GPT /VALIDATE /AllowFullos

If everything is fine. MBR disk and can be solved. Overload the PC through the Advanced Startup option in the Windows settings section

PC will overload the expanded load mode (blue screen). there we choose Trubleshoot (elimination of problems), then. Advanced Options (additional options). and after. Command Prompt (command line).

In the launched command line, we launch the MBR2GPT /Convert command and wait for the end of the disk conversion.

After the conversion is completed, overload the computer, go to the BIOS and switch UEFI, Secure Boot options and the correct loading. It will change to Windows Boot Manager

The other day I literally found out what can be adjusted through the Aomei Partition Assistant Pro. There, in two buttons, you can convert, without unnecessary actions from under Windows with CMD. Friends through this disk attached to this without loss of data.

A little about UEFI and Secure Boot

UEFI (Unified Extensible Firmware Interface). replacing the outdated BIOS. This specification was invented by Intel for Itanium, then it was also called EFI (Extensible Firmware Interface), and then was ported to X86, X64 and ARM. It is strikingly different from BIOS both the loading procedure itself and the methods of interaction with the OS. If you bought a computer in 2010 and later, then, most likely, you have UEFI.

The main differences between UEFI and BIOS:

How is the loading in UEFI?

With the GPT section with the EF00 identifier and the FAT32 file system, the \ EFI \ Boot \ Boot file is loaded and launched by default [architecture name].EFI, for example \ EFI \ BOOT \ BOOTX64.Efi t.e. To, for example, create a bootable flash drive with Windows, just mark the flash drive in GPT, create a FAT32 section on it and simply copy all files from the ISO-image. There is no more boot sectors, forget about them. Loading in UEFI is much faster, for example, loading my laptop with Archlinux by pressing the power button to a completely efficient state is only 30 seconds. As far as I know, Windows 8 also has very good optimization of download speeds in UEFI mode.

Secure Boot

“I heard Microsoft implementing Secure Boot in Windows 8. This technology does not allow unauthorized code to be performed, for example, to bootloaders to protect the user from Malware. And there is a campaign from Free Software Foundation against Secure Boot, and many people were against it. If I buy a computer with Windows 8, can I install Linux or other OS? Or this technology allows you to run only Windows?””

To begin with, this technology was not invented in Microsoft, but it is included in the UEFI 2 specification.2. The included Secure Boot does not mean that you cannot run the OS that is different from Windows. In fact, computers and laptopes certified for launching Windows 8 are required to be able to disable Secure Boot and the ability to control the keys, so there is nothing to worry about here. Unlotted Secure Boot is only on ARM tablets with a pre.installed Windows!

What does Secure Boot give? It protects against the execution of the unsigned code not only at the loading stage, but also at the stage of the OS, for example, both in Windows and in Linux, the signatures of the nucleus are checked, so you cannot execute the malicious code in the kernel mode. But this is true only if there is no physical access to the computer, t.to., In most cases, with physical access, the keys can be replaced with your.

Secure Boot has 2 modes: setup and user. The first mode is for configuration, from it you can replace PK (Platform Key, by default from OEM), Kek (Key Exchange Keys), DB (base of the allowed keys) and DBX (base of the recalled keys). Kek may not be, and everything can be signed by PK, but no one does so, it seems like. PK is the main key signed by KEK, in turn, KEK keys (there may be several) sign DB and DBX. So that you can start some signed.EFI-file from under the user mode, it must be signed by the key, which in DB, and not in DBX.

For Linux there are 2 converters that support Secure Boot: Shim and Preloader. They are similar, but there are small nuances. SHIM has 3 types of keys: secure boot keys (those in UEFI), shim keys (which can be generated yourself and indicated during compilation), and MOK (Machine Owner Key, stored in NVRAM). SHIM does not use the loading mechanism through UEFI, so the bootloader that does not support SHIM and does not know anything about MOK will not be able to execute the code (thus, the Gummiboot bootloader will not work). Preloader, on the contrary, embeds its authentication mechanisms in UEFI, and there are no problems. Shim depends on MOK, T.e. binary should be changed (signed) before performing them. Preloader “remembers” the right binary, you inform him if you trust them or not. Both converters are compiled with a valid signature from Microsoft, so it is not necessary to change UEFI keys.

Secure Boot is designed to protect against Butitkites, from an evil MaID attack, and, in my opinion, does it effectively. Thank you for your attention!

Part is the fifth. Secureboot

That’s what at all?

I do not think that after a dozen articles on Habre it is worth talking about Secureboot too much. this has already been done more than once and without me. Nevertheless, it would not be anything at all to tell a crime against a stranger with the topic of the reader, so let’s go at the top, and those who want to know everything and thoroughly send them to the specification.

SecureBoot — это программная технология, при помощи которой UEFI-совместимая прошивка может проверить подлинность исполняемых ей внешних компонентов (загрузчиков, драйверов и UEFI OptionROM’ов). Эти исполняемые компоненты должны быть подписаны ЭЦП, которая проверяется во время загрузки и в случае ее полного отсутствия, повреждения, отсутствия в списке доверенных (db) или присутствия в списке запрещенных (dbx) запуск соответствующего компонента не происходит (иногда это поведение настраивается, что тоже может сыграть злую шутку, но об этом позже). В качестве алгоритма ЭЦП в данный момент стандартом рекомендуется комбинация из RSA2048 и SHA256, которые и используются почти на всех виденных мной в живую системах.

Немного о ключах

SecureBoot использует следующую иерархию ключей:

В зависимости от необходимого уровня безопасности, PK может быть сгенерирован следующим образом:

  • Собственный ключ для каждого отдельного PC. Максимальная безопасность, она же — максимальный геморрой с управлением ключами, зато и утечки практически не страшны, и компрометация системы с утекшим ключом не ведет к компрометации соседней с ней.
  • Общий ключ для каждой модели мат. платы. Менее безопасно, но проще в обслуживании, особенно если парк машин собран на одних и тех же платах.
  • Общий ключ каждой линейки мат. плат. То же самое, что и в предыдущем пункте, еще немного меньшая безопасность по цене чуть большего удобства, классический случай security-convenience trade-off.
  • Общий ключ для всех плат производителя. Самое нелепое с точки зрения безопасности, но при этом, к сожалению, чуть ли не самое популярное решение. Ключ при этом хранится прямо в дереве исходных текстов и утекает вместе с ними, после чего никакой SecureBoot на платах этого производителя уже не помеха. При этом исходники чаще всего утекают тихо, и производитель может еще пару лет выпускать заведомо уязвимую продукцию.

Кто тут в цари первый?

В большинстве конфигураций SecureBoot по умолчанию PK предоставляется производителем мат. платы, в KEK лежит единственный сертификат Microsoft Corporation KEK CA 2011, а в db обязательно присутствует сертификат Microsoft Windows Production CA 2011, но иногда к нему добавляют сертификат Canonical и сертификат производителя платформы, которым подписаны разного рода утилиты для обновления прошивки и вот это все. Хранилище dbx на большинстве систем пустое, но не так давно MS внесли в него несколько записей и теперь требуют их наличия на новых системах для получения сертификата Windows 10 Ready. Получается, что с точки зрения SecureBoot в конфигурации по умолчанию, вашей системой владеет производитель мат. платы, а единственный ее авторизованный пользователь — Microsoft. К счастью (и по большей части благодаря давлению сообщества СПО) эта печальная картина на подавляющем большинстве систем для x86 может быть разрушена удалением стандартных ключей и добавлением собственных из BIOS Setup, но про это я планирую написать отдельно.

Несовместимость с CSM

Атаки на SecureBoot

О векторах

Для начала следует понять, какие именно части SecureBoot могут быть атакованы и чем грозит успешная атака:

  • NVRAM. Так как и PK, и KEK, и db и dbx, и другие относящиеся к SecureBoot переменные хранятся в NVRAM, то успешная атака на нее чаще всего приводит к отключению или компрометации SecureBoot.
  • Реализация. Если с NVRAM все в порядке, проблемы могут быть в реализации проверки подписи, хранения ключей и т.п.
  • Ключи. Атака одновременно и сложная, и простая. Всего-то надо стащить у кого-нибудь из цепочки доверия его закрытый ключ и подписать им свой вредоносный загрузчик.
  • Доверенный загрузчик. Еще проще, чем предыдущий пункт, особенно для обладателей сертификата Canonical в db. Просто меняем текущий загрузчик на подписанный вышеупомянутым сертификатом GRUB2 из репозиториев Ubuntu, который в свою очередь загрузит что угодно любой степени вредоносности.

Собственно атаки

Отключение SecureBoot удалением PK

Если у атакующего имеется доступ на запись в хранилище NVRAM, что нередко случается у любителей защитить микросхему SPI лишь при помощи пары PR-регистров, то текущий PK можно банально удалить, что автоматически отключит SecureBoot, переведя его в режим установки новых ключей.

Отключение SecureBoot правкой CurrentMode

Эта атака — комбинация из атаки на NVRAM и реализацию. На некоторых системах текущий режим SecureBoot управляется записью в переменной Setup, и если она неожиданно для всех имеет флаг RT, то атакующий может отключить SecureBoot просто записав в Setup ноль по нужному смещению, которое, в свою очередь, легко можно найти анализом дампа IFR. Атака тупая как валенок, но до сих пор имеется куча систем, которые ей подвержены.

enable, secure, boot, setting

Обход SecureBoot правкой ExecutionPolicy

How To Enable or Turn on Secure Boot in Any BIOS | Fix Vanguard Problem | This PC can run Windows 11

Вариация предыдущей атаки, но отключается на этот раз не сам SecureBoot, а запрет на продолжение загрузки при несовпадении или отсутствии ЭЦП. Тоже требует флага RT на переменной Setup и встречается чуть реже, чем предыдущий вариант, но зато позволяет обойти SecureBoot тихо, не отключая его.

Обход SecureBoot повреждением NVRAM

На некоторых системах для обхода SecureBoot достаточно немного испортить NVRAM (к примеру, заполнив хранилище под завязку), чтобы отключить либо обойти SecureBoot. Встречается такое поведение редко, но атака настолько простая, что есть смысл опробовать ее на любой системе. В крайнем случае, вместо обхода SecureBoot может получиться DoS, если драйвер NVRAM совсем плохой.

Обход SecureBoot при помощи PCI(e)-устройства

Теоретически, запуск UEFI OptionROM’ов из PCI-устройств при включенном SecureBoot не должен происходить, если соответствующий OROM не прошел верификацию, но на практике огромно количество систем доверяет PCI-устройствам безоговорочно и запускает оттуда все без каких-либо проверок. Примеров подобного поведения много, а любые системы без SecureBoot подвержены такой атаке автоматически, именно поэтому вынос PCI(e) на внешние разъемы, вроде Thunderbolt, Firewire, PCMCIA, ExpressCard и т.п. — преступление против безопасности платформы, даже без учета того, что любое PCI-устройство может инициировать DMA с любым регионом физической памяти, кроме SMRAM (и то только если производитель платформы не забыл установить защиту) и утащить у ОС и пользователя все их секреты.

Обход SecureBoot преобразованием загрузчика из PE в TE

Обход SecureBoot загрузкой с внешнего носителя

Это даже не совсем атака, а скорее непонимание некоторых пользователей, что SecureBoot вообще не защищает от подмены загрузчика, и физически присутствующий атакующий может загрузить систему со своего носителя. Иногда от этого пытаются защититься паролем на BIOS и меню выбора загрузочного устройства, но добрые разработчики из MS позволяют выбрать его и из Windows, для чего достаточно зажать Shift и выбрать действие «перезагрузка» на экране входа в систему, а затем выбрать в появившемся меню нужно загрузочное устройство. Дорогим товарищам из MS — мое большое спасибо.

Готовим плацдарм

Начнем с лирического отступления о наличии нужного софта для разных ОС. Несмотря на то, что Microsoft является одним из разработчиков технологии, в открытом доступе до сих пор отсутствуют нормальные средства для работы с ней из Windows (ключи можно сгенерировать утилитой MakeCert из Windows SDK, а для всего остального предлагается использовать HSM третьих лиц за большие деньги). Я подумывал сначала взять и написать нужную утилиту на Qt, но потому решил, что ключи и подписи каждый день генерировать не нужно, а на пару раз хватит и существующих решений. Можете попробовать переубедить меня в комментариях, если хотите. В общем, для всего нижеперечисленного вам понадобится Linux (который можно запустить с LiveUSB, если он у вас не установлен). Для него существует целых два набора утилит для работы с SecureBoot: efitools/sbsigntool и EFIKeyGen/pesign. У меня есть положительный опыт работы с первым набором, поэтому речь пойдет именно о нем. В итоге, кроме Linux, нам понадобятся несколько вещей: 1. Пакет openssl и одноименная утилита из него для генерирования ключевых пар и преобразования сертификатов из DER в PEM. 2. Пакет efitools, а точнее утилиты cert-to-efi-sig-list, sign-efi-sig-list для преобразования сертификатов в формат ESL и подписи файлов в этом формате, и KeyTool.efi для управления ключами системы, находящейся в SetupMode. 3. Пакет sbsigntool, а точнее утилита sbsign для подписи исполняемых файлов UEFI (т.е. загрузчиков, DXE-драйверов, OptionROM’ов и приложений для UEFI Shell) вашим ключом. Загрузите Linux, установите вышеуказанные пакеты, откройте терминал в домашней директории и переходите к следующему шагу.

Как обычно, есть несколько способов сделать что-либо, и чем мощнее используемый инструмент, тем таких способов больше. OpenSSL же как инструмент развит настолько, что кажется, что он умеет делать вообще всё, а если почитать к нему man — то и абсолютно всё остальное. Поэтому в этой статье я ограничусь непосредственной генерацией ключевых файлов, а танцы вокруг создания собственного CA оставлю на самостоятельное изучение.

Генерируем ключевые пары

Конвертируем открытые ключи в формат ESL

Теперь нужно сконвертировать открытые ключи из формата PEM в понятный UEFI SecureBoot формат ESL. Этот бинарный формат описан в спецификации UEFI (раздел 30.4.1 в текущей версии 2.5) и интересен тем, что файлы в нем можно соединять друг с другом конкатенацией, и этот факт нам еще пригодится. Ключ.g добавляет к сгенерированному ESL-файлу GUID, в нашем случае — случайный, полученый запуском утилиты uuidgen и использованием ее вывода. Если этой утилиты у вас нет — придумывайте GUIDы сами или оставьте значение по умолчанию.

Подписываем ESL-файлы

Для правильно работы SecureBoot необходимо, чтобы PK был подписан сам собой, KEK подписан PK, а хранилища db и dbx — сответственно KEK. При этом PK не может быть несколько, а вот ситуация с несколькими KEK хоть и встречается в дикой природе, но я все же настоятельно рекомендую удалить предустановленный ключ Microsoft из KEK по простой причине — db и dbx могут быть подписаны любым ключом из хранилища KEK, т.е. если ключ MS оттуда не удалить, то у MS будет возможность управлять содержимым db и dbx, т.е. добавлять любые новые ключи или хеши в список доверенной загрузки и удалять из него существующие. На мой взгляд, это немного слишком, и если мы берем управление ключами в свои руки, то нужно делать это до конца.

Ну тогда вам прямая дорога вот сюда, там в самом конце раздела 1.3.4.3 есть ссылка на сертификат Microsoft Corporation KEK CA 2011 в формате DER, из которого нужно сначала получить PEM командой затем сконвертировать полученный PEM в ESL командой после чего добавить получившийся файл к нашему файлу KEK.esl командой Теперь Microsoft такой же авторизованный пользователь вашей платформы, как и вы сами, с чем я вас и поздравляю.

С другой стороны, если вы не хотите терять возможность загрузки Windows и подписанных ключом Microsoft исполняемых компонентов (к примеру, GOP-драйверов внешних видеокарт и PXE-драйверов внешних сетевых карточек), то к нашему ISK.esl надо будет добавить еще пару ключей — ключ Microsoft Windows Production CA 2011, которым MS подписывает собственные загрузчики и ключ Microsoft UEFI driver signing CA, которым подписываются компоненты третьих сторон (именно им, кстати, подписан загрузчик Shim, с помощью которого теперь стартуют разные дистрибутивы Linux, поддерживающие SecureBoot из коробки). Последовательность та же, что и под спойлером выше. Конвертируем из DER в PEM, затем из PEM в ESL, затем добавляем к db.esl, который в конце концов надо будет подписать любым ключом из KEK:

enable, secure, boot, setting

Теперь подписываем PK самим собой: Подписываем KEK.esl ключом PK: Подписываем db.esl ключом KEK:

Если еще не надоело, можно добавить чего-нибудь еще в db или создать хранилище dbx, нужные команды вы теперь знаете, все дальнейшее — на ваше усмотрение.

Подписываем загрузчик

Осталось подписать какой-нибудь исполняемый файл ключом ISK, чтобы проверить работу SecureBoot после добавления ваших ключей. Для тестов я советую подписать утилиту RU.efi, она графическая и яркая, и даже издалека видно, запустилась она или нет. На самом деле, утилита эта чрезвычайно мощная и ей можно натворить немало добрых и не очень дел, поэтому после тестов лучше всего будет её удалить, и в дальнейшем подписывать только загрузчики. В любом случае, подписываются исполняемые файлы вот такой командой: Здесь я заодно переименовал исполняемый файл в bootx64.efi, который нужно положить в директорию /EFI/BOOT тестового USB-носителя с ФС FAT32. Для 32-битных UEFI (избавь вас рандом от работы с ними) используйте bootia32.efi и RU32.efi.

В результате вот этого всего у вас получились три файла.auth, которые нужно будет записать «как есть» в NVRAM-переменные db, KEK и PK, причем именно в таком порядке. Скопируйте все три файла в корень другого USB-носителя с ФС FAT32, на котором в качестве /EFI/BOOT/bootx64.efi выступит /usr/share/efitools/efi/KeyTool.efi (скопируйте его еще и в корень, на всякий случай) и ваш «набор укротителя SecureBoot» готов.

Укрощение строптивого

AMI AptioV

У большинства прошивок, основанных на коде AMI, управление технологией SecureBoot находится на вкладке Security, у меня это управление выглядит так: Заходим в меню Key Management (раньше оно было на той же вкладке, сейчас его выделили в отдельное) и видим там следующее: Выбираем нужную нам переменную, после чего сначала предлагают выбрать между установкой нового ключа и добавлением к уже имеющимся, выбираем первое: Теперь предлагается либо установить значение по умолчанию, либо загрузить собственное из файла, выбираем последнее: Далее нужно устройство и файл на нем, а затем выбрать формат этого файла, в нашем случае это Authenticated Variable: Затем нужно подтвердить обновление файла, и если все до этого шло хорошо, в результате получим лаконичное сообщение: Повторяем то же самое для KEK и PK, и получам на выходе вот такое состояние: Все верно, у нас есть единственный PK, всего один ключ в KEK и три ключа в db, возвращаемся в предыдущее меню кнопкой Esc и включаем SecureBoot: Готово, сохраняем настройки и выходим с перезагрузкой, после чего пытаемся загрузиться с нашей флешки и видим вот такую картину: Отлично, неподписанные загрузчики идут лесом, осталось проверить подписанный. Вставляем другую флешку, перезагружаемся и видим что-то такое: Вот теперь можно сказать, что SecureBoot работает как надо. Если у вашего AMI UEFI такого интеейса для добавления ключей нет, то вам подойдет другой способ, о котором далее.

Insyde H2O

Здесь все несколько хуже, чем в предыдущем случае. Никакого интеейса для добавления собственных ключей нет, и возможностей настройки SecureBoot предлагается всего три: либо удалить все переменные разом, переведя SecureBoot в Setup Mode, либо выбрать исполняемый файл, хеш которого будет добавлен в db, и его можно будет запускать даже в том случае, если он не подписан вообще, либо вернуться к стандартным ключам, в качестве которых на этой машине выступают PK от Acer, по ключу от Acer и MS в KEK и куча всякого от Acer и MS в db. Впрочем, нет интеейса — ну и черт с ним, у нас для этого KeyTool есть, главное, что в Setup Mode перейти можно. Интересно, что BIOS Setup не дает включить SecureBoot, если пароль Supervisor Password не установлен, поэтому устанавливаем сначала его, затем выполняем стирание ключей: После чего на соседней вкладке Boot выбираем режим загрузки UEFI и включаем SecureBoot: Т.к. фотографии у меня посреди ночи получаются невыносимо отвратительными, то скриншоты KeyTool‘а я сделаю на предыдущей системе, и придется вам поверить в то, что на этой все выглядит точно также (мамой клянусь!). Загружаемся с нашего носителя в KeyTool, и видим примерно следующее: Выбираем Edit Keys, попадаем в меню выбора хранилища: Там сначала выбираем db, затем Replace Keys, затем наше USB-устройство, а затем и файл: Нажимаем Enter и без всяких сообщений об успехе нам снова показывают меню выбора хранилища. Повторяем то же самое сначала для KEK, а затем и для PK, после выходим в главное меню двойным нажатием на Esc. Выключаем машину, включаем заново, пытаемся загрузить KeyTool снова и видим такую картину (которую я утащил из дампа прошивки, ее фото на глянцевом экране еще кошмарнее, чем предыдущие): Ну вот, одна часть SecureBoot’а работает, другая проверяется запуском подписанной нами RU.efi и тоже работает. У меня на этой системе Windows 8 установлена в UEFI-режиме, так вот — работает и она, Microsoft с сертификатом не подвели.

Phoenix SCT

Здесь возможностей еще меньше, и во всем меню Secure Boot Configuration на вкладке Security всего два пункта: возврат к стандартным ключам и удаление всех ключей с переводом системы в SetupMode, нам нужно как раз второе: Затем на вкладке Boot нужно выбрать тип загрузки UEFI, включить SecureBoot, и создать загрузочную запись для KeyTool‘а, иначе на этой платформе его запустить не получится: Нажимаем Yes, выходим с сохранением изменений, перезагружаемся, нажимаем при загрузке F12, чтобы попасть в загрузочное меню, оттуда выбираем KeyTool, работа с которым описана выше. После добавления ключей и перезагрузки попытка повторного запуска KeyTool‘а заканчивается вот так: При этом установленный на той же машине Linux продолжает исправно загружаться, как и подписанная нами RU.efi, так что SecureBoot можно признать работоспособным.