Skip to contentSkip to conversation

Automatic TPM Disk Unlock

PATCH In review Hernan Gatta 5 participants 12 messages Feb 1, 2022 – Feb 6, 2023 Kbuild

lore
Share & tools
lore
#0 lore raw

v2 cover Automatic TPM Disk Unlock

Updates since v1:

1. One key can unlock multiple disks:
It is now possible to use key protectors with cryptomount's -a and -b options.

2. No passphrase prompt on error if key protector(s) specified:
cryptomount no longer prompts for a passphrase if key protectors are specified but fail to provide a working unlock key seeing as the user explicitly requested unlocking via key protectors.

3. Key protector parameterization is separate:
Previously, one would parameterize a key protector via a colon-separated argument list nested within a cryptomount argument. Now, key protectors are expected to provide an initialization function, if necessary.

As such, instead of:

cryptomount -k tpm2:mode=srk:keyfile=KEYFILE:pcrs=7,11...

one now writes:

tpm2_key_protector_init --mode=srk --keyfile=KEYFILE --pcrs=7,11 ... cryptomount -k tpm2

Additionally, one may write:

cryptomount -k protector_1 -k protector_2 ...

where cryptomount will try each in order on failure.

4. Standard argument parsing:
The TPM2 key protector now uses 'struct grub_arg_option' and the grub-protect tool uses 'struct argp_option'. Additionally, common argument parsing functionality is now shared between the module and the tool.

5. More useful messages:
Both the TPM2 module and the grub-protect tool now provide more useful messages to help the user learn how to use their functionality (--help and --usage) as well as to determine what is wrong, if anything. Furthermore, the module now prints additional debug output to help diagnose problems.

I forgot to mention last time that this patch series intends to address:
https://bugzilla.redhat.com/show_bug.cgi?id=1854177

Previous series:
https://lists.gnu.org/archive/html/grub-devel/2022-01/msg00125.html

Thank you,
Hernan

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                      |   19 +
 configure.ac                           |    1 +
 grub-core/Makefile.am                  |    1 +
 grub-core/Makefile.core.def            |   11 +
 grub-core/disk/cryptodisk.c            |  166 +++-
 grub-core/kern/protectors.c            |   75 ++
 grub-core/tpm2/args.c                  |  129 ++++
 grub-core/tpm2/buffer.c                |  145 ++++
 grub-core/tpm2/module.c                |  710 +++++++++++++++++
 grub-core/tpm2/mu.c                    |  807 ++++++++++++++++++++
 grub-core/tpm2/tcg2.c                  |  143 ++++
 grub-core/tpm2/tpm2.c                  |  711 +++++++++++++++++
 include/grub/cryptodisk.h              |   14 +
 include/grub/protector.h               |   48 ++
 include/grub/tpm2/buffer.h             |   65 ++
 include/grub/tpm2/internal/args.h      |   39 +
 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                    | 1314 ++++++++++++++++++++++++++++++++
 24 files changed, 5897 insertions(+), 30 deletions(-)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 grub-core/tpm2/args.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/args.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
#1 lore raw

PATCH v2 1/5 protectors: Add key protectors framework

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 by name. If a key protector with the specified name exists and if an unlocking key is successfully retrieved by it, 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 | 75 +++++++++++++++++++++++++++++++++++++++++++++
 include/grub/protector.h    | 48 +++++++++++++++++++++++++++++
 4 files changed, 125 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 +75 -0

75 lines not on this page · raw message

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

48 lines not on this page · raw message

Signature · 1 line
1.8.3.1
#2 lore raw

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

In reply to Hernan Gatta

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..4b7a9fb

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.

#3 lore raw

PATCH v2 3/5 protectors: Add TPM2 Key Protector

In reply to Hernan Gatta

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 and 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.

The TPM2 key protector registers two commands:

- tpm2_key_protector_init: Initializes the state of the TPM2 key protector for later usage, clearing any previous state, too, if any.

- tpm2_key_protector_clear: Clears any state set by tpm2_key_protector_init.

The way this is expected to be used requires the user to, either interactively or, normally, via a boot script, initialize (i.e., configure) the key protector and then specify that it be used by the cryptomount command (modifications to this command are in a different patch).

For instance:

tpm2_key_protector_init --keyfile=KEYFILE1
cryptomount DISK1 -k tpm2

tpm2_key_protector_init --keyfile=KEYFILE2 --pcrs=7,11 cryptomount DISK2 -k tpm2

If a user does not initialize the key protector and attempts to use it anyway, the protector returns an error.

---
 grub-core/Makefile.core.def       |  10 +
 grub-core/tpm2/args.c             | 129 +++++++
 grub-core/tpm2/module.c           | 710 ++++++++++++++++++++++++++++++++++++++
 include/grub/tpm2/internal/args.h |  39 +++
 4 files changed, 888 insertions(+)
 create mode 100644 grub-core/tpm2/args.c
 create mode 100644 grub-core/tpm2/module.c
 create mode 100644 include/grub/tpm2/internal/args.h
