Skip to contentSkip to conversation

Automatic TPM Disk Unlock

PATCH Superseded Hernan Gatta 5 participants 21 messages Jan 24, 2022 – Jan 28, 2022 Kbuild

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#1 lore raw

PATCH 1/5 protectors: Add key protectors framework

In reply to Hernan Gatta

From: Hernan Gatta <[email protected]>

A key protector encapsulates functionality to retrieve an unlocking key for a fully-encrypted disk from a specific source. A key protector module registers itself with the key protectors framework when it is loaded and unregisters when unloaded. Additionally, a key protector may accept parameters that describe how it should operate.

The key protectors framework, besides offering registration and unregistration functions, also offers a one-stop routine for finding and invoking a key protector. This method accepts a formatted string with the name of a key protector followed optionally by colon-separated, key protector-specific parameters. If a key protector with the specified name exists and if an unlocking key is successfully retrieved by the latter, the function returns to the caller the retrieved key and its length.

---
 grub-core/Makefile.am       |  1 +
 grub-core/Makefile.core.def |  1 +
 grub-core/kern/protectors.c | 98 +++++++++++++++++++++++++++++++++++++++++++++
 include/grub/protector.h    | 55 +++++++++++++++++++++++++
 4 files changed, 155 insertions(+)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 include/grub/protector.h
grub-core/Makefile.am +1 -0
index ee88e44..f78cd9d 100644
@@ -90,6 +90,7 @@ endif
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/mm.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/parser.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/partition.h
+KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/protector.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/stack_protector.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/term.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/time.h
grub-core/Makefile.core.def +1 -0
index 8022e1c..e4ae78b 100644
@@ -138,6 +138,7 @@ kernel = {
   common = kern/misc.c;
   common = kern/parser.c;
   common = kern/partition.c;
+  common = kern/protectors.c;
   common = kern/rescue_parser.c;
   common = kern/rescue_reader.c;
   common = kern/term.c;
grub-core/kern/protectors.c new file +98 -0

98 lines not on this page · raw message

include/grub/protector.h new file +55 -0

55 lines not on this page · raw message

Signature · 1 line
1.8.3.1
#9 lore raw

PATCH 4/5 cryptodisk: Support key protectors

In reply to Hernan Gatta

From: Hernan Gatta <[email protected]>

Add a new parameter to cryptomount to support the key protectors framework: -k. This parameter is accepted whenever the cryptomount command is used to mount a specific disk either via a disk specification (e.g., (hd0,gpt1)) or by UUID, but not when disks are mounted in bulk (i.e., via -a or -b). The parameter is used to automatically retrieve a key from the specified key protector.

Signed-off-by <Hernan Gatta [email protected]>
---
 Makefile.util.def           |  1 +
 grub-core/disk/cryptodisk.c | 21 ++++++++++++++++++++-
 2 files changed, 21 insertions(+), 1 deletion(-)
Makefile.util.def +1 -0
index f8b356c..39b53b3 100644
@@ -35,6 +35,7 @@ library = {
   common = grub-core/kern/list.c;
   common = grub-core/kern/misc.c;
   common = grub-core/kern/partition.c;
+  common = grub-core/kern/protectors.c;
   common = grub-core/lib/crypto.c;
   common = grub-core/lib/json/json.c;
   common = grub-core/disk/luks.c;
grub-core/disk/cryptodisk.c +20 -1
index 4970973..176dd56 100644
@@ -26,6 +26,7 @@
 #include <grub/file.h>
 #include <grub/procfs.h>
 #include <grub/partition.h>
+#include <grub/protector.h>
 
 #ifdef GRUB_UTIL
 #include <grub/emu/hostdisk.h>
@@ -42,6 +43,7 @@ static const struct grub_arg_option options[] =
     {"all", 'a', 0, N_("Mount all."), 0, 0},
     {"boot", 'b', 0, N_("Mount all volumes with `boot' flag set."), 0, 0},
     {"password", 'p', 0, N_("Password to open volumes."), 0, ARG_TYPE_STRING},
+    {"protector", 'k', 0, N_("Unlock disk using the specified key protector."), 0, ARG_TYPE_STRING},
     {0, 0, 0, 0, 0, 0}
   };
 
@@ -1160,6 +1162,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
 {
   struct grub_arg_list *state = ctxt->state;
   struct grub_cryptomount_args cargs = {0};
+  grub_err_t err;
 
   if (argc < 1 && !state[1].set && !state[2].set)
     return grub_error (GRUB_ERR_BAD_ARGUMENT, "device name required");
@@ -1167,12 +1170,28 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
   if (grub_cryptodisk_list == NULL)
     return grub_error (GRUB_ERR_BAD_MODULE, "no cryptodisk modules loaded");
 
+  if (state[3].set && state[4].set) /* password and key protector */
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       "a password and a key protector cannot both be set");
+
+  if (state[4].set && argc < 1) /* key protector */
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       "key protectors require a device name or UUID");
+
   if (state[3].set) /* password */
     {
       cargs.key_data = (grub_uint8_t *) state[3].arg;
       cargs.key_len = grub_strlen (state[3].arg);
     }
 