grub-core/Makefile.core.def +10 -0
index e4ae78b..78d09d9 100644
@@ -2498,6 +2498,16 @@ module = {
 };
 
 module = {
+  name = tpm2;
+  common = tpm2/args.c;
+  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/args.c new file +129 -0

129 lines not on this page · raw message

grub-core/tpm2/module.c new file +710 -0

710 lines not on this page · raw message

include/grub/tpm2/internal/args.h new file +39 -0
new file mode 100644
index 0000000..6341fce
@@ -0,0 +1,39 @@
+/*
+ *  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_TPM2_INTERNAL_ARGS_HEADER
+#define GRUB_TPM2_INTERNAL_ARGS_HEADER 1
+
+#include <grub/err.h>
+#include <grub/tpm2/tpm2.h>
+
+grub_err_t
+grub_tpm2_protector_parse_pcrs (char *value, grub_uint8_t *pcrs,
+                                grub_uint8_t *pcr_count);
+
+grub_err_t
+grub_tpm2_protector_parse_asymmetric (const char *value,
+                                      TPM_ALG_ID *asymmetric);
+
+grub_err_t
+grub_tpm2_protector_parse_bank (const char *value, TPM_ALG_ID *bank);
+
+grub_err_t
+grub_tpm2_protector_parse_tpm_handle (const char *value, TPM_HANDLE *handle);
+
+#endif /* ! GRUB_TPM2_INTERNAL_ARGS_HEADER */
Signature · 1 line
1.8.3.1
#4 lore raw

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

Quoted 57 lines · Hernan Gatta

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 and 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.

The TPM2 key protector registers two commands:

- tpm2_key_protector_init: Initializes the state of the TPM2 key protector for later usage, clearing any previous state, too, if any.

- tpm2_key_protector_clear: Clears any state set by tpm2_key_protector_init.

The way this is expected to be used requires the user to, either interactively or, normally, via a boot script, initialize (i.e., configure) the key protector and then specify that it be used by the cryptomount command (modifications to this command are in a different patch).

For instance:

tpm2_key_protector_init --keyfile=KEYFILE1
cryptomount DISK1 -k tpm2

tpm2_key_protector_init --keyfile=KEYFILE2 --pcrs=7,11 cryptomount DISK2 -k tpm2

If a user does not initialize the key protector and attempts to use it anyway, the protector returns an error.

---
 grub-core/Makefile.core.def       |  10 +
 grub-core/tpm2/args.c             | 129 +++++++
 grub-core/tpm2/module.c           | 710 ++++++++++++++++++++++++++++++++++++++
 include/grub/tpm2/internal/args.h |  39 +++
 4 files changed, 888 insertions(+)
 create mode 100644 grub-core/tpm2/args.c
 create mode 100644 grub-core/tpm2/module.c
 create mode 100644 include/grub/tpm2/internal/args.h
grub-core/Makefile.core.def +0 -0
index e4ae78b..78d09d9 100644

grub-core/Makefile.core.def module = { · line 2507

Quoted 10 lines
grub-core/Makefile.core.def +7 -0
@@ -2498,6 +2498,16 @@ module = {
 };
 
 module = {
+  name = tpm2;
+  common = tpm2/args.c;
+  common = tpm2/buffer.c;
+  common = tpm2/module.c;
+  common = tpm2/mu.c;
+  common = tpm2/tpm2.c;
+  efi = tpm2/tcg2.c;

The tpm2 module fails to build on non-efi platforms because of undefined symbols from tpm2/tcg2.c. Maybe adding enable = efi is required here as long as supporting other platform seems not to be intended.

Thanks,
Michael

Quoted 910 lines
grub-core/Makefile.core.def +3 -0
+};
+
+module = {
   name = tr;
   common = commands/tr.c;
 };
grub-core/tpm2/args.c new file +129 -0
new file mode 100644
index 0000000..90c7cd8
@@ -0,0 +1,129 @@
+/*
+ *  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/err.h>
+#include <grub/mm.h>
+#include <grub/misc.h>
+#include <grub/tpm2/internal/args.h>
+
+grub_err_t
+grub_tpm2_protector_parse_pcrs (char *value, grub_uint8_t *pcrs,
+                                grub_uint8_t *pcr_count)
+{
+  char *current_pcr = value;
+  char *next_pcr;
+  unsigned long pcr;
+  grub_uint8_t i;
+
+  if (grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  *pcr_count = 0;
+  for (i = 0; i < TPM_MAX_PCRS; i++)
+    {
+      next_pcr = grub_strchr (current_pcr, ',');
+      if (next_pcr == current_pcr)
+        return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                           N_("Empty entry in PCR list"));
+      if (next_pcr)
+        *next_pcr = '\0';
+
+      grub_errno = GRUB_ERR_NONE;
+      pcr = grub_strtoul (current_pcr, NULL, 10);
+      if (grub_errno != GRUB_ERR_NONE)
+        return grub_error (grub_errno,
+                           N_("Entry '%s' in PCR list is not a number"),
+                           current_pcr);
+
+      if (pcr > TPM_MAX_PCRS)
+        return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                           N_("Entry %lu in PCR list is too large to be a PCR "
+                              "number, PCR numbers range from 0 to %u"),
+                           pcr, TPM_MAX_PCRS);
+
+      pcrs[i] = (grub_uint8_t)pcr;
+      *pcr_count += 1;
+
+      if (!next_pcr)
+        break;
+
+      current_pcr = next_pcr + 1;
+      if (*current_pcr == '\0')
+        return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                           N_("Trailing comma at the end of PCR list"));
+    }
+
+  if (i == TPM_MAX_PCRS)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                       N_("Too many PCRs in PCR list, the maximum number of "
+                          "PCRs is %u"), TPM_MAX_PCRS);
+
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_tpm2_protector_parse_asymmetric (const char *value, TPM_ALG_ID *asymmetric)
+{
+  if (grub_strcasecmp (value, "ECC") == 0)
+    *asymmetric = TPM_ALG_ECC;
+  else if (grub_strcasecmp (value, "RSA") == 0)
+    *asymmetric = TPM_ALG_RSA;
+  else
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                       N_("Value '%s' is not a valid asymmetric key type"),
+                       value);
+
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_tpm2_protector_parse_bank (const char *value, TPM_ALG_ID *bank)
+{
+  if (grub_strcasecmp (value, "SHA1") == 0)
+    *bank = TPM_ALG_SHA1;
+  else if (grub_strcasecmp (value, "SHA256") == 0)
+    *bank = TPM_ALG_SHA256;
+  else if (grub_strcasecmp (value, "SHA384") == 0)
+    *bank = TPM_ALG_SHA384;
+  else
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                       N_("Value '%s' is not a valid PCR bank"), value);
+
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_tpm2_protector_parse_tpm_handle (const char *value, TPM_HANDLE *handle)
+{
+  unsigned long num;
+
+  grub_errno = GRUB_ERR_NONE;
+  num = grub_strtoul (value, NULL, 0);
+  if (grub_errno != GRUB_ERR_NONE)
+    return grub_error (grub_errno, N_("TPM handle value '%s' is not a number"),
+                       value);
+
+  if (num > GRUB_UINT_MAX)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                       N_("Value %lu is too large to be a TPM handle, TPM "
+                          "handles are unsigned 32-bit integers"), num);
+
+  *handle = (TPM_HANDLE)num;
+
+  return GRUB_ERR_NONE;
+}
grub-core/tpm2/module.c new file +710 -0
new file mode 100644
index 0000000..3f2f386
@@ -0,0 +1,710 @@
+/*
+ *  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/extcmd.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/internal/args.h>
+#include <grub/tpm2/mu.h>
+#include <grub/tpm2/tpm2.h>
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+typedef enum grub_tpm2_protector_mode
+{
+  GRUB_TPM2_PROTECTOR_MODE_UNSET,
+  GRUB_TPM2_PROTECTOR_MODE_SRK,
+  GRUB_TPM2_PROTECTOR_MODE_NV
+} grub_tpm2_protector_mode_t;
+
+struct grub_tpm2_protector_context
+{
+  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 const struct grub_arg_option grub_tpm2_protector_init_cmd_options[] =
+  {
+    /* Options for all modes */
+    {
+      .longarg  = "mode",
+      .shortarg = 'm',
+      .flags    = 0,
+      .arg      = NULL,
+      .type     = ARG_TYPE_STRING,
+      .doc      =
+        N_("Unseal key using SRK ('srk') (default) or retrieve it from an NV "
+           "Index ('nv')."),
+    },
+    {
+      .longarg  = "pcrs",
+      .shortarg = 'p',
+      .flags    = 0,
+      .arg      = NULL,
+      .type     = ARG_TYPE_STRING,
+      .doc      =
+        N_("Comma-separated list of PCRs used to authorize key release "
+           "(e.g., '7,11', default is 7."),
+    },
+    {
+      .longarg  = "bank",
+      .shortarg = 'b',
+      .flags    = 0,
+      .arg      = NULL,
+      .type     = ARG_TYPE_STRING,
+      .doc      =
+        N_("Bank of PCRs used to authorize key release: "
+           "SHA1, SHA256 (default), or SHA384."),
+    },
+    /* SRK-mode options */
+    {
+      .longarg  = "keyfile",
+      .shortarg = 'k',
+      .flags    = 0,
+      .arg      = NULL,
+      .type     = ARG_TYPE_STRING,
+      .doc      =
+        N_("Required in SRK mode, path to the sealed key file to unseal using "
+           "the TPM (e.g., (hd0,gpt1)/boot/grub2/sealed_key)."),
+    },
+    {
+      .longarg  = "srk",
+      .shortarg = 's',
+      .flags    = 0,
+      .arg      = NULL,
+      .type     = ARG_TYPE_STRING,
+      .doc      =
+        N_("In SRK mode, the SRK handle if the SRK is persistent "
+           "(default is 0x81000001)."),
+    },
+    {
+      .longarg  = "asymmetric",
+      .shortarg = 'a',
+      .flags    = 0,
+      .arg      = NULL,
+      .type     = ARG_TYPE_STRING,
+      .doc      =
+        N_("In SRK mode, the type of SRK: RSA (default) or ECC."),
+    },
+    /* NV Index-mode options */
+    {
+      .longarg  = "nvindex",
+      .shortarg = 'n',
+      .flags    = 0,
+      .arg      = NULL,
+      .type     = ARG_TYPE_STRING,
+      .doc      =
+        N_("Required in NV Index mode, the NV handle to read which must "
+           "readily exist on the TPM and which contains the key."),
+    },
+    /* End of list */
+    {0, 0, 0, 0, 0, 0}
+  };
+
+static grub_extcmd_t grub_tpm2_protector_init_cmd;
+static grub_extcmd_t grub_tpm2_protector_clear_cmd;
+static struct grub_tpm2_protector_context grub_tpm2_protector_ctx = { 0 };
+
+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_dprintf ("tpm2", "Could not open sealed key file.\n");
+      /* 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_dprintf ("tpm2", "Could not read sealed key file size.\n");
+      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_dprintf ("tpm2", "Could not allocate buffer for sealed key.\n");
+      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_dprintf ("tpm2", "Could not retrieve sealed key file contents.\n");
+      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)
+    {
+      grub_dprintf ("tpm2", "Sealed key file is larger than decode buffer "
+                            "(%lu vs %lu bytes).\n", 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);
+
+  if (buf.error)
+    {
+      grub_dprintf ("tpm2", "Could not unmarshal sealed key file, it is likely "
+                            "malformed.\n");
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  return 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)
+    {
+      grub_dprintf ("tpm2", "The SRK handle (0x%x) exists on the TPM but its "
+                            "public area could not be read (TPM2_ReadPublic "
+                            "failed with TSS/TPM error %u).\n", ctx->srk, rc);
+      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)
+    {
+      grub_dprintf ("tpm2", "Could not create SRK (TPM2_CreatePrimary failed "
+                            "with TSS/TPM error %u).\n", rc);
+      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 grub_error (err, N_("Failed to read key file %s"), ctx->keyfile);
+
+  err = grub_tpm2_protector_srk_unmarshal_keyfile (sealed_key_bytes,
+                                                   sealed_key_size,
+                                                   &sealed_key);
+  if (err)
+    {
+      grub_error (err, N_("Failed to unmarshal key, ensure the key file is in "
+                          "TPM wire format"));
+      goto exit1;
+    }
+
+  /* Get SRK */
+  err = grub_tpm2_protector_srk_get (ctx, &srk_handle);
+  if (err)
+    {
+      grub_error (err, N_("Failed to retrieve the SRK"));
+      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)
+    {
+      grub_error (err, N_("Failed to start auth session (TPM2_StartAuthSession "
+                          "failed with TSS/TPM error %u)"), 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)
+    {
+      grub_error (err, N_("Failed to submit PCR policy (TPM2_PolicyPCR failed "
+                          "with TSS/TPM error %u)"), 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)
+    {
+      grub_error (err, N_("Failed to load sealed key (TPM2_Load failed with "
+                          "TSS/TPM error %u)"), 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)
+    {
+      grub_error (err, N_("Failed to unseal sealed key (TPM2_Unseal failed "
+                          "with TSS/TPM error %u)"), rc);
+      goto exit4;
+    }
+
+  /* Epilogue */
+  key_out = grub_malloc (data.size);
+  if (!key_out)
+    {
+      err = GRUB_ERR_OUT_OF_MEMORY;
+      grub_error (err, N_("No memory left to allocate unlock key buffer"));
+      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_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                     N_("NV Index mode is 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 (grub_uint8_t **key, grub_size_t *key_size)
+{
+  grub_err_t err;
+
+  /* Expect a call to tpm2_protector_init before anybody tries to use us */
+  if (grub_tpm2_protector_ctx.mode == GRUB_TPM2_PROTECTOR_MODE_UNSET)
+    return grub_error (GRUB_ERR_INVALID_COMMAND,
+                       N_("Cannot use TPM2 key protector without initializing "
+                          "it, call tpm2_protector_init first"));
+
+  if (!key)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  err = grub_tpm2_protector_recover (&grub_tpm2_protector_ctx, key, key_size);
+  if (err)
+    return err;
+
+  return GRUB_ERR_NONE;
+}
+
+
+static grub_err_t
+grub_tpm2_protector_check_args (struct grub_tpm2_protector_context *ctx)
+{
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_UNSET)
+    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_SRK;
+
+  /* Checks for SRK mode */
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && !ctx->keyfile)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In SRK mode, a key file must be specified: "
+                          "--keyfile or -k"));
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && ctx->nv)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In SRK mode, an NV Index cannot be specified"));
+
+  /* Checks for NV mode */
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && !ctx->nv)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In NV Index mode, an NV Index must be specified: "
+                           "--nvindex or -n"));
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->keyfile)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In NV Index mode, a keyfile cannot be specified"));
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->srk)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In NV Index mode, an SRK cannot be specified"));
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->asymmetric)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In NV Index mode, an asymmetric key type cannot be "
+                          "specified"));
+
+  /* Defaults assignment */
+  if (!ctx->bank)
+    ctx->bank = TPM_ALG_SHA256;
+
+  if (!ctx->pcr_count)
+    {
+      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;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_keyfile (const char *value, const char **keyfile)
+{
+  if (grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  *keyfile = grub_strdup (value);
+  if (!*keyfile)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                       N_("No memory to duplicate keyfile path"));
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_mode (const char *value,
+                                grub_tpm2_protector_mode_t *mode)
+{
+  if (grub_strcmp (value, "srk") == 0)
+    *mode = GRUB_TPM2_PROTECTOR_MODE_SRK;
+  else if (grub_strcmp (value, "nv") == 0)
+    *mode = GRUB_TPM2_PROTECTOR_MODE_NV;
+  else
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                       N_("Value '%s' is not a valid TPM2 key protector mode"),
+                       value);
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_init_cmd_handler (grub_extcmd_context_t ctxt, int argc,
+                                 char **args __attribute__ ((unused)))
+{
+  struct grub_arg_list *state = ctxt->state;
+  grub_err_t err;
+
+  if (argc)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("The TPM2 key protector does not accept any "
+                          "non-option arguments (i.e., like -o and/or --option "
+                          "only)"));
+
+  grub_free ((void *) grub_tpm2_protector_ctx.keyfile);
+  grub_memset (&grub_tpm2_protector_ctx, 0, sizeof (grub_tpm2_protector_ctx));
+
+  if (state[0].set)  /* mode */
+    {
+      err = grub_tpm2_protector_parse_mode (state[0].arg,
+                                            &grub_tpm2_protector_ctx.mode);
+      if (err)
+        return err;
+    }
+
+  if (state[1].set)  /* pcrs */
+    {
+      err = grub_tpm2_protector_parse_pcrs (state[1].arg,
+                                            grub_tpm2_protector_ctx.pcrs,
+                                            &grub_tpm2_protector_ctx.pcr_count);
+      if (err)
+        return err;
+    }
+
+  if (state[2].set)  /* bank */
+    {
+      err = grub_tpm2_protector_parse_bank (state[2].arg,
+                                            &grub_tpm2_protector_ctx.bank);
+      if (err)
+        return err;
+    }
+
+  if (state[3].set)  /* keyfile */
+    {
+      err = grub_tpm2_protector_parse_keyfile (state[3].arg,
+                                               &grub_tpm2_protector_ctx.keyfile);
+      if (err)
+        return err;
+    }
+
+  if (state[4].set)  /* srk */
+    {
+      err = grub_tpm2_protector_parse_tpm_handle (state[4].arg,
+                                                  &grub_tpm2_protector_ctx.srk);
+      if (err)
+        return err;
+    }
+
+  if (state[5].set)  /* asymmetric */
+    {
+      err = grub_tpm2_protector_parse_asymmetric (state[5].arg,
+                                                  &grub_tpm2_protector_ctx.asymmetric);
+      if (err)
+        return err;
+    }
+
+  if (state[6].set)  /* nvindex */
+    {
+      err = grub_tpm2_protector_parse_tpm_handle (state[6].arg,
+                                                  &grub_tpm2_protector_ctx.nv);
+      if (err)
+        return err;
+    }
+
+  err = grub_tpm2_protector_check_args (&grub_tpm2_protector_ctx);
+
+  /* This command only initializes the protector, so nothing else to do. */
+
+  return err;
+}
+
+static grub_err_t
+grub_tpm2_protector_clear_cmd_handler (grub_extcmd_context_t ctxt __attribute__ ((unused)),
+                                       int argc,
+                                       char **args __attribute__ ((unused)))
+{
+  if (argc)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("tpm2_key_protector_clear accepts no arguments"));
+
+  grub_free ((void *) grub_tpm2_protector_ctx.keyfile);
+  grub_memset (&grub_tpm2_protector_ctx, 0, sizeof (grub_tpm2_protector_ctx));
+
+  return GRUB_ERR_NONE;
+}
+
+static struct grub_key_protector grub_tpm2_key_protector =
+  {
+    .name = "tpm2",
+    .recover_key = grub_tpm2_protector_recover_key
+  };
+
+GRUB_MOD_INIT (tpm2)
+{
+  grub_tpm2_protector_init_cmd =
+    grub_register_extcmd ("tpm2_key_protector_init",
+                          grub_tpm2_protector_init_cmd_handler, 0,
+                          N_("[-m mode] "
+                             "[-p pcr_list] "
+                             "[-b pcr_bank] "
+                             "[-k sealed_key_file_path] "
+                             "[-s srk_handle] "
+                             "[-a asymmetric_key_type] "
+                             "[-n nv_index]"),
+                          N_("Initialize the TPM2 key protector."),
+                          grub_tpm2_protector_init_cmd_options);
+  grub_tpm2_protector_clear_cmd =
+    grub_register_extcmd ("tpm2_key_protector_clear",
+                          grub_tpm2_protector_clear_cmd_handler, 0, NULL,
+                          N_("Clear the TPM2 key protector if previously initialized."),
+                          NULL);
+  grub_key_protector_register (&grub_tpm2_key_protector);
+}
+
+GRUB_MOD_FINI (tpm2)
+{
+  grub_free ((void *) grub_tpm2_protector_ctx.keyfile);
+  grub_memset (&grub_tpm2_protector_ctx, 0, sizeof (grub_tpm2_protector_ctx));
+
+  grub_key_protector_unregister (&grub_tpm2_key_protector);
+  grub_unregister_extcmd (grub_tpm2_protector_clear_cmd);
+  grub_unregister_extcmd (grub_tpm2_protector_init_cmd);
+}
include/grub/tpm2/internal/args.h new file +39 -0
new file mode 100644
index 0000000..6341fce
@@ -0,0 +1,39 @@
+/*
+ *  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_TPM2_INTERNAL_ARGS_HEADER
+#define GRUB_TPM2_INTERNAL_ARGS_HEADER 1
+
+#include <grub/err.h>
+#include <grub/tpm2/tpm2.h>
+
+grub_err_t
+grub_tpm2_protector_parse_pcrs (char *value, grub_uint8_t *pcrs,
+                                grub_uint8_t *pcr_count);
+
+grub_err_t
+grub_tpm2_protector_parse_asymmetric (const char *value,
+                                      TPM_ALG_ID *asymmetric);
+
+grub_err_t
+grub_tpm2_protector_parse_bank (const char *value, TPM_ALG_ID *bank);
+
+grub_err_t
+grub_tpm2_protector_parse_tpm_handle (const char *value, TPM_HANDLE *handle);
+
+#endif /* ! GRUB_TPM2_INTERNAL_ARGS_HEADER */
Signature · 7 lines
1.8.3.1


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#5 lore raw

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