+  if (state[4].set) /* key protector */
+    {
+      err = grub_key_protector_recover_key (state[4].arg, &cargs.key_data,
+                                                          &cargs.key_len);
+      if (err)
+        grub_printf_ (N_("Could not recover key from key protector.\n"));
+    }
+
   if (state[0].set) /* uuid */
     {
       int found_uuid;
@@ -1385,7 +1404,7 @@ GRUB_MOD_INIT (cryptodisk)
 {
   grub_disk_dev_register (&grub_cryptodisk_dev);
   cmd = grub_register_extcmd ("cryptomount", grub_cmd_cryptomount, 0,
-			      N_("[-p password] <SOURCE|-u UUID|-a|-b>"),
+			      N_("[-p password] [-k protector[:args]] <SOURCE|-u UUID|-a|-b>"),
 			      N_("Mount a crypto device."), options);
   grub_procfs_register ("luks_script", &luks_script);
 }
Signature · 1 line
1.8.3.1
#0 lore raw

cover Automatic TPM Disk Unlock

This patch series adds support for automatically unlocking fully-encrypted disks using a TPM 2.0.

Currently, when GRUB encounters a fully-encrypted disk that it must access, its corresponding cryptodisk module (LUKS 1, LUKS2, or GELI) interactively prompts the user for a passphrase. An improvement to the boot process would be for GRUB to automatically retrieve the unlocking key for fully-encrypted disks from a protected location and to unlock these transparently. To this end, a TPM may be used to protect the unlocking key to a known-good state of the platform. Once the key is protected in this way, assuming that the platform remains trustworthy, GRUB can then utilize the TPM to release the key during boot and thus unlock fully-encrypted disks without user interaction. Such a model would not only be more convenient for end-users but also for virtual machines in cloud environments where no user is ever present.

Design
------

This patchset first adds a key protectors framework. This framework allows for key protector modules to register when loaded. A key protector is defined as a module that knows how to retrieve an unlocking key from a specific source. This patchset adds a single such key protector module that understands how to retrieve an unlocking key from a TPM 2.0 by unsealing a sealed key file via a Storage Root Key (SRK).

Additionally, this patchset expands the cryptomount command to accept a key protector parameter. This parameter carries the information necessary to select and parameterize a key protector to be used to retrieve an unlocking key for the disk in question. That is, given an invocation of cryptomount to mount a specific disk (e.g., "cryptomount (hd0,gpt2)", "cryptomount -u UUID"), a key protector can be used to automatically retrieve an unlocking key without an interactive prompt.

Lastly, this patchset also includes a new tool, grub-protect, that allows the user to seal a key file against a set of Platform Configuration Registers (PCRs) using an SRK. This sealed key file is expected to be stored in an unencrypted partition, such as the EFI System Partition (ESP), where GRUB can read it. The sealed key is then unsealed by the TPM2 key protector automatically, provided that the PCRs selected match on subsequent boots.

Hernan Gatta (5):
protectors: Add key protectors framework
tpm2: Add TPM Software Stack (TSS)
protectors: Add TPM2 Key Protector
cryptodisk: Support key protectors
util/grub-protect: Add new tool

 .gitignore                             |    1 +
 Makefile.util.def                      |   17 +
 configure.ac                           |    1 +
 grub-core/Makefile.am                  |    1 +
 grub-core/Makefile.core.def            |   10 +
 grub-core/disk/cryptodisk.c            |   21 +-
 grub-core/kern/protectors.c            |   98 +++
 grub-core/tpm2/buffer.c                |  145 ++++
 grub-core/tpm2/module.c                |  742 ++++++++++++++++++
 grub-core/tpm2/mu.c                    |  807 +++++++++++++++++++
 grub-core/tpm2/tcg2.c                  |  143 ++++
 grub-core/tpm2/tpm2.c                  |  711 +++++++++++++++++
 include/grub/protector.h               |   55 ++
 include/grub/tpm2/buffer.h             |   65 ++
 include/grub/tpm2/internal/functions.h |  117 +++
 include/grub/tpm2/internal/structs.h   |  675 ++++++++++++++++
 include/grub/tpm2/internal/types.h     |  372 +++++++++
 include/grub/tpm2/mu.h                 |  292 +++++++
 include/grub/tpm2/tcg2.h               |   34 +
 include/grub/tpm2/tpm2.h               |   38 +
 util/grub-protect.c                    | 1344 ++++++++++++++++++++++++++++++++
 21 files changed, 5688 insertions(+), 1 deletion(-)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 grub-core/tpm2/buffer.c
 create mode 100644 grub-core/tpm2/module.c
 create mode 100644 grub-core/tpm2/mu.c
 create mode 100644 grub-core/tpm2/tcg2.c
 create mode 100644 grub-core/tpm2/tpm2.c
 create mode 100644 include/grub/protector.h
 create mode 100644 include/grub/tpm2/buffer.h
 create mode 100644 include/grub/tpm2/internal/functions.h
 create mode 100644 include/grub/tpm2/internal/structs.h
 create mode 100644 include/grub/tpm2/internal/types.h
 create mode 100644 include/grub/tpm2/mu.h
 create mode 100644 include/grub/tpm2/tcg2.h
 create mode 100644 include/grub/tpm2/tpm2.h
 create mode 100644 util/grub-protect.c
Signature · 1 line
1.8.3.1
#5 lore raw

PATCH 3/5 protectors: Add TPM2 Key Protector

From: Hernan Gatta <[email protected]>

The TPM2 key protector is a module that enables the automatic retrieval of a fully-encrypted disk's unlocking key from a TPM 2.0.

The theory of operation is such that the module accepts various arguments, most of which are optional therefore possess reasonable defaults. One of these arguments is the keyfile parameter, which is mandatory.

The value of this parameter must be a path to a sealed key file (e.g., (hd0,gpt1)/boot/grub2/sealed_key). This sealed key file is created via the grub-protect tool. The tool utilizes the TPM's sealing functionality to seal (i.e., encrypt) an unlocking key using a Storage Root Key (SRK) to the values of various Platform Configuration Registers (PCRs). These PCRs reflect the state of the system as it boots. If the values are as expected, the system may be considered trustworthy, at which point the TPM allows for a caller to utilize the private component of the SRK to unseal (i.e., decrypt) the sealed key file. The caller, in this case, is this key protector.

---
 grub-core/Makefile.core.def |   9 +
 grub-core/tpm2/module.c     | 742 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 751 insertions(+)
 create mode 100644 grub-core/tpm2/module.c
grub-core/Makefile.core.def +9 -0
index e4ae78b..8691440 100644
@@ -2498,6 +2498,15 @@ module = {
 };
 
 module = {
+  name = tpm2;
+  common = tpm2/buffer.c;
+  common = tpm2/module.c;
+  common = tpm2/mu.c;
+  common = tpm2/tpm2.c;
+  efi = tpm2/tcg2.c;
+};
+
+module = {
   name = tr;
   common = commands/tr.c;
 };
grub-core/tpm2/module.c new file +742 -0

742 lines not on this page · raw message

Signature · 1 line
1.8.3.1
#14 lore raw

PATCH 5/5 util/grub-protect: Add new tool

In reply to Hernan Gatta

From: Hernan Gatta <[email protected]>

To utilize the key protectors framework, there must be a way to protect full-disk encryption keys in the first place. The grub-protect tool includes support for the TPM2 key protector but other protectors that require setup ahead of time can be supported in the future.

For the TPM2 key protector, the intended flow is for a user to have a LUKS 1 or LUKS 2-protected fully-encrypted disk. The user then creates a new key file, say by reading /dev/urandom into a file, and creates a new LUKS key slot for this key. Then, the user invokes the grub-protect tool to seal this key file to a set of PCRs using the system's TPM 2.0. The resulting sealed key file is stored in an unencrypted partition such as the EFI System Partition (ESP) so that GRUB may read it. The user also ensures the cryptomount command is included in GRUB's boot script and that it carries the requisite --protector (or -p) parameter.

Sample usage:

$ dd if=/dev/urandom of=key count=32
$ sudo cryptsetup luksAddKey /dev/sdb1 key --pbkdf=pbkdf2 --hash=sha512
$ sudo grub-protect --action=add
--protector=tpm2
--tpm2-keyfile=key
--tpm2-outfile=/boot/efi/boot/grub2/sealed_key

Then, in the boot script (wrapped for display):

cryptomount -u b20f95d0834842bc9197bd78b36732f8
-p tpm2:keyfile=(hd0,gpt1)/boot/grub2/sealed_key

where the UUID corresponds to /dev/sdb1.

---
 .gitignore          |    1 +
 Makefile.util.def   |   16 +
 configure.ac        |    1 +
 util/grub-protect.c | 1344 +++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 1362 insertions(+)
 create mode 100644 util/grub-protect.c
.gitignore +1 -0
index f6a1bd0..852327d 100644
@@ -167,6 +167,7 @@ widthspec.bin
 /grub-ofpathname.exe
 /grub-probe
 /grub-probe.exe
+/grub-protect
 /grub-reboot
 /grub-render-label
 /grub-render-label.exe
Makefile.util.def +16 -0
index 39b53b3..05f9f09 100644
@@ -52,6 +52,9 @@ library = {
   common = grub-core/partmap/msdos.c;
   common = grub-core/fs/proc.c;
   common = grub-core/fs/archelp.c;
+  common = grub-core/tpm2/buffer.c;
+  common = grub-core/tpm2/mu.c;
+  common = grub-core/tpm2/tpm2.c;
 };
 
 library = {
@@ -207,6 +210,19 @@ program = {
 };
 
 program = {
+  name = grub-protect;
+  common = grub-core/osdep/init.c;
+  common = util/grub-protect.c;
+  common = util/probe.c;
+
+  ldadd = libgrubmods.a;
+  ldadd = libgrubgcry.a;
+  ldadd = libgrubkern.a;
+  ldadd = grub-core/lib/gnulib/libgnu.a;
+  ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
+};
+
+program = {
   name = grub-mkrelpath;
   mansection = 1;
 
configure.ac +1 -0
index 4f649ed..3a4dc5a 100644
@@ -71,6 +71,7 @@ grub_TRANSFORM([grub-mkpasswd-pbkdf2])
 grub_TRANSFORM([grub-mkrelpath])
 grub_TRANSFORM([grub-mkrescue])
 grub_TRANSFORM([grub-probe])
+grub_TRANSFORM([grub-protect])
 grub_TRANSFORM([grub-reboot])
 grub_TRANSFORM([grub-script-check])
 grub_TRANSFORM([grub-set-default])
util/grub-protect.c new file +1344 -0

1,344 lines not on this page · raw message

Signature · 1 line
1.8.3.1
#4 lore raw

PATCH 2/5 tpm2: Add TPM Software Stack (TSS)

In reply to Hernan Gatta

From: Hernan Gatta <[email protected]>

A Trusted Platform Module (TPM) Software Stack (TSS) provides logic to compose, submit, and parse TPM commands and responses.

A limited number of TPM commands may be accessed via the EFI TCG2 protocol. This protocol exposes functionality that is primarily geared toward TPM usage within the context of Secure Boot. For all other TPM commands, however, such as sealing and unsealing, this protocol does not provide any help, with the exception of passthrough command submission.

The SubmitCommand method allows a caller to send raw commands to the system's TPM and to receive the corresponding response. These command/response pairs are formatted using the TPM wire protocol. To construct commands in this way, and to parse the TPM's response, it is necessary to, first, possess knowledge of the various TPM structures, and, two, of the TPM wire protocol itself.

As such, this patch includes a set of header files that define the necessary TPM structures and TSS functions, implementations of various TPM2_* functions (inventoried below), and logic to write and read command and response buffers, respectively, using the TPM wire protocol.

Functions: TPM2_Create, TPM2_CreatePrimary, TPM2_EvictControl, TPM2_FlushContext, TPM2_Load, TPM2_PCR_Read, TPM2_PolicyGetDigest, TPM2_PolicyPCR, TPM2_ReadPublic, TPM2_StartAuthSession, TPM2_Unseal.

---
 grub-core/tpm2/buffer.c                | 145 ++++++
 grub-core/tpm2/mu.c                    | 807 +++++++++++++++++++++++++++++++++
 grub-core/tpm2/tcg2.c                  | 143 ++++++
 grub-core/tpm2/tpm2.c                  | 711 +++++++++++++++++++++++++++++
 include/grub/tpm2/buffer.h             |  65 +++
 include/grub/tpm2/internal/functions.h | 117 +++++
 include/grub/tpm2/internal/structs.h   | 675 +++++++++++++++++++++++++++
 include/grub/tpm2/internal/types.h     | 372 +++++++++++++++
 include/grub/tpm2/mu.h                 | 292 ++++++++++++
 include/grub/tpm2/tcg2.h               |  34 ++
 include/grub/tpm2/tpm2.h               |  38 ++
 11 files changed, 3399 insertions(+)
 create mode 100644 grub-core/tpm2/buffer.c
 create mode 100644 grub-core/tpm2/mu.c
 create mode 100644 grub-core/tpm2/tcg2.c
 create mode 100644 grub-core/tpm2/tpm2.c
 create mode 100644 include/grub/tpm2/buffer.h
 create mode 100644 include/grub/tpm2/internal/functions.h
 create mode 100644 include/grub/tpm2/internal/structs.h
 create mode 100644 include/grub/tpm2/internal/types.h
 create mode 100644 include/grub/tpm2/mu.h
 create mode 100644 include/grub/tpm2/tcg2.h
 create mode 100644 include/grub/tpm2/tpm2.h
grub-core/tpm2/buffer.c new file +145 -0
new file mode 100644
index 0000000..fee42d5
@@ -0,0 +1,145 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/misc.h>
+#include <grub/tpm2/buffer.h>
+
+void grub_tpm2_buffer_init (grub_tpm2_buffer_t buffer)
+{
+  grub_memset (buffer->data, 0xDD, sizeof (buffer->data));
+  buffer->size = 0;
+  buffer->offset = 0;
+  buffer->cap = sizeof (buffer->data);
+  buffer->error = 0;
+}
+
+void
+grub_tpm2_buffer_pack (grub_tpm2_buffer_t buffer, const void* data,
+                       grub_size_t size)
+{
+  grub_uint32_t r = buffer->cap - buffer->size;
+
+  if (buffer->error)
+    return;
+
+  if (size > r)
+    {
+      buffer->error = 1;
+      return;
+    }
+
+  grub_memcpy (&buffer->data[buffer->size], (void*) data, size);
+  buffer->size += size;
+}
+
+void
+grub_tpm2_buffer_pack_u8 (grub_tpm2_buffer_t buffer, grub_uint8_t value)
+{
+  grub_tpm2_buffer_pack (buffer, (const char*) &value, sizeof (value));
+}
+
+void
+grub_tpm2_buffer_pack_u16 (grub_tpm2_buffer_t buffer, grub_uint16_t value)
+{
+  grub_uint16_t tmp = grub_swap_bytes16 (value);
+  grub_tpm2_buffer_pack (buffer, (const char*) &tmp, sizeof (tmp));
+}
+
+void
+grub_tpm2_buffer_pack_u32 (grub_tpm2_buffer_t buffer, grub_uint32_t value)
+{
+  grub_uint32_t tmp = grub_swap_bytes32 (value);
+  grub_tpm2_buffer_pack (buffer, (const char*) &tmp, sizeof (tmp));
+}
+
+void
+grub_tpm2_buffer_unpack (grub_tpm2_buffer_t buffer, void* data,
+                         grub_size_t size)
+{
+  grub_uint32_t r = buffer->size - buffer->offset;
+
+  if (buffer->error)
+    return;
+
+  if (size > r)
+    {
+      buffer->error = 1;
+      return;
+    }
+
+  grub_memcpy (data, &buffer->data[buffer->offset], size);
+  buffer->offset += size;
+}
+
+void
+grub_tpm2_buffer_unpack_u8 (grub_tpm2_buffer_t buffer, grub_uint8_t* value)
+{
+  grub_uint32_t r = buffer->size - buffer->offset;
+
+  if (buffer->error)
+    return;
+
+  if (sizeof (*value) > r)
+    {
+      buffer->error = 1;
+      return;
+    }
+
+  grub_memcpy (value, &buffer->data[buffer->offset], sizeof (*value));
+  buffer->offset += sizeof (*value);
+}
+
+void
+grub_tpm2_buffer_unpack_u16 (grub_tpm2_buffer_t buffer, grub_uint16_t* value)
+{
+  grub_uint16_t tmp;
+  grub_uint32_t r = buffer->size - buffer->offset;
+
+  if (buffer->error)
+    return;
+
+  if (sizeof (tmp) > r)
+    {
+      buffer->error = 1;
+      return;
+    }
+
+  grub_memcpy (&tmp, &buffer->data[buffer->offset], sizeof (tmp));
+  buffer->offset += sizeof (tmp);
+  *value = grub_swap_bytes16 (tmp);
+}
+
+void
+grub_tpm2_buffer_unpack_u32 (grub_tpm2_buffer_t buffer, grub_uint32_t* value)
+{
+  grub_uint32_t tmp;
+  grub_uint32_t r = buffer->size - buffer->offset;
+
+  if (buffer->error)
+    return;
+
+  if (sizeof (tmp) > r)
+    {
+      buffer->error = 1;
+      return;
+    }
+
+  grub_memcpy (&tmp, &buffer->data[buffer->offset], sizeof (tmp));
+  buffer->offset += sizeof (tmp);
+  *value = grub_swap_bytes32 (tmp);
+}
grub-core/tpm2/mu.c new file +807 -0

807 lines not on this page · raw message

grub-core/tpm2/tcg2.c new file +143 -0

143 lines not on this page · raw message

grub-core/tpm2/tpm2.c new file +711 -0

711 lines not on this page · raw message

include/grub/tpm2/buffer.h new file +65 -0

65 lines not on this page · raw message

include/grub/tpm2/internal/functions.h new file +117 -0

117 lines not on this page · raw message

include/grub/tpm2/internal/structs.h new file +675 -0

675 lines not on this page · raw message

include/grub/tpm2/internal/types.h new file +372 -0

337 lines not on this page · raw message

include/grub/tpm2/mu.h new file +292 -0

292 lines not on this page · raw message

include/grub/tpm2/tcg2.h new file +34 -0
new file mode 100644
index 0000000..99f2fdd

Lines of this file are not shown. View the raw message.

include/grub/tpm2/tpm2.h new file +38 -0
new file mode 100644
index 0000000..1569ea7

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
1.8.3.1

Part of the diff is not shown here. View the raw message.

#17 lore raw
In reply to Hernan Gatta

Hi,

Le 24/01/2022 à 15:12, Hernan Gatta a écrit :

Quoted 33 lines

This patch series adds support for automatically unlocking fully-encrypted disks using a TPM 2.0.

Currently, when GRUB encounters a fully-encrypted disk that it must access, its corresponding cryptodisk module (LUKS 1, LUKS2, or GELI) interactively prompts the user for a passphrase. An improvement to the boot process would be for GRUB to automatically retrieve the unlocking key for fully-encrypted disks from a protected location and to unlock these transparently. To this end, a TPM may be used to protect the unlocking key to a known-good state of the platform. Once the key is protected in this way, assuming that the platform remains trustworthy, GRUB can then utilize the TPM to release the key during boot and thus unlock fully-encrypted disks without user interaction. Such a model would not only be more convenient for end-users but also for virtual machines in cloud environments where no user is ever present.

Design
------

This patchset first adds a key protectors framework. This framework allows for key protector modules to register when loaded. A key protector is defined as a module that knows how to retrieve an unlocking key from a specific source. This patchset adds a single such key protector module that understands how to retrieve an unlocking key from a TPM 2.0 by unsealing a sealed key file via a Storage Root Key (SRK).

Additionally, this patchset expands the cryptomount command to accept a key protector parameter. This parameter carries the information necessary to select and parameterize a key protector to be used to retrieve an unlocking key for the disk in question. That is, given an invocation of cryptomount to mount a specific disk (e.g., "cryptomount (hd0,gpt2)", "cryptomount -u UUID"), a key protector can be used to automatically retrieve an unlocking key without an interactive prompt.

Quoted 6 lines

Lastly, this patchset also includes a new tool, grub-protect, that allows the user to seal a key file against a set of Platform Configuration Registers (PCRs) using an SRK. This sealed key file is expected to be stored in an unencrypted partition, such as the EFI System Partition (ESP), where GRUB can read it. The sealed key is then unsealed by the TPM2 key protector automatically, provided that the PCRs selected match on subsequent boots.

Sorry for a newbie question (I plan to allow installing Slint on a Secure Boot enabled machine if/when I can but know almost nothing yet on this topic).

Currently we allow in the "auto" mode of installation to install Slint in a fully encrypted drive (minus the ESP and the BIOS Boot partition), the user typing then a passphrase only once when politely requested by GRUB before displaying its menu (without using LVM as we store a LUKS key in the initramfs).

The main purpose is to forbid access to the system when the machine is powered off, for instance in case of a laptop stolen during a travel.

Would the feature you describe possibly allow to circumvent this protection?

Thanks,
Didier
--
Didier Spaier
Slint maintainer

#2 lore raw

Re: [PATCH 1/5] protectors: Add key protectors framework

In reply to Hernan Gatta
Quoted 127 lines · On Mon, 24 Jan 2022 06:12:14 -0800 Hernan Gatta <[email protected]>…

From: Hernan Gatta <[email protected]>

A key protector encapsulates functionality to retrieve an unlocking key for a fully-encrypted disk from a specific source. A key protector module registers itself with the key protectors framework when it is loaded and unregisters when unloaded. Additionally, a key protector may accept parameters that describe how it should operate.

The key protectors framework, besides offering registration and unregistration functions, also offers a one-stop routine for finding and invoking a key protector. This method accepts a formatted string with the name of a key protector followed optionally by colon-separated, key protector-specific parameters. If a key protector with the specified name exists and if an unlocking key is successfully retrieved by the latter, the function returns to the caller the retrieved key and its length.

---
 grub-core/Makefile.am       |  1 +
 grub-core/Makefile.core.def |  1 +
 grub-core/kern/protectors.c | 98 +++++++++++++++++++++++++++++++++++++++++++++
 include/grub/protector.h    | 55 +++++++++++++++++++++++++
 4 files changed, 155 insertions(+)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 include/grub/protector.h
grub-core/Makefile.am +1 -0
index ee88e44..f78cd9d 100644
@@ -90,6 +90,7 @@ endif
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/mm.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/parser.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/partition.h
+KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/protector.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/stack_protector.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/term.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/time.h
grub-core/Makefile.core.def +1 -0
index 8022e1c..e4ae78b 100644
@@ -138,6 +138,7 @@ kernel = {
   common = kern/misc.c;
   common = kern/parser.c;
   common = kern/partition.c;
+  common = kern/protectors.c;
   common = kern/rescue_parser.c;
   common = kern/rescue_reader.c;
   common = kern/term.c;
grub-core/kern/protectors.c new file +71 -0
new file mode 100644
index 0000000..2df0c60
@@ -0,0 +1,98 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/list.h>
+#include <grub/misc.h>
+#include <grub/mm.h>
+#include <grub/protector.h>
+
+struct grub_key_protector *grub_key_protectors = NULL;
+
+grub_err_t
+grub_key_protector_register (struct grub_key_protector *protector)
+{
+  if (!protector || !protector->name || !grub_strlen(protector->name))
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (grub_key_protectors &&
+      grub_named_list_find (GRUB_AS_NAMED_LIST (grub_key_protectors),
+                            protector->name))
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  grub_list_push (GRUB_AS_LIST_P (&grub_key_protectors),
+                  GRUB_AS_LIST (protector));
+
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_key_protector_unregister (struct grub_key_protector *protector)
+{
+  if (!protector)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  grub_list_remove (GRUB_AS_LIST (protector));
+
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_key_protector_recover_key (char *args, grub_uint8_t **key,
+                                grub_size_t *key_size)
+{
+  char *first_separator = NULL;
+  char *protector_args = NULL;
+  struct grub_key_protector *protector = NULL;
+
+  if (!grub_key_protectors)
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  if (!args || !grub_strlen (args))
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  /* Find the position of the first parameter separator: the stuff before it is
+   * the name of the requested key protector and the stuff after it are the
+   * parameters for said key protector, if any. */
+  first_separator = grub_strchr (args, ':');

grub-core/kern/protectors.c line 81

Quoted 10 lines
grub-core/kern/protectors.c new file +10 -0
+  if (first_separator)
+    {
+      /* Reject a separator at the very beginning. */
+      if (first_separator == args)
+        return GRUB_ERR_BAD_ARGUMENT;
+
+      /* Having a lone colon after the name of the key protector with no
+       * further parameters thereafter does not make any sense. */
+      if (*(first_separator + 1) == '\0')
+        return GRUB_ERR_BAD_ARGUMENT;

This should be allowed, its an unnecessary restriction. For instance, it prevents building this string without logic to determine if a colon is needed or not. Instead of this if block, I suggest having...

grub-core/kern/protectors.c line 85

Quoted 4 lines
grub-core/kern/protectors.c new file +4 -0
+
+      /* Consume the colon, effectively splitting 'args' in two. */
+      first_separator[0] = '\0';
+

... here, an if with the opposite conditional.

if (*(first_separator + 1) != '\0')

Quoted 64 lines
grub-core/kern/protectors.c new file +13 -0
+      /* The protector-specific arguments are after the first colon. */
+      protector_args = first_separator + 1;
+    }
+
+  /* Try to find a key protector with the specified name. */
+  protector = grub_named_list_find (GRUB_AS_NAMED_LIST (grub_key_protectors),
+                                    args);
+  if (!protector)
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  /* 'protector_args' may be NULL. */
+  return protector->recover_key (protector_args, key, key_size);
+}
include/grub/protector.h new file +45 -0
new file mode 100644
index 0000000..d445a33
@@ -0,0 +1,55 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef GRUB_PROTECTOR_HEADER
+#define GRUB_PROTECTOR_HEADER 1
+
+#include <grub/err.h>
+#include <grub/types.h>
+
+enum grub_key_protector_flags
+  {
+    GRUB_KEY_PROTECTOR_FLAG_NONE = 0,
+    GRUB_KEY_PROTECTOR_FLAG_REPEATABLE = 1 << 0
+  };
+
+struct grub_key_protector
+{
+  struct grub_key_protector *next;
+  struct grub_key_protector **prev;
+
+  const char *name;
+  enum grub_key_protector_flags flags;
+
+  grub_err_t (*recover_key) (char *args, grub_uint8_t **key,
+                             grub_size_t *key_size);
+};
+
+extern struct grub_key_protector *EXPORT_VAR (grub_key_protectors);
+
+grub_err_t

include/grub/protector.h line 55

Quoted 10 lines
include/grub/protector.h new file +10 -0
+EXPORT_FUNC (grub_key_protector_register) (struct grub_key_protector *protector);
+
+grub_err_t
+EXPORT_FUNC (grub_key_protector_unregister) (struct grub_key_protector *protector);
+
+grub_err_t
+EXPORT_FUNC (grub_key_protector_recover_key) (char args[], grub_uint8_t **key,
+                                              grub_size_t *key_size);
+
+#endif /* ! GRUB_PROTECTOR_HEADER */

Glenn

#6 lore raw

Re: [PATCH 3/5] protectors: Add TPM2 Key Protector

In reply to Hernan Gatta
Quoted 9 lines · On Mon, 24 Jan 2022 06:12:16 -0800 Hernan Gatta <[email protected]>…

From: Hernan Gatta <[email protected]>

The TPM2 key protector is a module that enables the automatic retrieval of a fully-encrypted disk's unlocking key from a TPM 2.0.

The theory of operation is such that the module accepts various arguments, most of which are optional therefore possess reasonable defaults. One of these arguments is the keyfile parameter, which is mandatory.

Quoted 10 lines

The value of this parameter must be a path to a sealed key file (e.g., (hd0,gpt1)/boot/grub2/sealed_key). This sealed key file is created via the grub-protect tool. The tool utilizes the TPM's sealing functionality to seal (i.e., encrypt) an unlocking key using a Storage Root Key (SRK) to the values of various Platform Configuration Registers (PCRs). These PCRs reflect the state of the system as it boots. If the values are as expected, the system may be considered trustworthy, at which point the TPM allows for a caller to utilize the private component of the SRK to unseal (i.e., decrypt) the sealed key file. The caller, in this case, is this key protector.

There are a lot of points in this code where an error can be returned. In this case, all I'm going to get is a non-descript error code (almost always GRUB_ERR_BAD_ARGUMENT). So as a user, how am I to know where the error is actually coming from? For this reason, I like the use of grub_error(error_code, error_format_string, fmtstr_args...), which will set grub_errno and an error message, which can be retrieved up the stack and presented to the user. I'm not sure that every return of a naked error code should be replaced by grub_error(), depends on how granular of an error message you want to see. I would error on the side of more granular. For instance, its really nice that GCC will tell me which format code type specifier and a argument its choking on, rather than a catch all "I'm failing to compile your code because you have an incorrect format code somewhere in your format string".

Quoted 249 lines
---
 grub-core/Makefile.core.def |   9 +
 grub-core/tpm2/module.c     | 742 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 751 insertions(+)
 create mode 100644 grub-core/tpm2/module.c
grub-core/Makefile.core.def +9 -0
index e4ae78b..8691440 100644
@@ -2498,6 +2498,15 @@ module = {
 };
 
 module = {
+  name = tpm2;
+  common = tpm2/buffer.c;
+  common = tpm2/module.c;
+  common = tpm2/mu.c;
+  common = tpm2/tpm2.c;
+  efi = tpm2/tcg2.c;
+};
+
+module = {
   name = tr;
   common = commands/tr.c;
 };
grub-core/tpm2/module.c new file +216 -0
new file mode 100644
index 0000000..cd97452
@@ -0,0 +1,742 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/dl.h>
+#include <grub/file.h>
+#include <grub/misc.h>
+#include <grub/mm.h>
+#include <grub/protector.h>
+#include <grub/tpm2/buffer.h>
+#include <grub/tpm2/mu.h>
+#include <grub/tpm2/tpm2.h>
+#include <grub/types.h>
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+typedef enum grub_tpm2_protector_args
+{
+  GRUB_TPM2_PROTECTOR_ARG_MODE       = 1 << 0,
+  GRUB_TPM2_PROTECTOR_ARG_PCRS       = 1 << 1,
+  GRUB_TPM2_PROTECTOR_ARG_ASYMMETRIC = 1 << 2,
+  GRUB_TPM2_PROTECTOR_ARG_BANK       = 1 << 3,
+  GRUB_TPM2_PROTECTOR_ARG_KEYFILE    = 1 << 4,
+  GRUB_TPM2_PROTECTOR_ARG_SRK        = 1 << 5,
+  GRUB_TPM2_PROTECTOR_ARG_NV         = 1 << 6
+} grub_tpm2_protector_args_t;
+
+typedef enum grub_tpm2_protector_mode
+{
+  GRUB_TPM2_PROTECTOR_MODE_SRK = 1,
+  GRUB_TPM2_PROTECTOR_MODE_NV  = 2
+} grub_tpm2_protector_mode_t;
+
+struct grub_tpm2_protector_context
+{
+  grub_tpm2_protector_args_t args;
+  grub_tpm2_protector_mode_t mode;
+  grub_uint8_t pcrs[TPM_MAX_PCRS];
+  grub_uint8_t pcr_count;
+  TPM_ALG_ID asymmetric;
+  TPM_ALG_ID bank;
+  const char *keyfile;
+  TPM_HANDLE srk;
+  TPM_HANDLE nv;
+};
+
+static grub_err_t
+grub_tpm2_protector_parse_mode (struct grub_tpm2_protector_context *ctx,
+                                const char *value)
+{
+  if (grub_strcmp (value, "srk") == 0)
+    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_SRK;
+  else if (grub_strcmp (value, "nv") == 0)
+    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_NV;
+  else
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_pcrs (struct grub_tpm2_protector_context *ctx,
+                                char *value)
+{
+  grub_err_t err;
+  char *current_pcr = value;
+  char *next_pcr;
+  unsigned long pcr;
+  grub_uint8_t i;
+
+  if (grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  ctx->pcr_count = 0;
+  for (i = 0; i < TPM_MAX_PCRS; i++)
+    {
+      next_pcr = grub_strchr (current_pcr, ',');
+      if (next_pcr)
+        *next_pcr = '\0';
+      if (next_pcr == current_pcr)
+        return GRUB_ERR_BAD_ARGUMENT;
+
+      grub_errno = GRUB_ERR_NONE;
+      pcr = grub_strtoul (current_pcr, NULL, 10);
+      if (grub_errno != GRUB_ERR_NONE)
+        {
+          err = grub_errno;
+          grub_errno = GRUB_ERR_NONE;
+          return err;
+        }
+
+      if (pcr > GRUB_UCHAR_MAX)
+        return GRUB_ERR_OUT_OF_RANGE;
+
+      ctx->pcrs[i] = (grub_uint8_t)pcr;
+      ctx->pcr_count++;
+
+      if (!next_pcr)
+        break;
+
+      current_pcr = next_pcr + 1;
+      if (*current_pcr == '\0')
+        return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (i == TPM_MAX_PCRS)
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_asymmetric (struct grub_tpm2_protector_context *ctx,
+                                      const char *value)
+{
+  if (grub_strcasecmp (value, "ECC") == 0)
+    ctx->asymmetric = TPM_ALG_ECC;
+  else if (grub_strcasecmp (value, "RSA") == 0)
+    ctx->asymmetric = TPM_ALG_RSA;
+  else
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_bank (struct grub_tpm2_protector_context *ctx,
+                                const char *value)
+{
+  if (grub_strcasecmp (value, "SHA1") == 0)
+    ctx->bank = TPM_ALG_SHA1;
+  else if (grub_strcasecmp (value, "SHA256") == 0)
+    ctx->bank = TPM_ALG_SHA256;
+  else if (grub_strcasecmp (value, "SHA384") == 0)
+    ctx->bank = TPM_ALG_SHA384;
+  else
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_keyfile (struct grub_tpm2_protector_context *ctx,
+                                   const char *value)
+{
+  if (grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  ctx->keyfile = value;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_tpm_handle (const char *value, TPM_HANDLE *handle)
+{
+  grub_err_t err;
+  unsigned long num;
+
+  grub_errno = GRUB_ERR_NONE;
+  num = grub_strtoul (value, NULL, 0);
+  if (grub_errno != GRUB_ERR_NONE)
+    {
+      err = grub_errno;
+      grub_errno = GRUB_ERR_NONE;
+      return err;
+    }
+
+  if (num > GRUB_UINT_MAX)
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  *handle = (TPM_HANDLE)num;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_srk (struct grub_tpm2_protector_context *ctx,
+                               const char *value)
+{
+  return grub_tpm2_protector_parse_tpm_handle (value, &ctx->srk);
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_nvindex (struct grub_tpm2_protector_context *ctx,
+                                   const char *value)
+{
+  return grub_tpm2_protector_parse_tpm_handle (value, &ctx->nv);
+}
+
+static grub_err_t
+grub_tpm2_protector_match_arg (struct grub_tpm2_protector_context *ctx,
+                               const char *key, char *value)
+{
+  grub_err_t err;
+
+  if (grub_strlen (key) == 0 || grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (grub_strcmp (key, "mode") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_MODE)

grub-core/tpm2/module.c line 226

Quoted 10 lines
grub-core/tpm2/module.c new file +10 -0
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_mode (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_MODE;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "pcrs") == 0)

Minor nit, why wouldn't this be better as an "else if"? Seems unnecessary to check all the "if" statements if we've already found a match.

grub-core/tpm2/module.c line 238

Quoted 12 lines
grub-core/tpm2/module.c new file +12 -0
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_PCRS)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_pcrs (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_PCRS;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "asymmetric") == 0)

Ditto, for the rest of these ifs.

Quoted 467 lines
grub-core/tpm2/module.c new file +467 -0
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_ASYMMETRIC)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_asymmetric (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_ASYMMETRIC;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "bank") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_BANK)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_bank (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_BANK;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "keyfile") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_KEYFILE)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_keyfile (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_KEYFILE;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "srk") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_SRK)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_srk (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_SRK;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "nvindex") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_NV)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_nvindex (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_NV;
+
+    return err;
+  }
+
+  return GRUB_ERR_OUT_OF_RANGE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_arg (struct grub_tpm2_protector_context *ctx,
+                               char *arg)
+{
+  char *key = arg;
+  char *value = NULL;
+
+  if (grub_strlen (arg) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  value = grub_strchr (arg, '=');
+  if (!value)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  *value = '\0';
+  value++;
+
+  if (*value == '\0')
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  return grub_tpm2_protector_match_arg (ctx, key, value);
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_args (struct grub_tpm2_protector_context *ctx,
+                                char *args)
+{
+  grub_err_t err;
+  char *cur_arg;
+  char *next_arg;
+
+  if (args == NULL)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (grub_strlen (args) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  cur_arg = args;
+  for (;;)
+    {
+      next_arg = grub_strchr (cur_arg, ':');
+      if (next_arg == cur_arg)
+        return GRUB_ERR_BAD_ARGUMENT;
+      if (next_arg)
+        *next_arg = '\0';
+
+      err = grub_tpm2_protector_parse_arg (ctx, cur_arg);
+      if (err)
+        return err;
+
+      if (!next_arg)
+        break;
+
+      cur_arg = next_arg + 1;
+      if (*cur_arg == '\0')
+        return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_check_args (struct grub_tpm2_protector_context *ctx)
+{
+  if (!(ctx->args & GRUB_TPM2_PROTECTOR_ARG_MODE))
+    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_SRK;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && !ctx->keyfile)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && ctx->nv)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->srk)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && !ctx->nv)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->asymmetric)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->bank)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (!(ctx->args & GRUB_TPM2_PROTECTOR_ARG_PCRS))
+    {
+      ctx->pcrs[0] = 7;
+      ctx->pcr_count = 1;
+    }
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK)
+    {
+      if (!ctx->srk)
+        ctx->srk = TPM2_SRK_HANDLE;
+
+      if (!ctx->asymmetric)
+        ctx->asymmetric = TPM_ALG_RSA;
+
+      if (!ctx->bank)
+        ctx->bank = TPM_ALG_SHA256;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_srk_read_keyfile (const char *filepath, void **buffer,
+                                      grub_size_t *buffer_size)
+{
+  grub_file_t sealed_key_file;
+  grub_off_t sealed_key_size;
+  void *sealed_key_buffer;
+  grub_off_t sealed_key_read;
+
+  sealed_key_file = grub_file_open (filepath, GRUB_FILE_TYPE_NONE);
+  if (!sealed_key_file)
+    {
+      /* grub_file_open sets grub_errno on error, and if we do no unset it,
+       * future calls to grub_file_open will fail (and so will anybody up the
+       * stack who checks the value, if any). */
+      grub_errno = GRUB_ERR_NONE;
+      return GRUB_ERR_FILE_NOT_FOUND;
+    }
+
+  sealed_key_size = grub_file_size (sealed_key_file);
+  if (!sealed_key_size)
+    {
+      grub_file_close (sealed_key_file);
+      return GRUB_ERR_OUT_OF_RANGE;
+    }
+
+  sealed_key_buffer = grub_malloc (sealed_key_size);
+  if (!sealed_key_buffer)
+    {
+      grub_file_close (sealed_key_file);
+      return GRUB_ERR_OUT_OF_MEMORY;
+    }
+
+  sealed_key_read = grub_file_read (sealed_key_file, sealed_key_buffer,
+                                    sealed_key_size);
+  if (sealed_key_read != sealed_key_size)
+    {
+      grub_free (sealed_key_buffer);
+      grub_file_close (sealed_key_file);
+      return GRUB_ERR_FILE_READ_ERROR;
+    }
+
+  grub_file_close (sealed_key_file);
+
+  *buffer = sealed_key_buffer;
+  *buffer_size = sealed_key_size;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_srk_unmarshal_keyfile (void *sealed_key,
+                                           grub_size_t sealed_key_size,
+                                           TPM2_SEALED_KEY *sk)
+{
+  struct grub_tpm2_buffer buf;
+
+  grub_tpm2_buffer_init (&buf);
+  if (sealed_key_size > buf.cap)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  grub_memcpy (buf.data, sealed_key, sealed_key_size);
+  buf.size = sealed_key_size;
+
+  grub_tpm2_mu_TPM2B_PUBLIC_Unmarshal (&buf, &sk->public);
+  grub_tpm2_mu_TPM2B_Unmarshal (&buf, (TPM2B *)&sk->private);
+
+  return buf.error ? GRUB_ERR_BAD_ARGUMENT : GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_srk_get (const struct grub_tpm2_protector_context *ctx,
+                             TPM_HANDLE *srk)
+{
+  TPM_RC rc;
+  TPM2B_PUBLIC public;
+  TPMS_AUTH_COMMAND authCommand = { 0 };
+  TPM2B_SENSITIVE_CREATE inSensitive = { 0 };
+  TPM2B_PUBLIC inPublic = { 0 };
+  TPM2B_DATA outsideInfo = { 0 };
+  TPML_PCR_SELECTION creationPcr = { 0 };
+  TPM2B_PUBLIC outPublic = { 0 };
+  TPM2B_CREATION_DATA creationData = { 0 };
+  TPM2B_DIGEST creationHash = { 0 };
+  TPMT_TK_CREATION creationTicket = { 0 };
+  TPM2B_NAME srkName = { 0 };
+  TPM_HANDLE srkHandle;
+
+  /* Find SRK */
+  rc = TPM2_ReadPublic (ctx->srk, NULL, &public);
+  if (rc == TPM_RC_SUCCESS)
+    {
+      *srk = ctx->srk;
+      return GRUB_ERR_NONE;
+    }
+
+  /* The handle exists but its public area could not be read. */
+  if ((rc & ~TPM_RC_N_MASK) != TPM_RC_HANDLE)
+    return GRUB_ERR_BAD_DEVICE;
+
+  /* Create SRK */
+  authCommand.sessionHandle = TPM_RS_PW;
+  inPublic.publicArea.type = ctx->asymmetric;
+  inPublic.publicArea.nameAlg  = TPM_ALG_SHA256;
+  inPublic.publicArea.objectAttributes.restricted = 1;
+  inPublic.publicArea.objectAttributes.userWithAuth = 1;
+  inPublic.publicArea.objectAttributes.decrypt = 1;
+  inPublic.publicArea.objectAttributes.fixedTPM = 1;
+  inPublic.publicArea.objectAttributes.fixedParent = 1;
+  inPublic.publicArea.objectAttributes.sensitiveDataOrigin = 1;
+  inPublic.publicArea.objectAttributes.noDA = 1;
+
+  if (ctx->asymmetric == TPM_ALG_RSA)
+    {
+      inPublic.publicArea.parameters.rsaDetail.symmetric.algorithm = TPM_ALG_AES;
+      inPublic.publicArea.parameters.rsaDetail.symmetric.keyBits.aes = 128;
+      inPublic.publicArea.parameters.rsaDetail.symmetric.mode.aes = TPM_ALG_CFB;
+      inPublic.publicArea.parameters.rsaDetail.scheme.scheme = TPM_ALG_NULL;
+      inPublic.publicArea.parameters.rsaDetail.keyBits = 2048;
+      inPublic.publicArea.parameters.rsaDetail.exponent = 0;
+    }
+  else if (ctx->asymmetric == TPM_ALG_ECC)
+    {
+      inPublic.publicArea.parameters.eccDetail.symmetric.algorithm = TPM_ALG_AES;
+      inPublic.publicArea.parameters.eccDetail.symmetric.keyBits.aes = 128;
+      inPublic.publicArea.parameters.eccDetail.symmetric.mode.aes = TPM_ALG_CFB;
+      inPublic.publicArea.parameters.eccDetail.scheme.scheme = TPM_ALG_NULL;
+      inPublic.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256;
+      inPublic.publicArea.parameters.eccDetail.kdf.scheme = TPM_ALG_NULL;
+    }
+  else
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  rc = TPM2_CreatePrimary (TPM_RH_OWNER, &authCommand, &inSensitive, &inPublic,
+                           &outsideInfo, &creationPcr, &srkHandle, &outPublic,
+                           &creationData, &creationHash, &creationTicket,
+                           &srkName, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    return GRUB_ERR_BAD_DEVICE;
+
+  *srk = srkHandle;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_srk_recover (const struct grub_tpm2_protector_context *ctx,
+                                 grub_uint8_t **key, grub_size_t *key_size)
+{
+  TPM_RC rc;
+  TPM2_SEALED_KEY sealed_key;
+  void *sealed_key_bytes;
+  grub_size_t sealed_key_size;
+  TPM_HANDLE srk_handle;
+  TPM2B_NONCE nonceCaller = { 0 };
+  TPM2B_ENCRYPTED_SECRET salt = { 0 };
+  TPMT_SYM_DEF symmetric = { 0 };
+  TPM2B_NONCE nonceTPM = { 0 };
+  TPMI_SH_AUTH_SESSION session;
+  TPML_PCR_SELECTION pcrSel = {
+    .count = 1,
+    .pcrSelections = {
+      {
+        .hash = ctx->bank,
+        .sizeOfSelect = 3,
+        .pcrSelect = { 0 }
+      },
+    }
+  };
+  TPMS_AUTH_COMMAND authCmd = { 0 };
+  TPM_HANDLE sealed_key_handle;
+  TPM2B_NAME name;
+  TPMS_AUTH_RESPONSE authResponse;
+  TPM2B_SENSITIVE_DATA data;
+  grub_uint8_t *key_out;
+  grub_uint8_t i;
+  grub_err_t err;
+
+  /* Retrieve Sealed Key */
+  err = grub_tpm2_protector_srk_read_keyfile (ctx->keyfile, &sealed_key_bytes,
+                                              &sealed_key_size);
+  if (err)
+    return err;
+
+  err = grub_tpm2_protector_srk_unmarshal_keyfile (sealed_key_bytes,
+                                                   sealed_key_size,
+                                                   &sealed_key);
+  if (err)
+    goto exit1;
+
+  /* Get SRK */
+  err = grub_tpm2_protector_srk_get (ctx, &srk_handle);
+  if (err)
+    goto exit1;
+
+  err = GRUB_ERR_BAD_DEVICE;
+
+  /* Start Auth Session */
+  nonceCaller.size = TPM_SHA256_DIGEST_SIZE;
+  symmetric.algorithm = TPM_ALG_NULL;
+
+  rc = TPM2_StartAuthSession (TPM_RH_NULL, TPM_RH_NULL, 0, &nonceCaller, &salt,
+                              TPM_SE_POLICY, &symmetric, TPM_ALG_SHA256,
+                              &session, &nonceTPM, 0);
+  if (rc)
+    goto exit2;
+
+  /* Policy PCR */
+  for (i = 0; i < ctx->pcr_count; i++)
+    pcrSel
+      .pcrSelections[0]
+      .pcrSelect[TPM2_PCR_TO_SELECT(ctx->pcrs[i])]
+        |= TPM2_PCR_TO_BIT(ctx->pcrs[i]);
+
+  rc = TPM2_PolicyPCR (session, NULL, NULL, &pcrSel, NULL);
+  if (rc)
+    goto exit3;
+
+  /* Load Sealed Key */
+  authCmd.sessionHandle = TPM_RS_PW;
+  rc = TPM2_Load (srk_handle, &authCmd, &sealed_key.private, &sealed_key.public,
+                  &sealed_key_handle, &name, &authResponse);
+  if (rc)
+    goto exit3;
+
+  /* Unseal Sealed Key */
+  authCmd.sessionHandle = session;
+  grub_memset (&authResponse, 0, sizeof (authResponse));
+
+  rc = TPM2_Unseal (sealed_key_handle, &authCmd, &data, &authResponse);
+  if (rc)
+    goto exit4;
+
+  /* Epilogue */
+  key_out = grub_malloc (data.size);
+  if (!key_out)
+    {
+      err = GRUB_ERR_OUT_OF_MEMORY;
+      goto exit4;
+    }
+
+  grub_memcpy (key_out, data.buffer, data.size);
+
+  *key = key_out;
+  *key_size = data.size;
+
+  err = GRUB_ERR_NONE;
+
+exit4:
+  TPM2_FlushContext (sealed_key_handle);
+
+exit3:
+  TPM2_FlushContext (session);
+
+exit2:
+  TPM2_FlushContext (srk_handle);
+
+exit1:
+  grub_free (sealed_key_bytes);
+  return err;
+}
+
+static grub_err_t
+grub_tpm2_protector_nv_recover (const struct grub_tpm2_protector_context *ctx,
+                                grub_uint8_t **key, grub_size_t *key_size)
+{
+  (void)ctx;
+  (void)key;
+  (void)key_size;
+
+  return GRUB_ERR_NOT_IMPLEMENTED_YET;
+}
+
+static grub_err_t
+grub_tpm2_protector_recover (const struct grub_tpm2_protector_context *ctx,
+                             grub_uint8_t **key, grub_size_t *key_size)
+{
+  switch (ctx->mode)
+    {
+    case GRUB_TPM2_PROTECTOR_MODE_SRK:
+      return grub_tpm2_protector_srk_recover (ctx, key, key_size);
+    case GRUB_TPM2_PROTECTOR_MODE_NV:
+      return grub_tpm2_protector_nv_recover (ctx, key, key_size);
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+}
+
+static grub_err_t
+grub_tpm2_protector_recover_key (char *args, grub_uint8_t **key,
+                                 grub_size_t *key_size)
+{
+  grub_err_t err;
+  struct grub_tpm2_protector_context ctx = { 0 };
+
+  grub_dprintf ("tpm2", "Args: %s\n", args);
+
+  if (!args || !key)
+    return GRUB_ERR_BAD_ARGUMENT;

grub-core/tpm2/module.c line 715

Quoted 10 lines
grub-core/tpm2/module.c new file +10 -0
+
+  err = grub_tpm2_protector_parse_args (&ctx, args);
+  if (err) {
+    grub_dprintf("tpm2", "Failed to parse arguments\n");
+    return err;
+  }
+
+  err = grub_tpm2_protector_check_args (&ctx);
+  if (err) {
+    grub_dprintf("tpm2", "Invalid arguments\n");

It's nice that this is here to at least let the user know that the failure was because of invalid arguments as opposed to a failure in the parsing. Even still, which argument was invalid? why was it invalid? As a user, this might be frustrating to diagnose. This is why a message specific to the error would be appreciated.

Glenn

Quoted 27 lines
grub-core/tpm2/module.c new file +27 -0
+    return err;
+  }
+
+  err = grub_tpm2_protector_recover (&ctx, key, key_size);
+  if (err) {
+    grub_dprintf("tpm2", "Failed to recover key\n");
+    return err;
+  }
+
+  return GRUB_ERR_NONE;
+}
+
+struct grub_key_protector grub_tpm2_key_protector = {
+  .name = "tpm2",
+  .flags = GRUB_KEY_PROTECTOR_FLAG_NONE,
+  .recover_key = grub_tpm2_protector_recover_key
+};
+
+GRUB_MOD_INIT(tpm2)
+{
+  grub_key_protector_register (&grub_tpm2_key_protector);
+}
+
+GRUB_MOD_FINI(tpm2)
+{
+  grub_key_protector_unregister (&grub_tpm2_key_protector);
+}
#10 lore raw

Re: [PATCH 4/5] cryptodisk: Support key protectors

In reply to Hernan Gatta
Quoted 7 lines · On Mon, 24 Jan 2022 06:12:17 -0800 Hernan Gatta <[email protected]>…

From: Hernan Gatta <[email protected]>

Add a new parameter to cryptomount to support the key protectors framework: -k. This parameter is accepted whenever the cryptomount command is used to mount a specific disk either via a disk specification (e.g., (hd0,gpt1)) or by UUID, but not when disks are mounted in bulk (i.e., via -a or -b). The parameter is used to automatically retrieve a key from the specified key protector.

Why shouldn't key protectors be used to try to unlock all devices that a backend identified as being able to unlock? Specifically, can a key stored via the TPM be used for multiple devices? With respect to a future unencrypted keyfile protector, it is certainly the case that it can be applied to multiple devices.

Quoted 32 lines
Signed-off-by <Hernan Gatta [email protected]>
---
 Makefile.util.def           |  1 +
 grub-core/disk/cryptodisk.c | 21 ++++++++++++++++++++-
 2 files changed, 21 insertions(+), 1 deletion(-)
Makefile.util.def +1 -0
index f8b356c..39b53b3 100644
@@ -35,6 +35,7 @@ library = {
   common = grub-core/kern/list.c;
   common = grub-core/kern/misc.c;
   common = grub-core/kern/partition.c;
+  common = grub-core/kern/protectors.c;
   common = grub-core/lib/crypto.c;
   common = grub-core/lib/json/json.c;
   common = grub-core/disk/luks.c;
grub-core/disk/cryptodisk.c +1 -0
index 4970973..176dd56 100644
@@ -26,6 +26,7 @@
 #include <grub/file.h>
 #include <grub/procfs.h>
 #include <grub/partition.h>
+#include <grub/protector.h>
 
 #ifdef GRUB_UTIL
 #include <grub/emu/hostdisk.h>

grub-core/disk/cryptodisk.c static const struct grub_arg_option options[] = · line 46

Quoted 4 lines
grub-core/disk/cryptodisk.c +1 -0
@@ -42,6 +43,7 @@ static const struct grub_arg_option options[] =
     {"all", 'a', 0, N_("Mount all."), 0, 0},
     {"boot", 'b', 0, N_("Mount all volumes with `boot' flag set."), 0, 0},
     {"password", 'p', 0, N_("Password to open volumes."), 0, ARG_TYPE_STRING},
+    {"protector", 'k', 0, N_("Unlock disk using the specified key protector."), 0, ARG_TYPE_STRING},

This conflicts with the keyfile and detached header patch series as is. Ultimately, this is probably the right way to go and there will be an protector for using unencrypted keyfiles.

Another option is to use -P for protectors and -k for keyfiles and have two separate methods of using unencrypted keyfiles. I generally don't like having two methods, the only benefit is that I believe the --keyfile method is more intuitive. To use the keyfile protector the user unfamiliar with these features will likely need to consult the documentation.

Quoted 12 lines
grub-core/disk/cryptodisk.c +1 -0
     {0, 0, 0, 0, 0, 0}
   };
 
@@ -1160,6 +1162,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
 {
   struct grub_arg_list *state = ctxt->state;
   struct grub_cryptomount_args cargs = {0};
+  grub_err_t err;
 
   if (argc < 1 && !state[1].set && !state[2].set)
     return grub_error (GRUB_ERR_BAD_ARGUMENT, "device name required");

grub-core/disk/cryptodisk.c grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args) · line 1179

Quoted 10 lines
grub-core/disk/cryptodisk.c +7 -0
@@ -1167,12 +1170,28 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
   if (grub_cryptodisk_list == NULL)
     return grub_error (GRUB_ERR_BAD_MODULE, "no cryptodisk modules loaded");
 
+  if (state[3].set && state[4].set) /* password and key protector */
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       "a password and a key protector cannot both be set");
+
+  if (state[4].set && argc < 1) /* key protector */
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       "key protectors require a device name or UUID");

Referring to the my first comment, I think we can get rid of this if block.

grub-core/disk/cryptodisk.c grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args) · line 1192

Quoted 13 lines
grub-core/disk/cryptodisk.c +7 -0
+
   if (state[3].set) /* password */
     {
       cargs.key_data = (grub_uint8_t *) state[3].arg;
       cargs.key_len = grub_strlen (state[3].arg);
     }
 
+  if (state[4].set) /* key protector */
+    {
+      err = grub_key_protector_recover_key (state[4].arg, &cargs.key_data,
+                                                          &cargs.key_len);
+      if (err)
+        grub_printf_ (N_("Could not recover key from key protector.\n"));

Why is this not returning with an error here? Is it believed that perhaps the device can be unlocked without recovering a key (even though the user explicitly specified that a key should be used?)?

grub-core/disk/cryptodisk.c GRUB_MOD_INIT (cryptodisk) · line 1407

Quoted 11 lines
grub-core/disk/cryptodisk.c +3 -1
+    }
+
   if (state[0].set) /* uuid */
     {
       int found_uuid;
@@ -1385,7 +1404,7 @@ GRUB_MOD_INIT (cryptodisk)
 {
   grub_disk_dev_register (&grub_cryptodisk_dev);
   cmd = grub_register_extcmd ("cryptomount", grub_cmd_cryptomount, 0,
-			      N_("[-p password] <SOURCE|-u UUID|-a|-b>"),
+			      N_("[-p password] [-k protector[:args]] <SOURCE|-u UUID|-a|-b>"),

This looks eerily similiar to what I proposed to James in response to his SEV patches[1]. As such, I am in favor of this syntax and it looks to me like a framework that James can use for his SEV series.

Glenn

grub-core/disk/cryptodisk.c GRUB_MOD_INIT (cryptodisk) · line 1410

Quoted 3 lines
grub-core/disk/cryptodisk.c +0 -0
 			      N_("Mount a crypto device."), options);
   grub_procfs_register ("luks_script", &luks_script);
 }

[1] https://lists.gnu.org/archive/html/grub-devel/2020-11/msg00105.html

#15 lore raw

Re: [PATCH 5/5] util/grub-protect: Add new tool

In reply to Hernan Gatta
Quoted 7 lines · On Mon, 24 Jan 2022 06:12:18 -0800 Hernan Gatta <[email protected]>…

From: Hernan Gatta <[email protected]>

To utilize the key protectors framework, there must be a way to protect full-disk encryption keys in the first place. The grub-protect tool includes support for the TPM2 key protector but other protectors that require setup ahead of time can be supported in the future.

Quoted 8 lines

For the TPM2 key protector, the intended flow is for a user to have a LUKS 1 or LUKS 2-protected fully-encrypted disk. The user then creates a new key file, say by reading /dev/urandom into a file, and creates a new LUKS key slot for this key. Then, the user invokes the grub-protect tool to seal this key file to a set of PCRs using the system's TPM 2.0. The resulting sealed key file is stored in an unencrypted partition such as the EFI System Partition (ESP) so that GRUB may read it. The user also ensures the cryptomount command is included in GRUB's boot script and that it carries the requisite --protector (or -p) parameter.

I think you mean '-k' instead of '-p' here.

Quoted 10 lines

Sample usage:

$ dd if=/dev/urandom of=key count=32
$ sudo cryptsetup luksAddKey /dev/sdb1 key --pbkdf=pbkdf2 --hash=sha512
$ sudo grub-protect --action=add
--protector=tpm2
--tpm2-keyfile=key
--tpm2-outfile=/boot/efi/boot/grub2/sealed_key

Why not have a syntax that is similar to whats given to cryptomount? (eg. $ sudo grub-protect --action=add --protector=tpm2:keyfile=/boot/efi/boot/grub2/sealed_key ) This would allow you to re-use the parsing code from patch #3. Yes, its less UNIXy, but I think could be more intuitive and cuts down on code size. I'm not completely wedded to this idea either.

Quoted 5 lines

Then, in the boot script (wrapped for display):

cryptomount -u b20f95d0834842bc9197bd78b36732f8
-p tpm2:keyfile=(hd0,gpt1)/boot/grub2/sealed_key

Also, -k here.

Quoted 844 lines

where the UUID corresponds to /dev/sdb1.

---
 .gitignore          |    1 +
 Makefile.util.def   |   16 +
 configure.ac        |    1 +
 util/grub-protect.c | 1344 +++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 1362 insertions(+)
 create mode 100644 util/grub-protect.c
.gitignore +1 -0
index f6a1bd0..852327d 100644
@@ -167,6 +167,7 @@ widthspec.bin
 /grub-ofpathname.exe
 /grub-probe
 /grub-probe.exe
+/grub-protect
 /grub-reboot
 /grub-render-label
 /grub-render-label.exe
Makefile.util.def +16 -0
index 39b53b3..05f9f09 100644
@@ -52,6 +52,9 @@ library = {
   common = grub-core/partmap/msdos.c;
   common = grub-core/fs/proc.c;
   common = grub-core/fs/archelp.c;
+  common = grub-core/tpm2/buffer.c;
+  common = grub-core/tpm2/mu.c;
+  common = grub-core/tpm2/tpm2.c;
 };
 
 library = {
@@ -207,6 +210,19 @@ program = {
 };
 
 program = {
+  name = grub-protect;
+  common = grub-core/osdep/init.c;
+  common = util/grub-protect.c;
+  common = util/probe.c;
+
+  ldadd = libgrubmods.a;
+  ldadd = libgrubgcry.a;
+  ldadd = libgrubkern.a;
+  ldadd = grub-core/lib/gnulib/libgnu.a;
+  ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
+};
+
+program = {
   name = grub-mkrelpath;
   mansection = 1;
 
configure.ac +1 -0
index 4f649ed..3a4dc5a 100644
@@ -71,6 +71,7 @@ grub_TRANSFORM([grub-mkpasswd-pbkdf2])
 grub_TRANSFORM([grub-mkrelpath])
 grub_TRANSFORM([grub-mkrescue])
 grub_TRANSFORM([grub-probe])
+grub_TRANSFORM([grub-protect])
 grub_TRANSFORM([grub-reboot])
 grub_TRANSFORM([grub-script-check])
 grub_TRANSFORM([grub-set-default])
util/grub-protect.c new file +768 -0
new file mode 100644
index 0000000..4e4bbd7
@@ -0,0 +1,1344 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <config.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <grub/crypto.h>
+#include <grub/emu/getroot.h>
+#include <grub/emu/hostdisk.h>
+#include <grub/emu/misc.h>
+#include <grub/tpm2/buffer.h>
+#include <grub/tpm2/mu.h>
+#include <grub/tpm2/tcg2.h>
+#include <grub/tpm2/tpm2.h>
+#include <grub/util/misc.h>
+
+#include "progname.h"
+
+typedef enum grub_protect_arg
+{
+  GRUB_PROTECT_ARG_ACTION          = 1 << 0,
+  GRUB_PROTECT_ARG_PROTECTOR       = 1 << 1,
+  GRUB_PROTECT_ARG_TPM2_DEVICE     = 1 << 2,
+  GRUB_PROTECT_ARG_TPM2_PCRS       = 1 << 3,
+  GRUB_PROTECT_ARG_TPM2_ASYMMETRIC = 1 << 4,
+  GRUB_PROTECT_ARG_TPM2_BANK       = 1 << 5,
+  GRUB_PROTECT_ARG_TPM2_SRK        = 1 << 6,
+  GRUB_PROTECT_ARG_TPM2_KEYFILE    = 1 << 7,
+  GRUB_PROTECT_ARG_TPM2_OUTFILE    = 1 << 8,
+  GRUB_PROTECT_ARG_TPM2_PERSIST    = 1 << 9,
+  GRUB_PROTECT_ARG_TPM2_EVICT      = 1 << 10
+} grub_protect_arg_t;
+
+typedef enum grub_protect_protector
+{
+  GRUB_PROTECT_TYPE_ERROR,
+  GRUB_PROTECT_TYPE_TPM2
+} grub_protect_protector_t;
+
+typedef enum grub_protect_action
+{
+  GRUB_PROTECT_ACTION_ERROR,
+  GRUB_PROTECT_ACTION_ADD,
+  GRUB_PROTECT_ACTION_REMOVE
+} grub_protect_action_t;
+
+struct grub_protect_args
+{
+  grub_protect_arg_t args;
+  grub_protect_action_t action;
+  grub_protect_protector_t protector;
+
+  const char *tpm2_device;
+  grub_uint8_t tpm2_pcrs[TPM_MAX_PCRS];
+  grub_uint8_t tpm2_pcr_count;
+  TPM_ALG_ID tpm2_asymmetric;
+  TPM_ALG_ID tpm2_bank;
+  TPM_HANDLE tpm2_srk;
+  const char *tpm2_keyfile;
+  const char *tpm2_outfile;
+  int tpm2_persist;
+  int tpm2_evict;
+};
+
+static int tpm2_fd = -1;
+
+static grub_err_t
+grub_protect_read_file (const char *filepath, void **buffer,
+                        size_t *buffer_size)
+{
+  grub_err_t err;
+  FILE *f;
+  long len;
+  void *buf;
+
+  f = fopen (filepath, "rb");
+  if (!f)
+    return GRUB_ERR_FILE_NOT_FOUND;
+
+  if (fseek (f, 0, SEEK_END))
+    {
+       err = GRUB_ERR_FILE_READ_ERROR;
+       goto exit1;
+    }
+
+  len = ftell (f);
+  if (!len)
+    {
+       err = GRUB_ERR_FILE_READ_ERROR;
+       goto exit1;
+    }
+
+  rewind (f);
+
+  buf = grub_malloc (len);
+  if (!buf)
+    {
+       err = GRUB_ERR_OUT_OF_MEMORY;
+       goto exit1;
+    }
+
+  if (fread (buf, len, 1, f) != 1)
+    {
+       err = GRUB_ERR_FILE_READ_ERROR;
+       goto exit2;
+    }
+
+  *buffer = buf;
+  *buffer_size = len;
+
+  buf = NULL;
+  err = GRUB_ERR_NONE;
+
+exit2:
+  grub_free (buf);
+
+exit1:
+  fclose (f);
+
+  return err;
+}
+
+static grub_err_t
+grub_protect_write_file (const char *filepath, void *buffer, size_t buffer_size)
+{
+  grub_err_t err;
+  FILE *f;
+
+  f = fopen (filepath, "wb");
+  if (!f)
+    return GRUB_ERR_FILE_NOT_FOUND;
+
+  if (fwrite (buffer, buffer_size, 1, f) != 1)
+  {
+    err = GRUB_ERR_WRITE_ERROR;
+    goto exit1;
+  }
+
+  err = GRUB_ERR_NONE;
+
+exit1:
+  fclose (f);
+
+  return err;
+}
+
+static grub_err_t
+grub_protect_get_grub_drive_for_file (const char *filepath, char **drive)
+{
+  grub_err_t err = GRUB_ERR_IO;
+  char *disk;
+  char **devices;
+  char *grub_dev;
+  char *grub_path;
+  char *efi_drive;
+  char *partition;
+  char *grub_drive;
+  grub_device_t dev;
+  grub_size_t grub_drive_len;
+  int n;
+
+  grub_path = grub_canonicalize_file_name (filepath);
+  if (!grub_path)
+    goto exit1;
+
+  devices = grub_guess_root_devices (grub_path);
+  if (!devices || !devices[0])
+    goto exit2;
+
+  disk = devices[0];
+
+  grub_util_pull_device (disk);
+
+  grub_dev = grub_util_get_grub_dev (disk);
+  if (!grub_dev)
+    goto exit3;
+
+  dev = grub_device_open (grub_dev);
+  if (!dev)
+    goto exit4;
+
+  efi_drive = grub_util_guess_efi_drive (disk);
+  if (!efi_drive)
+    goto exit5;
+
+  partition = grub_partition_get_name (dev->disk->partition);
+  if (!partition)
+    goto exit6;
+
+  grub_drive_len = grub_strlen (efi_drive) + grub_strlen (partition) + 3;
+  grub_drive = grub_malloc (grub_drive_len + 1);
+  if (!grub_drive)
+    goto exit7;
+
+  n = grub_snprintf (grub_drive, grub_drive_len + 1, "(%s,%s)", efi_drive,
+                     partition);
+  if (n != grub_drive_len)
+    goto exit8;
+
+  *drive = grub_drive;
+  grub_drive = NULL;
+  err = GRUB_ERR_NONE;
+
+exit8:
+  grub_free (grub_drive);
+
+exit7:
+  grub_free (partition);
+
+exit6:
+  grub_free (efi_drive);
+
+exit5:
+  grub_device_close (dev);
+
+exit4:
+  grub_free (grub_dev);
+
+exit3:
+  grub_free (devices);
+
+exit2:
+  grub_free (grub_path);
+
+exit1:
+  return err;
+}
+
+grub_err_t
+grub_tcg2_get_max_output_size (grub_size_t *size)
+{
+  if (!size)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  *size = GRUB_TPM2_BUFFER_CAPACITY;
+
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_tcg2_submit_command (grub_size_t input_size, grub_uint8_t *input,
+                          grub_size_t output_size, grub_uint8_t *output)
+{
+  static const grub_size_t header_size = sizeof (grub_uint16_t) +
+                                         (2 * sizeof(grub_uint32_t));
+
+  if (write (tpm2_fd, input, input_size) != input_size)
+    return GRUB_ERR_BAD_DEVICE;
+
+  if (read (tpm2_fd, output, output_size) < header_size)
+    return GRUB_ERR_BAD_DEVICE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_open_device (const char *dev_node)
+{
+  if (tpm2_fd != -1)
+    return GRUB_ERR_NONE;
+
+  tpm2_fd = open (dev_node, O_RDWR);
+  if (tpm2_fd == -1)
+    {
+      fprintf (stderr, _("Could not open TPM device (Error: %u).\n"), errno);
+      return GRUB_ERR_FILE_NOT_FOUND;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_close_device (void)
+{
+  int err;
+
+  if (tpm2_fd == -1)
+    return GRUB_ERR_NONE;
+
+  err = close (tpm2_fd);
+  if (err)
+  {
+    fprintf (stderr, _("Could not close TPM device (Error: %u).\n"), errno);
+    return GRUB_ERR_IO;
+  }
+
+  tpm2_fd = -1;
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_get_policy_digest (struct grub_protect_args *args,
+                                     TPM2B_DIGEST *digest)
+{
+  TPM_RC rc;
+  TPML_PCR_SELECTION pcr_sel = {
+    .count = 1,
+    .pcrSelections = {
+      {
+        .hash = args->tpm2_bank,
+        .sizeOfSelect = 3,
+        .pcrSelect = { 0 }
+      },
+    }
+  };
+  TPML_PCR_SELECTION pcr_sel_out = { 0 };
+  TPML_DIGEST pcr_values = { 0 };
+  grub_uint8_t *pcr_digest;
+  grub_size_t pcr_digest_len;
+  grub_uint8_t *pcr_concat;
+  grub_size_t pcr_concat_len;
+  grub_uint8_t *pcr_cursor;
+  const gcry_md_spec_t *hash_spec;
+  TPM2B_NONCE nonce = { 0 };
+  TPM2B_ENCRYPTED_SECRET salt = { 0 };
+  TPMT_SYM_DEF symmetric = { 0 };
+  TPMI_SH_AUTH_SESSION session = 0;
+  TPM2B_DIGEST pcr_digest_in = {
+    .size = TPM_SHA256_DIGEST_SIZE,
+    .buffer = { 0 }
+  };
+  TPM2B_DIGEST policy_digest = { 0 };
+  grub_uint8_t i;
+  grub_err_t err;
+
+  /* PCR Read */
+  for (i = 0; i < args->tpm2_pcr_count; i++)
+    pcr_sel
+      .pcrSelections[0]
+      .pcrSelect[TPM2_PCR_TO_SELECT(args->tpm2_pcrs[i])]
+        |= TPM2_PCR_TO_BIT(args->tpm2_pcrs[i]);
+
+  rc = TPM2_PCR_Read (NULL, &pcr_sel, NULL, &pcr_sel_out, &pcr_values, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("Failed to read PCRs (TPM error: 0x%x).\n"), rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  if ((pcr_sel_out.count != pcr_sel.count) ||
+       (pcr_sel.pcrSelections[0].sizeOfSelect !=
+        pcr_sel_out.pcrSelections[0].sizeOfSelect))
+    {
+      fprintf (stderr, _("Could not read all the specified PCRs.\n"));
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Compute PCR Digest */
+  switch (args->tpm2_bank)
+    {
+    case TPM_ALG_SHA1:
+      pcr_digest_len = TPM_SHA1_DIGEST_SIZE;
+      hash_spec = GRUB_MD_SHA1;
+      break;
+    case TPM_ALG_SHA256:
+      pcr_digest_len = TPM_SHA256_DIGEST_SIZE;
+      hash_spec = GRUB_MD_SHA256;
+      break;
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  pcr_digest = grub_malloc (pcr_digest_len);
+  if (!pcr_digest)
+    {
+      fprintf (stderr, _("Failed to allocate PCR digest buffer.\n"));
+      return GRUB_ERR_OUT_OF_MEMORY;
+    }
+
+  pcr_concat_len = pcr_digest_len * args->tpm2_pcr_count;
+  pcr_concat = grub_malloc (pcr_concat_len);
+  if (!pcr_concat)
+    {
+      err = GRUB_ERR_OUT_OF_MEMORY;
+      fprintf (stderr, _("Failed to allocate PCR concatenation buffer.\n"));
+      goto exit1;
+    }
+
+  pcr_cursor = pcr_concat;
+  for (i = 0; i < args->tpm2_pcr_count; i++)
+    {
+      if (pcr_values.digests[i].size != pcr_digest_len)
+        {
+          fprintf (stderr,
+                   _("Bad PCR value size: expected %lu bytes but got %u bytes.\n"),
+                   pcr_digest_len, pcr_values.digests[i].size);
+          goto exit2;
+        }
+
+      grub_memcpy (pcr_cursor, pcr_values.digests[i].buffer, pcr_digest_len);
+      pcr_cursor += pcr_digest_len;
+    }
+
+  grub_crypto_hash (hash_spec, pcr_digest, pcr_concat, pcr_concat_len);
+
+  /* Start Trial Session */
+  nonce.size = TPM_SHA256_DIGEST_SIZE;
+  symmetric.algorithm = TPM_ALG_NULL;
+
+  rc = TPM2_StartAuthSession (TPM_RH_NULL, TPM_RH_NULL, 0, &nonce, &salt,
+                              TPM_SE_TRIAL, &symmetric, TPM_ALG_SHA256,
+                              &session, NULL, 0);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr,
+               _("Failed to start trial policy session (TPM error: 0x%x).\n"),
+               rc);
+      err = GRUB_ERR_BAD_DEVICE;
+      goto exit2;
+    }
+
+  /* PCR Policy */
+  memcpy (pcr_digest_in.buffer, pcr_digest, TPM_SHA256_DIGEST_SIZE);
+
+  rc = TPM2_PolicyPCR (session, NULL, &pcr_digest_in, &pcr_sel, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("Failed to submit PCR policy (TPM error: 0x%x).\n"),
+               rc);
+      err = GRUB_ERR_BAD_DEVICE;
+      goto exit3;
+    }
+
+  /* Retrieve Policy Digest */
+  rc = TPM2_PolicyGetDigest (session, NULL, &policy_digest, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("Failed to get policy digest (TPM error: 0x%x).\n"),
+               rc);
+      err = GRUB_ERR_BAD_DEVICE;
+      goto exit3;
+    }
+
+  /* Epilogue */
+  *digest = policy_digest;
+  err = GRUB_ERR_NONE;
+
+exit3:
+  TPM2_FlushContext (session);
+
+exit2:
+  grub_free (pcr_concat);
+
+exit1:
+  grub_free (pcr_digest);
+
+  return err;
+}
+
+static grub_err_t
+grub_protect_tpm2_get_srk (struct grub_protect_args *args, TPM_HANDLE *srk)
+{
+  TPM_RC rc;
+  TPM2B_PUBLIC public;
+  TPMS_AUTH_COMMAND authCommand = { 0 };
+  TPM2B_SENSITIVE_CREATE inSensitive = { 0 };
+  TPM2B_PUBLIC inPublic = { 0 };
+  TPM2B_DATA outsideInfo = { 0 };
+  TPML_PCR_SELECTION creationPcr = { 0 };
+  TPM2B_PUBLIC outPublic = { 0 };
+  TPM2B_CREATION_DATA creationData = { 0 };
+  TPM2B_DIGEST creationHash = { 0 };
+  TPMT_TK_CREATION creationTicket = { 0 };
+  TPM2B_NAME srkName = { 0 };
+  TPM_HANDLE srkHandle;
+
+  /* Find SRK */
+  rc = TPM2_ReadPublic (args->tpm2_srk, NULL, &public);
+  if (rc == TPM_RC_SUCCESS)
+    {
+      if (args->tpm2_persist)
+        fprintf (stderr,
+                 _("Warning: --tpm2-persist was specified but the SRK already exists on the TPM. Continuing anyway...\n"));
+
+      *srk = TPM2_SRK_HANDLE;
+      return GRUB_ERR_NONE;
+    }
+
+  /* The handle exists but its public area could not be read. */
+  if ((rc & ~TPM_RC_N_MASK) != TPM_RC_HANDLE)
+    {
+      fprintf (stderr,
+               _("The SRK exists on the TPM but its public area cannot be read (TPM error: 0x%x).\n"),
+               rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Create SRK */
+  authCommand.sessionHandle = TPM_RS_PW;
+  inPublic.publicArea.type = args->tpm2_asymmetric;
+  inPublic.publicArea.nameAlg  = TPM_ALG_SHA256;
+  inPublic.publicArea.objectAttributes.restricted = 1;
+  inPublic.publicArea.objectAttributes.userWithAuth = 1;
+  inPublic.publicArea.objectAttributes.decrypt = 1;
+  inPublic.publicArea.objectAttributes.fixedTPM = 1;
+  inPublic.publicArea.objectAttributes.fixedParent = 1;
+  inPublic.publicArea.objectAttributes.sensitiveDataOrigin = 1;
+  inPublic.publicArea.objectAttributes.noDA = 1;
+
+  switch (args->tpm2_asymmetric)
+    {
+    case TPM_ALG_RSA:
+      inPublic.publicArea.parameters.rsaDetail.symmetric.algorithm = TPM_ALG_AES;
+      inPublic.publicArea.parameters.rsaDetail.symmetric.keyBits.aes = 128;
+      inPublic.publicArea.parameters.rsaDetail.symmetric.mode.aes = TPM_ALG_CFB;
+      inPublic.publicArea.parameters.rsaDetail.scheme.scheme = TPM_ALG_NULL;
+      inPublic.publicArea.parameters.rsaDetail.keyBits = 2048;
+      inPublic.publicArea.parameters.rsaDetail.exponent = 0;
+      break;
+
+    case TPM_ALG_ECC:
+      inPublic.publicArea.parameters.eccDetail.symmetric.algorithm = TPM_ALG_AES;
+      inPublic.publicArea.parameters.eccDetail.symmetric.keyBits.aes = 128;
+      inPublic.publicArea.parameters.eccDetail.symmetric.mode.aes = TPM_ALG_CFB;
+      inPublic.publicArea.parameters.eccDetail.scheme.scheme = TPM_ALG_NULL;
+      inPublic.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256;
+      inPublic.publicArea.parameters.eccDetail.kdf.scheme = TPM_ALG_NULL;
+      break;
+
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  rc = TPM2_CreatePrimary (TPM_RH_OWNER, &authCommand, &inSensitive, &inPublic,
+                           &outsideInfo, &creationPcr, &srkHandle, &outPublic,
+                           &creationData, &creationHash, &creationTicket,
+                           &srkName, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("Failed to create SRK (TPM error: 0x%x).\n"), rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Persist SRK */
+  if (args->tpm2_persist)
+    {
+      rc = TPM2_EvictControl (TPM_RH_OWNER, srkHandle, args->tpm2_srk,
+                              &authCommand, NULL);
+      if (rc == TPM_RC_SUCCESS)
+        {
+          TPM2_FlushContext (srkHandle);
+          srkHandle = args->tpm2_srk;
+        }
+      else
+        fprintf (stderr,
+                 _("Warning: Failed to persist SRK (TPM error: 0x%x\n). Continuing anyway...\n"),
+                 rc);
+    }
+
+  /* Epilogue */
+  *srk = srkHandle;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_seal (TPM2B_DIGEST *policyDigest, TPM_HANDLE srk,
+                        grub_uint8_t *clearText, grub_size_t clearTextLength,
+                        TPM2_SEALED_KEY *sealed_key)
+{
+  TPM_RC rc;
+  TPMS_AUTH_COMMAND authCommand = { 0 };
+  TPM2B_SENSITIVE_CREATE inSensitive = { 0 };
+  TPM2B_PUBLIC inPublic  = { 0 };
+  TPM2B_DATA outsideInfo = { 0 };
+  TPML_PCR_SELECTION pcr_sel = { 0 };
+  TPM2B_PRIVATE outPrivate = { 0 };
+  TPM2B_PUBLIC outPublic = { 0 };
+
+  /* Seal Data */
+  authCommand.sessionHandle = TPM_RS_PW;
+
+  inSensitive.sensitive.data.size = clearTextLength;
+  memcpy(inSensitive.sensitive.data.buffer, clearText, clearTextLength);
+
+  inPublic.publicArea.type = TPM_ALG_KEYEDHASH;
+  inPublic.publicArea.nameAlg = TPM_ALG_SHA256;
+  inPublic.publicArea.parameters.keyedHashDetail.scheme.scheme = TPM_ALG_NULL;
+  inPublic.publicArea.authPolicy = *policyDigest;
+
+  rc = TPM2_Create (srk, &authCommand, &inSensitive, &inPublic, &outsideInfo,
+                    &pcr_sel, &outPrivate, &outPublic, NULL, NULL, NULL, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("Failed to seal key (TPM error: 0x%x).\n"), rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Epilogue */
+  sealed_key->public = outPublic;
+  sealed_key->private = outPrivate;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_export_sealed_key (const char *filepath,
+                                     TPM2_SEALED_KEY *sealed_key)
+{
+  grub_err_t err;
+  struct grub_tpm2_buffer buf;
+
+  grub_tpm2_buffer_init (&buf);
+  grub_tpm2_mu_TPM2B_PUBLIC_Marshal (&buf, &sealed_key->public);
+  grub_tpm2_mu_TPM2B_Marshal (&buf, sealed_key->private.size,
+                              sealed_key->private.buffer);
+  if (buf.error)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  err = grub_protect_write_file (filepath, buf.data, buf.size);
+  if (err)
+    fprintf (stderr, _("Could not write sealed key file (Error: %u).\n"),
+             errno);
+
+  return err;
+}
+
+static grub_err_t
+grub_protect_tpm2_add (struct grub_protect_args *args)
+{
+  grub_err_t err;
+  grub_uint8_t *key;
+  grub_size_t key_size;
+  TPM_HANDLE srk;
+  TPM2B_DIGEST policy_digest;
+  TPM2_SEALED_KEY sealed_key;
+  char *grub_drive = NULL;
+
+  grub_protect_get_grub_drive_for_file (args->tpm2_outfile, &grub_drive);
+
+  err = grub_protect_tpm2_open_device (args->tpm2_device);
+  if (err)
+    return err;
+
+  err = grub_protect_read_file (args->tpm2_keyfile, (void **)&key, &key_size);
+  if (err)
+    goto exit1;
+
+  if (key_size > TPM_MAX_SYM_DATA)
+  {
+    fprintf (stderr,
+             _("Input key is too long, maximum allowed size is %u bytes.\n"),
+             TPM_MAX_SYM_DATA);
+    return GRUB_ERR_OUT_OF_RANGE;
+  }
+
+  err = grub_protect_tpm2_get_srk (args, &srk);
+  if (err)
+    goto exit2;
+
+  err = grub_protect_tpm2_get_policy_digest (args, &policy_digest);
+  if (err)
+    goto exit3;
+
+  err = grub_protect_tpm2_seal (&policy_digest, srk, key, key_size,
+                                &sealed_key);
+  if (err)
+    goto exit3;
+
+  err = grub_protect_tpm2_export_sealed_key (args->tpm2_outfile, &sealed_key);
+  if (err)
+    goto exit3;
+
+  if (grub_drive)
+    {
+      printf (_("GRUB drive for the sealed key file: %s\n"), grub_drive);
+      grub_free (grub_drive);
+    }
+  else
+    {
+      fprintf (stderr,
+               _("Warning: Could not determine GRUB drive for sealed key file.\n"));
+      err = GRUB_ERR_NONE;
+    }
+
+exit3:
+  TPM2_FlushContext (srk);
+
+exit2:
+  grub_free (key);
+
+exit1:
+  grub_protect_tpm2_close_device ();
+
+  return err;
+}
+
+static grub_err_t
+grub_protect_tpm2_remove (struct grub_protect_args *args)
+{
+  TPM_RC rc;
+  TPM2B_PUBLIC public;
+  TPMS_AUTH_COMMAND authCommand = { 0 };
+  grub_err_t err;
+
+  if (!args->tpm2_evict)
+    {
+      printf (_("--tpm2-evict not specified, nothing to do.\n"));
+      return GRUB_ERR_NONE;
+    }
+
+  err = grub_protect_tpm2_open_device (args->tpm2_device);
+  if (err)
+    return err;
+
+  /* Find SRK */
+  rc = TPM2_ReadPublic (args->tpm2_srk, NULL, &public);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("SRK with handle 0x%x not found.\n"), args->tpm2_srk);
+      err = GRUB_ERR_BAD_ARGUMENT;
+      goto exit1;
+    }
+
+  /* Evict SRK */
+  authCommand.sessionHandle = TPM_RS_PW;
+
+  rc = TPM2_EvictControl (TPM_RH_OWNER, args->tpm2_srk, args->tpm2_srk,
+                          &authCommand, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr,
+               _("Failed to evict SRK with handle 0x%x (TPM Error: 0x%x).\n"),
+               args->tpm2_srk, rc);
+      err = GRUB_ERR_BAD_DEVICE;
+      goto exit2;
+    }
+
+  err = GRUB_ERR_NONE;
+
+exit2:
+  TPM2_FlushContext (args->tpm2_srk);
+
+exit1:
+  grub_protect_tpm2_close_device ();
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_run (struct grub_protect_args *args)
+{
+  switch (args->action)
+    {
+    case GRUB_PROTECT_ACTION_ADD:
+      return grub_protect_tpm2_add (args);
+
+    case GRUB_PROTECT_ACTION_REMOVE:

util/grub-protect.c line 778

Quoted 10 lines
util/grub-protect.c new file +10 -0
+      return grub_protect_tpm2_remove (args);
+
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+}
+
+static grub_err_t
+grub_protect_tpm2_args_verify (struct grub_protect_args *args)
+{

I'm wondering if it wouldn't be a good idea to merge this function with grub_tpm2_protector_check_args from patch #3. This is probably only manageable if the protector argument looks like the one from grub as well, so they can share error messages.

Quoted 14 lines
util/grub-protect.c new file +14 -0
+  switch (args->action)
+    {
+    case GRUB_PROTECT_ACTION_ADD:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_EVICT)
+        {
+          fprintf (stderr,
+                   _("--tpm2-evict is invalid when --action is 'add'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (!args->tpm2_keyfile)
+        {
+          fprintf (stderr, _("--tpm2-keyfile must be specified.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;

util/grub-protect.c line 802

Quoted 10 lines
util/grub-protect.c new file +10 -0
+        }
+
+      if (!args->tpm2_outfile)
+        {
+          fprintf (stderr, _("--tpm2-outfile must be specified.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (!args->tpm2_device)
+        args->tpm2_device = "/dev/tpm0";

Seems like this...

util/grub-protect.c line 811

Quoted 9 lines
util/grub-protect.c new file +9 -0
+
+      if (!args->tpm2_pcr_count)
+        {
+          args->tpm2_pcrs[0] = 7;
+          args->tpm2_pcr_count = 1;
+        }
+
+      if (!args->tpm2_srk)
+        args->tpm2_srk = TPM2_SRK_HANDLE;

and maybe this, can be done outside the switch since they are common to both cases.

Quoted 148 lines
util/grub-protect.c new file +148 -0
+
+      if (!args->tpm2_asymmetric)
+        args->tpm2_asymmetric = TPM_ALG_RSA;
+
+      if (!args->tpm2_bank)
+        args->tpm2_bank = TPM_ALG_SHA256;
+
+      break;
+
+    case GRUB_PROTECT_ACTION_REMOVE:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_ASYMMETRIC)
+        {
+          fprintf (stderr,
+                   _("--tpm2-asymmetric is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (args->args & GRUB_PROTECT_ARG_TPM2_BANK)
+        {
+          fprintf (stderr,
+                   _("--tpm2-bank is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (args->args & GRUB_PROTECT_ARG_TPM2_KEYFILE)
+        {
+          fprintf (stderr,
+                   _("--tpm2-keyfile is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (args->args & GRUB_PROTECT_ARG_TPM2_OUTFILE)
+        {
+          fprintf (stderr,
+                   _("--tpm2-outfile is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (args->args & GRUB_PROTECT_ARG_TPM2_PCRS)
+        {
+          fprintf (stderr,
+                   _("--tpm2-pcrs is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (args->args & GRUB_PROTECT_ARG_TPM2_PERSIST)
+        {
+          fprintf (stderr,
+                   _("--tpm2-persist is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (!args->tpm2_device)
+        args->tpm2_device = "/dev/tpm0";
+
+      if (!args->tpm2_srk)
+        args->tpm2_srk = TPM2_SRK_HANDLE;
+
+      break;
+
+    default:
+      fprintf (stderr,
+               _("The TPM2 key protector only supports the following actions: add, remove.\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protector_args_kvp_parse (char *kvp, const char **key, char **value)
+{
+  char divider;
+  char *separator;
+  grub_size_t len;
+
+  if (!kvp)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  len = grub_strlen (kvp);
+  if (!len || len < 2)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (kvp[0] == '-' && kvp[1] != '-')
+    divider = ' ';
+  else if (kvp[0] == '-' && kvp[1] == '-')
+    divider = '=';
+  else
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  separator = grub_strchr (kvp, divider);
+  if (!separator)
+    goto exit;
+
+  *separator = '\0';
+  separator += 1;
+
+  if (separator - kvp >= len)
+  {
+    separator = NULL;
+    goto exit;
+  }
+
+exit:
+  *key = kvp;
+  *value = separator;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_args_parse (int argc, char *argv[],
+                         struct grub_protect_args *args)
+{
+  grub_err_t err;
+  char *current_arg;
+  const char *key;
+  char *value;
+  int i;
+
+  for (i = 1; i < argc; i++)
+    {
+      current_arg = argv[i];
+
+      err = grub_protector_args_kvp_parse (current_arg, &key, &value);
+      if (err)
+        return err;
+
+      if (grub_strcmp (key, "--action") == 0 ||
+          grub_strcmp (key, "-a") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_ACTION)
+            {
+              fprintf (stderr,
+                       _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (grub_strcmp (value, "add") == 0)
+            args->action = GRUB_PROTECT_ACTION_ADD;
+          else if (grub_strcmp (value, "remove") == 0)
+            args->action = GRUB_PROTECT_ACTION_REMOVE;

util/grub-protect.c line 969

Quoted 10 lines
util/grub-protect.c new file +10 -0
+          else
+            {
+              fprintf (stderr, _("'%s' is not a valid action.\n"), value);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->args |= GRUB_PROTECT_ARG_ACTION;
+        }
+      else if (grub_strcmp (key, "--protector") == 0 ||
+               grub_strcmp (key, "-p") == 0)

This might be confusing because its -p here but -k to cryptomount.

Quoted 365 lines
util/grub-protect.c new file +365 -0
+        {
+          if (args->args & GRUB_PROTECT_ARG_PROTECTOR)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (grub_strcmp (value, "tpm2") == 0)
+            args->protector = GRUB_PROTECT_TYPE_TPM2;
+          else
+            {
+              fprintf (stderr, _("'%s' is not a valid protector.\n"), value);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->args |= GRUB_PROTECT_ARG_PROTECTOR;
+        }
+      else if (grub_strcmp (key, "--tpm2-device") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_DEVICE)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->tpm2_device = value;
+          args->args |= GRUB_PROTECT_ARG_TPM2_DEVICE;
+        }
+      else if (grub_strcmp (key, "--tpm2-pcrs") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_PCRS)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          grub_size_t len = grub_strlen (value);
+          grub_size_t dist;
+
+          long pcr;
+          char *next_pcr;
+          char *current_pcr = value;
+          grub_uint8_t pcr_u8;
+          grub_uint8_t j;
+          grub_uint8_t k;
+
+          for (j = 0;; j++)
+            {
+              next_pcr = grub_strchr (current_pcr, ',');
+              if (next_pcr)
+                *next_pcr = '\0';
+
+              grub_errno = GRUB_ERR_NONE;
+              pcr = grub_strtoul (current_pcr, NULL, 0);
+              if (grub_errno != GRUB_ERR_NONE)
+                {
+                  fprintf (stderr, _("'%s' is not a valid PCR number.\n"),
+                           current_pcr);
+                  return grub_errno;
+                }
+
+              if (pcr > TPM_MAX_PCRS)
+                {
+                  fprintf (stderr,
+                           _("%lu larger than the maximum number of PCRs.\n"),
+                           pcr);
+                  return GRUB_ERR_OUT_OF_RANGE;
+                }
+
+              pcr_u8 = (grub_uint8_t)pcr;
+
+              for (k = 0; k < args->tpm2_pcr_count; k++)
+              {
+                if (args->tpm2_pcrs[k] == pcr_u8)
+                  {
+                    fprintf (stderr, _("PCR %u was already specified.\n"),
+                             pcr_u8);
+                    return GRUB_ERR_BAD_ARGUMENT;
+                  }
+              }
+
+              args->tpm2_pcrs[j] = pcr_u8;
+              args->tpm2_pcr_count++;
+
+              if (!next_pcr)
+                break;
+
+              current_pcr = next_pcr + 1;
+
+              dist = (current_pcr - value);
+              if (dist >= len)
+                break;
+            }
+
+          args->args |= GRUB_PROTECT_ARG_TPM2_PCRS;
+        }
+      else if (grub_strcmp (key, "--tpm2-srk") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_SRK)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          long srk;
+
+          grub_errno = GRUB_ERR_NONE;
+          srk = grub_strtoul (value, NULL, 0);
+          if (grub_errno != GRUB_ERR_NONE)
+            {
+              fprintf (stderr, _("'%s' is not a valid SRK handle.\n"), value);
+              return grub_errno;
+            }
+
+          if (srk > GRUB_UINT_MAX)
+            {
+              fprintf (stderr,
+                       _("%lu is too large to be a valid SRK handle.\n"), srk);
+              return GRUB_ERR_OUT_OF_RANGE;
+            }
+
+          args->tpm2_srk = (TPM_HANDLE)srk;
+          args->args |= GRUB_PROTECT_ARG_TPM2_SRK;
+        }
+      else if (grub_strcmp (key, "--tpm2-asymmetric") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_ASYMMETRIC)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (grub_strcasecmp (value, "ECC") == 0)
+            args->tpm2_asymmetric = TPM_ALG_ECC;
+          else if (grub_strcasecmp (value, "RSA") == 0)
+            args->tpm2_asymmetric = TPM_ALG_RSA;
+          else
+            {
+              fprintf (stderr, _("'%s' is not a valid asymmetric algorithm.\n"),
+                       value);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->args |= GRUB_PROTECT_ARG_TPM2_ASYMMETRIC;
+        }
+      else if (grub_strcmp (key, "--tpm2-bank") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_BANK)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (grub_strcasecmp (value, "SHA1") == 0)
+            args->tpm2_bank = TPM_ALG_SHA1;
+          else if (grub_strcasecmp (value, "SHA256") == 0)
+            args->tpm2_bank = TPM_ALG_SHA256;
+          else
+            {
+              fprintf (stderr, _("'%s' is not a valid PCR bank.\n"), value);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->args |= GRUB_PROTECT_ARG_TPM2_BANK;
+        }
+      else if (grub_strcmp (key, "--tpm2-keyfile") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_KEYFILE)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+	  args->tpm2_keyfile = value;
+          args->args |= GRUB_PROTECT_ARG_TPM2_KEYFILE;
+        }
+      else if (grub_strcmp (key, "--tpm2-outfile") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_OUTFILE)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->tpm2_outfile = value;
+          args->args |= GRUB_PROTECT_ARG_TPM2_OUTFILE;
+        }
+      else if (grub_strcmp (key, "--tpm2-persist") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_PERSIST)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (value)
+            {
+              fprintf (stderr, _("Argument %s does not accept a value.\n"),
+                       key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->tpm2_persist = 1;
+          args->args |= GRUB_PROTECT_ARG_TPM2_PERSIST;
+        }
+      else if (grub_strcmp (key, "--tpm2-evict") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_EVICT)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (value)
+            {
+              fprintf (stderr, _("Argument %s does not accept a value.\n"),
+                       key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->tpm2_evict = 1;
+          args->args |= GRUB_PROTECT_ARG_TPM2_EVICT;
+        }
+        else
+          {
+            fprintf (stderr, _("'%s' is not a valid argument.\n"), key);
+            return GRUB_ERR_BAD_ARGUMENT;
+          }
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_args_verify (struct grub_protect_args *args)
+{
+  if (args->action == GRUB_PROTECT_ACTION_ERROR)
+    {
+      fprintf (stderr, "--action is mandatory.\n");
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  /* At the moment, the only configurable key protector is the TPM2 one, so it
+   * is the only keu protector supported by this tool. */
+  if (args->protector != GRUB_PROTECT_TYPE_TPM2)
+    {
+      fprintf (stderr,
+               _("--protector is mandatory and only 'tpm2' is currently supported.\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  switch (args->protector)
+    {
+    case GRUB_PROTECT_TYPE_TPM2:
+      return grub_protect_tpm2_args_verify (args);
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_dispatch (struct grub_protect_args *args)
+{
+  switch (args->protector)
+    {
+    case GRUB_PROTECT_TYPE_TPM2:
+      return grub_protect_tpm2_run (args);
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+}
+
+static void
+grub_protect_init (int *argc, char **argv[])
+{
+  grub_util_host_init (argc, argv);
+
+  grub_util_biosdisk_init (NULL);
+
+  grub_init_all ();
+  grub_gcry_init_all ();
+
+  grub_lvm_fini ();
+  grub_mdraid09_fini ();
+  grub_mdraid1x_fini ();
+  grub_diskfilter_fini ();
+  grub_diskfilter_init ();
+  grub_mdraid09_init ();
+  grub_mdraid1x_init ();
+  grub_lvm_init ();
+}
+
+static void
+grub_protect_fini (void)
+{
+  grub_gcry_fini_all ();
+  grub_fini_all ();
+  grub_util_biosdisk_fini ();
+}
+
+int
+main (int argc, char *argv[])
+{
+  grub_err_t err;
+  struct grub_protect_args args = { 0 };
+
+  grub_protect_init (&argc, &argv);
+
+  err = grub_protect_args_parse (argc, argv, &args);
+  if (err)
+    goto exit;
+
+  err = grub_protect_args_verify (&args);
+  if (err)
+    goto exit;

util/grub-protect.c line 1344

Quoted 10 lines
util/grub-protect.c new file +10 -0
+
+  err = grub_protect_dispatch (&args);
+  if (err)
+    goto exit;
+
+exit:
+  grub_protect_fini ();
+
+  return err;
+}

It would be nice to take arguments --help and -h and spit out something useful.

Glenn

#11 lore raw

Re: [PATCH 4/5] cryptodisk: Support key protectors

In reply to Glenn Washburn
Quoted 2 lines · Glenn Washburn

On Mon, 24 Jan 2022 06:12:17 -0800
Hernan Gatta <[email protected]> wrote:

[...]

Quoted 10 lines
Quoted 10 lines
grub-core/disk/cryptodisk.c +2 -0
+    }
+
   if (state[0].set) /* uuid */
     {
       int found_uuid;
@@ -1385,7 +1404,7 @@ GRUB_MOD_INIT (cryptodisk)
 {
   grub_disk_dev_register (&grub_cryptodisk_dev);
   cmd = grub_register_extcmd ("cryptomount", grub_cmd_cryptomount,
 0,
Quoted 8 lines

Review GRUB_MOD_INIT (cryptodisk) · line 1410

Quoted 4 lines
(quoted diff) +1 -1
-			      N_("[-p password] <SOURCE|-u UUID|-a|-
 b>"),
+			      N_("[-p password] [-k protector[:args]]
 <SOURCE|-u UUID|-a|-b>"),

This looks eerily similiar to what I proposed to James in response to his SEV patches[1]. As such, I am in favor of this syntax and it looks to me like a framework that James can use for his SEV series.

Well, I could, but I've got to say for a shell like system, which grub is, argument lists passed as a single argument always cause problems with quoting and interpolation. if the protector needs additional arguments to initialize, then it should really be done as a separate module to avoid the arguments within argument problem, so

protector_init [args]
crtptomount -k protector ...

means that [args] can use the standard arguments and doesn't have any internal quoting issues.

James

#18 lore raw
In reply to Hernan Gatta
Quoted 33 lines · On Mon, 24 Jan 2022 06:12:13 -0800 Hernan Gatta <[email protected]>…

This patch series adds support for automatically unlocking fully-encrypted disks using a TPM 2.0.

Currently, when GRUB encounters a fully-encrypted disk that it must access, its corresponding cryptodisk module (LUKS 1, LUKS2, or GELI) interactively prompts the user for a passphrase. An improvement to the boot process would be for GRUB to automatically retrieve the unlocking key for fully-encrypted disks from a protected location and to unlock these transparently. To this end, a TPM may be used to protect the unlocking key to a known-good state of the platform. Once the key is protected in this way, assuming that the platform remains trustworthy, GRUB can then utilize the TPM to release the key during boot and thus unlock fully-encrypted disks without user interaction. Such a model would not only be more convenient for end-users but also for virtual machines in cloud environments where no user is ever present.

Design
------

This patchset first adds a key protectors framework. This framework allows for key protector modules to register when loaded. A key protector is defined as a module that knows how to retrieve an unlocking key from a specific source. This patchset adds a single such key protector module that understands how to retrieve an unlocking key from a TPM 2.0 by unsealing a sealed key file via a Storage Root Key (SRK).

Additionally, this patchset expands the cryptomount command to accept a key protector parameter. This parameter carries the information necessary to select and parameterize a key protector to be used to retrieve an unlocking key for the disk in question. That is, given an invocation of cryptomount to mount a specific disk (e.g., "cryptomount (hd0,gpt2)", "cryptomount -u UUID"), a key protector can be used to automatically retrieve an unlocking key without an interactive prompt.

Quoted 6 lines

Lastly, this patchset also includes a new tool, grub-protect, that allows the user to seal a key file against a set of Platform Configuration Registers (PCRs) using an SRK. This sealed key file is expected to be stored in an unencrypted partition, such as the EFI System Partition (ESP), where GRUB can read it. The sealed key is then unsealed by the TPM2 key protector automatically, provided that the PCRs selected match on subsequent boots.

This series should include a documentation patch at a minimum. I would also like to see a QEMU test added. But it should use my cryptomount test series, which hasn't made it to master yet. So this shouldn't be a hard requirement. It would be nice for someone more familiar with Secure boot and TPM to figure out how to get it working in QEMU so we/I can easily add it to the tests. It looks like this should work with the required software[1].

Glenn

[1] https://en.opensuse.org/Software_TPM_Emulator_For_QEMU

Quoted 48 lines

Hernan Gatta (5):
protectors: Add key protectors framework
tpm2: Add TPM Software Stack (TSS)
protectors: Add TPM2 Key Protector
cryptodisk: Support key protectors
util/grub-protect: Add new tool

 .gitignore                             |    1 +
 Makefile.util.def                      |   17 +
 configure.ac                           |    1 +
 grub-core/Makefile.am                  |    1 +
 grub-core/Makefile.core.def            |   10 +
 grub-core/disk/cryptodisk.c            |   21 +-
 grub-core/kern/protectors.c            |   98 +++
 grub-core/tpm2/buffer.c                |  145 ++++
 grub-core/tpm2/module.c                |  742 ++++++++++++++++++
 grub-core/tpm2/mu.c                    |  807 +++++++++++++++++++
 grub-core/tpm2/tcg2.c                  |  143 ++++
 grub-core/tpm2/tpm2.c                  |  711 +++++++++++++++++
 include/grub/protector.h               |   55 ++
 include/grub/tpm2/buffer.h             |   65 ++
 include/grub/tpm2/internal/functions.h |  117 +++
 include/grub/tpm2/internal/structs.h   |  675 ++++++++++++++++
 include/grub/tpm2/internal/types.h     |  372 +++++++++
 include/grub/tpm2/mu.h                 |  292 +++++++
 include/grub/tpm2/tcg2.h               |   34 +
 include/grub/tpm2/tpm2.h               |   38 +
 util/grub-protect.c                    | 1344 ++++++++++++++++++++++++++++++++
 21 files changed, 5688 insertions(+), 1 deletion(-)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 grub-core/tpm2/buffer.c
 create mode 100644 grub-core/tpm2/module.c
 create mode 100644 grub-core/tpm2/mu.c
 create mode 100644 grub-core/tpm2/tcg2.c
 create mode 100644 grub-core/tpm2/tpm2.c
 create mode 100644 include/grub/protector.h
 create mode 100644 include/grub/tpm2/buffer.h
 create mode 100644 include/grub/tpm2/internal/functions.h
 create mode 100644 include/grub/tpm2/internal/structs.h
 create mode 100644 include/grub/tpm2/internal/types.h
 create mode 100644 include/grub/tpm2/mu.h
 create mode 100644 include/grub/tpm2/tcg2.h
 create mode 100644 include/grub/tpm2/tpm2.h
 create mode 100644 util/grub-protect.c
#7 lore raw

Re: [PATCH 3/5] protectors: Add TPM2 Key Protector

In reply to Glenn Washburn
Quoted 23 lines · Glenn Washburn
Quoted 9 lines · On Mon, 24 Jan 2022 06:12:16 -0800 Hernan Gatta <[email protected]>…

From: Hernan Gatta <[email protected]>

The TPM2 key protector is a module that enables the automatic retrieval of a fully-encrypted disk's unlocking key from a TPM 2.0.

The theory of operation is such that the module accepts various arguments, most of which are optional therefore possess reasonable defaults. One of these arguments is the keyfile parameter, which is mandatory.

Quoted 10 lines

The value of this parameter must be a path to a sealed key file (e.g., (hd0,gpt1)/boot/grub2/sealed_key). This sealed key file is created via the grub-protect tool. The tool utilizes the TPM's sealing functionality to seal (i.e., encrypt) an unlocking key using a Storage Root Key (SRK) to the values of various Platform Configuration Registers (PCRs). These PCRs reflect the state of the system as it boots. If the values are as expected, the system may be considered trustworthy, at which point the TPM allows for a caller to utilize the private component of the SRK to unseal (i.e., decrypt) the sealed key file. The caller, in this case, is this key protector.

Quoted 14 lines

There are a lot of points in this code where an error can be returned. In this case, all I'm going to get is a non-descript error code (almost always GRUB_ERR_BAD_ARGUMENT). So as a user, how am I to know where the error is actually coming from? For this reason, I like the use of grub_error(error_code, error_format_string, fmtstr_args...), which will set grub_errno and an error message, which can be retrieved up the stack and presented to the user. I'm not sure that every return of a naked error code should be replaced by grub_error(), depends on how granular of an error message you want to see. I would error on the side of more granular. For instance, its really nice that GCC will tell me which format code type specifier and a argument its choking on, rather than a catch all "I'm failing to compile your code because you have an incorrect format code somewhere in your format string".

Agreed. I'll add calls to grub_error to indicate why things fail and, when they do, capture the error up the stack (I was thinking in the command handler for cryptomount), and print it.

Quoted 255 lines
Quoted 255 lines
---
 grub-core/Makefile.core.def |   9 +
 grub-core/tpm2/module.c     | 742 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 751 insertions(+)
 create mode 100644 grub-core/tpm2/module.c
grub-core/Makefile.core.def +9 -0
index e4ae78b..8691440 100644
@@ -2498,6 +2498,15 @@ module = {
 };
 
 module = {
+  name = tpm2;
+  common = tpm2/buffer.c;
+  common = tpm2/module.c;
+  common = tpm2/mu.c;
+  common = tpm2/tpm2.c;
+  efi = tpm2/tcg2.c;
+};
+
+module = {
   name = tr;
   common = commands/tr.c;
 };
grub-core/tpm2/module.c new file +222 -0
new file mode 100644
index 0000000..cd97452
@@ -0,0 +1,742 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/dl.h>
+#include <grub/file.h>
+#include <grub/misc.h>
+#include <grub/mm.h>
+#include <grub/protector.h>
+#include <grub/tpm2/buffer.h>
+#include <grub/tpm2/mu.h>
+#include <grub/tpm2/tpm2.h>
+#include <grub/types.h>
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+typedef enum grub_tpm2_protector_args
+{
+  GRUB_TPM2_PROTECTOR_ARG_MODE       = 1 << 0,
+  GRUB_TPM2_PROTECTOR_ARG_PCRS       = 1 << 1,
+  GRUB_TPM2_PROTECTOR_ARG_ASYMMETRIC = 1 << 2,
+  GRUB_TPM2_PROTECTOR_ARG_BANK       = 1 << 3,
+  GRUB_TPM2_PROTECTOR_ARG_KEYFILE    = 1 << 4,
+  GRUB_TPM2_PROTECTOR_ARG_SRK        = 1 << 5,
+  GRUB_TPM2_PROTECTOR_ARG_NV         = 1 << 6
+} grub_tpm2_protector_args_t;
+
+typedef enum grub_tpm2_protector_mode
+{
+  GRUB_TPM2_PROTECTOR_MODE_SRK = 1,
+  GRUB_TPM2_PROTECTOR_MODE_NV  = 2
+} grub_tpm2_protector_mode_t;
+
+struct grub_tpm2_protector_context
+{
+  grub_tpm2_protector_args_t args;
+  grub_tpm2_protector_mode_t mode;
+  grub_uint8_t pcrs[TPM_MAX_PCRS];
+  grub_uint8_t pcr_count;
+  TPM_ALG_ID asymmetric;
+  TPM_ALG_ID bank;
+  const char *keyfile;
+  TPM_HANDLE srk;
+  TPM_HANDLE nv;
+};
+
+static grub_err_t
+grub_tpm2_protector_parse_mode (struct grub_tpm2_protector_context *ctx,
+                                const char *value)
+{
+  if (grub_strcmp (value, "srk") == 0)
+    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_SRK;
+  else if (grub_strcmp (value, "nv") == 0)
+    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_NV;
+  else
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_pcrs (struct grub_tpm2_protector_context *ctx,
+                                char *value)
+{
+  grub_err_t err;
+  char *current_pcr = value;
+  char *next_pcr;
+  unsigned long pcr;
+  grub_uint8_t i;
+
+  if (grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  ctx->pcr_count = 0;
+  for (i = 0; i < TPM_MAX_PCRS; i++)
+    {
+      next_pcr = grub_strchr (current_pcr, ',');
+      if (next_pcr)
+        *next_pcr = '\0';
+      if (next_pcr == current_pcr)
+        return GRUB_ERR_BAD_ARGUMENT;
+
+      grub_errno = GRUB_ERR_NONE;
+      pcr = grub_strtoul (current_pcr, NULL, 10);
+      if (grub_errno != GRUB_ERR_NONE)
+        {
+          err = grub_errno;
+          grub_errno = GRUB_ERR_NONE;
+          return err;
+        }
+
+      if (pcr > GRUB_UCHAR_MAX)
+        return GRUB_ERR_OUT_OF_RANGE;
+
+      ctx->pcrs[i] = (grub_uint8_t)pcr;
+      ctx->pcr_count++;
+
+      if (!next_pcr)
+        break;
+
+      current_pcr = next_pcr + 1;
+      if (*current_pcr == '\0')
+        return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (i == TPM_MAX_PCRS)
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_asymmetric (struct grub_tpm2_protector_context *ctx,
+                                      const char *value)
+{
+  if (grub_strcasecmp (value, "ECC") == 0)
+    ctx->asymmetric = TPM_ALG_ECC;
+  else if (grub_strcasecmp (value, "RSA") == 0)
+    ctx->asymmetric = TPM_ALG_RSA;
+  else
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_bank (struct grub_tpm2_protector_context *ctx,
+                                const char *value)
+{
+  if (grub_strcasecmp (value, "SHA1") == 0)
+    ctx->bank = TPM_ALG_SHA1;
+  else if (grub_strcasecmp (value, "SHA256") == 0)
+    ctx->bank = TPM_ALG_SHA256;
+  else if (grub_strcasecmp (value, "SHA384") == 0)
+    ctx->bank = TPM_ALG_SHA384;
+  else
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_keyfile (struct grub_tpm2_protector_context *ctx,
+                                   const char *value)
+{
+  if (grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  ctx->keyfile = value;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_tpm_handle (const char *value, TPM_HANDLE *handle)
+{
+  grub_err_t err;
+  unsigned long num;
+
+  grub_errno = GRUB_ERR_NONE;
+  num = grub_strtoul (value, NULL, 0);
+  if (grub_errno != GRUB_ERR_NONE)
+    {
+      err = grub_errno;
+      grub_errno = GRUB_ERR_NONE;
+      return err;
+    }
+
+  if (num > GRUB_UINT_MAX)
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  *handle = (TPM_HANDLE)num;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_srk (struct grub_tpm2_protector_context *ctx,
+                               const char *value)
+{
+  return grub_tpm2_protector_parse_tpm_handle (value, &ctx->srk);
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_nvindex (struct grub_tpm2_protector_context *ctx,
+                                   const char *value)
+{
+  return grub_tpm2_protector_parse_tpm_handle (value, &ctx->nv);
+}
+
+static grub_err_t
+grub_tpm2_protector_match_arg (struct grub_tpm2_protector_context *ctx,
+                               const char *key, char *value)
+{
+  grub_err_t err;
+
+  if (grub_strlen (key) == 0 || grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (grub_strcmp (key, "mode") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_MODE)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_mode (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_MODE;
+
Quoted 9 lines

grub-core/tpm2/module.c line 226

Quoted 4 lines
grub-core/tpm2/module.c new file +4 -0
+    return err;
+  }
+
+  if (grub_strcmp (key, "pcrs") == 0)

Minor nit, why wouldn't this be better as an "else if"? Seems unnecessary to check all the "if" statements if we've already found a match.

The reason why I wrote this in this way without an "else if" is because each "if" clause has an unconditional return. So, in the end, the entire sequence behaves in the manner you describe.

Would you prefer that I add the "else if"'s anyway for readability?

Quoted 6 lines
Quoted 6 lines
grub-core/tpm2/module.c new file +6 -0
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_PCRS)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_pcrs (ctx, value);
+    if (!err)
Quoted 9 lines

grub-core/tpm2/module.c line 238

Quoted 6 lines
grub-core/tpm2/module.c new file +6 -0
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_PCRS;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "asymmetric") == 0)

Ditto, for the rest of these ifs.

As above.

Quoted 475 lines
Quoted 475 lines
grub-core/tpm2/module.c new file +475 -0
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_ASYMMETRIC)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_asymmetric (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_ASYMMETRIC;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "bank") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_BANK)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_bank (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_BANK;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "keyfile") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_KEYFILE)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_keyfile (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_KEYFILE;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "srk") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_SRK)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_srk (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_SRK;
+
+    return err;
+  }
+
+  if (grub_strcmp (key, "nvindex") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_NV)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_nvindex (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_NV;
+
+    return err;
+  }
+
+  return GRUB_ERR_OUT_OF_RANGE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_arg (struct grub_tpm2_protector_context *ctx,
+                               char *arg)
+{
+  char *key = arg;
+  char *value = NULL;
+
+  if (grub_strlen (arg) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  value = grub_strchr (arg, '=');
+  if (!value)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  *value = '\0';
+  value++;
+
+  if (*value == '\0')
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  return grub_tpm2_protector_match_arg (ctx, key, value);
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_args (struct grub_tpm2_protector_context *ctx,
+                                char *args)
+{
+  grub_err_t err;
+  char *cur_arg;
+  char *next_arg;
+
+  if (args == NULL)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (grub_strlen (args) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  cur_arg = args;
+  for (;;)
+    {
+      next_arg = grub_strchr (cur_arg, ':');
+      if (next_arg == cur_arg)
+        return GRUB_ERR_BAD_ARGUMENT;
+      if (next_arg)
+        *next_arg = '\0';
+
+      err = grub_tpm2_protector_parse_arg (ctx, cur_arg);
+      if (err)
+        return err;
+
+      if (!next_arg)
+        break;
+
+      cur_arg = next_arg + 1;
+      if (*cur_arg == '\0')
+        return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_check_args (struct grub_tpm2_protector_context *ctx)
+{
+  if (!(ctx->args & GRUB_TPM2_PROTECTOR_ARG_MODE))
+    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_SRK;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && !ctx->keyfile)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && ctx->nv)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->srk)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && !ctx->nv)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->asymmetric)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->bank)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (!(ctx->args & GRUB_TPM2_PROTECTOR_ARG_PCRS))
+    {
+      ctx->pcrs[0] = 7;
+      ctx->pcr_count = 1;
+    }
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK)
+    {
+      if (!ctx->srk)
+        ctx->srk = TPM2_SRK_HANDLE;
+
+      if (!ctx->asymmetric)
+        ctx->asymmetric = TPM_ALG_RSA;
+
+      if (!ctx->bank)
+        ctx->bank = TPM_ALG_SHA256;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_srk_read_keyfile (const char *filepath, void **buffer,
+                                      grub_size_t *buffer_size)
+{
+  grub_file_t sealed_key_file;
+  grub_off_t sealed_key_size;
+  void *sealed_key_buffer;
+  grub_off_t sealed_key_read;
+
+  sealed_key_file = grub_file_open (filepath, GRUB_FILE_TYPE_NONE);
+  if (!sealed_key_file)
+    {
+      /* grub_file_open sets grub_errno on error, and if we do no unset it,
+       * future calls to grub_file_open will fail (and so will anybody up the
+       * stack who checks the value, if any). */
+      grub_errno = GRUB_ERR_NONE;
+      return GRUB_ERR_FILE_NOT_FOUND;
+    }
+
+  sealed_key_size = grub_file_size (sealed_key_file);
+  if (!sealed_key_size)
+    {
+      grub_file_close (sealed_key_file);
+      return GRUB_ERR_OUT_OF_RANGE;
+    }
+
+  sealed_key_buffer = grub_malloc (sealed_key_size);
+  if (!sealed_key_buffer)
+    {
+      grub_file_close (sealed_key_file);
+      return GRUB_ERR_OUT_OF_MEMORY;
+    }
+
+  sealed_key_read = grub_file_read (sealed_key_file, sealed_key_buffer,
+                                    sealed_key_size);
+  if (sealed_key_read != sealed_key_size)
+    {
+      grub_free (sealed_key_buffer);
+      grub_file_close (sealed_key_file);
+      return GRUB_ERR_FILE_READ_ERROR;
+    }
+
+  grub_file_close (sealed_key_file);
+
+  *buffer = sealed_key_buffer;
+  *buffer_size = sealed_key_size;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_srk_unmarshal_keyfile (void *sealed_key,
+                                           grub_size_t sealed_key_size,
+                                           TPM2_SEALED_KEY *sk)
+{
+  struct grub_tpm2_buffer buf;
+
+  grub_tpm2_buffer_init (&buf);
+  if (sealed_key_size > buf.cap)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  grub_memcpy (buf.data, sealed_key, sealed_key_size);
+  buf.size = sealed_key_size;
+
+  grub_tpm2_mu_TPM2B_PUBLIC_Unmarshal (&buf, &sk->public);
+  grub_tpm2_mu_TPM2B_Unmarshal (&buf, (TPM2B *)&sk->private);
+
+  return buf.error ? GRUB_ERR_BAD_ARGUMENT : GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_srk_get (const struct grub_tpm2_protector_context *ctx,
+                             TPM_HANDLE *srk)
+{
+  TPM_RC rc;
+  TPM2B_PUBLIC public;
+  TPMS_AUTH_COMMAND authCommand = { 0 };
+  TPM2B_SENSITIVE_CREATE inSensitive = { 0 };
+  TPM2B_PUBLIC inPublic = { 0 };
+  TPM2B_DATA outsideInfo = { 0 };
+  TPML_PCR_SELECTION creationPcr = { 0 };
+  TPM2B_PUBLIC outPublic = { 0 };
+  TPM2B_CREATION_DATA creationData = { 0 };
+  TPM2B_DIGEST creationHash = { 0 };
+  TPMT_TK_CREATION creationTicket = { 0 };
+  TPM2B_NAME srkName = { 0 };
+  TPM_HANDLE srkHandle;
+
+  /* Find SRK */
+  rc = TPM2_ReadPublic (ctx->srk, NULL, &public);
+  if (rc == TPM_RC_SUCCESS)
+    {
+      *srk = ctx->srk;
+      return GRUB_ERR_NONE;
+    }
+
+  /* The handle exists but its public area could not be read. */
+  if ((rc & ~TPM_RC_N_MASK) != TPM_RC_HANDLE)
+    return GRUB_ERR_BAD_DEVICE;
+
+  /* Create SRK */
+  authCommand.sessionHandle = TPM_RS_PW;
+  inPublic.publicArea.type = ctx->asymmetric;
+  inPublic.publicArea.nameAlg  = TPM_ALG_SHA256;
+  inPublic.publicArea.objectAttributes.restricted = 1;
+  inPublic.publicArea.objectAttributes.userWithAuth = 1;
+  inPublic.publicArea.objectAttributes.decrypt = 1;
+  inPublic.publicArea.objectAttributes.fixedTPM = 1;
+  inPublic.publicArea.objectAttributes.fixedParent = 1;
+  inPublic.publicArea.objectAttributes.sensitiveDataOrigin = 1;
+  inPublic.publicArea.objectAttributes.noDA = 1;
+
+  if (ctx->asymmetric == TPM_ALG_RSA)
+    {
+      inPublic.publicArea.parameters.rsaDetail.symmetric.algorithm = TPM_ALG_AES;
+      inPublic.publicArea.parameters.rsaDetail.symmetric.keyBits.aes = 128;
+      inPublic.publicArea.parameters.rsaDetail.symmetric.mode.aes = TPM_ALG_CFB;
+      inPublic.publicArea.parameters.rsaDetail.scheme.scheme = TPM_ALG_NULL;
+      inPublic.publicArea.parameters.rsaDetail.keyBits = 2048;
+      inPublic.publicArea.parameters.rsaDetail.exponent = 0;
+    }
+  else if (ctx->asymmetric == TPM_ALG_ECC)
+    {
+      inPublic.publicArea.parameters.eccDetail.symmetric.algorithm = TPM_ALG_AES;
+      inPublic.publicArea.parameters.eccDetail.symmetric.keyBits.aes = 128;
+      inPublic.publicArea.parameters.eccDetail.symmetric.mode.aes = TPM_ALG_CFB;
+      inPublic.publicArea.parameters.eccDetail.scheme.scheme = TPM_ALG_NULL;
+      inPublic.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256;
+      inPublic.publicArea.parameters.eccDetail.kdf.scheme = TPM_ALG_NULL;
+    }
+  else
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  rc = TPM2_CreatePrimary (TPM_RH_OWNER, &authCommand, &inSensitive, &inPublic,
+                           &outsideInfo, &creationPcr, &srkHandle, &outPublic,
+                           &creationData, &creationHash, &creationTicket,
+                           &srkName, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    return GRUB_ERR_BAD_DEVICE;
+
+  *srk = srkHandle;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_srk_recover (const struct grub_tpm2_protector_context *ctx,
+                                 grub_uint8_t **key, grub_size_t *key_size)
+{
+  TPM_RC rc;
+  TPM2_SEALED_KEY sealed_key;
+  void *sealed_key_bytes;
+  grub_size_t sealed_key_size;
+  TPM_HANDLE srk_handle;
+  TPM2B_NONCE nonceCaller = { 0 };
+  TPM2B_ENCRYPTED_SECRET salt = { 0 };
+  TPMT_SYM_DEF symmetric = { 0 };
+  TPM2B_NONCE nonceTPM = { 0 };
+  TPMI_SH_AUTH_SESSION session;
+  TPML_PCR_SELECTION pcrSel = {
+    .count = 1,
+    .pcrSelections = {
+      {
+        .hash = ctx->bank,
+        .sizeOfSelect = 3,
+        .pcrSelect = { 0 }
+      },
+    }
+  };
+  TPMS_AUTH_COMMAND authCmd = { 0 };
+  TPM_HANDLE sealed_key_handle;
+  TPM2B_NAME name;
+  TPMS_AUTH_RESPONSE authResponse;
+  TPM2B_SENSITIVE_DATA data;
+  grub_uint8_t *key_out;
+  grub_uint8_t i;
+  grub_err_t err;
+
+  /* Retrieve Sealed Key */
+  err = grub_tpm2_protector_srk_read_keyfile (ctx->keyfile, &sealed_key_bytes,
+                                              &sealed_key_size);
+  if (err)
+    return err;
+
+  err = grub_tpm2_protector_srk_unmarshal_keyfile (sealed_key_bytes,
+                                                   sealed_key_size,
+                                                   &sealed_key);
+  if (err)
+    goto exit1;
+
+  /* Get SRK */
+  err = grub_tpm2_protector_srk_get (ctx, &srk_handle);
+  if (err)
+    goto exit1;
+
+  err = GRUB_ERR_BAD_DEVICE;
+
+  /* Start Auth Session */
+  nonceCaller.size = TPM_SHA256_DIGEST_SIZE;
+  symmetric.algorithm = TPM_ALG_NULL;
+
+  rc = TPM2_StartAuthSession (TPM_RH_NULL, TPM_RH_NULL, 0, &nonceCaller, &salt,
+                              TPM_SE_POLICY, &symmetric, TPM_ALG_SHA256,
+                              &session, &nonceTPM, 0);
+  if (rc)
+    goto exit2;
+
+  /* Policy PCR */
+  for (i = 0; i < ctx->pcr_count; i++)
+    pcrSel
+      .pcrSelections[0]
+      .pcrSelect[TPM2_PCR_TO_SELECT(ctx->pcrs[i])]
+        |= TPM2_PCR_TO_BIT(ctx->pcrs[i]);
+
+  rc = TPM2_PolicyPCR (session, NULL, NULL, &pcrSel, NULL);
+  if (rc)
+    goto exit3;
+
+  /* Load Sealed Key */
+  authCmd.sessionHandle = TPM_RS_PW;
+  rc = TPM2_Load (srk_handle, &authCmd, &sealed_key.private, &sealed_key.public,
+                  &sealed_key_handle, &name, &authResponse);
+  if (rc)
+    goto exit3;
+
+  /* Unseal Sealed Key */
+  authCmd.sessionHandle = session;
+  grub_memset (&authResponse, 0, sizeof (authResponse));
+
+  rc = TPM2_Unseal (sealed_key_handle, &authCmd, &data, &authResponse);
+  if (rc)
+    goto exit4;
+
+  /* Epilogue */
+  key_out = grub_malloc (data.size);
+  if (!key_out)
+    {
+      err = GRUB_ERR_OUT_OF_MEMORY;
+      goto exit4;
+    }
+
+  grub_memcpy (key_out, data.buffer, data.size);
+
+  *key = key_out;
+  *key_size = data.size;
+
+  err = GRUB_ERR_NONE;
+
+exit4:
+  TPM2_FlushContext (sealed_key_handle);
+
+exit3:
+  TPM2_FlushContext (session);
+
+exit2:
+  TPM2_FlushContext (srk_handle);
+
+exit1:
+  grub_free (sealed_key_bytes);
+  return err;
+}
+
+static grub_err_t
+grub_tpm2_protector_nv_recover (const struct grub_tpm2_protector_context *ctx,
+                                grub_uint8_t **key, grub_size_t *key_size)
+{
+  (void)ctx;
+  (void)key;
+  (void)key_size;
+
+  return GRUB_ERR_NOT_IMPLEMENTED_YET;
+}
+
+static grub_err_t
+grub_tpm2_protector_recover (const struct grub_tpm2_protector_context *ctx,
+                             grub_uint8_t **key, grub_size_t *key_size)
+{
+  switch (ctx->mode)
+    {
+    case GRUB_TPM2_PROTECTOR_MODE_SRK:
+      return grub_tpm2_protector_srk_recover (ctx, key, key_size);
+    case GRUB_TPM2_PROTECTOR_MODE_NV:
+      return grub_tpm2_protector_nv_recover (ctx, key, key_size);
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+}
+
+static grub_err_t
+grub_tpm2_protector_recover_key (char *args, grub_uint8_t **key,
+                                 grub_size_t *key_size)
+{
+  grub_err_t err;
+  struct grub_tpm2_protector_context ctx = { 0 };
+
+  grub_dprintf ("tpm2", "Args: %s\n", args);
+
+  if (!args || !key)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  err = grub_tpm2_protector_parse_args (&ctx, args);
+  if (err) {
+    grub_dprintf("tpm2", "Failed to parse arguments\n");
+    return err;
+  }
+
+  err = grub_tpm2_protector_check_args (&ctx);
Quoted 9 lines

grub-core/tpm2/module.c line 715

Quoted 2 lines
grub-core/tpm2/module.c new file +2 -0
+  if (err) {
+    grub_dprintf("tpm2", "Invalid arguments\n");

It's nice that this is here to at least let the user know that the failure was because of invalid arguments as opposed to a failure in the parsing. Even still, which argument was invalid? why was it invalid? As a user, this might be frustrating to diagnose. This is why a message specific to the error would be appreciated.

I'll remove these from here, add more granular error messages within the rest of the code, and have the message, if any, be printed upon error up the stack.

Quoted 21 lines

Glenn

Quoted 19 lines
grub-core/tpm2/module.c new file +19 -0
+    return err;
+  }
+
+  err = grub_tpm2_protector_recover (&ctx, key, key_size);
+  if (err) {
+    grub_dprintf("tpm2", "Failed to recover key\n");
+    return err;
+  }
+
+  return GRUB_ERR_NONE;
+}
+
+struct grub_key_protector grub_tpm2_key_protector = {
+  .name = "tpm2",
+  .flags = GRUB_KEY_PROTECTOR_FLAG_NONE,
+  .recover_key = grub_tpm2_protector_recover_key
+};
+
+GRUB_MOD_INIT(tpm2)
Quoted 9 lines

grub-core/tpm2/module.c line 742

Quoted 8 lines
grub-core/tpm2/module.c new file +8 -0
+{
+  grub_key_protector_register (&grub_tpm2_key_protector);
+}
+
+GRUB_MOD_FINI(tpm2)
+{
+  grub_key_protector_unregister (&grub_tpm2_key_protector);
+}

Thank you,
Hernan

#3 lore raw

Re: [PATCH 1/5] protectors: Add key protectors framework

In reply to Glenn Washburn
Quoted 145 lines · Glenn Washburn
Quoted 127 lines · On Mon, 24 Jan 2022 06:12:14 -0800 Hernan Gatta <[email protected]>…

From: Hernan Gatta <[email protected]>

A key protector encapsulates functionality to retrieve an unlocking key for a fully-encrypted disk from a specific source. A key protector module registers itself with the key protectors framework when it is loaded and unregisters when unloaded. Additionally, a key protector may accept parameters that describe how it should operate.

The key protectors framework, besides offering registration and unregistration functions, also offers a one-stop routine for finding and invoking a key protector. This method accepts a formatted string with the name of a key protector followed optionally by colon-separated, key protector-specific parameters. If a key protector with the specified name exists and if an unlocking key is successfully retrieved by the latter, the function returns to the caller the retrieved key and its length.

---
 grub-core/Makefile.am       |  1 +
 grub-core/Makefile.core.def |  1 +
 grub-core/kern/protectors.c | 98 +++++++++++++++++++++++++++++++++++++++++++++
 include/grub/protector.h    | 55 +++++++++++++++++++++++++
 4 files changed, 155 insertions(+)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 include/grub/protector.h
grub-core/Makefile.am +1 -0
index ee88e44..f78cd9d 100644
@@ -90,6 +90,7 @@ endif
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/mm.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/parser.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/partition.h
+KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/protector.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/stack_protector.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/term.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/time.h
grub-core/Makefile.core.def +1 -0
index 8022e1c..e4ae78b 100644
@@ -138,6 +138,7 @@ kernel = {
   common = kern/misc.c;
   common = kern/parser.c;
   common = kern/partition.c;
+  common = kern/protectors.c;
   common = kern/rescue_parser.c;
   common = kern/rescue_reader.c;
   common = kern/term.c;
grub-core/kern/protectors.c new file +71 -0
new file mode 100644
index 0000000..2df0c60
@@ -0,0 +1,98 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/list.h>
+#include <grub/misc.h>
+#include <grub/mm.h>
+#include <grub/protector.h>
+
+struct grub_key_protector *grub_key_protectors = NULL;
+
+grub_err_t
+grub_key_protector_register (struct grub_key_protector *protector)
+{
+  if (!protector || !protector->name || !grub_strlen(protector->name))
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (grub_key_protectors &&
+      grub_named_list_find (GRUB_AS_NAMED_LIST (grub_key_protectors),
+                            protector->name))
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  grub_list_push (GRUB_AS_LIST_P (&grub_key_protectors),
+                  GRUB_AS_LIST (protector));
+
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_key_protector_unregister (struct grub_key_protector *protector)
+{
+  if (!protector)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  grub_list_remove (GRUB_AS_LIST (protector));
+
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_key_protector_recover_key (char *args, grub_uint8_t **key,
+                                grub_size_t *key_size)
+{
+  char *first_separator = NULL;
+  char *protector_args = NULL;
+  struct grub_key_protector *protector = NULL;
+
+  if (!grub_key_protectors)
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  if (!args || !grub_strlen (args))
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  /* Find the position of the first parameter separator: the stuff before it is
+   * the name of the requested key protector and the stuff after it are the
+   * parameters for said key protector, if any. */
+  first_separator = grub_strchr (args, ':');

grub-core/kern/protectors.c line 81

Quoted 10 lines
grub-core/kern/protectors.c new file +10 -0
+  if (first_separator)
+    {
+      /* Reject a separator at the very beginning. */
+      if (first_separator == args)
+        return GRUB_ERR_BAD_ARGUMENT;
+
+      /* Having a lone colon after the name of the key protector with no
+       * further parameters thereafter does not make any sense. */
+      if (*(first_separator + 1) == '\0')
+        return GRUB_ERR_BAD_ARGUMENT;

This should be allowed, its an unnecessary restriction. For instance, it prevents building this string without logic to determine if a colon is needed or not. Instead of this if block, I suggest having...

Quoted 9 lines

grub-core/kern/protectors.c line 85

Quoted 4 lines
grub-core/kern/protectors.c new file +4 -0
+
+      /* Consume the colon, effectively splitting 'args' in two. */
+      first_separator[0] = '\0';
+

... here, an if with the opposite conditional.

if (*(first_separator + 1) != '\0')

I'll modify this as suggested.

Quoted 68 lines
Quoted 68 lines
grub-core/kern/protectors.c new file +13 -0
+      /* The protector-specific arguments are after the first colon. */
+      protector_args = first_separator + 1;
+    }
+
+  /* Try to find a key protector with the specified name. */
+  protector = grub_named_list_find (GRUB_AS_NAMED_LIST (grub_key_protectors),
+                                    args);
+  if (!protector)
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  /* 'protector_args' may be NULL. */
+  return protector->recover_key (protector_args, key, key_size);
+}
include/grub/protector.h new file +49 -0
new file mode 100644
index 0000000..d445a33
@@ -0,0 +1,55 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef GRUB_PROTECTOR_HEADER
+#define GRUB_PROTECTOR_HEADER 1
+
+#include <grub/err.h>
+#include <grub/types.h>
+
+enum grub_key_protector_flags
+  {
+    GRUB_KEY_PROTECTOR_FLAG_NONE = 0,
+    GRUB_KEY_PROTECTOR_FLAG_REPEATABLE = 1 << 0
+  };
+
+struct grub_key_protector
+{
+  struct grub_key_protector *next;
+  struct grub_key_protector **prev;
+
+  const char *name;
+  enum grub_key_protector_flags flags;
+
+  grub_err_t (*recover_key) (char *args, grub_uint8_t **key,
+                             grub_size_t *key_size);
+};
+
+extern struct grub_key_protector *EXPORT_VAR (grub_key_protectors);
+
+grub_err_t
+EXPORT_FUNC (grub_key_protector_register) (struct grub_key_protector *protector);
+
+grub_err_t
+EXPORT_FUNC (grub_key_protector_unregister) (struct grub_key_protector *protector);
Quoted 9 lines

include/grub/protector.h line 55

Quoted 6 lines
include/grub/protector.h new file +6 -0
+
+grub_err_t
+EXPORT_FUNC (grub_key_protector_recover_key) (char args[], grub_uint8_t **key,
+                                              grub_size_t *key_size);
+
+#endif /* ! GRUB_PROTECTOR_HEADER */

Glenn

Thank you,
Hernan

#16 lore raw

Re: [PATCH 5/5] util/grub-protect: Add new tool

In reply to Glenn Washburn
Quoted 19 lines · Glenn Washburn
Quoted 7 lines · On Mon, 24 Jan 2022 06:12:18 -0800 Hernan Gatta <[email protected]>…

From: Hernan Gatta <[email protected]>

To utilize the key protectors framework, there must be a way to protect full-disk encryption keys in the first place. The grub-protect tool includes support for the TPM2 key protector but other protectors that require setup ahead of time can be supported in the future.

Quoted 8 lines

For the TPM2 key protector, the intended flow is for a user to have a LUKS 1 or LUKS 2-protected fully-encrypted disk. The user then creates a new key file, say by reading /dev/urandom into a file, and creates a new LUKS key slot for this key. Then, the user invokes the grub-protect tool to seal this key file to a set of PCRs using the system's TPM 2.0. The resulting sealed key file is stored in an unencrypted partition such as the EFI System Partition (ESP) so that GRUB may read it. The user also ensures the cryptomount command is included in GRUB's boot script and that it carries the requisite --protector (or -p) parameter.

Quoted 2 lines

I think you mean '-k' instead of '-p' here.

True. I wrote this before I saw the changes to cryptomount that added the password parameter and failed to change the commit message.

Quoted 11 lines
Quoted 10 lines

Sample usage:

$ dd if=/dev/urandom of=key count=32
$ sudo cryptsetup luksAddKey /dev/sdb1 key --pbkdf=pbkdf2 --hash=sha512
$ sudo grub-protect --action=add
--protector=tpm2
--tpm2-keyfile=key
--tpm2-outfile=/boot/efi/boot/grub2/sealed_key
Quoted 7 lines

Why not have a syntax that is similar to whats given to cryptomount? (eg. $ sudo grub-protect --action=add --protector=tpm2:keyfile=/boot/efi/boot/grub2/sealed_key ) This would allow you to re-use the parsing code from patch #3. Yes, its less UNIXy, but I think could be more intuitive and cuts down on code size. I'm not completely wedded to this idea either.

I'm thinking that if we go with James' idea of decoupling the protector-specific parameters from the cryptomount command, then we should more easily be able to share argument parsing logic. The duplication is in fact something that I wasn't terribly happy with myself, so I'm happy to address it.

Thoughts?

Quoted 8 lines
Quoted 5 lines

Then, in the boot script (wrapped for display):

cryptomount -u b20f95d0834842bc9197bd78b36732f8
-p tpm2:keyfile=(hd0,gpt1)/boot/grub2/sealed_key

Also, -k here.

Indeed.

Quoted 851 lines
Quoted 851 lines

where the UUID corresponds to /dev/sdb1.

---
 .gitignore          |    1 +
 Makefile.util.def   |   16 +
 configure.ac        |    1 +
 util/grub-protect.c | 1344 +++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 1362 insertions(+)
 create mode 100644 util/grub-protect.c
.gitignore +1 -0
index f6a1bd0..852327d 100644
@@ -167,6 +167,7 @@ widthspec.bin
 /grub-ofpathname.exe
 /grub-probe
 /grub-probe.exe
+/grub-protect
 /grub-reboot
 /grub-render-label
 /grub-render-label.exe
Makefile.util.def +16 -0
index 39b53b3..05f9f09 100644
@@ -52,6 +52,9 @@ library = {
   common = grub-core/partmap/msdos.c;
   common = grub-core/fs/proc.c;
   common = grub-core/fs/archelp.c;
+  common = grub-core/tpm2/buffer.c;
+  common = grub-core/tpm2/mu.c;
+  common = grub-core/tpm2/tpm2.c;
 };
 
 library = {
@@ -207,6 +210,19 @@ program = {
 };
 
 program = {
+  name = grub-protect;
+  common = grub-core/osdep/init.c;
+  common = util/grub-protect.c;
+  common = util/probe.c;
+
+  ldadd = libgrubmods.a;
+  ldadd = libgrubgcry.a;
+  ldadd = libgrubkern.a;
+  ldadd = grub-core/lib/gnulib/libgnu.a;
+  ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
+};
+
+program = {
   name = grub-mkrelpath;
   mansection = 1;
 
configure.ac +1 -0
index 4f649ed..3a4dc5a 100644
@@ -71,6 +71,7 @@ grub_TRANSFORM([grub-mkpasswd-pbkdf2])
 grub_TRANSFORM([grub-mkrelpath])
 grub_TRANSFORM([grub-mkrescue])
 grub_TRANSFORM([grub-probe])
+grub_TRANSFORM([grub-protect])
 grub_TRANSFORM([grub-reboot])
 grub_TRANSFORM([grub-script-check])
 grub_TRANSFORM([grub-set-default])
util/grub-protect.c new file +775 -0
new file mode 100644
index 0000000..4e4bbd7
@@ -0,0 +1,1344 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <config.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <grub/crypto.h>
+#include <grub/emu/getroot.h>
+#include <grub/emu/hostdisk.h>
+#include <grub/emu/misc.h>
+#include <grub/tpm2/buffer.h>
+#include <grub/tpm2/mu.h>
+#include <grub/tpm2/tcg2.h>
+#include <grub/tpm2/tpm2.h>
+#include <grub/util/misc.h>
+
+#include "progname.h"
+
+typedef enum grub_protect_arg
+{
+  GRUB_PROTECT_ARG_ACTION          = 1 << 0,
+  GRUB_PROTECT_ARG_PROTECTOR       = 1 << 1,
+  GRUB_PROTECT_ARG_TPM2_DEVICE     = 1 << 2,
+  GRUB_PROTECT_ARG_TPM2_PCRS       = 1 << 3,
+  GRUB_PROTECT_ARG_TPM2_ASYMMETRIC = 1 << 4,
+  GRUB_PROTECT_ARG_TPM2_BANK       = 1 << 5,
+  GRUB_PROTECT_ARG_TPM2_SRK        = 1 << 6,
+  GRUB_PROTECT_ARG_TPM2_KEYFILE    = 1 << 7,
+  GRUB_PROTECT_ARG_TPM2_OUTFILE    = 1 << 8,
+  GRUB_PROTECT_ARG_TPM2_PERSIST    = 1 << 9,
+  GRUB_PROTECT_ARG_TPM2_EVICT      = 1 << 10
+} grub_protect_arg_t;
+
+typedef enum grub_protect_protector
+{
+  GRUB_PROTECT_TYPE_ERROR,
+  GRUB_PROTECT_TYPE_TPM2
+} grub_protect_protector_t;
+
+typedef enum grub_protect_action
+{
+  GRUB_PROTECT_ACTION_ERROR,
+  GRUB_PROTECT_ACTION_ADD,
+  GRUB_PROTECT_ACTION_REMOVE
+} grub_protect_action_t;
+
+struct grub_protect_args
+{
+  grub_protect_arg_t args;
+  grub_protect_action_t action;
+  grub_protect_protector_t protector;
+
+  const char *tpm2_device;
+  grub_uint8_t tpm2_pcrs[TPM_MAX_PCRS];
+  grub_uint8_t tpm2_pcr_count;
+  TPM_ALG_ID tpm2_asymmetric;
+  TPM_ALG_ID tpm2_bank;
+  TPM_HANDLE tpm2_srk;
+  const char *tpm2_keyfile;
+  const char *tpm2_outfile;
+  int tpm2_persist;
+  int tpm2_evict;
+};
+
+static int tpm2_fd = -1;
+
+static grub_err_t
+grub_protect_read_file (const char *filepath, void **buffer,
+                        size_t *buffer_size)
+{
+  grub_err_t err;
+  FILE *f;
+  long len;
+  void *buf;
+
+  f = fopen (filepath, "rb");
+  if (!f)
+    return GRUB_ERR_FILE_NOT_FOUND;
+
+  if (fseek (f, 0, SEEK_END))
+    {
+       err = GRUB_ERR_FILE_READ_ERROR;
+       goto exit1;
+    }
+
+  len = ftell (f);
+  if (!len)
+    {
+       err = GRUB_ERR_FILE_READ_ERROR;
+       goto exit1;
+    }
+
+  rewind (f);
+
+  buf = grub_malloc (len);
+  if (!buf)
+    {
+       err = GRUB_ERR_OUT_OF_MEMORY;
+       goto exit1;
+    }
+
+  if (fread (buf, len, 1, f) != 1)
+    {
+       err = GRUB_ERR_FILE_READ_ERROR;
+       goto exit2;
+    }
+
+  *buffer = buf;
+  *buffer_size = len;
+
+  buf = NULL;
+  err = GRUB_ERR_NONE;
+
+exit2:
+  grub_free (buf);
+
+exit1:
+  fclose (f);
+
+  return err;
+}
+
+static grub_err_t
+grub_protect_write_file (const char *filepath, void *buffer, size_t buffer_size)
+{
+  grub_err_t err;
+  FILE *f;
+
+  f = fopen (filepath, "wb");
+  if (!f)
+    return GRUB_ERR_FILE_NOT_FOUND;
+
+  if (fwrite (buffer, buffer_size, 1, f) != 1)
+  {
+    err = GRUB_ERR_WRITE_ERROR;
+    goto exit1;
+  }
+
+  err = GRUB_ERR_NONE;
+
+exit1:
+  fclose (f);
+
+  return err;
+}
+
+static grub_err_t
+grub_protect_get_grub_drive_for_file (const char *filepath, char **drive)
+{
+  grub_err_t err = GRUB_ERR_IO;
+  char *disk;
+  char **devices;
+  char *grub_dev;
+  char *grub_path;
+  char *efi_drive;
+  char *partition;
+  char *grub_drive;
+  grub_device_t dev;
+  grub_size_t grub_drive_len;
+  int n;
+
+  grub_path = grub_canonicalize_file_name (filepath);
+  if (!grub_path)
+    goto exit1;
+
+  devices = grub_guess_root_devices (grub_path);
+  if (!devices || !devices[0])
+    goto exit2;
+
+  disk = devices[0];
+
+  grub_util_pull_device (disk);
+
+  grub_dev = grub_util_get_grub_dev (disk);
+  if (!grub_dev)
+    goto exit3;
+
+  dev = grub_device_open (grub_dev);
+  if (!dev)
+    goto exit4;
+
+  efi_drive = grub_util_guess_efi_drive (disk);
+  if (!efi_drive)
+    goto exit5;
+
+  partition = grub_partition_get_name (dev->disk->partition);
+  if (!partition)
+    goto exit6;
+
+  grub_drive_len = grub_strlen (efi_drive) + grub_strlen (partition) + 3;
+  grub_drive = grub_malloc (grub_drive_len + 1);
+  if (!grub_drive)
+    goto exit7;
+
+  n = grub_snprintf (grub_drive, grub_drive_len + 1, "(%s,%s)", efi_drive,
+                     partition);
+  if (n != grub_drive_len)
+    goto exit8;
+
+  *drive = grub_drive;
+  grub_drive = NULL;
+  err = GRUB_ERR_NONE;
+
+exit8:
+  grub_free (grub_drive);
+
+exit7:
+  grub_free (partition);
+
+exit6:
+  grub_free (efi_drive);
+
+exit5:
+  grub_device_close (dev);
+
+exit4:
+  grub_free (grub_dev);
+
+exit3:
+  grub_free (devices);
+
+exit2:
+  grub_free (grub_path);
+
+exit1:
+  return err;
+}
+
+grub_err_t
+grub_tcg2_get_max_output_size (grub_size_t *size)
+{
+  if (!size)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  *size = GRUB_TPM2_BUFFER_CAPACITY;
+
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_tcg2_submit_command (grub_size_t input_size, grub_uint8_t *input,
+                          grub_size_t output_size, grub_uint8_t *output)
+{
+  static const grub_size_t header_size = sizeof (grub_uint16_t) +
+                                         (2 * sizeof(grub_uint32_t));
+
+  if (write (tpm2_fd, input, input_size) != input_size)
+    return GRUB_ERR_BAD_DEVICE;
+
+  if (read (tpm2_fd, output, output_size) < header_size)
+    return GRUB_ERR_BAD_DEVICE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_open_device (const char *dev_node)
+{
+  if (tpm2_fd != -1)
+    return GRUB_ERR_NONE;
+
+  tpm2_fd = open (dev_node, O_RDWR);
+  if (tpm2_fd == -1)
+    {
+      fprintf (stderr, _("Could not open TPM device (Error: %u).\n"), errno);
+      return GRUB_ERR_FILE_NOT_FOUND;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_close_device (void)
+{
+  int err;
+
+  if (tpm2_fd == -1)
+    return GRUB_ERR_NONE;
+
+  err = close (tpm2_fd);
+  if (err)
+  {
+    fprintf (stderr, _("Could not close TPM device (Error: %u).\n"), errno);
+    return GRUB_ERR_IO;
+  }
+
+  tpm2_fd = -1;
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_get_policy_digest (struct grub_protect_args *args,
+                                     TPM2B_DIGEST *digest)
+{
+  TPM_RC rc;
+  TPML_PCR_SELECTION pcr_sel = {
+    .count = 1,
+    .pcrSelections = {
+      {
+        .hash = args->tpm2_bank,
+        .sizeOfSelect = 3,
+        .pcrSelect = { 0 }
+      },
+    }
+  };
+  TPML_PCR_SELECTION pcr_sel_out = { 0 };
+  TPML_DIGEST pcr_values = { 0 };
+  grub_uint8_t *pcr_digest;
+  grub_size_t pcr_digest_len;
+  grub_uint8_t *pcr_concat;
+  grub_size_t pcr_concat_len;
+  grub_uint8_t *pcr_cursor;
+  const gcry_md_spec_t *hash_spec;
+  TPM2B_NONCE nonce = { 0 };
+  TPM2B_ENCRYPTED_SECRET salt = { 0 };
+  TPMT_SYM_DEF symmetric = { 0 };
+  TPMI_SH_AUTH_SESSION session = 0;
+  TPM2B_DIGEST pcr_digest_in = {
+    .size = TPM_SHA256_DIGEST_SIZE,
+    .buffer = { 0 }
+  };
+  TPM2B_DIGEST policy_digest = { 0 };
+  grub_uint8_t i;
+  grub_err_t err;
+
+  /* PCR Read */
+  for (i = 0; i < args->tpm2_pcr_count; i++)
+    pcr_sel
+      .pcrSelections[0]
+      .pcrSelect[TPM2_PCR_TO_SELECT(args->tpm2_pcrs[i])]
+        |= TPM2_PCR_TO_BIT(args->tpm2_pcrs[i]);
+
+  rc = TPM2_PCR_Read (NULL, &pcr_sel, NULL, &pcr_sel_out, &pcr_values, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("Failed to read PCRs (TPM error: 0x%x).\n"), rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  if ((pcr_sel_out.count != pcr_sel.count) ||
+       (pcr_sel.pcrSelections[0].sizeOfSelect !=
+        pcr_sel_out.pcrSelections[0].sizeOfSelect))
+    {
+      fprintf (stderr, _("Could not read all the specified PCRs.\n"));
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Compute PCR Digest */
+  switch (args->tpm2_bank)
+    {
+    case TPM_ALG_SHA1:
+      pcr_digest_len = TPM_SHA1_DIGEST_SIZE;
+      hash_spec = GRUB_MD_SHA1;
+      break;
+    case TPM_ALG_SHA256:
+      pcr_digest_len = TPM_SHA256_DIGEST_SIZE;
+      hash_spec = GRUB_MD_SHA256;
+      break;
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  pcr_digest = grub_malloc (pcr_digest_len);
+  if (!pcr_digest)
+    {
+      fprintf (stderr, _("Failed to allocate PCR digest buffer.\n"));
+      return GRUB_ERR_OUT_OF_MEMORY;
+    }
+
+  pcr_concat_len = pcr_digest_len * args->tpm2_pcr_count;
+  pcr_concat = grub_malloc (pcr_concat_len);
+  if (!pcr_concat)
+    {
+      err = GRUB_ERR_OUT_OF_MEMORY;
+      fprintf (stderr, _("Failed to allocate PCR concatenation buffer.\n"));
+      goto exit1;
+    }
+
+  pcr_cursor = pcr_concat;
+  for (i = 0; i < args->tpm2_pcr_count; i++)
+    {
+      if (pcr_values.digests[i].size != pcr_digest_len)
+        {
+          fprintf (stderr,
+                   _("Bad PCR value size: expected %lu bytes but got %u bytes.\n"),
+                   pcr_digest_len, pcr_values.digests[i].size);
+          goto exit2;
+        }
+
+      grub_memcpy (pcr_cursor, pcr_values.digests[i].buffer, pcr_digest_len);
+      pcr_cursor += pcr_digest_len;
+    }
+
+  grub_crypto_hash (hash_spec, pcr_digest, pcr_concat, pcr_concat_len);
+
+  /* Start Trial Session */
+  nonce.size = TPM_SHA256_DIGEST_SIZE;
+  symmetric.algorithm = TPM_ALG_NULL;
+
+  rc = TPM2_StartAuthSession (TPM_RH_NULL, TPM_RH_NULL, 0, &nonce, &salt,
+                              TPM_SE_TRIAL, &symmetric, TPM_ALG_SHA256,
+                              &session, NULL, 0);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr,
+               _("Failed to start trial policy session (TPM error: 0x%x).\n"),
+               rc);
+      err = GRUB_ERR_BAD_DEVICE;
+      goto exit2;
+    }
+
+  /* PCR Policy */
+  memcpy (pcr_digest_in.buffer, pcr_digest, TPM_SHA256_DIGEST_SIZE);
+
+  rc = TPM2_PolicyPCR (session, NULL, &pcr_digest_in, &pcr_sel, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("Failed to submit PCR policy (TPM error: 0x%x).\n"),
+               rc);
+      err = GRUB_ERR_BAD_DEVICE;
+      goto exit3;
+    }
+
+  /* Retrieve Policy Digest */
+  rc = TPM2_PolicyGetDigest (session, NULL, &policy_digest, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("Failed to get policy digest (TPM error: 0x%x).\n"),
+               rc);
+      err = GRUB_ERR_BAD_DEVICE;
+      goto exit3;
+    }
+
+  /* Epilogue */
+  *digest = policy_digest;
+  err = GRUB_ERR_NONE;
+
+exit3:
+  TPM2_FlushContext (session);
+
+exit2:
+  grub_free (pcr_concat);
+
+exit1:
+  grub_free (pcr_digest);
+
+  return err;
+}
+
+static grub_err_t
+grub_protect_tpm2_get_srk (struct grub_protect_args *args, TPM_HANDLE *srk)
+{
+  TPM_RC rc;
+  TPM2B_PUBLIC public;
+  TPMS_AUTH_COMMAND authCommand = { 0 };
+  TPM2B_SENSITIVE_CREATE inSensitive = { 0 };
+  TPM2B_PUBLIC inPublic = { 0 };
+  TPM2B_DATA outsideInfo = { 0 };
+  TPML_PCR_SELECTION creationPcr = { 0 };
+  TPM2B_PUBLIC outPublic = { 0 };
+  TPM2B_CREATION_DATA creationData = { 0 };
+  TPM2B_DIGEST creationHash = { 0 };
+  TPMT_TK_CREATION creationTicket = { 0 };
+  TPM2B_NAME srkName = { 0 };
+  TPM_HANDLE srkHandle;
+
+  /* Find SRK */
+  rc = TPM2_ReadPublic (args->tpm2_srk, NULL, &public);
+  if (rc == TPM_RC_SUCCESS)
+    {
+      if (args->tpm2_persist)
+        fprintf (stderr,
+                 _("Warning: --tpm2-persist was specified but the SRK already exists on the TPM. Continuing anyway...\n"));
+
+      *srk = TPM2_SRK_HANDLE;
+      return GRUB_ERR_NONE;
+    }
+
+  /* The handle exists but its public area could not be read. */
+  if ((rc & ~TPM_RC_N_MASK) != TPM_RC_HANDLE)
+    {
+      fprintf (stderr,
+               _("The SRK exists on the TPM but its public area cannot be read (TPM error: 0x%x).\n"),
+               rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Create SRK */
+  authCommand.sessionHandle = TPM_RS_PW;
+  inPublic.publicArea.type = args->tpm2_asymmetric;
+  inPublic.publicArea.nameAlg  = TPM_ALG_SHA256;
+  inPublic.publicArea.objectAttributes.restricted = 1;
+  inPublic.publicArea.objectAttributes.userWithAuth = 1;
+  inPublic.publicArea.objectAttributes.decrypt = 1;
+  inPublic.publicArea.objectAttributes.fixedTPM = 1;
+  inPublic.publicArea.objectAttributes.fixedParent = 1;
+  inPublic.publicArea.objectAttributes.sensitiveDataOrigin = 1;
+  inPublic.publicArea.objectAttributes.noDA = 1;
+
+  switch (args->tpm2_asymmetric)
+    {
+    case TPM_ALG_RSA:
+      inPublic.publicArea.parameters.rsaDetail.symmetric.algorithm = TPM_ALG_AES;
+      inPublic.publicArea.parameters.rsaDetail.symmetric.keyBits.aes = 128;
+      inPublic.publicArea.parameters.rsaDetail.symmetric.mode.aes = TPM_ALG_CFB;
+      inPublic.publicArea.parameters.rsaDetail.scheme.scheme = TPM_ALG_NULL;
+      inPublic.publicArea.parameters.rsaDetail.keyBits = 2048;
+      inPublic.publicArea.parameters.rsaDetail.exponent = 0;
+      break;
+
+    case TPM_ALG_ECC:
+      inPublic.publicArea.parameters.eccDetail.symmetric.algorithm = TPM_ALG_AES;
+      inPublic.publicArea.parameters.eccDetail.symmetric.keyBits.aes = 128;
+      inPublic.publicArea.parameters.eccDetail.symmetric.mode.aes = TPM_ALG_CFB;
+      inPublic.publicArea.parameters.eccDetail.scheme.scheme = TPM_ALG_NULL;
+      inPublic.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256;
+      inPublic.publicArea.parameters.eccDetail.kdf.scheme = TPM_ALG_NULL;
+      break;
+
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  rc = TPM2_CreatePrimary (TPM_RH_OWNER, &authCommand, &inSensitive, &inPublic,
+                           &outsideInfo, &creationPcr, &srkHandle, &outPublic,
+                           &creationData, &creationHash, &creationTicket,
+                           &srkName, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("Failed to create SRK (TPM error: 0x%x).\n"), rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Persist SRK */
+  if (args->tpm2_persist)
+    {
+      rc = TPM2_EvictControl (TPM_RH_OWNER, srkHandle, args->tpm2_srk,
+                              &authCommand, NULL);
+      if (rc == TPM_RC_SUCCESS)
+        {
+          TPM2_FlushContext (srkHandle);
+          srkHandle = args->tpm2_srk;
+        }
+      else
+        fprintf (stderr,
+                 _("Warning: Failed to persist SRK (TPM error: 0x%x\n). Continuing anyway...\n"),
+                 rc);
+    }
+
+  /* Epilogue */
+  *srk = srkHandle;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_seal (TPM2B_DIGEST *policyDigest, TPM_HANDLE srk,
+                        grub_uint8_t *clearText, grub_size_t clearTextLength,
+                        TPM2_SEALED_KEY *sealed_key)
+{
+  TPM_RC rc;
+  TPMS_AUTH_COMMAND authCommand = { 0 };
+  TPM2B_SENSITIVE_CREATE inSensitive = { 0 };
+  TPM2B_PUBLIC inPublic  = { 0 };
+  TPM2B_DATA outsideInfo = { 0 };
+  TPML_PCR_SELECTION pcr_sel = { 0 };
+  TPM2B_PRIVATE outPrivate = { 0 };
+  TPM2B_PUBLIC outPublic = { 0 };
+
+  /* Seal Data */
+  authCommand.sessionHandle = TPM_RS_PW;
+
+  inSensitive.sensitive.data.size = clearTextLength;
+  memcpy(inSensitive.sensitive.data.buffer, clearText, clearTextLength);
+
+  inPublic.publicArea.type = TPM_ALG_KEYEDHASH;
+  inPublic.publicArea.nameAlg = TPM_ALG_SHA256;
+  inPublic.publicArea.parameters.keyedHashDetail.scheme.scheme = TPM_ALG_NULL;
+  inPublic.publicArea.authPolicy = *policyDigest;
+
+  rc = TPM2_Create (srk, &authCommand, &inSensitive, &inPublic, &outsideInfo,
+                    &pcr_sel, &outPrivate, &outPublic, NULL, NULL, NULL, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("Failed to seal key (TPM error: 0x%x).\n"), rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Epilogue */
+  sealed_key->public = outPublic;
+  sealed_key->private = outPrivate;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_export_sealed_key (const char *filepath,
+                                     TPM2_SEALED_KEY *sealed_key)
+{
+  grub_err_t err;
+  struct grub_tpm2_buffer buf;
+
+  grub_tpm2_buffer_init (&buf);
+  grub_tpm2_mu_TPM2B_PUBLIC_Marshal (&buf, &sealed_key->public);
+  grub_tpm2_mu_TPM2B_Marshal (&buf, sealed_key->private.size,
+                              sealed_key->private.buffer);
+  if (buf.error)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  err = grub_protect_write_file (filepath, buf.data, buf.size);
+  if (err)
+    fprintf (stderr, _("Could not write sealed key file (Error: %u).\n"),
+             errno);
+
+  return err;
+}
+
+static grub_err_t
+grub_protect_tpm2_add (struct grub_protect_args *args)
+{
+  grub_err_t err;
+  grub_uint8_t *key;
+  grub_size_t key_size;
+  TPM_HANDLE srk;
+  TPM2B_DIGEST policy_digest;
+  TPM2_SEALED_KEY sealed_key;
+  char *grub_drive = NULL;
+
+  grub_protect_get_grub_drive_for_file (args->tpm2_outfile, &grub_drive);
+
+  err = grub_protect_tpm2_open_device (args->tpm2_device);
+  if (err)
+    return err;
+
+  err = grub_protect_read_file (args->tpm2_keyfile, (void **)&key, &key_size);
+  if (err)
+    goto exit1;
+
+  if (key_size > TPM_MAX_SYM_DATA)
+  {
+    fprintf (stderr,
+             _("Input key is too long, maximum allowed size is %u bytes.\n"),
+             TPM_MAX_SYM_DATA);
+    return GRUB_ERR_OUT_OF_RANGE;
+  }
+
+  err = grub_protect_tpm2_get_srk (args, &srk);
+  if (err)
+    goto exit2;
+
+  err = grub_protect_tpm2_get_policy_digest (args, &policy_digest);
+  if (err)
+    goto exit3;
+
+  err = grub_protect_tpm2_seal (&policy_digest, srk, key, key_size,
+                                &sealed_key);
+  if (err)
+    goto exit3;
+
+  err = grub_protect_tpm2_export_sealed_key (args->tpm2_outfile, &sealed_key);
+  if (err)
+    goto exit3;
+
+  if (grub_drive)
+    {
+      printf (_("GRUB drive for the sealed key file: %s\n"), grub_drive);
+      grub_free (grub_drive);
+    }
+  else
+    {
+      fprintf (stderr,
+               _("Warning: Could not determine GRUB drive for sealed key file.\n"));
+      err = GRUB_ERR_NONE;
+    }
+
+exit3:
+  TPM2_FlushContext (srk);
+
+exit2:
+  grub_free (key);
+
+exit1:
+  grub_protect_tpm2_close_device ();
+
+  return err;
+}
+
+static grub_err_t
+grub_protect_tpm2_remove (struct grub_protect_args *args)
+{
+  TPM_RC rc;
+  TPM2B_PUBLIC public;
+  TPMS_AUTH_COMMAND authCommand = { 0 };
+  grub_err_t err;
+
+  if (!args->tpm2_evict)
+    {
+      printf (_("--tpm2-evict not specified, nothing to do.\n"));
+      return GRUB_ERR_NONE;
+    }
+
+  err = grub_protect_tpm2_open_device (args->tpm2_device);
+  if (err)
+    return err;
+
+  /* Find SRK */
+  rc = TPM2_ReadPublic (args->tpm2_srk, NULL, &public);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, _("SRK with handle 0x%x not found.\n"), args->tpm2_srk);
+      err = GRUB_ERR_BAD_ARGUMENT;
+      goto exit1;
+    }
+
+  /* Evict SRK */
+  authCommand.sessionHandle = TPM_RS_PW;
+
+  rc = TPM2_EvictControl (TPM_RH_OWNER, args->tpm2_srk, args->tpm2_srk,
+                          &authCommand, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr,
+               _("Failed to evict SRK with handle 0x%x (TPM Error: 0x%x).\n"),
+               args->tpm2_srk, rc);
+      err = GRUB_ERR_BAD_DEVICE;
+      goto exit2;
+    }
+
+  err = GRUB_ERR_NONE;
+
+exit2:
+  TPM2_FlushContext (args->tpm2_srk);
+
+exit1:
+  grub_protect_tpm2_close_device ();
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_tpm2_run (struct grub_protect_args *args)
+{
+  switch (args->action)
+    {
+    case GRUB_PROTECT_ACTION_ADD:
+      return grub_protect_tpm2_add (args);
+
+    case GRUB_PROTECT_ACTION_REMOVE:
+      return grub_protect_tpm2_remove (args);
+
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+}
+
Quoted 9 lines

util/grub-protect.c line 778

Quoted 3 lines
util/grub-protect.c new file +3 -0
+static grub_err_t
+grub_protect_tpm2_args_verify (struct grub_protect_args *args)
+{

I'm wondering if it wouldn't be a good idea to merge this function with grub_tpm2_protector_check_args from patch #3. This is probably only manageable if the protector argument looks like the one from grub as well, so they can share error messages.

Same comment as above.

Quoted 27 lines
Quoted 14 lines
util/grub-protect.c new file +14 -0
+  switch (args->action)
+    {
+    case GRUB_PROTECT_ACTION_ADD:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_EVICT)
+        {
+          fprintf (stderr,
+                   _("--tpm2-evict is invalid when --action is 'add'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (!args->tpm2_keyfile)
+        {
+          fprintf (stderr, _("--tpm2-keyfile must be specified.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;

util/grub-protect.c line 802

Quoted 10 lines
util/grub-protect.c new file +10 -0
+        }
+
+      if (!args->tpm2_outfile)
+        {
+          fprintf (stderr, _("--tpm2-outfile must be specified.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (!args->tpm2_device)
+        args->tpm2_device = "/dev/tpm0";

Seems like this...

Quoted 13 lines

util/grub-protect.c line 811

Quoted 9 lines
util/grub-protect.c new file +9 -0
+
+      if (!args->tpm2_pcr_count)
+        {
+          args->tpm2_pcrs[0] = 7;
+          args->tpm2_pcr_count = 1;
+        }
+
+      if (!args->tpm2_srk)
+        args->tpm2_srk = TPM2_SRK_HANDLE;

and maybe this, can be done outside the switch since they are common to both cases.

The reason why I wrote this in this way is because carrying out these actions is only valid when args->action is valid. In other words, if I take these statements out of the switch, they'll be executed regardless of the value of args->action. Technically, args->action is always correct by the time we reach this function since the argument parser would have rejected invalid values, but I still wrote the switch like this to express intent (i.e., there are only two valid actions), and outside of that, the program will not do anything, including setting these defaults.

What do you think?

Quoted 152 lines
Quoted 152 lines
util/grub-protect.c new file +152 -0
+
+      if (!args->tpm2_asymmetric)
+        args->tpm2_asymmetric = TPM_ALG_RSA;
+
+      if (!args->tpm2_bank)
+        args->tpm2_bank = TPM_ALG_SHA256;
+
+      break;
+
+    case GRUB_PROTECT_ACTION_REMOVE:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_ASYMMETRIC)
+        {
+          fprintf (stderr,
+                   _("--tpm2-asymmetric is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (args->args & GRUB_PROTECT_ARG_TPM2_BANK)
+        {
+          fprintf (stderr,
+                   _("--tpm2-bank is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (args->args & GRUB_PROTECT_ARG_TPM2_KEYFILE)
+        {
+          fprintf (stderr,
+                   _("--tpm2-keyfile is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (args->args & GRUB_PROTECT_ARG_TPM2_OUTFILE)
+        {
+          fprintf (stderr,
+                   _("--tpm2-outfile is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (args->args & GRUB_PROTECT_ARG_TPM2_PCRS)
+        {
+          fprintf (stderr,
+                   _("--tpm2-pcrs is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (args->args & GRUB_PROTECT_ARG_TPM2_PERSIST)
+        {
+          fprintf (stderr,
+                   _("--tpm2-persist is invalid when --action is 'remove'.\n"));
+          return GRUB_ERR_BAD_ARGUMENT;
+        }
+
+      if (!args->tpm2_device)
+        args->tpm2_device = "/dev/tpm0";
+
+      if (!args->tpm2_srk)
+        args->tpm2_srk = TPM2_SRK_HANDLE;
+
+      break;
+
+    default:
+      fprintf (stderr,
+               _("The TPM2 key protector only supports the following actions: add, remove.\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protector_args_kvp_parse (char *kvp, const char **key, char **value)
+{
+  char divider;
+  char *separator;
+  grub_size_t len;
+
+  if (!kvp)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  len = grub_strlen (kvp);
+  if (!len || len < 2)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (kvp[0] == '-' && kvp[1] != '-')
+    divider = ' ';
+  else if (kvp[0] == '-' && kvp[1] == '-')
+    divider = '=';
+  else
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  separator = grub_strchr (kvp, divider);
+  if (!separator)
+    goto exit;
+
+  *separator = '\0';
+  separator += 1;
+
+  if (separator - kvp >= len)
+  {
+    separator = NULL;
+    goto exit;
+  }
+
+exit:
+  *key = kvp;
+  *value = separator;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_args_parse (int argc, char *argv[],
+                         struct grub_protect_args *args)
+{
+  grub_err_t err;
+  char *current_arg;
+  const char *key;
+  char *value;
+  int i;
+
+  for (i = 1; i < argc; i++)
+    {
+      current_arg = argv[i];
+
+      err = grub_protector_args_kvp_parse (current_arg, &key, &value);
+      if (err)
+        return err;
+
+      if (grub_strcmp (key, "--action") == 0 ||
+          grub_strcmp (key, "-a") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_ACTION)
+            {
+              fprintf (stderr,
+                       _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (grub_strcmp (value, "add") == 0)
+            args->action = GRUB_PROTECT_ACTION_ADD;
+          else if (grub_strcmp (value, "remove") == 0)
+            args->action = GRUB_PROTECT_ACTION_REMOVE;
+          else
+            {
+              fprintf (stderr, _("'%s' is not a valid action.\n"), value);
+              return GRUB_ERR_BAD_ARGUMENT;
Quoted 9 lines

util/grub-protect.c line 969

Quoted 6 lines
util/grub-protect.c new file +6 -0
+            }
+
+          args->args |= GRUB_PROTECT_ARG_ACTION;
+        }
+      else if (grub_strcmp (key, "--protector") == 0 ||
+               grub_strcmp (key, "-p") == 0)

This might be confusing because its -p here but -k to cryptomount.

True. Another side-effect of me writing these patches before the password argument was added to cryptomount. Will fix.

Quoted 370 lines
Quoted 370 lines
util/grub-protect.c new file +370 -0
+        {
+          if (args->args & GRUB_PROTECT_ARG_PROTECTOR)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (grub_strcmp (value, "tpm2") == 0)
+            args->protector = GRUB_PROTECT_TYPE_TPM2;
+          else
+            {
+              fprintf (stderr, _("'%s' is not a valid protector.\n"), value);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->args |= GRUB_PROTECT_ARG_PROTECTOR;
+        }
+      else if (grub_strcmp (key, "--tpm2-device") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_DEVICE)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->tpm2_device = value;
+          args->args |= GRUB_PROTECT_ARG_TPM2_DEVICE;
+        }
+      else if (grub_strcmp (key, "--tpm2-pcrs") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_PCRS)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          grub_size_t len = grub_strlen (value);
+          grub_size_t dist;
+
+          long pcr;
+          char *next_pcr;
+          char *current_pcr = value;
+          grub_uint8_t pcr_u8;
+          grub_uint8_t j;
+          grub_uint8_t k;
+
+          for (j = 0;; j++)
+            {
+              next_pcr = grub_strchr (current_pcr, ',');
+              if (next_pcr)
+                *next_pcr = '\0';
+
+              grub_errno = GRUB_ERR_NONE;
+              pcr = grub_strtoul (current_pcr, NULL, 0);
+              if (grub_errno != GRUB_ERR_NONE)
+                {
+                  fprintf (stderr, _("'%s' is not a valid PCR number.\n"),
+                           current_pcr);
+                  return grub_errno;
+                }
+
+              if (pcr > TPM_MAX_PCRS)
+                {
+                  fprintf (stderr,
+                           _("%lu larger than the maximum number of PCRs.\n"),
+                           pcr);
+                  return GRUB_ERR_OUT_OF_RANGE;
+                }
+
+              pcr_u8 = (grub_uint8_t)pcr;
+
+              for (k = 0; k < args->tpm2_pcr_count; k++)
+              {
+                if (args->tpm2_pcrs[k] == pcr_u8)
+                  {
+                    fprintf (stderr, _("PCR %u was already specified.\n"),
+                             pcr_u8);
+                    return GRUB_ERR_BAD_ARGUMENT;
+                  }
+              }
+
+              args->tpm2_pcrs[j] = pcr_u8;
+              args->tpm2_pcr_count++;
+
+              if (!next_pcr)
+                break;
+
+              current_pcr = next_pcr + 1;
+
+              dist = (current_pcr - value);
+              if (dist >= len)
+                break;
+            }
+
+          args->args |= GRUB_PROTECT_ARG_TPM2_PCRS;
+        }
+      else if (grub_strcmp (key, "--tpm2-srk") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_SRK)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          long srk;
+
+          grub_errno = GRUB_ERR_NONE;
+          srk = grub_strtoul (value, NULL, 0);
+          if (grub_errno != GRUB_ERR_NONE)
+            {
+              fprintf (stderr, _("'%s' is not a valid SRK handle.\n"), value);
+              return grub_errno;
+            }
+
+          if (srk > GRUB_UINT_MAX)
+            {
+              fprintf (stderr,
+                       _("%lu is too large to be a valid SRK handle.\n"), srk);
+              return GRUB_ERR_OUT_OF_RANGE;
+            }
+
+          args->tpm2_srk = (TPM_HANDLE)srk;
+          args->args |= GRUB_PROTECT_ARG_TPM2_SRK;
+        }
+      else if (grub_strcmp (key, "--tpm2-asymmetric") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_ASYMMETRIC)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (grub_strcasecmp (value, "ECC") == 0)
+            args->tpm2_asymmetric = TPM_ALG_ECC;
+          else if (grub_strcasecmp (value, "RSA") == 0)
+            args->tpm2_asymmetric = TPM_ALG_RSA;
+          else
+            {
+              fprintf (stderr, _("'%s' is not a valid asymmetric algorithm.\n"),
+                       value);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->args |= GRUB_PROTECT_ARG_TPM2_ASYMMETRIC;
+        }
+      else if (grub_strcmp (key, "--tpm2-bank") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_BANK)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (grub_strcasecmp (value, "SHA1") == 0)
+            args->tpm2_bank = TPM_ALG_SHA1;
+          else if (grub_strcasecmp (value, "SHA256") == 0)
+            args->tpm2_bank = TPM_ALG_SHA256;
+          else
+            {
+              fprintf (stderr, _("'%s' is not a valid PCR bank.\n"), value);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->args |= GRUB_PROTECT_ARG_TPM2_BANK;
+        }
+      else if (grub_strcmp (key, "--tpm2-keyfile") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_KEYFILE)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+	  args->tpm2_keyfile = value;
+          args->args |= GRUB_PROTECT_ARG_TPM2_KEYFILE;
+        }
+      else if (grub_strcmp (key, "--tpm2-outfile") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_OUTFILE)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (!value)
+            {
+              fprintf (stderr, _("Argument %s requires a value.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->tpm2_outfile = value;
+          args->args |= GRUB_PROTECT_ARG_TPM2_OUTFILE;
+        }
+      else if (grub_strcmp (key, "--tpm2-persist") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_PERSIST)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (value)
+            {
+              fprintf (stderr, _("Argument %s does not accept a value.\n"),
+                       key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->tpm2_persist = 1;
+          args->args |= GRUB_PROTECT_ARG_TPM2_PERSIST;
+        }
+      else if (grub_strcmp (key, "--tpm2-evict") == 0)
+        {
+          if (args->args & GRUB_PROTECT_ARG_TPM2_EVICT)
+            {
+              fprintf (stderr, _("Argument %s was already specified.\n"), key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          if (value)
+            {
+              fprintf (stderr, _("Argument %s does not accept a value.\n"),
+                       key);
+              return GRUB_ERR_BAD_ARGUMENT;
+            }
+
+          args->tpm2_evict = 1;
+          args->args |= GRUB_PROTECT_ARG_TPM2_EVICT;
+        }
+        else
+          {
+            fprintf (stderr, _("'%s' is not a valid argument.\n"), key);
+            return GRUB_ERR_BAD_ARGUMENT;
+          }
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_args_verify (struct grub_protect_args *args)
+{
+  if (args->action == GRUB_PROTECT_ACTION_ERROR)
+    {
+      fprintf (stderr, "--action is mandatory.\n");
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  /* At the moment, the only configurable key protector is the TPM2 one, so it
+   * is the only keu protector supported by this tool. */
+  if (args->protector != GRUB_PROTECT_TYPE_TPM2)
+    {
+      fprintf (stderr,
+               _("--protector is mandatory and only 'tpm2' is currently supported.\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  switch (args->protector)
+    {
+    case GRUB_PROTECT_TYPE_TPM2:
+      return grub_protect_tpm2_args_verify (args);
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_protect_dispatch (struct grub_protect_args *args)
+{
+  switch (args->protector)
+    {
+    case GRUB_PROTECT_TYPE_TPM2:
+      return grub_protect_tpm2_run (args);
+    default:
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+}
+
+static void
+grub_protect_init (int *argc, char **argv[])
+{
+  grub_util_host_init (argc, argv);
+
+  grub_util_biosdisk_init (NULL);
+
+  grub_init_all ();
+  grub_gcry_init_all ();
+
+  grub_lvm_fini ();
+  grub_mdraid09_fini ();
+  grub_mdraid1x_fini ();
+  grub_diskfilter_fini ();
+  grub_diskfilter_init ();
+  grub_mdraid09_init ();
+  grub_mdraid1x_init ();
+  grub_lvm_init ();
+}
+
+static void
+grub_protect_fini (void)
+{
+  grub_gcry_fini_all ();
+  grub_fini_all ();
+  grub_util_biosdisk_fini ();
+}
+
+int
+main (int argc, char *argv[])
+{
+  grub_err_t err;
+  struct grub_protect_args args = { 0 };
+
+  grub_protect_init (&argc, &argv);
+
+  err = grub_protect_args_parse (argc, argv, &args);
+  if (err)
+    goto exit;
+
+  err = grub_protect_args_verify (&args);
+  if (err)
+    goto exit;
+
+  err = grub_protect_dispatch (&args);
+  if (err)
+    goto exit;
+
Quoted 9 lines

util/grub-protect.c line 1344

Quoted 5 lines
util/grub-protect.c new file +5 -0
+exit:
+  grub_protect_fini ();
+
+  return err;
+}

It would be nice to take arguments --help and -h and spit out something useful.

I should have added this already. Will do.

Quoted 2 lines

Glenn

Thank you,
Hernan

#12 lore raw

Re: [PATCH 4/5] cryptodisk: Support key protectors

In reply to James Bottomley
Quoted 29 lines · James Bottomley
Quoted 2 lines · Glenn Washburn

On Mon, 24 Jan 2022 06:12:17 -0800
Hernan Gatta <[email protected]> wrote:

[...]

Quoted 10 lines
Quoted 10 lines
grub-core/disk/cryptodisk.c +2 -0
+    }
+
   if (state[0].set) /* uuid */
     {
       int found_uuid;
@@ -1385,7 +1404,7 @@ GRUB_MOD_INIT (cryptodisk)
 {
   grub_disk_dev_register (&grub_cryptodisk_dev);
   cmd = grub_register_extcmd ("cryptomount", grub_cmd_cryptomount,
 0,
Quoted 8 lines

Review GRUB_MOD_INIT (cryptodisk) · line 1410

Quoted 4 lines
(quoted diff) +1 -1
-			      N_("[-p password] <SOURCE|-u UUID|-a|-
 b>"),
+			      N_("[-p password] [-k protector[:args]]
 <SOURCE|-u UUID|-a|-b>"),

This looks eerily similiar to what I proposed to James in response to his SEV patches[1]. As such, I am in favor of this syntax and it looks to me like a framework that James can use for his SEV series.

Well, I could, but I've got to say for a shell like system, which grub is, argument lists passed as a single argument always cause problems with quoting and interpolation. if the protector needs additional arguments to initialize, then it should really be done as a separate module to avoid the arguments within argument problem, so

Quoted 6 lines

protector_init [args]
crtptomount -k protector ...

means that [args] can use the standard arguments and doesn't have any internal quoting issues.

I agree that having nested argument lists can cause trouble, particularly for any future key protectors where escaping may be required.

As Glenn mentioned in his E-mail regarding the question of whether we should assume fallback on a passphrase, would you be in favor of a system where we do, say:

tpm2_protector_init [args]
sev_protector_init [args]

cryptomount -k sev,tpm2,passphrase

And then have cryptomount go through the list, falling back if protectors error out? (I'm not suggesting that the TPM2 and SEV protectors would be used simultaneously, I'm only using them as examples). Readily existing uses of cryptomount without -k would assume a passphrase protector by default where the user would be prompted in the usual way.

Another option would be to remove the -k parameter altogether and assume the order of execution on the basis of the initialization order of the protectors::

A_protector_init [args]
B_protector_init [args]
cryptomount // Would try A then B

protectors_clear

B_protector_init [args]
cryptomount // Would try B only

I like the first option best since it requires no global state.

Thoughts? Do you think that having the -k parameter as it is now would prevent you from using this patch series as it is for your purposes?

Quoted 3 lines

James

Thank you,
Hernan

#13 lore raw

Re: [PATCH 4/5] cryptodisk: Support key protectors

In reply to Glenn Washburn
Quoted 11 lines · Glenn Washburn
Quoted 7 lines · On Mon, 24 Jan 2022 06:12:17 -0800 Hernan Gatta <[email protected]>…

From: Hernan Gatta <[email protected]>

Add a new parameter to cryptomount to support the key protectors framework: -k. This parameter is accepted whenever the cryptomount command is used to mount a specific disk either via a disk specification (e.g., (hd0,gpt1)) or by UUID, but not when disks are mounted in bulk (i.e., via -a or -b). The parameter is used to automatically retrieve a key from the specified key protector.

Quoted 6 lines

Why shouldn't key protectors be used to try to unlock all devices that a backend identified as being able to unlock? Specifically, can a key stored via the TPM be used for multiple devices? With respect to a future unencrypted keyfile protector, it is certainly the case that it can be applied to multiple devices.

I was wondering about this myself and was hoping to hear feedback on it. I'll remove the limitation as suggested.

Quoted 63 lines
Quoted 32 lines
Signed-off-by <Hernan Gatta [email protected]>
---
 Makefile.util.def           |  1 +
 grub-core/disk/cryptodisk.c | 21 ++++++++++++++++++++-
 2 files changed, 21 insertions(+), 1 deletion(-)
Makefile.util.def +1 -0
index f8b356c..39b53b3 100644
@@ -35,6 +35,7 @@ library = {
   common = grub-core/kern/list.c;
   common = grub-core/kern/misc.c;
   common = grub-core/kern/partition.c;
+  common = grub-core/kern/protectors.c;
   common = grub-core/lib/crypto.c;
   common = grub-core/lib/json/json.c;
   common = grub-core/disk/luks.c;
grub-core/disk/cryptodisk.c +1 -0
index 4970973..176dd56 100644
@@ -26,6 +26,7 @@
 #include <grub/file.h>
 #include <grub/procfs.h>
 #include <grub/partition.h>
+#include <grub/protector.h>
 
 #ifdef GRUB_UTIL
 #include <grub/emu/hostdisk.h>

grub-core/disk/cryptodisk.c static const struct grub_arg_option options[] = · line 46

Quoted 4 lines
grub-core/disk/cryptodisk.c +1 -0
@@ -42,6 +43,7 @@ static const struct grub_arg_option options[] =
     {"all", 'a', 0, N_("Mount all."), 0, 0},
     {"boot", 'b', 0, N_("Mount all volumes with `boot' flag set."), 0, 0},
     {"password", 'p', 0, N_("Password to open volumes."), 0, ARG_TYPE_STRING},
+    {"protector", 'k', 0, N_("Unlock disk using the specified key protector."), 0, ARG_TYPE_STRING},

This conflicts with the keyfile and detached header patch series as is. Ultimately, this is probably the right way to go and there will be an protector for using unencrypted keyfiles.

Another option is to use -P for protectors and -k for keyfiles and have two separate methods of using unencrypted keyfiles. I generally don't like having two methods, the only benefit is that I believe the --keyfile method is more intuitive. To use the keyfile protector the user unfamiliar with these features will likely need to consult the documentation.

Quoted 15 lines
grub-core/disk/cryptodisk.c +1 -0
     {0, 0, 0, 0, 0, 0}
   };
 
@@ -1160,6 +1162,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
 {
   struct grub_arg_list *state = ctxt->state;
   struct grub_cryptomount_args cargs = {0};
+  grub_err_t err;
 
   if (argc < 1 && !state[1].set && !state[2].set)
     return grub_error (GRUB_ERR_BAD_ARGUMENT, "device name required");
@@ -1167,12 +1170,28 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
   if (grub_cryptodisk_list == NULL)
     return grub_error (GRUB_ERR_BAD_MODULE, "no cryptodisk modules loaded");
 
Quoted 11 lines

grub-core/disk/cryptodisk.c grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args) · line 1179

Quoted 7 lines
grub-core/disk/cryptodisk.c +7 -0
+  if (state[3].set && state[4].set) /* password and key protector */
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       "a password and a key protector cannot both be set");
+
+  if (state[4].set && argc < 1) /* key protector */
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       "key protectors require a device name or UUID");

Referring to the my first comment, I think we can get rid of this if block.

Will do.

Quoted 14 lines

grub-core/disk/cryptodisk.c grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args) · line 1192

Quoted 13 lines
grub-core/disk/cryptodisk.c +7 -0
+
   if (state[3].set) /* password */
     {
       cargs.key_data = (grub_uint8_t *) state[3].arg;
       cargs.key_len = grub_strlen (state[3].arg);
     }
 
+  if (state[4].set) /* key protector */
+    {
+      err = grub_key_protector_recover_key (state[4].arg, &cargs.key_data,
+                                                          &cargs.key_len);
+      if (err)
+        grub_printf_ (N_("Could not recover key from key protector.\n"));
Quoted 4 lines

Why is this not returning with an error here? Is it believed that perhaps the device can be unlocked without recovering a key (even though the user explicitly specified that a key should be used?)?

Yes, the idea was to let the user type in a passphrase in case something goes wrong with the key protector.

Another idea would be to have a passphrase key protector and have it prompt for input. Then, a user would type instead:

cryptomount -k tpm2:... -k passphrase

In this way, the user can be explicit about what the expectations are. cryptomount would try the first protector and, if that fails, then try the second, then the third, and so on.

If a user were then to specify:

cryptomount -k tpm2:...

but no "-k passphrase", no fallback would be initiated.

Thoughts?

Quoted 16 lines

grub-core/disk/cryptodisk.c GRUB_MOD_INIT (cryptodisk) · line 1407

Quoted 11 lines
grub-core/disk/cryptodisk.c +3 -1
+    }
+
   if (state[0].set) /* uuid */
     {
       int found_uuid;
@@ -1385,7 +1404,7 @@ GRUB_MOD_INIT (cryptodisk)
 {
   grub_disk_dev_register (&grub_cryptodisk_dev);
   cmd = grub_register_extcmd ("cryptomount", grub_cmd_cryptomount, 0,
-			      N_("[-p password] <SOURCE|-u UUID|-a|-b>"),
+			      N_("[-p password] [-k protector[:args]] <SOURCE|-u UUID|-a|-b>"),

This looks eerily similiar to what I proposed to James in response to his SEV patches[1]. As such, I am in favor of this syntax and it looks to me like a framework that James can use for his SEV series.

Quoted 8 lines

Glenn

grub-core/disk/cryptodisk.c GRUB_MOD_INIT (cryptodisk) · line 1410

Quoted 3 lines
grub-core/disk/cryptodisk.c +0 -0
 			      N_("Mount a crypto device."), options);
   grub_procfs_register ("luks_script", &luks_script);
 }

[1] https://lists.gnu.org/archive/html/grub-devel/2020-11/msg00105.html

Thank you,
Hernan

#19 lore raw
In reply to Glenn Washburn
Quoted 51 lines · Glenn Washburn
Quoted 33 lines · On Mon, 24 Jan 2022 06:12:13 -0800 Hernan Gatta <[email protected]>…

This patch series adds support for automatically unlocking fully-encrypted disks using a TPM 2.0.

Currently, when GRUB encounters a fully-encrypted disk that it must access, its corresponding cryptodisk module (LUKS 1, LUKS2, or GELI) interactively prompts the user for a passphrase. An improvement to the boot process would be for GRUB to automatically retrieve the unlocking key for fully-encrypted disks from a protected location and to unlock these transparently. To this end, a TPM may be used to protect the unlocking key to a known-good state of the platform. Once the key is protected in this way, assuming that the platform remains trustworthy, GRUB can then utilize the TPM to release the key during boot and thus unlock fully-encrypted disks without user interaction. Such a model would not only be more convenient for end-users but also for virtual machines in cloud environments where no user is ever present.

Design
------

This patchset first adds a key protectors framework. This framework allows for key protector modules to register when loaded. A key protector is defined as a module that knows how to retrieve an unlocking key from a specific source. This patchset adds a single such key protector module that understands how to retrieve an unlocking key from a TPM 2.0 by unsealing a sealed key file via a Storage Root Key (SRK).

Additionally, this patchset expands the cryptomount command to accept a key protector parameter. This parameter carries the information necessary to select and parameterize a key protector to be used to retrieve an unlocking key for the disk in question. That is, given an invocation of cryptomount to mount a specific disk (e.g., "cryptomount (hd0,gpt2)", "cryptomount -u UUID"), a key protector can be used to automatically retrieve an unlocking key without an interactive prompt.

Quoted 6 lines

Lastly, this patchset also includes a new tool, grub-protect, that allows the user to seal a key file against a set of Platform Configuration Registers (PCRs) using an SRK. This sealed key file is expected to be stored in an unencrypted partition, such as the EFI System Partition (ESP), where GRUB can read it. The sealed key is then unsealed by the TPM2 key protector automatically, provided that the PCRs selected match on subsequent boots.

This series should include a documentation patch at a minimum. I would also like to see a QEMU test added. But it should use my cryptomount test series, which hasn't made it to master yet. So this shouldn't be a hard requirement. It would be nice for someone more familiar with Secure boot and TPM to figure out how to get it working in QEMU so we/I can easily add it to the tests. It looks like this should work with the required software[1].

Quoted 4 lines

Glenn

[1] https://en.opensuse.org/Software_TPM_Emulator_For_QEMU

Agreed. I wanted to get feedback on the feature as a whole first before writing documentation for it since, I figured, the way it functions may change as a result of your comments. Once we settle on how it should work and, more importantly, on how a user might use it (I'm thinking of James' comment on separating the cryptomount command from the configuration of a key protector), then I'll add documentation.

With respect to your comment about adding tests, it should indeed be possible to test this using QEMU and a software TPM such as swtpm. I'm happy to take a look at that.

Would it be alright for me to submit a patch series for tests separately from this series?

Quoted 40 lines
Quoted 40 lines

Hernan Gatta (5):
protectors: Add key protectors framework
tpm2: Add TPM Software Stack (TSS)
protectors: Add TPM2 Key Protector
cryptodisk: Support key protectors
util/grub-protect: Add new tool

 .gitignore                             |    1 +
 Makefile.util.def                      |   17 +
 configure.ac                           |    1 +
 grub-core/Makefile.am                  |    1 +
 grub-core/Makefile.core.def            |   10 +
 grub-core/disk/cryptodisk.c            |   21 +-
 grub-core/kern/protectors.c            |   98 +++
 grub-core/tpm2/buffer.c                |  145 ++++
 grub-core/tpm2/module.c                |  742 ++++++++++++++++++
 grub-core/tpm2/mu.c                    |  807 +++++++++++++++++++
 grub-core/tpm2/tcg2.c                  |  143 ++++
 grub-core/tpm2/tpm2.c                  |  711 +++++++++++++++++
 include/grub/protector.h               |   55 ++
 include/grub/tpm2/buffer.h             |   65 ++
 include/grub/tpm2/internal/functions.h |  117 +++
 include/grub/tpm2/internal/structs.h   |  675 ++++++++++++++++
 include/grub/tpm2/internal/types.h     |  372 +++++++++
 include/grub/tpm2/mu.h                 |  292 +++++++
 include/grub/tpm2/tcg2.h               |   34 +
 include/grub/tpm2/tpm2.h               |   38 +
 util/grub-protect.c                    | 1344 ++++++++++++++++++++++++++++++++
 21 files changed, 5688 insertions(+), 1 deletion(-)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 grub-core/tpm2/buffer.c
 create mode 100644 grub-core/tpm2/module.c
 create mode 100644 grub-core/tpm2/mu.c
 create mode 100644 grub-core/tpm2/tcg2.c
 create mode 100644 grub-core/tpm2/tpm2.c
 create mode 100644 include/grub/protector.h
 create mode 100644 include/grub/tpm2/buffer.h
Quoted 9 lines
Quoted 8 lines
 create mode 100644 include/grub/tpm2/internal/functions.h
 create mode 100644 include/grub/tpm2/internal/structs.h
 create mode 100644 include/grub/tpm2/internal/types.h
 create mode 100644 include/grub/tpm2/mu.h
 create mode 100644 include/grub/tpm2/tcg2.h
 create mode 100644 include/grub/tpm2/tpm2.h
 create mode 100644 util/grub-protect.c

Thank you,
Hernan

#20 lore raw

On Thu, 27 Jan 2022 06:03:21 -0800 (PST)
Hernan Gatta <hegatta@linuxonhyperv3.guj3yctzbm1etfxqx2vob5hsef.xx.internal.cloudapp.net>

Quoted 60 lines · wrote:
Quoted 51 lines · Glenn Washburn
Quoted 33 lines · On Mon, 24 Jan 2022 06:12:13 -0800 Hernan Gatta <[email protected]>…

This patch series adds support for automatically unlocking fully-encrypted disks using a TPM 2.0.

Currently, when GRUB encounters a fully-encrypted disk that it must access, its corresponding cryptodisk module (LUKS 1, LUKS2, or GELI) interactively prompts the user for a passphrase. An improvement to the boot process would be for GRUB to automatically retrieve the unlocking key for fully-encrypted disks from a protected location and to unlock these transparently. To this end, a TPM may be used to protect the unlocking key to a known-good state of the platform. Once the key is protected in this way, assuming that the platform remains trustworthy, GRUB can then utilize the TPM to release the key during boot and thus unlock fully-encrypted disks without user interaction. Such a model would not only be more convenient for end-users but also for virtual machines in cloud environments where no user is ever present.

Design
------

This patchset first adds a key protectors framework. This framework allows for key protector modules to register when loaded. A key protector is defined as a module that knows how to retrieve an unlocking key from a specific source. This patchset adds a single such key protector module that understands how to retrieve an unlocking key from a TPM 2.0 by unsealing a sealed key file via a Storage Root Key (SRK).

Additionally, this patchset expands the cryptomount command to accept a key protector parameter. This parameter carries the information necessary to select and parameterize a key protector to be used to retrieve an unlocking key for the disk in question. That is, given an invocation of cryptomount to mount a specific disk (e.g., "cryptomount (hd0,gpt2)", "cryptomount -u UUID"), a key protector can be used to automatically retrieve an unlocking key without an interactive prompt.

Quoted 6 lines

Lastly, this patchset also includes a new tool, grub-protect, that allows the user to seal a key file against a set of Platform Configuration Registers (PCRs) using an SRK. This sealed key file is expected to be stored in an unencrypted partition, such as the EFI System Partition (ESP), where GRUB can read it. The sealed key is then unsealed by the TPM2 key protector automatically, provided that the PCRs selected match on subsequent boots.

This series should include a documentation patch at a minimum. I would also like to see a QEMU test added. But it should use my cryptomount test series, which hasn't made it to master yet. So this shouldn't be a hard requirement. It would be nice for someone more familiar with Secure boot and TPM to figure out how to get it working in QEMU so we/I can easily add it to the tests. It looks like this should work with the required software[1].

Quoted 4 lines

Glenn

[1] https://en.opensuse.org/Software_TPM_Emulator_For_QEMU

Quoted 6 lines

Agreed. I wanted to get feedback on the feature as a whole first before writing documentation for it since, I figured, the way it functions may change as a result of your comments. Once we settle on how it should work and, more importantly, on how a user might use it (I'm thinking of James' comment on separating the cryptomount command from the configuration of a key protector), then I'll add documentation.

Works for me.

Quoted 6 lines

With respect to your comment about adding tests, it should indeed be possible to test this using QEMU and a software TPM such as swtpm. I'm happy to take a look at that.

Would it be alright for me to submit a patch series for tests separately from this series?

I prefer strongly suggesting patches for testing be included in the patch series for new features they test. To my knowledge, this isn't something that has been stressed much for GRUB in the past, but I would like to change that. And having said that, I don't think it need be applied so strenuously for new features for cryptomount because the infrastructure for testing cryptomount isn't fully baked (IMO). I've got some patches to help address that, but they aren't the priority for reviewing at the moment (but hopefully will become more so after the detached headers patch series goes through). So yes, I think a separate patch series would be fine.

As for implementation, ideally it would be leveraging my "cryptomont-test" patch series, for which I'll need to submit an updated version. I should do that soon. I'm also open to other ideas on the implementation.

Glenn

Quoted 52 lines
Quoted 40 lines
Quoted 40 lines

Hernan Gatta (5):
protectors: Add key protectors framework
tpm2: Add TPM Software Stack (TSS)
protectors: Add TPM2 Key Protector
cryptodisk: Support key protectors
util/grub-protect: Add new tool

 .gitignore                             |    1 +
 Makefile.util.def                      |   17 +
 configure.ac                           |    1 +
 grub-core/Makefile.am                  |    1 +
 grub-core/Makefile.core.def            |   10 +
 grub-core/disk/cryptodisk.c            |   21 +-
 grub-core/kern/protectors.c            |   98 +++
 grub-core/tpm2/buffer.c                |  145 ++++
 grub-core/tpm2/module.c                |  742 ++++++++++++++++++
 grub-core/tpm2/mu.c                    |  807 +++++++++++++++++++
 grub-core/tpm2/tcg2.c                  |  143 ++++
 grub-core/tpm2/tpm2.c                  |  711 +++++++++++++++++
 include/grub/protector.h               |   55 ++
 include/grub/tpm2/buffer.h             |   65 ++
 include/grub/tpm2/internal/functions.h |  117 +++
 include/grub/tpm2/internal/structs.h   |  675 ++++++++++++++++
 include/grub/tpm2/internal/types.h     |  372 +++++++++
 include/grub/tpm2/mu.h                 |  292 +++++++
 include/grub/tpm2/tcg2.h               |   34 +
 include/grub/tpm2/tpm2.h               |   38 +
 util/grub-protect.c                    | 1344 ++++++++++++++++++++++++++++++++
 21 files changed, 5688 insertions(+), 1 deletion(-)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 grub-core/tpm2/buffer.c
 create mode 100644 grub-core/tpm2/module.c
 create mode 100644 grub-core/tpm2/mu.c
 create mode 100644 grub-core/tpm2/tcg2.c
 create mode 100644 grub-core/tpm2/tpm2.c
 create mode 100644 include/grub/protector.h
 create mode 100644 include/grub/tpm2/buffer.h
Quoted 9 lines
Quoted 8 lines
 create mode 100644 include/grub/tpm2/internal/functions.h
 create mode 100644 include/grub/tpm2/internal/structs.h
 create mode 100644 include/grub/tpm2/internal/types.h
 create mode 100644 include/grub/tpm2/mu.h
 create mode 100644 include/grub/tpm2/tcg2.h
 create mode 100644 include/grub/tpm2/tpm2.h
 create mode 100644 util/grub-protect.c

Thank you,
Hernan

#8 lore raw

Re: [PATCH 3/5] protectors: Add TPM2 Key Protector

In reply to Hernan Gatta

On Thu, 27 Jan 2022 06:11:03 -0800 (PST)
Hernan Gatta <hegatta@linuxonhyperv3.guj3yctzbm1etfxqx2vob5hsef.xx.internal.cloudapp.net>

Quoted 42 lines · wrote:
Quoted 23 lines · Glenn Washburn
Quoted 9 lines · On Mon, 24 Jan 2022 06:12:16 -0800 Hernan Gatta <[email protected]>…

From: Hernan Gatta <[email protected]>

The TPM2 key protector is a module that enables the automatic retrieval of a fully-encrypted disk's unlocking key from a TPM 2.0.

The theory of operation is such that the module accepts various arguments, most of which are optional therefore possess reasonable defaults. One of these arguments is the keyfile parameter, which is mandatory.

Quoted 10 lines

The value of this parameter must be a path to a sealed key file (e.g., (hd0,gpt1)/boot/grub2/sealed_key). This sealed key file is created via the grub-protect tool. The tool utilizes the TPM's sealing functionality to seal (i.e., encrypt) an unlocking key using a Storage Root Key (SRK) to the values of various Platform Configuration Registers (PCRs). These PCRs reflect the state of the system as it boots. If the values are as expected, the system may be considered trustworthy, at which point the TPM allows for a caller to utilize the private component of the SRK to unseal (i.e., decrypt) the sealed key file. The caller, in this case, is this key protector.

Quoted 14 lines

There are a lot of points in this code where an error can be returned. In this case, all I'm going to get is a non-descript error code (almost always GRUB_ERR_BAD_ARGUMENT). So as a user, how am I to know where the error is actually coming from? For this reason, I like the use of grub_error(error_code, error_format_string, fmtstr_args...), which will set grub_errno and an error message, which can be retrieved up the stack and presented to the user. I'm not sure that every return of a naked error code should be replaced by grub_error(), depends on how granular of an error message you want to see. I would error on the side of more granular. For instance, its really nice that GCC will tell me which format code type specifier and a argument its choking on, rather than a catch all "I'm failing to compile your code because you have an incorrect format code somewhere in your format string".

Quoted 3 lines

Agreed. I'll add calls to grub_error to indicate why things fail and, when they do, capture the error up the stack (I was thinking in the command handler for cryptomount), and print it.

IIRC, you shouldn't have to do anything, just return from cryptomount with the error code and have grub_errno and grub_errmsg set. If you swallow any errors, you should print the swallowed errors in grub_dprintf() (maybe not always, judgement required).

Quoted 266 lines
Quoted 256 lines
Quoted 256 lines
---
 grub-core/Makefile.core.def |   9 +
 grub-core/tpm2/module.c     | 742 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 751 insertions(+)
 create mode 100644 grub-core/tpm2/module.c
grub-core/Makefile.core.def +9 -0
index e4ae78b..8691440 100644
@@ -2498,6 +2498,15 @@ module = {
 };
 
 module = {
+  name = tpm2;
+  common = tpm2/buffer.c;
+  common = tpm2/module.c;
+  common = tpm2/mu.c;
+  common = tpm2/tpm2.c;
+  efi = tpm2/tcg2.c;
+};
+
+module = {
   name = tr;
   common = commands/tr.c;
 };
grub-core/tpm2/module.c new file +222 -0
new file mode 100644
index 0000000..cd97452
@@ -0,0 +1,742 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/dl.h>
+#include <grub/file.h>
+#include <grub/misc.h>
+#include <grub/mm.h>
+#include <grub/protector.h>
+#include <grub/tpm2/buffer.h>
+#include <grub/tpm2/mu.h>
+#include <grub/tpm2/tpm2.h>
+#include <grub/types.h>
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+typedef enum grub_tpm2_protector_args
+{
+  GRUB_TPM2_PROTECTOR_ARG_MODE       = 1 << 0,
+  GRUB_TPM2_PROTECTOR_ARG_PCRS       = 1 << 1,
+  GRUB_TPM2_PROTECTOR_ARG_ASYMMETRIC = 1 << 2,
+  GRUB_TPM2_PROTECTOR_ARG_BANK       = 1 << 3,
+  GRUB_TPM2_PROTECTOR_ARG_KEYFILE    = 1 << 4,
+  GRUB_TPM2_PROTECTOR_ARG_SRK        = 1 << 5,
+  GRUB_TPM2_PROTECTOR_ARG_NV         = 1 << 6
+} grub_tpm2_protector_args_t;
+
+typedef enum grub_tpm2_protector_mode
+{
+  GRUB_TPM2_PROTECTOR_MODE_SRK = 1,
+  GRUB_TPM2_PROTECTOR_MODE_NV  = 2
+} grub_tpm2_protector_mode_t;
+
+struct grub_tpm2_protector_context
+{
+  grub_tpm2_protector_args_t args;
+  grub_tpm2_protector_mode_t mode;
+  grub_uint8_t pcrs[TPM_MAX_PCRS];
+  grub_uint8_t pcr_count;
+  TPM_ALG_ID asymmetric;
+  TPM_ALG_ID bank;
+  const char *keyfile;
+  TPM_HANDLE srk;
+  TPM_HANDLE nv;
+};
+
+static grub_err_t
+grub_tpm2_protector_parse_mode (struct grub_tpm2_protector_context *ctx,
+                                const char *value)
+{
+  if (grub_strcmp (value, "srk") == 0)
+    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_SRK;
+  else if (grub_strcmp (value, "nv") == 0)
+    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_NV;
+  else
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_pcrs (struct grub_tpm2_protector_context *ctx,
+                                char *value)
+{
+  grub_err_t err;
+  char *current_pcr = value;
+  char *next_pcr;
+  unsigned long pcr;
+  grub_uint8_t i;
+
+  if (grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  ctx->pcr_count = 0;
+  for (i = 0; i < TPM_MAX_PCRS; i++)
+    {
+      next_pcr = grub_strchr (current_pcr, ',');
+      if (next_pcr)
+        *next_pcr = '\0';
+      if (next_pcr == current_pcr)
+        return GRUB_ERR_BAD_ARGUMENT;
+
+      grub_errno = GRUB_ERR_NONE;
+      pcr = grub_strtoul (current_pcr, NULL, 10);
+      if (grub_errno != GRUB_ERR_NONE)
+        {
+          err = grub_errno;
+          grub_errno = GRUB_ERR_NONE;
+          return err;
+        }
+
+      if (pcr > GRUB_UCHAR_MAX)
+        return GRUB_ERR_OUT_OF_RANGE;
+
+      ctx->pcrs[i] = (grub_uint8_t)pcr;
+      ctx->pcr_count++;
+
+      if (!next_pcr)
+        break;
+
+      current_pcr = next_pcr + 1;
+      if (*current_pcr == '\0')
+        return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (i == TPM_MAX_PCRS)
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_asymmetric (struct grub_tpm2_protector_context *ctx,
+                                      const char *value)
+{
+  if (grub_strcasecmp (value, "ECC") == 0)
+    ctx->asymmetric = TPM_ALG_ECC;
+  else if (grub_strcasecmp (value, "RSA") == 0)
+    ctx->asymmetric = TPM_ALG_RSA;
+  else
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_bank (struct grub_tpm2_protector_context *ctx,
+                                const char *value)
+{
+  if (grub_strcasecmp (value, "SHA1") == 0)
+    ctx->bank = TPM_ALG_SHA1;
+  else if (grub_strcasecmp (value, "SHA256") == 0)
+    ctx->bank = TPM_ALG_SHA256;
+  else if (grub_strcasecmp (value, "SHA384") == 0)
+    ctx->bank = TPM_ALG_SHA384;
+  else
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_keyfile (struct grub_tpm2_protector_context *ctx,
+                                   const char *value)
+{
+  if (grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  ctx->keyfile = value;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_tpm_handle (const char *value, TPM_HANDLE *handle)
+{
+  grub_err_t err;
+  unsigned long num;
+
+  grub_errno = GRUB_ERR_NONE;
+  num = grub_strtoul (value, NULL, 0);
+  if (grub_errno != GRUB_ERR_NONE)
+    {
+      err = grub_errno;
+      grub_errno = GRUB_ERR_NONE;
+      return err;
+    }
+
+  if (num > GRUB_UINT_MAX)
+    return GRUB_ERR_OUT_OF_RANGE;
+
+  *handle = (TPM_HANDLE)num;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_srk (struct grub_tpm2_protector_context *ctx,
+                               const char *value)
+{
+  return grub_tpm2_protector_parse_tpm_handle (value, &ctx->srk);
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_nvindex (struct grub_tpm2_protector_context *ctx,
+                                   const char *value)
+{
+  return grub_tpm2_protector_parse_tpm_handle (value, &ctx->nv);
+}
+
+static grub_err_t
+grub_tpm2_protector_match_arg (struct grub_tpm2_protector_context *ctx,
+                               const char *key, char *value)
+{
+  grub_err_t err;
+
+  if (grub_strlen (key) == 0 || grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  if (grub_strcmp (key, "mode") == 0)
+  {
+    if (ctx->args & GRUB_TPM2_PROTECTOR_ARG_MODE)
+      return GRUB_ERR_BAD_ARGUMENT;
+
+    err = grub_tpm2_protector_parse_mode (ctx, value);
+    if (!err)
+      ctx->args |= GRUB_TPM2_PROTECTOR_ARG_MODE;
+
Quoted 9 lines

grub-core/tpm2/module.c line 226

Quoted 4 lines
grub-core/tpm2/module.c new file +4 -0
+    return err;
+  }
+
+  if (grub_strcmp (key, "pcrs") == 0)

Minor nit, why wouldn't this be better as an "else if"? Seems unnecessary to check all the "if" statements if we've already found a match.

Quoted 5 lines

The reason why I wrote this in this way without an "else if" is because each "if" clause has an unconditional return. So, in the end, the entire sequence behaves in the manner you describe.

Would you prefer that I add the "else if"'s anyway for readability?

Somehow I missed the returns. I don't care as much now. Maybe Daniel will have an opinion when he gets to this.

Glenn