In reply to Hernan Gatta

On Tue, Feb 01, 2022 at 05:02:55AM -0800, Hernan Gatta wrote:

Sorry forgot to mention another build related issue in previous reply.

grub-core/tpm2/module.c line 198

Quoted 12 lines
grub-core/tpm2/module.c new file +12 -0
+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)
+    {
+      grub_dprintf ("tpm2", "Sealed key file is larger than decode buffer "
+                            "(%lu vs %lu bytes).\n", sealed_key_size, buf.cap);

This fails in i386-efi build with:

../../grub-core/tpm2/module.c: In function 'grub_tpm2_protector_srk_unmarshal_keyfile':
../../grub-core/tpm2/module.c:197:29: error: format '%lu' expects argument of type 'long unsigned int', but argument 5 has type 'grub_size_t' {aka 'unsigned int'} [-Werror=format=]

  197 |       grub_dprintf ("tpm2", "Sealed key file is larger than decode buffer "
      |                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  198 |                             "(%lu vs %lu bytes).\n", sealed_key_size, buf.cap);
      |                                                      ~~~~~~~~~~~~~~~
      |                                                      |
      |                                                      grub_size_t {aka unsigned int}

Maybe it's better to use generalized PRI[uxd]GRUB_.* macro defined in grub/types.h than lu to deal with platform dependent conversion specifiers.

Thanks,
Michael

Quoted 565 lines
grub-core/tpm2/module.c new file +512 -0
+      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);
+
+  if (buf.error)
+    {
+      grub_dprintf ("tpm2", "Could not unmarshal sealed key file, it is likely "
+                            "malformed.\n");
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  return 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)
+    {
+      grub_dprintf ("tpm2", "The SRK handle (0x%x) exists on the TPM but its "
+                            "public area could not be read (TPM2_ReadPublic "
+                            "failed with TSS/TPM error %u).\n", ctx->srk, rc);
+      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)
+    {
+      grub_dprintf ("tpm2", "Could not create SRK (TPM2_CreatePrimary failed "
+                            "with TSS/TPM error %u).\n", rc);
+      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 grub_error (err, N_("Failed to read key file %s"), ctx->keyfile);
+
+  err = grub_tpm2_protector_srk_unmarshal_keyfile (sealed_key_bytes,
+                                                   sealed_key_size,
+                                                   &sealed_key);
+  if (err)
+    {
+      grub_error (err, N_("Failed to unmarshal key, ensure the key file is in "
+                          "TPM wire format"));
+      goto exit1;
+    }
+
+  /* Get SRK */
+  err = grub_tpm2_protector_srk_get (ctx, &srk_handle);
+  if (err)
+    {
+      grub_error (err, N_("Failed to retrieve the SRK"));
+      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)
+    {
+      grub_error (err, N_("Failed to start auth session (TPM2_StartAuthSession "
+                          "failed with TSS/TPM error %u)"), 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)
+    {
+      grub_error (err, N_("Failed to submit PCR policy (TPM2_PolicyPCR failed "
+                          "with TSS/TPM error %u)"), 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)
+    {
+      grub_error (err, N_("Failed to load sealed key (TPM2_Load failed with "
+                          "TSS/TPM error %u)"), 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)
+    {
+      grub_error (err, N_("Failed to unseal sealed key (TPM2_Unseal failed "
+                          "with TSS/TPM error %u)"), rc);
+      goto exit4;
+    }
+
+  /* Epilogue */
+  key_out = grub_malloc (data.size);
+  if (!key_out)
+    {
+      err = GRUB_ERR_OUT_OF_MEMORY;
+      grub_error (err, N_("No memory left to allocate unlock key buffer"));
+      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_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                     N_("NV Index mode is 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 (grub_uint8_t **key, grub_size_t *key_size)
+{
+  grub_err_t err;
+
+  /* Expect a call to tpm2_protector_init before anybody tries to use us */
+  if (grub_tpm2_protector_ctx.mode == GRUB_TPM2_PROTECTOR_MODE_UNSET)
+    return grub_error (GRUB_ERR_INVALID_COMMAND,
+                       N_("Cannot use TPM2 key protector without initializing "
+                          "it, call tpm2_protector_init first"));
+
+  if (!key)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  err = grub_tpm2_protector_recover (&grub_tpm2_protector_ctx, key, key_size);
+  if (err)
+    return err;
+
+  return GRUB_ERR_NONE;
+}
+
+
+static grub_err_t
+grub_tpm2_protector_check_args (struct grub_tpm2_protector_context *ctx)
+{
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_UNSET)
+    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_SRK;
+
+  /* Checks for SRK mode */
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && !ctx->keyfile)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In SRK mode, a key file must be specified: "
+                          "--keyfile or -k"));
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && ctx->nv)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In SRK mode, an NV Index cannot be specified"));
+
+  /* Checks for NV mode */
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && !ctx->nv)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In NV Index mode, an NV Index must be specified: "
+                           "--nvindex or -n"));
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->keyfile)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In NV Index mode, a keyfile cannot be specified"));
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->srk)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In NV Index mode, an SRK cannot be specified"));
+
+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->asymmetric)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("In NV Index mode, an asymmetric key type cannot be "
+                          "specified"));
+
+  /* Defaults assignment */
+  if (!ctx->bank)
+    ctx->bank = TPM_ALG_SHA256;
+
+  if (!ctx->pcr_count)
+    {
+      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;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_keyfile (const char *value, const char **keyfile)
+{
+  if (grub_strlen (value) == 0)
+    return GRUB_ERR_BAD_ARGUMENT;
+
+  *keyfile = grub_strdup (value);
+  if (!*keyfile)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                       N_("No memory to duplicate keyfile path"));
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_parse_mode (const char *value,
+                                grub_tpm2_protector_mode_t *mode)
+{
+  if (grub_strcmp (value, "srk") == 0)
+    *mode = GRUB_TPM2_PROTECTOR_MODE_SRK;
+  else if (grub_strcmp (value, "nv") == 0)
+    *mode = GRUB_TPM2_PROTECTOR_MODE_NV;
+  else
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                       N_("Value '%s' is not a valid TPM2 key protector mode"),
+                       value);
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_tpm2_protector_init_cmd_handler (grub_extcmd_context_t ctxt, int argc,
+                                 char **args __attribute__ ((unused)))
+{
+  struct grub_arg_list *state = ctxt->state;
+  grub_err_t err;
+
+  if (argc)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("The TPM2 key protector does not accept any "
+                          "non-option arguments (i.e., like -o and/or --option "
+                          "only)"));
+
+  grub_free ((void *) grub_tpm2_protector_ctx.keyfile);
+  grub_memset (&grub_tpm2_protector_ctx, 0, sizeof (grub_tpm2_protector_ctx));
+
+  if (state[0].set)  /* mode */
+    {
+      err = grub_tpm2_protector_parse_mode (state[0].arg,
+                                            &grub_tpm2_protector_ctx.mode);
+      if (err)
+        return err;
+    }
+
+  if (state[1].set)  /* pcrs */
+    {
+      err = grub_tpm2_protector_parse_pcrs (state[1].arg,
+                                            grub_tpm2_protector_ctx.pcrs,
+                                            &grub_tpm2_protector_ctx.pcr_count);
+      if (err)
+        return err;
+    }
+
+  if (state[2].set)  /* bank */
+    {
+      err = grub_tpm2_protector_parse_bank (state[2].arg,
+                                            &grub_tpm2_protector_ctx.bank);
+      if (err)
+        return err;
+    }
+
+  if (state[3].set)  /* keyfile */
+    {
+      err = grub_tpm2_protector_parse_keyfile (state[3].arg,
+                                               &grub_tpm2_protector_ctx.keyfile);
+      if (err)
+        return err;
+    }
+
+  if (state[4].set)  /* srk */
+    {
+      err = grub_tpm2_protector_parse_tpm_handle (state[4].arg,
+                                                  &grub_tpm2_protector_ctx.srk);
+      if (err)
+        return err;
+    }
+
+  if (state[5].set)  /* asymmetric */
+    {
+      err = grub_tpm2_protector_parse_asymmetric (state[5].arg,
+                                                  &grub_tpm2_protector_ctx.asymmetric);
+      if (err)
+        return err;
+    }
+
+  if (state[6].set)  /* nvindex */
+    {
+      err = grub_tpm2_protector_parse_tpm_handle (state[6].arg,
+                                                  &grub_tpm2_protector_ctx.nv);
+      if (err)
+        return err;
+    }
+
+  err = grub_tpm2_protector_check_args (&grub_tpm2_protector_ctx);
+
+  /* This command only initializes the protector, so nothing else to do. */
+
+  return err;
+}
+
+static grub_err_t
+grub_tpm2_protector_clear_cmd_handler (grub_extcmd_context_t ctxt __attribute__ ((unused)),
+                                       int argc,
+                                       char **args __attribute__ ((unused)))
+{
+  if (argc)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("tpm2_key_protector_clear accepts no arguments"));
+
+  grub_free ((void *) grub_tpm2_protector_ctx.keyfile);
+  grub_memset (&grub_tpm2_protector_ctx, 0, sizeof (grub_tpm2_protector_ctx));
+
+  return GRUB_ERR_NONE;
+}
+
+static struct grub_key_protector grub_tpm2_key_protector =
+  {
+    .name = "tpm2",
+    .recover_key = grub_tpm2_protector_recover_key
+  };
+
+GRUB_MOD_INIT (tpm2)
+{
+  grub_tpm2_protector_init_cmd =
+    grub_register_extcmd ("tpm2_key_protector_init",
+                          grub_tpm2_protector_init_cmd_handler, 0,
+                          N_("[-m mode] "
+                             "[-p pcr_list] "
+                             "[-b pcr_bank] "
+                             "[-k sealed_key_file_path] "
+                             "[-s srk_handle] "
+                             "[-a asymmetric_key_type] "
+                             "[-n nv_index]"),
+                          N_("Initialize the TPM2 key protector."),
+                          grub_tpm2_protector_init_cmd_options);
+  grub_tpm2_protector_clear_cmd =
+    grub_register_extcmd ("tpm2_key_protector_clear",
+                          grub_tpm2_protector_clear_cmd_handler, 0, NULL,
+                          N_("Clear the TPM2 key protector if previously initialized."),
+                          NULL);
+  grub_key_protector_register (&grub_tpm2_key_protector);
+}
+
+GRUB_MOD_FINI (tpm2)
+{
+  grub_free ((void *) grub_tpm2_protector_ctx.keyfile);
+  grub_memset (&grub_tpm2_protector_ctx, 0, sizeof (grub_tpm2_protector_ctx));
+
+  grub_key_protector_unregister (&grub_tpm2_key_protector);
+  grub_unregister_extcmd (grub_tpm2_protector_clear_cmd);
+  grub_unregister_extcmd (grub_tpm2_protector_init_cmd);
+}
include/grub/tpm2/internal/args.h new file +39 -0
new file mode 100644
index 0000000..6341fce
@@ -0,0 +1,39 @@
+/*
+ *  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_TPM2_INTERNAL_ARGS_HEADER
+#define GRUB_TPM2_INTERNAL_ARGS_HEADER 1
+
+#include <grub/err.h>
+#include <grub/tpm2/tpm2.h>
+
+grub_err_t
+grub_tpm2_protector_parse_pcrs (char *value, grub_uint8_t *pcrs,
+                                grub_uint8_t *pcr_count);
+
+grub_err_t
+grub_tpm2_protector_parse_asymmetric (const char *value,
+                                      TPM_ALG_ID *asymmetric);
+
+grub_err_t
+grub_tpm2_protector_parse_bank (const char *value, TPM_ALG_ID *bank);
+
+grub_err_t
+grub_tpm2_protector_parse_tpm_handle (const char *value, TPM_HANDLE *handle);
+
+#endif /* ! GRUB_TPM2_INTERNAL_ARGS_HEADER */
Signature · 7 lines
1.8.3.1


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#6 lore raw

PATCH v2 4/5 cryptodisk: Support key protectors

In reply to Hernan Gatta

Add a new parameter to cryptomount to support the key protectors framework: -k. The parameter is used to automatically retrieve a key from specified key protectors. The parameter may be repeated to specify any number of key protectors. These are tried in order until one provides a usable key for any given disk.

Signed-off-by <Hernan Gatta [email protected]>
---
 Makefile.util.def           |   1 +
 grub-core/disk/cryptodisk.c | 166 ++++++++++++++++++++++++++++++++++++--------
 include/grub/cryptodisk.h   |  14 ++++
 3 files changed, 151 insertions(+), 30 deletions(-)
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 +136 -30

255 lines not on this page · raw message

include/grub/cryptodisk.h +14 -0
index c6524c9..b556498 100644
@@ -67,6 +67,16 @@ typedef gcry_err_code_t
 (*grub_cryptodisk_rekey_func_t) (struct grub_cryptodisk *dev,
 				 grub_uint64_t zoneno);
 
+struct grub_cryptomount_cached_key
+{
+  grub_uint8_t *key;
+  grub_size_t key_len;
+
+  /* The key protector associated with this cache entry failed, so avoid it
+   * even if the cached entry (an instance of this structure) is empty. */
+  int invalid;
+};
+
 struct grub_cryptomount_args
 {
   /* scan: Flag to indicate that only bootable volumes should be decrypted */
@@ -77,6 +87,10 @@ struct grub_cryptomount_args
   grub_uint8_t *key_data;
   /* recover_key: Length of key_data */
   grub_size_t key_len;
+  /* recover_key: Names of the key protectors to use (NULL-terminated) */
+  char **protectors;
+  /* recover_key: Key cache to avoid invoking the same key protector twice */
+  struct grub_cryptomount_cached_key *key_cache;
 };
 typedef struct grub_cryptomount_args *grub_cryptomount_args_t;
 
Signature · 1 line
1.8.3.1
#7 lore raw

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

In reply to Hernan Gatta

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 key protector (-k) parameter.

Sample usage:

$ dd if=/dev/urandom of=key bs=1 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:

tpm2_key_protector_init -k (hd0,gpt1)/boot/grub2/sealed_key cryptomount -u b20f95d0834842bc9197bd78b36732f8 -k tpm2

where the UUID corresponds to /dev/sdb1.

---
 .gitignore          |    1 +
 Makefile.util.def   |   18 +
 configure.ac        |    1 +
 util/grub-protect.c | 1314 +++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 1334 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 +18 -0
index 39b53b3..be2d6f4 100644
@@ -207,6 +207,24 @@ program = {
 };
 
 program = {
+  name = grub-protect;
+
+  common = grub-core/osdep/init.c;
+  common = grub-core/tpm2/args.c;
+  common = grub-core/tpm2/buffer.c;
+  common = grub-core/tpm2/mu.c;
+  common = grub-core/tpm2/tpm2.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 +1314 -0

1,314 lines not on this page · raw message

Signature · 1 line
1.8.3.1
#8 lore raw

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

On Tue, Feb 01, 2022 at 05:02:57AM -0800, Hernan Gatta wrote:

[snip]

Quoted 4 lines
util/grub-protect.c new file +4 -0
+static grub_err_t
+grub_protect_tpm2_get_policy_digest (struct grub_protect_args *args,
+                                     TPM2B_DIGEST *digest)
+{

[snip]

util/grub-protect.c line 546

Quoted 7 lines
util/grub-protect.c new file +7 -0
+  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);

Again please consider to use PRI[uxd]GRUB_.* for the conversion specifier, otherwise i386-efi will not build.

Thanks,
Michael

Quoted 776 lines
util/grub-protect.c new file +768 -0
+          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;
+    }
+}
+
+static grub_err_t
+grub_protect_tpm2_args_verify (struct grub_protect_args *args)
+{
+  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;
+        }
+
+      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";
+
+      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;
+
+      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 error_t
+grub_protect_argp_parser (int key, char *arg, struct argp_state *state)
+{
+  grub_err_t err;
+  struct grub_protect_args *args = state->input;
+
+  switch (key)
+    {
+    case GRUB_PROTECT_OPT_ACTION:
+      if (args->args & GRUB_PROTECT_ARG_ACTION)
+        {
+          fprintf (stderr, _("--action|-a can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      if (grub_strcmp (arg, "add") == 0)
+        args->action = GRUB_PROTECT_ACTION_ADD;
+      else if (grub_strcmp (arg, "remove") == 0)
+        args->action = GRUB_PROTECT_ACTION_REMOVE;
+      else
+        {
+          fprintf (stderr, _("'%s' is not a valid action.\n"), arg);
+          return EINVAL;
+        }
+
+      args->args |= GRUB_PROTECT_ARG_ACTION;
+      break;
+
+    case GRUB_PROTECT_OPT_PROTECTOR:
+      if (args->args & GRUB_PROTECT_ARG_PROTECTOR)
+        {
+          fprintf (stderr, _("--protector|-p can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      if (grub_strcmp (arg, "tpm2") == 0)
+        args->protector = GRUB_PROTECT_TYPE_TPM2;
+      else
+        {
+          fprintf (stderr, _("'%s' is not a valid protector.\n"), arg);
+          return EINVAL;
+        }
+
+      args->args |= GRUB_PROTECT_ARG_PROTECTOR;
+      break;
+
+    case GRUB_PROTECT_OPT_TPM2_DEVICE:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_DEVICE)
+        {
+          fprintf (stderr, _("--tpm2-device can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      args->tpm2_device = xstrdup(arg);
+      args->args |= GRUB_PROTECT_ARG_TPM2_DEVICE;
+      break;
+
+    case GRUB_PROTECT_OPT_TPM2_PCRS:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_PCRS)
+        {
+          fprintf (stderr, _("--tpm2-pcrs can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      err = grub_tpm2_protector_parse_pcrs (arg, args->tpm2_pcrs,
+                                            &args->tpm2_pcr_count);
+      if (err)
+        {
+          if (grub_errno)
+            grub_print_error ();
+          return EINVAL;
+        }
+
+      args->args |= GRUB_PROTECT_ARG_TPM2_PCRS;
+      break;
+
+    case GRUB_PROTECT_OPT_TPM2_SRK:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_SRK)
+        {
+          fprintf (stderr, _("--tpm2-srk can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      err = grub_tpm2_protector_parse_tpm_handle (arg, &args->tpm2_srk);
+      if (err)
+        {
+          if (grub_errno)
+            grub_print_error ();
+          return EINVAL;
+        }
+
+      args->args |= GRUB_PROTECT_ARG_TPM2_SRK;
+      break;
+
+    case GRUB_PROTECT_OPT_TPM2_ASYMMETRIC:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_ASYMMETRIC)
+        {
+          fprintf (stderr, _("--tpm2-asymmetric can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      err = grub_tpm2_protector_parse_asymmetric (arg, &args->tpm2_asymmetric);
+      if (err)
+        {
+          if (grub_errno)
+            grub_print_error ();
+          return EINVAL;
+        }
+
+      args->args |= GRUB_PROTECT_ARG_TPM2_ASYMMETRIC;
+      break;
+
+    case GRUB_PROTECT_OPT_TPM2_BANK:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_BANK)
+        {
+          fprintf (stderr, _("--tpm2-bank can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      err = grub_tpm2_protector_parse_bank (arg, &args->tpm2_bank);
+      if (err)
+        {
+          if (grub_errno)
+            grub_print_error ();
+          return EINVAL;
+        }
+
+      args->args |= GRUB_PROTECT_ARG_TPM2_BANK;
+      break;
+
+    case GRUB_PROTECT_OPT_TPM2_KEYFILE:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_KEYFILE)
+        {
+          fprintf (stderr, _("--tpm2-keyfile can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      args->tpm2_keyfile = xstrdup(arg);
+      args->args |= GRUB_PROTECT_ARG_TPM2_KEYFILE;
+      break;
+
+    case GRUB_PROTECT_OPT_TPM2_OUTFILE:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_OUTFILE)
+        {
+          fprintf (stderr, _("--tpm2-outfile can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      args->tpm2_outfile = xstrdup(arg);
+      args->args |= GRUB_PROTECT_ARG_TPM2_OUTFILE;
+      break;
+
+    case GRUB_PROTECT_OPT_TPM2_PERSIST:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_PERSIST)
+        {
+          fprintf (stderr, _("--tpm2-persist can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      args->tpm2_persist = 1;
+      args->args |= GRUB_PROTECT_ARG_TPM2_PERSIST;
+      break;
+
+    case GRUB_PROTECT_OPT_TPM2_EVICT:
+      if (args->args & GRUB_PROTECT_ARG_TPM2_EVICT)
+        {
+          fprintf (stderr, _("--tpm2-evict can only be specified once.\n"));
+          return EINVAL;
+        }
+
+      args->tpm2_evict = 1;
+      args->args |= GRUB_PROTECT_ARG_TPM2_EVICT;
+      break;
+
+    default:
+      return ARGP_ERR_UNKNOWN;
+    }
+
+  return 0;
+}
+
+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 key 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 ();
+}
+
+static struct argp grub_protect_argp =
+{
+  .options     = grub_protect_options,
+  .parser      = grub_protect_argp_parser,
+  .args_doc    = NULL,
+  .doc         =
+    N_("Protect a cleartext key using a GRUB key protector that can retrieve "
+       "the key during boot to unlock fully-encrypted disks automatically."),
+  .children    = NULL,
+  .help_filter = NULL,
+  .argp_domain = NULL
+};
+
+int
+main (int argc, char *argv[])
+{
+  grub_err_t err;
+  struct grub_protect_args args = { 0 };
+
+  if (argp_parse (&grub_protect_argp, argc, argv, 0, 0, &args) != 0)
+    {
+      fprintf (stderr, _("Could not parse arguments.\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  grub_protect_init (&argc, &argv);
+
+  err = grub_protect_args_verify (&args);
+  if (err)
+    goto exit;
+
+  err = grub_protect_dispatch (&args);
+  if (err)
+    goto exit;
+
+exit:
+  grub_protect_fini ();
+
+  return err;
+}
Signature · 7 lines
1.8.3.1


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#9 lore raw
In reply to Hernan Gatta

Hi,

pardon me to top post just once, the answer below was sent in reply to v1 but seems not to have made through as I do not find it in the archives, and it is about the proposal in general.

Here goes (initially posted on Tue, 25 Jan 2022):

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

Le 01/02/2022 à 14:02, Hernan Gatta a écrit :

Quoted 103 lines

Updates since v1:

1. One key can unlock multiple disks:
It is now possible to use key protectors with cryptomount's -a and -b options.

2. No passphrase prompt on error if key protector(s) specified:
cryptomount no longer prompts for a passphrase if key protectors are specified but fail to provide a working unlock key seeing as the user explicitly requested unlocking via key protectors.

3. Key protector parameterization is separate:
Previously, one would parameterize a key protector via a colon-separated argument list nested within a cryptomount argument. Now, key protectors are expected to provide an initialization function, if necessary.

As such, instead of:

cryptomount -k tpm2:mode=srk:keyfile=KEYFILE:pcrs=7,11...

one now writes:

tpm2_key_protector_init --mode=srk --keyfile=KEYFILE --pcrs=7,11 ... cryptomount -k tpm2

Additionally, one may write:

cryptomount -k protector_1 -k protector_2 ...

where cryptomount will try each in order on failure.

4. Standard argument parsing:
The TPM2 key protector now uses 'struct grub_arg_option' and the grub-protect tool uses 'struct argp_option'. Additionally, common argument parsing functionality is now shared between the module and the tool.

5. More useful messages:
Both the TPM2 module and the grub-protect tool now provide more useful messages to help the user learn how to use their functionality (--help and --usage) as well as to determine what is wrong, if anything. Furthermore, the module now prints additional debug output to help diagnose problems.

I forgot to mention last time that this patch series intends to address:
https://bugzilla.redhat.com/show_bug.cgi?id=1854177

Previous series:
https://lists.gnu.org/archive/html/grub-devel/2022-01/msg00125.html

Thank you,
Hernan

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                      |   19 +
 configure.ac                           |    1 +
 grub-core/Makefile.am                  |    1 +
 grub-core/Makefile.core.def            |   11 +
 grub-core/disk/cryptodisk.c            |  166 +++-
 grub-core/kern/protectors.c            |   75 ++
 grub-core/tpm2/args.c                  |  129 ++++
 grub-core/tpm2/buffer.c                |  145 ++++
 grub-core/tpm2/module.c                |  710 +++++++++++++++++
 grub-core/tpm2/mu.c                    |  807 ++++++++++++++++++++
 grub-core/tpm2/tcg2.c                  |  143 ++++
 grub-core/tpm2/tpm2.c                  |  711 +++++++++++++++++
 include/grub/cryptodisk.h              |   14 +
 include/grub/protector.h               |   48 ++
 include/grub/tpm2/buffer.h             |   65 ++
 include/grub/tpm2/internal/args.h      |   39 +
 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                    | 1314 ++++++++++++++++++++++++++++++++
 24 files changed, 5897 insertions(+), 30 deletions(-)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 grub-core/tpm2/args.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/args.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
#10 lore raw
In reply to Hernan Gatta

I really like the "key protector" interface as more of a generic provider interface. It seems like a great way to extend and create new unlock scenarios such as using security tokens, or chaining cryptographic features. If the interface is stable enough, it allows third party projects to create their own protector modules, so we don't wind up with people having to maintain full forks as happened with TrustedGrub.

To support this extensibility, I think labels for providers should be user-defined. The following is just scratching the surface of what's possible:

    tpm2_key_provider --name=platform --keyfile=/path/to/key
    passphrase_key_provider --name=pass
    xor_key_provider --name=combined --provider=platform --provider=pass
    cryptomount DISK1 --provider=combined

This would retrieve a key from the TPM, ask the user for a passphrase and then combine the two keys using xor, using the result to unlock the device. More advanced examples could use HSMs or biometric interfaces.

I think there only needs to be a few small changes to the interface (currently grub_key_protector) for this to happen:

1. It should be designed to store a reference to the context object
2. It should contain a function to cleanup the context object, wiping any sensitive data.
3. It should contain a user supplied label, and all key protector commands should require a user supplied label if they are registered.
4. The current name field should be renamed to 'module_name', for removing entries when the module is unloaded.

Basically something like:

  struct grub_key_producer
  {
    struct grub_key_producer *next;
    struct grub_key_producer **prev;
    const char *name;
    const char *module_name;
    void * ctx;

    grub_err_t (*recover_key) (grub_uint8_t **key, grub_size_t *key_size);
    grub_err_t (*destroy_ctx) (void * ctx);

};

I'll try and get a patch against master out this weekend supporting passphrase/keyfile providers.

--
Max Vohra

Quoted 103 lines · Hernan Gatta

Updates since v1:

1. One key can unlock multiple disks:
It is now possible to use key protectors with cryptomount's -a and -b options.

2. No passphrase prompt on error if key protector(s) specified:
cryptomount no longer prompts for a passphrase if key protectors are specified but fail to provide a working unlock key seeing as the user explicitly requested unlocking via key protectors.

3. Key protector parameterization is separate:
Previously, one would parameterize a key protector via a colon-separated argument list nested within a cryptomount argument. Now, key protectors are expected to provide an initialization function, if necessary.

As such, instead of:

cryptomount -k tpm2:mode=srk:keyfile=KEYFILE:pcrs=7,11...

one now writes:

tpm2_key_protector_init --mode=srk --keyfile=KEYFILE --pcrs=7,11 ... cryptomount -k tpm2

Additionally, one may write:

cryptomount -k protector_1 -k protector_2 ...

where cryptomount will try each in order on failure.

4. Standard argument parsing:
The TPM2 key protector now uses 'struct grub_arg_option' and the grub-protect tool uses 'struct argp_option'. Additionally, common argument parsing functionality is now shared between the module and the tool.

5. More useful messages:
Both the TPM2 module and the grub-protect tool now provide more useful messages to help the user learn how to use their functionality (--help and --usage) as well as to determine what is wrong, if anything. Furthermore, the module now prints additional debug output to help diagnose problems.

I forgot to mention last time that this patch series intends to address:
https://bugzilla.redhat.com/show_bug.cgi?id=1854177

Previous series:
https://lists.gnu.org/archive/html/grub-devel/2022-01/msg00125.html

Thank you,
Hernan

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                      |   19 +
  configure.ac                           |    1 +
  grub-core/Makefile.am                  |    1 +
  grub-core/Makefile.core.def            |   11 +
  grub-core/disk/cryptodisk.c            |  166 +++-
  grub-core/kern/protectors.c            |   75 ++
  grub-core/tpm2/args.c                  |  129 ++++
  grub-core/tpm2/buffer.c                |  145 ++++
  grub-core/tpm2/module.c                |  710 +++++++++++++++++
  grub-core/tpm2/mu.c                    |  807 ++++++++++++++++++++
  grub-core/tpm2/tcg2.c                  |  143 ++++
  grub-core/tpm2/tpm2.c                  |  711 +++++++++++++++++
  include/grub/cryptodisk.h              |   14 +
  include/grub/protector.h               |   48 ++
  include/grub/tpm2/buffer.h             |   65 ++
  include/grub/tpm2/internal/args.h      |   39 +
  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                    | 1314 ++++++++++++++++++++++++++++++++
  24 files changed, 5897 insertions(+), 30 deletions(-)

create mode 100644 grub-core/kern/protectors.c create mode 100644 grub-core/tpm2/args.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/args.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
Max Vohra
#11 lore raw
In reply to Hernan Gatta
Quoted 2 lines · Hernan Gatta

Updates since v1:

Hi,

Is there any further progress with this patchset?
I have prototype patchset to support authorized policy and it heavily rely on the TPM2 stack implemented by this patchset. Would love to see this patchset in upstream and contribute my patches.

Thanks,

Gary Lin

Quoted 105 lines

1. One key can unlock multiple disks:
It is now possible to use key protectors with cryptomount's -a and -b options.

2. No passphrase prompt on error if key protector(s) specified:
cryptomount no longer prompts for a passphrase if key protectors are specified but fail to provide a working unlock key seeing as the user explicitly requested unlocking via key protectors.

3. Key protector parameterization is separate:
Previously, one would parameterize a key protector via a colon-separated argument list nested within a cryptomount argument. Now, key protectors are expected to provide an initialization function, if necessary.

As such, instead of:

cryptomount -k tpm2:mode=srk:keyfile=KEYFILE:pcrs=7,11...

one now writes:

tpm2_key_protector_init --mode=srk --keyfile=KEYFILE --pcrs=7,11 ... cryptomount -k tpm2

Additionally, one may write:

cryptomount -k protector_1 -k protector_2 ...

where cryptomount will try each in order on failure.

4. Standard argument parsing:
The TPM2 key protector now uses 'struct grub_arg_option' and the grub-protect tool uses 'struct argp_option'. Additionally, common argument parsing functionality is now shared between the module and the tool.

5. More useful messages:
Both the TPM2 module and the grub-protect tool now provide more useful messages to help the user learn how to use their functionality (--help and --usage) as well as to determine what is wrong, if anything. Furthermore, the module now prints additional debug output to help diagnose problems.

I forgot to mention last time that this patch series intends to address:
https://bugzilla.redhat.com/show_bug.cgi?id=1854177

Previous series:
https://lists.gnu.org/archive/html/grub-devel/2022-01/msg00125.html

Thank you,
Hernan

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                      |   19 +
 configure.ac                           |    1 +
 grub-core/Makefile.am                  |    1 +
 grub-core/Makefile.core.def            |   11 +
 grub-core/disk/cryptodisk.c            |  166 +++-
 grub-core/kern/protectors.c            |   75 ++
 grub-core/tpm2/args.c                  |  129 ++++
 grub-core/tpm2/buffer.c                |  145 ++++
 grub-core/tpm2/module.c                |  710 +++++++++++++++++
 grub-core/tpm2/mu.c                    |  807 ++++++++++++++++++++
 grub-core/tpm2/tcg2.c                  |  143 ++++
 grub-core/tpm2/tpm2.c                  |  711 +++++++++++++++++
 include/grub/cryptodisk.h              |   14 +
 include/grub/protector.h               |   48 ++
 include/grub/tpm2/buffer.h             |   65 ++
 include/grub/tpm2/internal/args.h      |   39 +
 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                    | 1314 ++++++++++++++++++++++++++++++++
 24 files changed, 5897 insertions(+), 30 deletions(-)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 grub-core/tpm2/args.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/args.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