Skip to contentSkip to conversation

TPM2 key protector follow-up patches

PATCH Superseded Gary Lin via Grub-devel 4 participants 30 messages Jan 13, 2025 – Mar 26, 2025

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v3 cover TPM2 key protector follow-up patches

git: https://github.com/lcp/grub2/tree/tpm2-follow-up-v3

This patchset is the collection of several enhancements for TPM2 key protector.

* Patch 1 introduces the PCR dump to help debugging policy fail.
* Patch 2~3 adds the new command to dump PCRs in GRUB shell and the
* documentation of the command.
* Patch 4 fixes a minor issue in tss2.
* Patch 5~8 extends the NV index mode to support 'NV index' handles and TPM 2.0 Key File format.
- Thanks to James Bottomley for how to detect TPM 2.0 Key File format.

    https://lists.gnu.org/archive/html/grub-devel/2024-11/msg00078.html

* Patch 9~10 update the test cases and the documentation for NV index mode.

v3:
- Amending the function names to make them more comprehensive
- Fixing a few more typos and the indentations
- Improving the document

v2:
- Amending the commit messages and the error messages
- Fixing the return values and the checks for 'bool'
- Removing 'policywrite' when defining the NV index handle
- Fixing the typo and the stray whitespace
- Removing grub_tpm2_flushcontext() from the functions to remove the persistent handle and the NV index handle
- Avoiding one failure test case to stop the whole test
- Improving the document

Gary Lin (10):
tpm2_key_protector: dump PCRs on policy fail
tpm2_key_protector: Add 'tpm2_dump_pcr' command
docs: Document tpm2_dump_pcr
tss2: Fix the missing authCommand
tss2: Add TPM 2.0 NV index commands
tpm2_key_protector: Unseal key from a buffer
tpm2_key_protector: Support NV index handles util/grub-protect: Support NV index mode tests/tpm2_key_protector_test: Amend the NV index mode test
docs: Update NV index mode of TPM2 key protector

 docs/grub.texi                                | 202 ++++++++--
 .../commands/tpm2_key_protector/module.c      | 345 +++++++++++++++---
 grub-core/lib/tss2/tpm2_cmd.c                 | 211 ++++++++++-
 grub-core/lib/tss2/tpm2_cmd.h                 |  32 ++
 grub-core/lib/tss2/tss2_mu.c                  |  39 ++
 grub-core/lib/tss2/tss2_mu.h                  |  12 +
 grub-core/lib/tss2/tss2_types.h               |   6 +
 tests/tpm2_key_protector_test.in              | 155 +++-----
 util/grub-protect.c                           | 343 ++++++++++++++---
 9 files changed, 1113 insertions(+), 232 deletions(-)

Range-diff against v2:

 -:  --------- >  1:  cf2be1c66 tpm2_key_protector: dump PCRs on policy fail
 -:  --------- >  2:  052089a84 tpm2_key_protector: Add 'tpm2_dump_pcr' command
 -:  --------- >  3:  01f27df8a docs: Document tpm2_dump_pcr
 -:  --------- >  4:  242483c87 tss2: Fix the missing authCommand
 -:  --------- >  5:  3f0aca8af tss2: Add TPM 2.0 NV index commands
 1:  0e7b6fe17 !  6:  733b8c507 tpm2_key_protector: Unseal key from a buffer
    @@ grub-core/commands/tpm2_key_protector/module.c: tpm2_protector_dump_pcr (const T
      static grub_err_t
     -tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
     -			    grub_uint8_t **key, grub_size_t *key_size)
    -+tpm2_protector_unseal_buffer (const tpm2_protector_context_t *ctx,
    -+			      void *buffer, grub_size_t buf_size,
    -+			      grub_uint8_t **key, grub_size_t *key_size)
    ++tpm2_protector_key_from_buffer (const tpm2_protector_context_t *ctx,
    ++				void *buffer, grub_size_t buf_size,
    ++				grub_uint8_t **key, grub_size_t *key_size)
      {
        tpm2_sealed_key_t sealed_key = {0};
     -  void *file_bytes = NULL;
    @@ grub-core/commands/tpm2_key_protector/module.c: tpm2_protector_srk_recover (cons
     +  if (err != GRUB_ERR_NONE)
     +    return err;
     +
    -+  err = tpm2_protector_unseal_buffer (ctx, file_bytes, file_size, key, key_size);
    ++  err = tpm2_protector_key_from_buffer (ctx, file_bytes, file_size, key, key_size);
     +
        grub_free (file_bytes);
        return err;
 2:  1afe60a7e !  7:  b92cfb4b0 tpm2_key_protector: Support NV index handles
    @@ grub-core/commands/tpm2_key_protector/module.c: tpm2_protector_srk_recover (cons
      static grub_err_t
     -tpm2_protector_nv_recover (const tpm2_protector_context_t *ctx,
     -			   grub_uint8_t **key, grub_size_t *key_size)
    -+tpm2_protector_unseal_persistent (const tpm2_protector_context_t *ctx, TPM_HANDLE_t sealed_handle,
    -+				  grub_uint8_t **key, grub_size_t *key_size)
    ++tpm2_protector_load_persistent (const tpm2_protector_context_t *ctx, TPM_HANDLE_t sealed_handle,
    ++				grub_uint8_t **key, grub_size_t *key_size)
      {
     -  TPM_HANDLE_t sealed_handle = ctx->nv;
        tpm2key_policy_t policy_seq = NULL;
    @@ grub-core/commands/tpm2_key_protector/module.c: tpm2_protector_nv_recover (const
      }
      
     +static grub_err_t
    -+tpm2_protector_unseal_nvindex (const tpm2_protector_context_t *ctx, TPM_HANDLE_t nvindex,
    -+			       grub_uint8_t **key, grub_size_t *key_size)
    ++tpm2_protector_key_from_nvindex (const tpm2_protector_context_t *ctx, TPM_HANDLE_t nvindex,
    ++				 grub_uint8_t **key, grub_size_t *key_size)
     +{
     +  TPMS_AUTH_COMMAND_t authCmd = {0};
     +  TPM2B_NV_PUBLIC_t nv_public;
    @@ grub-core/commands/tpm2_key_protector/module.c: tpm2_protector_nv_recover (const
     +  if (rc != TPM_RC_SUCCESS)
     +    return grub_error (GRUB_ERR_BAD_ARGUMENT, "failed to read data from 0x%x (TPM2_NV_Read: 0x%x)", nvindex, rc);
     +
    -+  return tpm2_protector_unseal_buffer (ctx, data.buffer, data_size, key, key_size);
    ++  return tpm2_protector_key_from_buffer (ctx, data.buffer, data_size, key, key_size);
     +}
     +
     +static grub_err_t
    @@ grub-core/commands/tpm2_key_protector/module.c: tpm2_protector_nv_recover (const
     +  grub_err_t err;
     +
     +  if (TPM_HT_IS_PERSISTENT (ctx->nv) == true)
    -+    err = tpm2_protector_unseal_persistent (ctx, ctx->nv, key, key_size);
    ++    err = tpm2_protector_load_persistent (ctx, ctx->nv, key, key_size);
     +  else if (TPM_HT_IS_NVINDEX (ctx->nv) == true)
    -+    err = tpm2_protector_unseal_nvindex (ctx, ctx->nv, key, key_size);
    ++    err = tpm2_protector_key_from_nvindex (ctx, ctx->nv, key, key_size);
     +  else
     +    err = GRUB_ERR_BAD_ARGUMENT;
     +

3: e6e7982d5 ! 8: be4d93cb2 util/grub-protect: Support NV index mode
@@ Commit message
--tpm2-nvindex=0x1000000

+ Reviewed-by: Stefan Berger <[email protected]>

## util/grub-protect.c ##
@@ util/grub-protect.c: typedef enum protect_opt
@@ util/grub-protect.c: protect_tpm2_add (protect_args_t *args)
+ if (rc != TPM_RC_SUCCESS)
+ {
+ fprintf (stderr, "Handle 0x%x not found.\n", handle);
-+ return GRUB_ERR_BAD_ARGUMENT;;
++ return GRUB_ERR_BAD_ARGUMENT;
+ }
+
+ /* Undefine the nvindex handle */
4: 38de3037c ! 9: 15bce58ed tests/tpm2_key_protector_test: Amend the NV index mode test

    @@ Commit message
         that the other test cases could continue.
     
         Signed-off-by: Gary Lin <[email protected]>
    +    Reviewed-by: Stefan Berger <[email protected]>
     
      ## tests/tpm2_key_protector_test.in ##
     @@ tests/tpm2_key_protector_test.in: EOF
    @@ tests/tpm2_key_protector_test.in: srktests+=("ECC transient fallback_srk")
          tpm2_seal_unseal ${srktests[$i]} || ret=$?
          if [ "${ret}" -eq 0 ]; then
     -        echo "TPM2 [${srktests[$i]}]: PASS"
    -+        echo "TPM2 [SRK][${srktests[$i]}]: PASS"
    ++	echo "TPM2 [SRK][${srktests[$i]}]: PASS"
          elif [ "${ret}" -eq 1 ]; then
     -        echo "TPM2 [${srktests[$i]}]: FAIL"
    -+        echo "TPM2 [SRK][${srktests[$i]}]: FAIL"
    ++	echo "TPM2 [SRK][${srktests[$i]}]: FAIL"
     +	ret=0
          else
     -	echo "Unexpected failure [${srktests[$i]}]" >&2
 5:  d9bdd4bbc ! 10:  b782d0bdb docs: Update NV index mode of TPM2 key protector
    @@ docs/grub.texi: When/After the shim or GRUB are updated, it only requires to run
     -The last commands seal @file{luks.key} with the primary key and stores the
     -result in @kbd{0x81000000}.
     +If the key in the persistent handle becomes unwanted, the following
    -+@command{grub-protect} removes the specified persistent handle
    ++@command{grub-protect} command removes the specified persistent handle
     +@kbd{0x81000000}.
      
      @example
    @@ docs/grub.texi: When/After the shim or GRUB are updated, it only requires to run
     +so it can easily support both the TPM 2.0 Key File format as well as the raw
     +format.
     +
    -+The folloing @kbd{grub-protect} command seals the disk key @file{luks.key}
    ++The following @kbd{grub-protect} command seals the disk key @file{luks.key}
     +into the NV index handle @kbd{0x1000000} with the PCRs @kbd{0,2,4,7} while
     +using the TPM 2.0 Key File format.
      
    @@ docs/grub.texi: When/After the shim or GRUB are updated, it only requires to run
     +@end example
     +
     +Furthermore, it is also possible to insert an existing key file,
    -+@file{sealed.tpm}, into the specific NV index handle using the following
    ++@file{sealed.tpm}, into a specific NV index handle using the following
     +tpm2-tools (@url{https://github.com/tpm2-software/tpm2-tools}) commands.
     +
     +@example
    @@ docs/grub.texi: grub> @kbd{tpm2_key_protector_init -T (hd0,gpt1)/efi/grub/sealed
      grub> @kbd{cryptomount -u <UUID> -P tpm2}
      @end example
      
    -+Besides sealing the key into the file, @command{grub-protect} can seal the
    -+key into the TPM non-volatile memory. Here is the @command{grub-protect}
    -+command to seal the key into the NV index handle @samp{0x1000000}.
    ++Besides writing the PCR-sealed key into a file, @command{grub-protect} can
    ++write the sealed key into TPM non-volatile memory. Here is the
    ++@command{grub-protect} command to write the sealed key into the NV index
    ++handle @samp{0x1000000}.
     +
     +@example
     +@group
    @@ docs/grub.texi: grub> @kbd{tpm2_key_protector_init -T (hd0,gpt1)/efi/grub/sealed
     +@end group
     +@end example
     +
    -+Later, GRUB can fetch and unseal the key from @samp{0x1000000}.
    ++Later, GRUB can fetch the key from @samp{0x1000000}.
     +
     +@example
     +grub> @kbd{tpm2_key_protector_init --mode=nv --nvindex=0x1000000}
    @@ docs/grub.texi: grub> @kbd{tpm2_key_protector_init -T (hd0,gpt1)/efi/grub/sealed
     +handles and NV index handles, and @command{tpm2_getcap} can be used to
     +check the existing handles.
     +
    -+To get the existing persistent handles:
    ++To display the list of existing persistent handles:
     +
     +@example
     +@group
    @@ docs/grub.texi: grub> @kbd{tpm2_key_protector_init -T (hd0,gpt1)/efi/grub/sealed
     +@end group
     +@end example
     +
    -+Similarly, to get the existing nv-index handles:
    ++Similarly, to display the list of existing NV index handles:
     +
     +@example
     +@group
    @@ docs/grub.texi: grub> @kbd{tpm2_key_protector_init -T (hd0,gpt1)/efi/grub/sealed
     +@end group
     +@end example
     +
    -+If the sealed key in the handle is not needed anymore, the user can remove
    -+the handle with @kbd{--tpm2-nvindex} and @kbd{--tpm2-evict}. For example,
    -+this command removes the data from @samp{0x1000000}
    ++If the sealed key at an NV index handle is not needed anymore, the user can
    ++remove the handle with @kbd{--tpm2-nvindex} and @kbd{--tpm2-evict}. For
    ++example, this command removes the data from NV index @samp{0x1000000}:
     +
     +@example
     +@group
Signature · 7 lines
2.43.0


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

PATCH v3 1/10 tpm2_key_protector: dump PCRs on policy fail

PCR mismatching is one common cause of TPM key unsealing fail. Since the system may be compromised, it is not safe to boot into OS to get the PCR values and TPM eventlog for the further investigation.

To provide some hints, GRUB now dumps PCRs on policy fail, so the user can check the current PCR values. PCR 0~15 are chosen to cover the firmware, bootloader, and OS.

The sample output:

PCR Mismatching! Check firmware and bootloader before typing passphrase!
TPM PCR [sha256]:
00: 115c89bfa0e59e050cda5d2664031d225305f3582cf0c2afcb7c1f1ac2a7cf8d
01: 079b3eadca25e10248daea4b1d508e5cfb703db28386be809a0b375c0a0a80a5
02: 2cd8ec3de6a07e1fd39676100db57ba62372e820c19812fee55899f65746e192
03: 9423b585d4eac05c97a0c06bca8898ad0ca519a6b810dcb91129bcdc10f4b112
04: fa36bf5c9110d3891f040e2146d157484cd41123fa8faf4bc6b91db3d12b70ca
05: 13e9ea9e38e5258e6ee2b6ae94a3cece0137490ef95c65caaac10cdf5e1bc40d
06: 3ac10d749054a818806788f4e4eaa2fb4dd7d13ce0e99dc175145b63c34bb71c
07: a6657a60f77928cad614a7ad153ab9ae0bed48e33b70348ae11a26762002b3bc
08: 42e04f5bac1965535cb6bdb30c62bb199b1ba21d1ec6b22d0da159dfc925b8bb
09: 5c83e8be79d4a432e6d409610de389ee6f1ac0c193f38d84a9ff94f360bd458b
10: 0000000000000000000000000000000000000000000000000000000000000000
11: 0000000000000000000000000000000000000000000000000000000000000000
12: 0000000000000000000000000000000000000000000000000000000000000000
13: 0000000000000000000000000000000000000000000000000000000000000000
14: 894dd8e4ca1bb62e055f674f9390a39c4643ebdd1014702feef000c47e36a003
15: 0000000000000000000000000000000000000000000000000000000000000000
16: 0000000000000000000000000000000000000000000000000000000000000000
17: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
18: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
19: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
20: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
21: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
22: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
23: 0000000000000000000000000000000000000000000000000000000000000000
error: failed to unseal sealed key (TPM2_Unseal: 0x99d).
error: no key protector provided a usable key for luks (af16e48f-746b-4a12-aae1-c14dcee429e0).

If the user happens to have the PCR values for key sealing, the PCR dump can be used to identify the changed PCRs and narrow down the scope for closer inspection.

Please note that the PCR dump is trustworthy only if the GRUB binary is authentic, so the user has to check the GRUB binary thoroughly before using the PCR dump.

---
 .../commands/tpm2_key_protector/module.c      | 118 +++++++++++++++++-
 1 file changed, 114 insertions(+), 4 deletions(-)
grub-core/commands/tpm2_key_protector/module.c +114 -4
index 74e79a545..d5e530f77 100644
@@ -790,7 +790,7 @@ tpm2_protector_simple_policy_seq (const tpm2_protector_context_t *ctx,
 
 static grub_err_t
 tpm2_protector_unseal (tpm2key_policy_t policy_seq, TPM_HANDLE_t sealed_handle,
-		       grub_uint8_t **key, grub_size_t *key_size)
+		       grub_uint8_t **key, grub_size_t *key_size, bool *dump_pcr)
 {
   TPMS_AUTH_COMMAND_t authCmd = {0};
   TPM2B_SENSITIVE_DATA_t data;
@@ -801,6 +801,8 @@ tpm2_protector_unseal (tpm2key_policy_t policy_seq, TPM_HANDLE_t sealed_handle,
   TPM_RC_t rc;
   grub_err_t err;
 
+  *dump_pcr = false;
+
   /* Start Auth Session */
   nonceCaller.size = TPM_SHA256_DIGEST_SIZE;
   symmetric.algorithm = TPM_ALG_NULL;
@@ -820,6 +822,13 @@ tpm2_protector_unseal (tpm2key_policy_t policy_seq, TPM_HANDLE_t sealed_handle,
   rc = grub_tpm2_unseal (sealed_handle, &authCmd, &data, NULL);
   if (rc != TPM_RC_SUCCESS)
     {
+      /*
+       * Trigger PCR dump on policy fail
+       * TPM_RC_S (0x800) | TPM_RC_1 (0x100) | RC_FMT (0x80) | TPM_RC_POLICY_FAIL (0x1D)
+       */
+      if (rc == 0x99D)
+	*dump_pcr = true;
+
       err = grub_error (GRUB_ERR_BAD_DEVICE, "failed to unseal sealed key (TPM2_Unseal: 0x%x)", rc);
       goto error;
     }
@@ -845,6 +854,91 @@ tpm2_protector_unseal (tpm2key_policy_t policy_seq, TPM_HANDLE_t sealed_handle,
   return err;
 }
 
+#define TPM_PCR_STR_SIZE (sizeof (TPMU_HA_t) * 2 + 1)
+
+static grub_err_t
+tpm2_protector_get_pcr_str (const TPM_ALG_ID_t algo, grub_uint32_t index, char *pcr_str, grub_uint16_t buf_size)
+{
+  TPML_PCR_SELECTION_t pcr_sel = {
+    .count = 1,
+    .pcrSelections = {
+      {
+	.hash = algo,
+	.sizeOfSelect = 3,
+	.pcrSelect = {0}
+      },
+    }
+  };
+  TPML_DIGEST_t digest = {0};
+  grub_uint16_t i;
+  TPM_RC_t rc;
+
+  if (buf_size < TPM_PCR_STR_SIZE)
+    {
+      grub_snprintf (pcr_str, buf_size, "insufficient buffer");
+      return GRUB_ERR_OUT_OF_MEMORY;
+    }
+
+  TPMS_PCR_SELECTION_SelectPCR (&pcr_sel.pcrSelections[0], index);
+
+  rc = grub_tpm2_pcr_read (NULL, &pcr_sel, NULL, NULL, &digest, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      grub_snprintf (pcr_str, buf_size, "TPM2_PCR_Read: 0x%x", rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Check the returned digest number and size */
+  if (digest.count != 1 || digest.digests[0].size > sizeof (TPMU_HA_t))
+    {
+      grub_snprintf (pcr_str, buf_size, "invalid digest");
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Print the digest to the buffer */
+  for (i = 0; i < digest.digests[0].size; i++)
+    grub_snprintf (pcr_str + 2 * i, buf_size - 2 * i, "%02x", digest.digests[0].buffer[i]);
+
+  return GRUB_ERR_NONE;
+}
+
+static void
+tpm2_protector_dump_pcr (const TPM_ALG_ID_t bank)
+{
+  const char *algo_name;
+  char pcr_str[TPM_PCR_STR_SIZE];
+  grub_uint8_t i;
+  grub_err_t err;
+
+  if (bank == TPM_ALG_SHA1)
+    algo_name = "sha1";
+  else if (bank == TPM_ALG_SHA256)
+    algo_name = "sha256";
+  else if (bank == TPM_ALG_SHA384)
+    algo_name = "sha384";
+  else if (bank == TPM_ALG_SHA512)
+    algo_name = "sha512";
+  else
+    algo_name = "other";
+
+  /* Try to fetch PCR 0 */
+  err = tpm2_protector_get_pcr_str (bank, 0, pcr_str, sizeof (pcr_str));
+  if (err != GRUB_ERR_NONE)
+    {
+      grub_printf ("Unsupported PCR bank [%s]: %s\n", algo_name, pcr_str);
+      return;
+    }
+
+  grub_printf ("TPM PCR [%s]:\n", algo_name);
+
+  grub_printf ("  %02d: %s\n", 0, pcr_str);
+  for (i = 1; i < TPM_MAX_PCRS; i++)
+    {
+      tpm2_protector_get_pcr_str (bank, i, pcr_str, sizeof (pcr_str));
+      grub_printf ("  %02d: %s\n", i, pcr_str);
+    }
+}
+
 static grub_err_t
 tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
 			    grub_uint8_t **key, grub_size_t *key_size)
@@ -859,6 +953,7 @@ tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
   tpm2key_policy_t policy_seq = NULL;
   tpm2key_authpolicy_t authpol = NULL;
   tpm2key_authpolicy_t authpol_seq = NULL;
+  bool dump_pcr = false;
   grub_err_t err;
 
   /*
@@ -924,7 +1019,7 @@ tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
   /* Iterate the authpolicy sequence to find one that unseals the key */
   FOR_LIST_ELEMENTS (authpol, authpol_seq)
     {
-      err = tpm2_protector_unseal (authpol->policy_seq, sealed_handle, key, key_size);
+      err = tpm2_protector_unseal (authpol->policy_seq, sealed_handle, key, key_size, &dump_pcr);
       if (err == GRUB_ERR_NONE)
         break;
 
@@ -952,13 +1047,20 @@ tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
 	    goto exit2;
 	}
 
-      err = tpm2_protector_unseal (policy_seq, sealed_handle, key, key_size);
+      err = tpm2_protector_unseal (policy_seq, sealed_handle, key, key_size, &dump_pcr);
     }
 
   /* Pop error messages on success */
   if (err == GRUB_ERR_NONE)
     while (grub_error_pop ());
 
+  /* Dump PCRs if necessary */
+  if (dump_pcr == true)
+    {
+      grub_printf ("PCR Mismatch! Check firmware and bootloader before typing passphrase!\n");
+      tpm2_protector_dump_pcr (ctx->bank);
+    }
+
  exit2:
   grub_tpm2_flushcontext (sealed_handle);
 
@@ -978,6 +1080,7 @@ tpm2_protector_nv_recover (const tpm2_protector_context_t *ctx,
 {
   TPM_HANDLE_t sealed_handle = ctx->nv;
   tpm2key_policy_t policy_seq = NULL;
+  bool dump_pcr = false;
   grub_err_t err;
 
   /* Create a basic policy sequence based on the given PCR selection */
@@ -985,7 +1088,14 @@ tpm2_protector_nv_recover (const tpm2_protector_context_t *ctx,
   if (err != GRUB_ERR_NONE)
     goto exit;
 
-  err = tpm2_protector_unseal (policy_seq, sealed_handle, key, key_size);
+  err = tpm2_protector_unseal (policy_seq, sealed_handle, key, key_size, &dump_pcr);
+
+  /* Dump PCRs if necessary */
+  if (dump_pcr == true)
+    {
+      grub_printf ("PCR Mismatch! Check firmware and bootloader before typing passphrase!\n");
+      tpm2_protector_dump_pcr (ctx->bank);
+    }
 
  exit:
   grub_tpm2_flushcontext (sealed_handle);
Signature · 7 lines
2.43.0


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

Re: [PATCH v3 01/10] tpm2_key_protector: dump PCRs on policy fail

Quoted 11 lines · Gary Lin via Grub-devel

PCR mismatching is one common cause of TPM key unsealing fail. Since the system may be compromised, it is not safe to boot into OS to get the PCR values and TPM eventlog for the further investigation.

To provide some hints, GRUB now dumps PCRs on policy fail, so the user can check the current PCR values. PCR 0~15 are chosen to cover the firmware, bootloader, and OS.

The sample output:

PCR Mismatching! Check firmware and bootloader before typing passphrase!

s/Mismatching/Mismatch/

This suggests that this dump may not be produced by the code below. Please fix it as needed.

Quoted 32 lines

TPM PCR [sha256]:
00: 115c89bfa0e59e050cda5d2664031d225305f3582cf0c2afcb7c1f1ac2a7cf8d
01: 079b3eadca25e10248daea4b1d508e5cfb703db28386be809a0b375c0a0a80a5
02: 2cd8ec3de6a07e1fd39676100db57ba62372e820c19812fee55899f65746e192
03: 9423b585d4eac05c97a0c06bca8898ad0ca519a6b810dcb91129bcdc10f4b112
04: fa36bf5c9110d3891f040e2146d157484cd41123fa8faf4bc6b91db3d12b70ca
05: 13e9ea9e38e5258e6ee2b6ae94a3cece0137490ef95c65caaac10cdf5e1bc40d
06: 3ac10d749054a818806788f4e4eaa2fb4dd7d13ce0e99dc175145b63c34bb71c
07: a6657a60f77928cad614a7ad153ab9ae0bed48e33b70348ae11a26762002b3bc
08: 42e04f5bac1965535cb6bdb30c62bb199b1ba21d1ec6b22d0da159dfc925b8bb
09: 5c83e8be79d4a432e6d409610de389ee6f1ac0c193f38d84a9ff94f360bd458b
10: 0000000000000000000000000000000000000000000000000000000000000000
11: 0000000000000000000000000000000000000000000000000000000000000000
12: 0000000000000000000000000000000000000000000000000000000000000000
13: 0000000000000000000000000000000000000000000000000000000000000000
14: 894dd8e4ca1bb62e055f674f9390a39c4643ebdd1014702feef000c47e36a003
15: 0000000000000000000000000000000000000000000000000000000000000000
16: 0000000000000000000000000000000000000000000000000000000000000000
17: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
18: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
19: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
20: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
21: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
22: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
23: 0000000000000000000000000000000000000000000000000000000000000000
error: failed to unseal sealed key (TPM2_Unseal: 0x99d).
error: no key protector provided a usable key for luks (af16e48f-746b-4a12-aae1-c14dcee429e0).

If the user happens to have the PCR values for key sealing, the PCR dump can be used to identify the changed PCRs and narrow down the scope for closer inspection.

Quoted 6 lines

Please note that the PCR dump is trustworthy only if the GRUB binary is authentic, so the user has to check the GRUB binary thoroughly before using the PCR dump.

If you fix the nit mentioned above you can add my RB to this patch.

Daniel

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

#3 lore raw

Re: [PATCH v3 01/10] tpm2_key_protector: dump PCRs on policy fail

Quoted 9 lines · Daniel Kiper
Quoted 8 lines · Gary Lin via Grub-devel

PCR mismatching is one common cause of TPM key unsealing fail. Since the system may be compromised, it is not safe to boot into OS to get the PCR values and TPM eventlog for the further investigation.

To provide some hints, GRUB now dumps PCRs on policy fail, so the user can check the current PCR values. PCR 0~15 are chosen to cover the firmware, bootloader, and OS.

Quoted 9 lines
Quoted 3 lines

The sample output:

PCR Mismatching! Check firmware and bootloader before typing passphrase!

s/Mismatching/Mismatch/

This suggests that this dump may not be produced by the code below. Please fix it as needed.

Urgh, I forgot to update the commit message.

Quoted 32 lines
Quoted 32 lines

TPM PCR [sha256]:
00: 115c89bfa0e59e050cda5d2664031d225305f3582cf0c2afcb7c1f1ac2a7cf8d
01: 079b3eadca25e10248daea4b1d508e5cfb703db28386be809a0b375c0a0a80a5
02: 2cd8ec3de6a07e1fd39676100db57ba62372e820c19812fee55899f65746e192
03: 9423b585d4eac05c97a0c06bca8898ad0ca519a6b810dcb91129bcdc10f4b112
04: fa36bf5c9110d3891f040e2146d157484cd41123fa8faf4bc6b91db3d12b70ca
05: 13e9ea9e38e5258e6ee2b6ae94a3cece0137490ef95c65caaac10cdf5e1bc40d
06: 3ac10d749054a818806788f4e4eaa2fb4dd7d13ce0e99dc175145b63c34bb71c
07: a6657a60f77928cad614a7ad153ab9ae0bed48e33b70348ae11a26762002b3bc
08: 42e04f5bac1965535cb6bdb30c62bb199b1ba21d1ec6b22d0da159dfc925b8bb
09: 5c83e8be79d4a432e6d409610de389ee6f1ac0c193f38d84a9ff94f360bd458b
10: 0000000000000000000000000000000000000000000000000000000000000000
11: 0000000000000000000000000000000000000000000000000000000000000000
12: 0000000000000000000000000000000000000000000000000000000000000000
13: 0000000000000000000000000000000000000000000000000000000000000000
14: 894dd8e4ca1bb62e055f674f9390a39c4643ebdd1014702feef000c47e36a003
15: 0000000000000000000000000000000000000000000000000000000000000000
16: 0000000000000000000000000000000000000000000000000000000000000000
17: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
18: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
19: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
20: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
21: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
22: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
23: 0000000000000000000000000000000000000000000000000000000000000000
error: failed to unseal sealed key (TPM2_Unseal: 0x99d).
error: no key protector provided a usable key for luks (af16e48f-746b-4a12-aae1-c14dcee429e0).

If the user happens to have the PCR values for key sealing, the PCR dump can be used to identify the changed PCRs and narrow down the scope for closer inspection.

Quoted 9 lines
Quoted 6 lines

Please note that the PCR dump is trustworthy only if the GRUB binary is authentic, so the user has to check the GRUB binary thoroughly before using the PCR dump.

If you fix the nit mentioned above you can add my RB to this patch.

I'll update the commit message and add your RB.

Thanks,

Gary Lin

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

#4 lore raw

PATCH v3 2/10 tpm2_key_protector: Add 'tpm2_dump_pcr' command

In reply to Gary Lin via Grub-devel

The user may need to inspect the TPM 2.0 PCR values with the GRUB shell, so the new 'tpm2_dump_pcr' command is added to print all PCRs of the specified bank.

---
 .../commands/tpm2_key_protector/module.c      | 35 +++++++++++++++++++
 1 file changed, 35 insertions(+)
grub-core/commands/tpm2_key_protector/module.c +35 -0
index d5e530f77..0a5d81e4c 100644
@@ -160,6 +160,8 @@ static grub_extcmd_t tpm2_protector_init_cmd;
 static grub_extcmd_t tpm2_protector_clear_cmd;
 static tpm2_protector_context_t tpm2_protector_ctx = {0};
 
+static grub_command_t tpm2_dump_pcr_cmd;
+
 static grub_err_t
 tpm2_protector_srk_read_file (const char *filepath, void **buffer, grub_size_t *buffer_size)
 {
@@ -1315,6 +1317,33 @@ static struct grub_key_protector tpm2_key_protector =
     .recover_key = tpm2_protector_recover_key
   };
 
+static grub_err_t
+tpm2_dump_pcr (grub_command_t cmd __attribute__((__unused__)),
+	       int argc, char *argv[])
+{
+  TPM_ALG_ID_t pcr_bank;
+
+  if (argc == 0)
+    pcr_bank = TPM_ALG_SHA256;
+  else if (grub_strcmp (argv[0], "sha1") == 0)
+    pcr_bank = TPM_ALG_SHA1;
+  else if (grub_strcmp (argv[0], "sha256") == 0)
+    pcr_bank = TPM_ALG_SHA256;
+  else if (grub_strcmp (argv[0], "sha384") == 0)
+    pcr_bank = TPM_ALG_SHA384;
+  else if (grub_strcmp (argv[0], "sha512") == 0)
+    pcr_bank = TPM_ALG_SHA512;
+  else
+    {
+      grub_printf ("Unknown PCR bank\n");
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  tpm2_protector_dump_pcr (pcr_bank);
+
+  return GRUB_ERR_NONE;
+}
+
 GRUB_MOD_INIT (tpm2_key_protector)
 {
   tpm2_protector_init_cmd =
@@ -1336,6 +1365,10 @@ GRUB_MOD_INIT (tpm2_key_protector)
 			  N_("Clear the TPM2 key protector if previously initialized."),
 			  NULL);
   grub_key_protector_register (&tpm2_key_protector);
+
+  tpm2_dump_pcr_cmd =
+    grub_register_command ("tpm2_dump_pcr", tpm2_dump_pcr, N_("Dump TPM2 PCRs"),
+			   N_("Print all PCRs of the specified TPM 2.0 bank"));
 }
 
 GRUB_MOD_FINI (tpm2_key_protector)
@@ -1345,4 +1378,6 @@ GRUB_MOD_FINI (tpm2_key_protector)
   grub_key_protector_unregister (&tpm2_key_protector);
   grub_unregister_extcmd (tpm2_protector_clear_cmd);
   grub_unregister_extcmd (tpm2_protector_init_cmd);
+
+  grub_unregister_command (tpm2_dump_pcr_cmd);
 }
Signature · 7 lines
2.43.0


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

Re: [PATCH v3 02/10] tpm2_key_protector: Add 'tpm2_dump_pcr' command

Quoted 3 lines · Gary Lin via Grub-devel

The user may need to inspect the TPM 2.0 PCR values with the GRUB shell, so the new 'tpm2_dump_pcr' command is added to print all PCRs of the specified bank.

Please update a documentation as well.

Daniel

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

#6 lore raw

Re: [PATCH v3 02/10] tpm2_key_protector: Add 'tpm2_dump_pcr' command

Quoted 6 lines · Daniel Kiper
Quoted 3 lines · Gary Lin via Grub-devel

The user may need to inspect the TPM 2.0 PCR values with the GRUB shell, so the new 'tpm2_dump_pcr' command is added to print all PCRs of the specified bank.

Please update a documentation as well.

Ugh... Sorry, now I can see the docs update in next patch. Please merge it with this one. Feel free to add my RB to this patch if you do that.

Daniel

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

#7 lore raw

Re: [PATCH v3 02/10] tpm2_key_protector: Add 'tpm2_dump_pcr' command

Quoted 11 lines · Daniel Kiper
Quoted 6 lines · Daniel Kiper
Quoted 3 lines · Gary Lin via Grub-devel

The user may need to inspect the TPM 2.0 PCR values with the GRUB shell, so the new 'tpm2_dump_pcr' command is added to print all PCRs of the specified bank.

Please update a documentation as well.

Ugh... Sorry, now I can see the docs update in next patch. Please merge it with this one. Feel free to add my RB to this patch if you do that.

No problem. I'll merge the doc patch and mention it in the commit message.

Thanks,

Gary Lin

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

#8 lore raw

PATCH v3 3/10 docs: Document tpm2_dump_pcr

In reply to Gary Lin via Grub-devel

Update the documentation to address tpm2_dump_pcr.

---
 docs/grub.texi | 13 +++++++++++++
 1 file changed, 13 insertions(+)
docs/grub.texi +13 -0
index 200e747af..aba43e35e 100644
@@ -6433,6 +6433,7 @@ you forget a command, you can run the command @command{help}
 * test::                        Check file types and compare values
 * tpm2_key_protector_init::     Initialize the TPM2 key protector
 * tpm2_key_protector_clear::    Clear the TPM2 key protector
+* tpm2_dump_pcr::               Dump TPM2 PCRs
 * true::                        Do nothing, successfully
 * trust::                       Add public key to list of trusted keys
 * unset::                       Unset an environment variable
@@ -8044,6 +8045,18 @@ key and unseal it with the given PCR list and bank.
 Clear the TPM2 key protector if previously initialized.
 @end deffn
 
+@node tpm2_dump_pcr
+@subsection tpm2_dump_pcr
+
+@deffn Command tpm2_dump_pcr [@var{bank}]
+Print all PCRs of the specified TPM 2.0 @var{bank}. The supported banks are
+@samp{sha1}, @samp{sha256}, @samp{sha384}, and @samp{sha512}. If @var{bank}
+is not specified, @samp{sha256} is chosen by default.
+
+Since GRUB measures every command into PCR 8, invoking @command{tpm2_dump_pcr}
+also extends PCR 8, so PCR 8 will not be a stable value in GRUB shell.
+@end deffn
+
 @node true
 @subsection true
 
Signature · 7 lines
2.43.0


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

PATCH v3 4/10 tss2: Fix the missing authCommand

In reply to Gary Lin via Grub-devel

grub_tpm2_readpublic() and grub_tpm2_testparms() didn't check 'authCommand' when marshaling the input data buffer. Currently, there is no caller using non-NULL 'authCommand'. However, to avoid the potential issue, the conditional check is added to insert 'authCommand' into the input buffer if necessary.

Also fix a few pointer checks.

---
 grub-core/lib/tss2/tpm2_cmd.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
grub-core/lib/tss2/tpm2_cmd.c +7 -3
index cd0c6fd31..211d807d5 100644
@@ -341,6 +341,8 @@ grub_tpm2_readpublic (const TPMI_DH_OBJECT_t objectHandle,
   /* Marshal */
   grub_tpm2_buffer_init (&in);
   grub_tpm2_buffer_pack_u32 (&in, objectHandle);
+  if (authCommand != NULL)
+    grub_Tss2_MU_TPMS_AUTH_COMMAND_Marshal (&in, authCommand);
   if (in.error != 0)
     return TPM_RC_FAILURE;
 
@@ -398,7 +400,7 @@ grub_tpm2_load (const TPMI_DH_OBJECT_t parent_handle,
   /* Marshal */
   grub_tpm2_buffer_init (&in);
   grub_tpm2_buffer_pack_u32 (&in, parent_handle);
-  if (authCommand)
+  if (authCommand != NULL)
     grub_Tss2_MU_TPMS_AUTH_COMMAND_Marshal (&in, authCommand);
   grub_Tss2_MU_TPM2B_Marshal (&in, inPrivate->size, inPrivate->buffer);
   grub_Tss2_MU_TPM2B_PUBLIC_Marshal (&in, inPublic);
@@ -461,9 +463,9 @@ grub_tpm2_loadexternal (const TPMS_AUTH_COMMAND_t *authCommand,
 
   /* Marshal */
   grub_tpm2_buffer_init (&in);
-  if (authCommand)
+  if (authCommand != NULL)
     grub_Tss2_MU_TPMS_AUTH_COMMAND_Marshal (&in, authCommand);
-  if (inPrivate)
+  if (inPrivate != NULL)
     grub_Tss2_MU_TPM2B_SENSITIVE_Marshal (&in, inPrivate);
   else
     grub_tpm2_buffer_pack_u16 (&in, 0);
@@ -1023,6 +1025,8 @@ grub_tpm2_testparms (const TPMT_PUBLIC_PARMS_t *parms,
   /* Marshal */
   grub_tpm2_buffer_init (&in);
   grub_Tss2_MU_TPMT_PUBLIC_PARMS_Marshal (&in, parms);
+  if (authCommand != NULL)
+    grub_Tss2_MU_TPMS_AUTH_COMMAND_Marshal (&in, authCommand);
   if (in.error != 0)
     return TPM_RC_FAILURE;
 
Signature · 7 lines
2.43.0


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v3 4/10
#10 lore raw

Re: [PATCH v3 04/10] tss2: Fix the missing authCommand

Quoted 10 lines · Gary Lin via Grub-devel

grub_tpm2_readpublic() and grub_tpm2_testparms() didn't check 'authCommand' when marshaling the input data buffer. Currently, there is no caller using non-NULL 'authCommand'. However, to avoid the potential issue, the conditional check is added to insert 'authCommand' into the input buffer if necessary.

Also fix a few pointer checks.

Daniel

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

#11 lore raw

PATCH v3 5/10 tss2: Add TPM 2.0 NV index commands

In reply to Gary Lin via Grub-devel

The following TPM 2.0 commands are introduced to tss2 to access the TPM non-volatile memory associated with the NV index handles.

- TPM2_NV_DefineSpace
- TPM2_NV_UndefineSpace
- TPM2_NV_ReadPublic
- TPM2_NV_Read
- TPM2_NV_Write

The related marshal/unmarshal functions are also introduced.

---
 grub-core/lib/tss2/tpm2_cmd.c   | 201 ++++++++++++++++++++++++++++++++
 grub-core/lib/tss2/tpm2_cmd.h   |  32 +++++
 grub-core/lib/tss2/tss2_mu.c    |  39 +++++++
 grub-core/lib/tss2/tss2_mu.h    |  12 ++
 grub-core/lib/tss2/tss2_types.h |   6 +
 5 files changed, 290 insertions(+)
grub-core/lib/tss2/tpm2_cmd.c +201 -0
index 211d807d5..6d25db1ab 100644
@@ -1045,3 +1045,204 @@ grub_tpm2_testparms (const TPMT_PUBLIC_PARMS_t *parms,
 
   return TPM_RC_SUCCESS;
 }
+
+TPM_RC_t
+grub_tpm2_nv_definespace (const TPMI_RH_PROVISION_t authHandle,
+			  const TPMS_AUTH_COMMAND_t *authCommand,
+			  const TPM2B_AUTH_t *auth,
+			  const TPM2B_NV_PUBLIC_t *publicInfo)
+{
+  TPM_RC_t rc;
+  struct grub_tpm2_buffer in;
+  struct grub_tpm2_buffer out;
+  TPMI_ST_COMMAND_TAG_t tag = authCommand ? TPM_ST_SESSIONS : TPM_ST_NO_SESSIONS;
+  TPM_RC_t responseCode;
+
+  if (publicInfo == NULL)
+    return TPM_RC_VALUE;
+
+  /* Marshal */
+  grub_tpm2_buffer_init (&in);
+  grub_tpm2_buffer_pack_u32 (&in, authHandle);
+  if (authCommand != NULL)
+    grub_Tss2_MU_TPMS_AUTH_COMMAND_Marshal (&in, authCommand);
+  if (auth != NULL)
+    grub_Tss2_MU_TPM2B_Marshal (&in, auth->size, auth->buffer);
+  else
+    grub_tpm2_buffer_pack_u16 (&in, 0);
+  grub_Tss2_MU_TPM2B_NV_PUBLIC_Marshal (&in, publicInfo);
+  if (in.error != 0)
+    return TPM_RC_FAILURE;
+
+  /* Submit */
+  grub_tpm2_buffer_init (&out);
+  rc = tpm2_submit_command (tag, TPM_CC_NV_DefineSpace, &responseCode, &in, &out);
+  if (rc != TPM_RC_SUCCESS)
+    return rc;
+  if (responseCode != TPM_RC_SUCCESS)
+    return responseCode;
+
+  /* Unmarshal */
+  if (out.error != 0)
+    return TPM_RC_FAILURE;
+
+  return TPM_RC_SUCCESS;
+}
+
+TPM_RC_t
+grub_tpm2_nv_undefinespace (const TPMI_RH_PROVISION_t authHandle,
+			    const TPMI_RH_NV_INDEX_t nvIndex,
+			    const TPMS_AUTH_COMMAND_t *authCommand)
+{
+  TPM_RC_t rc;
+  struct grub_tpm2_buffer in;
+  struct grub_tpm2_buffer out;
+  TPMI_ST_COMMAND_TAG_t tag = authCommand ? TPM_ST_SESSIONS : TPM_ST_NO_SESSIONS;
+  TPM_RC_t responseCode;
+
+  /* Marshal */
+  grub_tpm2_buffer_init (&in);
+  grub_tpm2_buffer_pack_u32 (&in, authHandle);
+  grub_tpm2_buffer_pack_u32 (&in, nvIndex);
+  if (authCommand != NULL)
+    grub_Tss2_MU_TPMS_AUTH_COMMAND_Marshal (&in, authCommand);
+  if (in.error != 0)
+    return TPM_RC_FAILURE;
+
+  /* Submit */
+  grub_tpm2_buffer_init (&out);
+  rc = tpm2_submit_command (tag, TPM_CC_NV_UndefineSpace, &responseCode, &in, &out);
+  if (rc != TPM_RC_SUCCESS)
+    return rc;
+  if (responseCode != TPM_RC_SUCCESS)
+    return responseCode;
+
+  /* Unmarshal */
+  if (out.error != 0)
+    return TPM_RC_FAILURE;
+
+  return TPM_RC_SUCCESS;
+}
+
+TPM_RC_t
+grub_tpm2_nv_readpublic (const TPMI_RH_NV_INDEX_t nvIndex,
+			 const TPMS_AUTH_COMMAND_t *authCommand,
+			 TPM2B_NV_PUBLIC_t *nvPublic,
+			 TPM2B_NAME_t *nvName)
+{
+  TPM_RC_t rc;
+  struct grub_tpm2_buffer in;
+  struct grub_tpm2_buffer out;
+  TPMI_ST_COMMAND_TAG_t tag = authCommand ? TPM_ST_SESSIONS : TPM_ST_NO_SESSIONS;
+  TPM_RC_t responseCode;
+  grub_uint32_t param_size;
+
+  /* Marshal */
+  grub_tpm2_buffer_init (&in);
+  grub_tpm2_buffer_pack_u32 (&in, nvIndex);
+  if (authCommand != NULL)
+    grub_Tss2_MU_TPMS_AUTH_COMMAND_Marshal (&in, authCommand);
+  if (in.error != 0)
+    return TPM_RC_FAILURE;
+
+  /* Submit */
+  grub_tpm2_buffer_init (&out);
+  rc = tpm2_submit_command (tag, TPM_CC_NV_ReadPublic, &responseCode, &in, &out);
+  if (rc != TPM_RC_SUCCESS)
+    return rc;
+  if (responseCode != TPM_RC_SUCCESS)
+    return responseCode;
+
+  /* Unmarshal */
+  if (tag == TPM_ST_SESSIONS)
+    grub_tpm2_buffer_unpack_u32 (&out, &param_size);
+  grub_Tss2_MU_TPM2B_NV_PUBLIC_Unmarshal (&out, nvPublic);
+  grub_Tss2_MU_TPM2B_NAME_Unmarshal (&out, nvName);
+  if (out.error != 0)
+    return TPM_RC_FAILURE;
+
+  return TPM_RC_SUCCESS;
+}
+
+TPM_RC_t
+grub_tpm2_nv_read (const TPMI_RH_NV_AUTH_t authHandle,
+		   const TPMI_RH_NV_INDEX_t nvIndex,
+		   const TPMS_AUTH_COMMAND_t *authCommand,
+		   const grub_uint16_t size,
+		   const grub_uint16_t offset,
+		   TPM2B_MAX_NV_BUFFER_t *data)
+{
+  TPM_RC_t rc;
+  struct grub_tpm2_buffer in;
+  struct grub_tpm2_buffer out;
+  TPMI_ST_COMMAND_TAG_t tag = authCommand ? TPM_ST_SESSIONS : TPM_ST_NO_SESSIONS;
+  TPM_RC_t responseCode;
+  grub_uint32_t param_size;
+
+  /* Marshal */
+  grub_tpm2_buffer_init (&in);
+  grub_tpm2_buffer_pack_u32 (&in, authHandle);
+  grub_tpm2_buffer_pack_u32 (&in, nvIndex);
+  if (authCommand != NULL)
+    grub_Tss2_MU_TPMS_AUTH_COMMAND_Marshal (&in, authCommand);
+  grub_tpm2_buffer_pack_u16 (&in, size);
+  grub_tpm2_buffer_pack_u16 (&in, offset);
+  if (in.error != 0)
+    return TPM_RC_FAILURE;
+
+  /* Submit */
+  grub_tpm2_buffer_init (&out);
+  rc = tpm2_submit_command (tag, TPM_CC_NV_Read, &responseCode, &in, &out);
+  if (rc != TPM_RC_SUCCESS)
+    return rc;
+  if (responseCode != TPM_RC_SUCCESS)
+    return responseCode;
+
+  /* Unmarshal */
+  if (tag == TPM_ST_SESSIONS)
+    grub_tpm2_buffer_unpack_u32 (&out, &param_size);
+  grub_Tss2_MU_TPM2B_NAX_NV_BUFFER_Unmarshal (&out, data);
+  if (out.error != 0)
+    return TPM_RC_FAILURE;
+
+  return TPM_RC_SUCCESS;
+}
+
+TPM_RC_t
+grub_tpm2_nv_write (const TPMI_RH_NV_AUTH_t authHandle,
+		    const TPMI_RH_NV_INDEX_t nvIndex,
+		    const TPMS_AUTH_COMMAND_t *authCommand,
+		    const TPM2B_MAX_NV_BUFFER_t *data,
+		    const grub_uint16_t offset)
+{
+  TPM_RC_t rc;
+  struct grub_tpm2_buffer in;
+  struct grub_tpm2_buffer out;
+  TPMI_ST_COMMAND_TAG_t tag = authCommand ? TPM_ST_SESSIONS : TPM_ST_NO_SESSIONS;
+  TPM_RC_t responseCode;
+
+  /* Marshal */
+  grub_tpm2_buffer_init (&in);
+  grub_tpm2_buffer_pack_u32 (&in, authHandle);
+  grub_tpm2_buffer_pack_u32 (&in, nvIndex);
+  if (authCommand != NULL)
+    grub_Tss2_MU_TPMS_AUTH_COMMAND_Marshal (&in, authCommand);
+  grub_Tss2_MU_TPM2B_Marshal (&in, data->size, data->buffer);
+  grub_tpm2_buffer_pack_u16 (&in, offset);
+  if (in.error != 0)
+    return TPM_RC_FAILURE;
+
+  /* Submit */
+  grub_tpm2_buffer_init (&out);
+  rc = tpm2_submit_command (tag, TPM_CC_NV_Write, &responseCode, &in, &out);
+  if (rc != TPM_RC_SUCCESS)
+    return rc;
+  if (responseCode != TPM_RC_SUCCESS)
+    return responseCode;
+
+  /* Unmarshal */
+  if (out.error != 0)
+    return TPM_RC_FAILURE;
+
+  return TPM_RC_SUCCESS;
+}
grub-core/lib/tss2/tpm2_cmd.h +32 -0
index d313cba00..90b42efec 100644
@@ -154,4 +154,36 @@ extern TPM_RC_t
 grub_tpm2_testparms (const TPMT_PUBLIC_PARMS_t *parms,
 		     const TPMS_AUTH_COMMAND_t *authCommand);
 
+extern TPM_RC_t
+grub_tpm2_nv_definespace (const TPMI_RH_PROVISION_t authHandle,
+			  const TPMS_AUTH_COMMAND_t *authCommand,
+			  const TPM2B_AUTH_t *auth,
+			  const TPM2B_NV_PUBLIC_t *publicInfo);
+
+extern TPM_RC_t
+grub_tpm2_nv_undefinespace (const TPMI_RH_PROVISION_t authHandle,
+			    const TPMI_RH_NV_INDEX_t nvIndex,
+			    const TPMS_AUTH_COMMAND_t *authCommand);
+
+extern TPM_RC_t
+grub_tpm2_nv_readpublic (const TPMI_RH_NV_INDEX_t nvIndex,
+			 const TPMS_AUTH_COMMAND_t *authCommand,
+			 TPM2B_NV_PUBLIC_t *nvPublic,
+			 TPM2B_NAME_t *nvName);
+
+extern TPM_RC_t
+grub_tpm2_nv_read (const TPMI_RH_NV_AUTH_t authHandle,
+		   const TPMI_RH_NV_INDEX_t nvIndex,
+		   const TPMS_AUTH_COMMAND_t *authCommand,
+		   const grub_uint16_t size,
+		   const grub_uint16_t offset,
+		   TPM2B_MAX_NV_BUFFER_t *data);
+
+extern TPM_RC_t
+grub_tpm2_nv_write (const TPMI_RH_NV_AUTH_t authHandle,
+		    const TPMI_RH_NV_INDEX_t nvIndex,
+		    const TPMS_AUTH_COMMAND_t *authCommand,
+		    const TPM2B_MAX_NV_BUFFER_t *data,
+		    const grub_uint16_t offset);
+
 #endif /* ! GRUB_TPM2_COMMANDS_HEADER */
grub-core/lib/tss2/tss2_mu.c +39 -0
index 86134cc0a..816e5b37f 100644
@@ -17,6 +17,7 @@
  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+#include <grub/mm.h>
 #include <grub/misc.h>
 
 #include <tss2_mu.h>
@@ -572,6 +573,37 @@ grub_Tss2_MU_TPMT_TK_VERIFIED_Marshal (grub_tpm2_buffer_t buffer,
   grub_Tss2_MU_TPM2B_Marshal (buffer, p->digest.size, p->digest.buffer);
 }
 
+void
+grub_Tss2_MU_TPMS_NV_PUBLIC_Marshal (grub_tpm2_buffer_t buffer,
+				     const TPMS_NV_PUBLIC_t *p)
+{
+  grub_tpm2_buffer_pack_u32 (buffer, p->nvIndex);
+  grub_tpm2_buffer_pack_u16 (buffer, p->nameAlg);
+  grub_tpm2_buffer_pack_u32 (buffer, p->attributes);
+  grub_Tss2_MU_TPM2B_Marshal (buffer, p->authPolicy.size, p->authPolicy.buffer);
+  grub_tpm2_buffer_pack_u16 (buffer, p->dataSize);
+}
+
+void
+grub_Tss2_MU_TPM2B_NV_PUBLIC_Marshal (grub_tpm2_buffer_t buffer,
+				      const TPM2B_NV_PUBLIC_t *p)
+{
+  grub_uint32_t start;
+  grub_uint16_t size;
+
+  if (p != NULL)
+    {
+      grub_tpm2_buffer_pack_u16 (buffer, p->size);
+
+      start = buffer->size;
+      grub_Tss2_MU_TPMS_NV_PUBLIC_Marshal (buffer, &p->nvPublic);
+      size = grub_cpu_to_be16 (buffer->size - start);
+      grub_memcpy (&buffer->data[start - sizeof (grub_uint16_t)], &size, sizeof (size));
+    }
+  else
+    grub_tpm2_buffer_pack_u16 (buffer, 0);
+}
+
 static void
 __Tss2_MU_TPM2B_BUFFER_Unmarshal (grub_tpm2_buffer_t buffer,
 				  TPM2B_t *p, grub_uint16_t bound)
@@ -982,6 +1014,13 @@ grub_Tss2_MU_TPM2B_NV_PUBLIC_Unmarshal (grub_tpm2_buffer_t buffer,
   grub_Tss2_MU_TPMS_NV_PUBLIC_Unmarshal (buffer, &p->nvPublic);
 }
 
+void
+grub_Tss2_MU_TPM2B_NAX_NV_BUFFER_Unmarshal (grub_tpm2_buffer_t buffer,
+					    TPM2B_MAX_NV_BUFFER_t *p)
+{
+  TPM2B_BUFFER_UNMARSHAL (buffer, TPM2B_MAX_NV_BUFFER_t, p);
+}
+
 void
 grub_Tss2_MU_TPM2B_NAME_Unmarshal (grub_tpm2_buffer_t buffer,
 				   TPM2B_NAME_t *n)
grub-core/lib/tss2/tss2_mu.h +12 -0
index 8f82126e1..6440de57c 100644
@@ -193,6 +193,14 @@ extern void
 grub_Tss2_MU_TPMT_TK_VERIFIED_Marshal (grub_tpm2_buffer_t buffer,
                                        const TPMT_TK_VERIFIED_t *p);
 
+extern void
+grub_Tss2_MU_TPMS_NV_PUBLIC_Marshal (grub_tpm2_buffer_t buffer,
+				     const TPMS_NV_PUBLIC_t *p);
+
+extern void
+grub_Tss2_MU_TPM2B_NV_PUBLIC_Marshal (grub_tpm2_buffer_t buffer,
+				      const TPM2B_NV_PUBLIC_t *p);
+
 extern void
 grub_Tss2_MU_TPMS_AUTH_RESPONSE_Unmarshal (grub_tpm2_buffer_t buffer,
 					   TPMS_AUTH_RESPONSE_t *p);
@@ -336,6 +344,10 @@ extern void
 grub_Tss2_MU_TPM2B_NV_PUBLIC_Unmarshal (grub_tpm2_buffer_t buffer,
 					TPM2B_NV_PUBLIC_t *p);
 
+extern void
+grub_Tss2_MU_TPM2B_NAX_NV_BUFFER_Unmarshal (grub_tpm2_buffer_t buffer,
+					    TPM2B_MAX_NV_BUFFER_t *p);
+
 extern void
 grub_Tss2_MU_TPM2B_NAME_Unmarshal (grub_tpm2_buffer_t buffer,
 				   TPM2B_NAME_t *n);
grub-core/lib/tss2/tss2_types.h +6 -0
index 5b1a7947d..bddde7191 100644
@@ -270,6 +270,7 @@ typedef TPM_HANDLE_t TPMI_RH_NV_INDEX_t;
 
 /* TPM_HT_t Constants */
 typedef grub_uint8_t TPM_HT_t;
+#define TPM_HT_NV_INDEX   ((TPM_HT_t) 0x01)
 #define TPM_HT_PERMANENT  ((TPM_HT_t) 0x40)
 #define TPM_HT_PERSISTENT ((TPM_HT_t) 0x81)
 
@@ -300,6 +301,7 @@ typedef TPM_HANDLE_t TPM_HC_t;
 #define TPM_HR_HANDLE_MASK   ((TPM_HC_t) 0x00FFFFFF)
 #define TPM_HR_RANGE_MASK    ((TPM_HC_t) 0xFF000000)
 #define TPM_HR_SHIFT         ((TPM_HC_t) 24)
+#define TPM_HR_NV_INDEX      ((TPM_HC_t) (TPM_HT_NV_INDEX << TPM_HR_SHIFT))
 #define TPM_HR_PERSISTENT    ((TPM_HC_t) (TPM_HT_PERSISTENT << TPM_HR_SHIFT))
 #define TPM_HR_PERMANENT     ((TPM_HC_t) (TPM_HT_PERMANENT << TPM_HR_SHIFT))
 #define TPM_PERSISTENT_FIRST ((TPM_HC_t) (TPM_HR_PERSISTENT + 0))
@@ -308,6 +310,7 @@ typedef TPM_HANDLE_t TPM_HC_t;
 #define TPM_PERMANENT_LAST   ((TPM_HC_t) TPM_RH_LAST)
 
 /* TPM Handle Type Checks */
+#define TPM_HT_IS_NVINDEX(HANDLE) (((HANDLE) >> TPM_HR_SHIFT) == TPM_HT_NV_INDEX)
 #define TPM_HT_IS_PERMANENT(HANDLE) (((HANDLE) >> TPM_HR_SHIFT) == TPM_HT_PERMANENT)
 #define TPM_HT_IS_PERSISTENT(HANDLE) (((HANDLE) >> TPM_HR_SHIFT) == TPM_HT_PERSISTENT)
 
@@ -334,8 +337,11 @@ typedef grub_uint32_t TPM_CC_t;
 #define TPM_CC_ReadPublic       ((TPM_CC_t) 0x00000173)
 #define TPM_CC_StartAuthSession ((TPM_CC_t) 0x00000176)
 #define TPM_CC_PolicyPCR        ((TPM_CC_t) 0x0000017f)
+#define TPM_CC_NV_DefineSpace   ((TPM_CC_t) 0x0000012a)
 #define TPM_CC_NV_Read          ((TPM_CC_t) 0x0000014e)
 #define TPM_CC_NV_ReadPublic    ((TPM_CC_t) 0x00000169)
+#define TPM_CC_NV_Write         ((TPM_CC_t) 0x00000137)
+#define TPM_CC_NV_UndefineSpace ((TPM_CC_t) 0x00000122)
 #define TPM_CC_GetCapability    ((TPM_CC_t) 0x0000017a)
 #define TPM_CC_PCR_Read         ((TPM_CC_t) 0x0000017e)
 #define TPM_CC_Load             ((TPM_CC_t) 0x00000157)
Signature · 7 lines
2.43.0


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author Reviewed-by Daniel Kiper on v3 5/10
#12 lore raw

Re: [PATCH v3 05/10] tss2: Add TPM 2.0 NV index commands

Quoted 9 lines · Gary Lin

The following TPM 2.0 commands are introduced to tss2 to access the TPM non-volatile memory associated with the NV index handles.

- TPM2_NV_DefineSpace
- TPM2_NV_UndefineSpace
- TPM2_NV_ReadPublic
- TPM2_NV_Read
- TPM2_NV_Write

Quoted 4 lines

The related marshal/unmarshal functions are also introduced.

grub-core/lib/tss2/tss2_mu.c line 20

Quoted 9 lines
grub-core/lib/tss2/tss2_mu.c +1 -0
index 86134cc0a..816e5b37f 100644
@@ -17,6 +17,7 @@
  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+#include <grub/mm.h>

I am not sure why you include grub/mm.h...

grub-core/lib/tss2/tss2_mu.c line 23

Quoted 3 lines
grub-core/lib/tss2/tss2_mu.c +0 -0
 #include <grub/misc.h>
 
 #include <tss2_mu.h>

Daniel

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

#13 lore raw

Re: [PATCH v3 05/10] tss2: Add TPM 2.0 NV index commands

Quoted 25 lines · Daniel Kiper
Quoted 9 lines · Gary Lin

The following TPM 2.0 commands are introduced to tss2 to access the TPM non-volatile memory associated with the NV index handles.

- TPM2_NV_DefineSpace
- TPM2_NV_UndefineSpace
- TPM2_NV_ReadPublic
- TPM2_NV_Read
- TPM2_NV_Write

Quoted 4 lines

The related marshal/unmarshal functions are also introduced.

Quoted 8 lines
grub-core/lib/tss2/tss2_mu.c +0 -0
index 86134cc0a..816e5b37f 100644
@@ -17,6 +17,7 @@
  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
  */
 
Quoted 4 lines

grub-core/lib/tss2/tss2_mu.c line 20

Quoted 1 line
grub-core/lib/tss2/tss2_mu.c +1 -0
+#include <grub/mm.h>

I am not sure why you include grub/mm.h...

It's because 'NULL' is defined in grub/mm.h or the compiler would complain that 'NULL' is not declared.

Gary Lin

Quoted 5 lines

grub-core/lib/tss2/tss2_mu.c line 23

Quoted 3 lines
grub-core/lib/tss2/tss2_mu.c +0 -0
 #include <grub/misc.h>
 
 #include <tss2_mu.h>

Daniel

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

#14 lore raw

PATCH v3 6/10 tpm2_key_protector: Unseal key from a buffer

In reply to Gary Lin via Grub-devel

Extract the logic to handle the file buffer from the SRK recover function to prepare to load the sealed key from the NV index handle. The SRK recover function now only reads the file and sends the file buffer to the new function. Besides this, the file format is detected automatically before unmarshalling the data, so there is no need to use the command option to specify the file format anymore. In other words, '--tpm2key' and '--keyfile' are the same now.

---
 .../commands/tpm2_key_protector/module.c      | 122 +++++++++++++-----
 1 file changed, 89 insertions(+), 33 deletions(-)
grub-core/commands/tpm2_key_protector/module.c +89 -33
index 0a5d81e4c..795f61518 100644
@@ -218,10 +218,51 @@ tpm2_protector_srk_read_file (const char *filepath, void **buffer, grub_size_t *
   return err;
 }
 
+/* Check if the data is in TPM 2.0 Key File format */
+static bool
+tpm2_protector_is_tpm2key (grub_uint8_t *buffer, grub_size_t buffer_size)
+{
+  /* id-sealedkey OID (2.23.133.10.1.5) in DER */
+  const grub_uint8_t sealed_key_oid[] = {0x06, 0x06, 0x67, 0x81, 0x05, 0x0a};
+  grub_size_t skip = 0;
+
+  /* Need at least the first two bytes to check the tag and the length */
+  if (buffer_size < 2)
+    return false;
+
+  /* The first byte is always 0x30 (SEQUENCE). */
+  if (buffer[0] != 0x30)
+    return false;
+
+  /*
+   * Get the bytes of the length
+   *
+   * If the bit 8 of the second byte is 0, it is in the short form, so the second byte
+   * alone represents the length. Thus, the first two bytes are skipped.
+   *
+   * Otherwise, it is in the long form, and bits 1~7 indicate how many more bytes are in
+   * the length field, so we skip the first two bytes plus the bytes for the length.
+   */
+  if ((buffer[1] & 0x80) == 0)
+    skip = 2;
+  else
+    skip = (buffer[1] & 0x7F) + 2;
+
+  /* Make sure the buffer is large enough to contain id-sealedkey OID */
+  if (buffer_size < skip + sizeof (sealed_key_oid))
+    return false;
+
+  /* Check id-sealedkey OID */
+  if (grub_memcmp (buffer + skip, sealed_key_oid, sizeof (sealed_key_oid)) != 0)
+    return false;
+
+  return true;
+}
+
 static grub_err_t
-tpm2_protector_srk_unmarshal_keyfile (void *sealed_key,
-				      grub_size_t sealed_key_size,
-				      tpm2_sealed_key_t *sk)
+tpm2_protector_unmarshal_raw (void *sealed_key,
+			      grub_size_t sealed_key_size,
+			      tpm2_sealed_key_t *sk)
 {
   struct grub_tpm2_buffer buf;
 
@@ -242,13 +283,13 @@ tpm2_protector_srk_unmarshal_keyfile (void *sealed_key,
 }
 
 static grub_err_t
-tpm2_protector_srk_unmarshal_tpm2key (void *sealed_key,
-				      grub_size_t sealed_key_size,
-				      tpm2key_policy_t *policy_seq,
-				      tpm2key_authpolicy_t *authpol_seq,
-				      grub_uint8_t *rsaparent,
-				      grub_uint32_t *parent,
-				      tpm2_sealed_key_t *sk)
+tpm2_protector_unmarshal_tpm2key (void *sealed_key,
+				  grub_size_t sealed_key_size,
+				  tpm2key_policy_t *policy_seq,
+				  tpm2key_authpolicy_t *authpol_seq,
+				  grub_uint8_t *rsaparent,
+				  grub_uint32_t *parent,
+				  tpm2_sealed_key_t *sk)
 {
   asn1_node tpm2key = NULL;
   grub_uint8_t rsaparent_tmp;
@@ -942,12 +983,11 @@ tpm2_protector_dump_pcr (const TPM_ALG_ID_t bank)
 }
 
 static grub_err_t
-tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
-			    grub_uint8_t **key, grub_size_t *key_size)
+tpm2_protector_key_from_buffer (const tpm2_protector_context_t *ctx,
+				void *buffer, grub_size_t buf_size,
+				grub_uint8_t **key, grub_size_t *key_size)
 {
   tpm2_sealed_key_t sealed_key = {0};
-  void *file_bytes = NULL;
-  grub_size_t file_size = 0;
   grub_uint8_t rsaparent = 0;
   TPM_HANDLE_t parent_handle = 0;
   TPM_HANDLE_t srk_handle = 0;
@@ -960,22 +1000,17 @@ tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
 
   /*
    * Retrieve sealed key, parent handle, policy sequence, and authpolicy
-   * sequence from the key file
+   * sequence from the buffer
   */
-  if (ctx->tpm2key != NULL)
+  if (tpm2_protector_is_tpm2key (buffer, buf_size) == true)
     {
-      err = tpm2_protector_srk_read_file (ctx->tpm2key, &file_bytes,
-					       &file_size);
-      if (err != GRUB_ERR_NONE)
-	return err;
-
-      err = tpm2_protector_srk_unmarshal_tpm2key (file_bytes,
-						  file_size,
-						  &policy_seq,
-						  &authpol_seq,
-						  &rsaparent,
-						  &parent_handle,
-						  &sealed_key);
+      err = tpm2_protector_unmarshal_tpm2key (buffer,
+					      buf_size,
+					      &policy_seq,
+					      &authpol_seq,
+					      &rsaparent,
+					      &parent_handle,
+					      &sealed_key);
       if (err != GRUB_ERR_NONE)
 	goto exit1;
 
@@ -991,12 +1026,8 @@ tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
     }
   else
     {
-      err = tpm2_protector_srk_read_file (ctx->keyfile, &file_bytes, &file_size);
-      if (err != GRUB_ERR_NONE)
-	return err;
-
       parent_handle = TPM_RH_OWNER;
-      err = tpm2_protector_srk_unmarshal_keyfile (file_bytes, file_size, &sealed_key);
+      err = tpm2_protector_unmarshal_raw (buffer, buf_size, &sealed_key);
       if (err != GRUB_ERR_NONE)
 	goto exit1;
     }
@@ -1072,6 +1103,31 @@ tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
  exit1:
   grub_tpm2key_free_policy_seq (policy_seq);
   grub_tpm2key_free_authpolicy_seq (authpol_seq);
+  return err;
+}
+
+static grub_err_t
+tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
+			    grub_uint8_t **key, grub_size_t *key_size)
+{
+  const char *filepath;
+  void *file_bytes = NULL;
+  grub_size_t file_size = 0;
+  grub_err_t err;
+
+  if (ctx->tpm2key != NULL)
+    filepath = ctx->tpm2key;
+  else if (ctx->keyfile != NULL)
+    filepath = ctx->keyfile;
+  else
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("key file not specified"));
+
+  err = tpm2_protector_srk_read_file (filepath, &file_bytes, &file_size);
+  if (err != GRUB_ERR_NONE)
+    return err;
+
+  err = tpm2_protector_key_from_buffer (ctx, file_bytes, file_size, key, key_size);
+
   grub_free (file_bytes);
   return err;
 }
Signature · 7 lines
2.43.0


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

Re: [PATCH v3 06/10] tpm2_key_protector: Unseal key from a buffer

Quoted 7 lines · Gary Lin via Grub-devel

Extract the logic to handle the file buffer from the SRK recover function to prepare to load the sealed key from the NV index handle. The SRK recover function now only reads the file and sends the file buffer to the new function. Besides this, the file format is detected automatically before unmarshalling the data, so there is no need to use the command option to specify the file format anymore. In other words, '--tpm2key' and '--keyfile' are the same now.

Should not you update the docs then?

Additionally, I think commit message misses explanation why this patch is needed.

Daniel

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

#16 lore raw

Re: [PATCH v3 06/10] tpm2_key_protector: Unseal key from a buffer

Quoted 11 lines · Daniel Kiper
Quoted 7 lines · Gary Lin via Grub-devel

Extract the logic to handle the file buffer from the SRK recover function to prepare to load the sealed key from the NV index handle. The SRK recover function now only reads the file and sends the file buffer to the new function. Besides this, the file format is detected automatically before unmarshalling the data, so there is no need to use the command option to specify the file format anymore. In other words, '--tpm2key' and '--keyfile' are the same now.

Should not you update the docs then?

Ok, I'll update the document in v4.

Quoted 3 lines

Additionally, I think commit message misses explanation why this patch is needed.

The main purpose is to simplify the next patch. I'll explain it more.

Gary Lin

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

#17 lore raw

PATCH v3 7/10 tpm2_key_protector: Support NV index handles

In reply to Gary Lin via Grub-devel

Previously, NV index mode only supported persistent handles which are only for TPM objects.

On the other hand, the "NV index" handle allows the user-defined data, so it can be an alternative to the key file and support TPM 2.0 Key File format immediately.

The following tpm2-tools commands store the given key file, sealed.tpm, in either TPM 2.0 Key File format or the raw format into the NV index handle 0x1000000.

  # tpm2_nvdefine -C o \
      -a "ownerread|ownerwrite" \
      -s $(stat -c %s sealed.tpm) \
      0x1000000
  # tpm2_nvwrite -C o -i sealed.tpm 0x1000000

To unseal the key in GRUB, add the 'tpm2_key_protector_init' command to grub.cfg:

  tpm2_key_protector_init --mode=nv --nvindex=0x1000000
  cryptomount -u <UUID> --protector tpm2

To remove the NV index handle:

  # tpm2_nvundefine -C o 0x1000000
---
 .../commands/tpm2_key_protector/module.c      | 70 ++++++++++++++++---
 1 file changed, 60 insertions(+), 10 deletions(-)
grub-core/commands/tpm2_key_protector/module.c +60 -10
index 795f61518..857f3753f 100644
@@ -1133,10 +1133,9 @@ tpm2_protector_srk_recover (const tpm2_protector_context_t *ctx,
 }
 
 static grub_err_t
-tpm2_protector_nv_recover (const tpm2_protector_context_t *ctx,
-			   grub_uint8_t **key, grub_size_t *key_size)
+tpm2_protector_load_persistent (const tpm2_protector_context_t *ctx, TPM_HANDLE_t sealed_handle,
+				grub_uint8_t **key, grub_size_t *key_size)
 {
-  TPM_HANDLE_t sealed_handle = ctx->nv;
   tpm2key_policy_t policy_seq = NULL;
   bool dump_pcr = false;
   grub_err_t err;
@@ -1163,6 +1162,51 @@ tpm2_protector_nv_recover (const tpm2_protector_context_t *ctx,
   return err;
 }
 
+static grub_err_t
+tpm2_protector_key_from_nvindex (const tpm2_protector_context_t *ctx, TPM_HANDLE_t nvindex,
+				 grub_uint8_t **key, grub_size_t *key_size)
+{
+  TPMS_AUTH_COMMAND_t authCmd = {0};
+  TPM2B_NV_PUBLIC_t nv_public;
+  TPM2B_NAME_t nv_name;
+  grub_uint16_t data_size;
+  TPM2B_MAX_NV_BUFFER_t data;
+  TPM_RC_t rc;
+
+  /* Get the data size in the NV index handle */
+  rc = grub_tpm2_nv_readpublic (nvindex, NULL, &nv_public, &nv_name);
+  if (rc != TPM_RC_SUCCESS)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, "failed to retrieve info from 0x%x (TPM2_NV_ReadPublic: 0x%x)", nvindex, rc);
+
+  data_size = nv_public.nvPublic.dataSize;
+  if (data_size > TPM_MAX_NV_BUFFER_SIZE)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, "insufficient data buffer");
+
+  /* Read the data from the NV index handle */
+  authCmd.sessionHandle = TPM_RS_PW;
+  rc = grub_tpm2_nv_read (TPM_RH_OWNER, nvindex, &authCmd, data_size, 0, &data);
+  if (rc != TPM_RC_SUCCESS)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, "failed to read data from 0x%x (TPM2_NV_Read: 0x%x)", nvindex, rc);
+
+  return tpm2_protector_key_from_buffer (ctx, data.buffer, data_size, key, key_size);
+}
+
+static grub_err_t
+tpm2_protector_nv_recover (const tpm2_protector_context_t *ctx,
+			   grub_uint8_t **key, grub_size_t *key_size)
+{
+  grub_err_t err;
+
+  if (TPM_HT_IS_PERSISTENT (ctx->nv) == true)
+    err = tpm2_protector_load_persistent (ctx, ctx->nv, key, key_size);
+  else if (TPM_HT_IS_NVINDEX (ctx->nv) == true)
+    err = tpm2_protector_key_from_nvindex (ctx, ctx->nv, key, key_size);
+  else
+    err = GRUB_ERR_BAD_ARGUMENT;
+
+  return err;
+}
+
 static grub_err_t
 tpm2_protector_recover (const tpm2_protector_context_t *ctx,
 			grub_uint8_t **key, grub_size_t *key_size)
@@ -1215,14 +1259,15 @@ tpm2_protector_check_args (tpm2_protector_context_t *ctx)
 
   if (ctx->mode == TPM2_PROTECTOR_MODE_NV &&
       (ctx->tpm2key != NULL || ctx->keyfile != NULL))
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("in NV Index mode, a keyfile cannot be specified"));
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("a key file cannot be specified when using NV index mode"));
 
-  if (ctx->mode == TPM2_PROTECTOR_MODE_NV && ctx->srk != 0)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("in NV Index mode, an SRK cannot be specified"));
+  if (ctx->mode == TPM2_PROTECTOR_MODE_NV && TPM_HT_IS_PERSISTENT (ctx->nv) == true &&
+      (ctx->srk != 0 || ctx->srk_type.type != TPM_ALG_ERROR))
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("an SRK cannot be specified when using NV index mode with a persistent handle"));
 
   if (ctx->mode == TPM2_PROTECTOR_MODE_NV &&
-      ctx->srk_type.type != TPM_ALG_ERROR)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("in NV Index mode, an asymmetric key type cannot be specified"));
+      (TPM_HT_IS_PERSISTENT (ctx->nv) == false && TPM_HT_IS_NVINDEX (ctx->nv) == false))
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("an NV index must be either a persistent handle or an NV index handle when using NV index mode"));
 
   /* Defaults assignment */
   if (ctx->bank == TPM_ALG_ERROR)
@@ -1234,8 +1279,13 @@ tpm2_protector_check_args (tpm2_protector_context_t *ctx)
       ctx->pcr_count = 1;
     }
 
-  if (ctx->mode == TPM2_PROTECTOR_MODE_SRK &&
-      ctx->srk_type.type == TPM_ALG_ERROR)
+  /*
+   * Set ECC_NIST_P256 as the default SRK when using SRK mode or NV mode with
+   * an NV index handle
+   */
+  if (ctx->srk_type.type == TPM_ALG_ERROR &&
+      (ctx->mode == TPM2_PROTECTOR_MODE_SRK ||
+       (ctx->mode == TPM2_PROTECTOR_MODE_NV && TPM_HT_IS_NVINDEX (ctx->nv) == true)))
     {
       ctx->srk_type.type = TPM_ALG_ECC;
       ctx->srk_type.detail.ecc_curve = TPM_ECC_NIST_P256;
Signature · 7 lines
2.43.0


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v3 7/10
#18 lore raw

Re: [PATCH v3 07/10] tpm2_key_protector: Support NV index handles

Quoted 20 lines · Gary Lin via Grub-devel

Previously, NV index mode only supported persistent handles which are only for TPM objects.

On the other hand, the "NV index" handle allows the user-defined data, so it can be an alternative to the key file and support TPM 2.0 Key File format immediately.

The following tpm2-tools commands store the given key file, sealed.tpm, in either TPM 2.0 Key File format or the raw format into the NV index handle 0x1000000.

  # tpm2_nvdefine -C o \
      -a "ownerread|ownerwrite" \
      -s $(stat -c %s sealed.tpm) \
      0x1000000
  # tpm2_nvwrite -C o -i sealed.tpm 0x1000000

To unseal the key in GRUB, add the 'tpm2_key_protector_init' command to grub.cfg:

Quoted 8 lines
  tpm2_key_protector_init --mode=nv --nvindex=0x1000000
  cryptomount -u <UUID> --protector tpm2

To remove the NV index handle:

  # tpm2_nvundefine -C o 0x1000000

Daniel

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

#19 lore raw

PATCH v3 8/10 util/grub-protect: Support NV index mode

In reply to Gary Lin via Grub-devel

This commit implements the missing NV index mode support in 'grub-protect'. NV index mode stores the sealed key in the TPM non-volatile memory (NVRAM) instead of a file. There are two supported types of TPM handles.

1. Persistent handle (0x81000000~0x81FFFFFF)
TPM 2.0 Key File format (--tpm2key) is not supported due to the limitation of persistent handles. This 'grub-protect' command seals the key into the persistent handle 0x81000000.

  # grub-protect \
      --protector=tpm2 \
      --action=add \
      --tpm2-bank=sha256 \
      --tpm2-pcrs=7,11 \
      --tpm2-keyfile=luks-key \
      --tpm2-nvindex=0x81000000

2. NV index handle (0x1000000~0x1FFFFFF)
Both TPM 2.0 Key File format and the raw format are supported by NV index handles. Here is the 'grub-protect' command to seal the key in TPM 2.0 Key File format into the NV index handle 0x1000000.

  # grub-protect \
      --protector=tpm2 \
      --action=add \
      --tpm2key \
      --tpm2-bank=sha256 \
      --tpm2-pcrs=7,11 \
      --tpm2-keyfile=luks-key \
      --tpm2-nvindex=0x1000000

Besides the 'add' action, the corresponding 'remove' action is also introduced. To remove the data from a persistent or NV index handle, just use '--tpm2-nvindex=HANDLE' combining with '--tpm2-evict'. This sample command removes the data from the NV index handle 0x1000000.

  # grub-protect \
      --protector=tpm2 \
      --action=remove \
      --tpm2-evict \
      --tpm2-nvindex=0x1000000
---
 util/grub-protect.c | 343 ++++++++++++++++++++++++++++++++++++--------
 1 file changed, 287 insertions(+), 56 deletions(-)
util/grub-protect.c +287 -56
index 5b7e952f4..40d4a3fc5 100644
@@ -61,7 +61,8 @@ typedef enum protect_opt
   PROTECT_OPT_TPM2_KEYFILE,
   PROTECT_OPT_TPM2_OUTFILE,
   PROTECT_OPT_TPM2_EVICT,
-  PROTECT_OPT_TPM2_TPM2KEY
+  PROTECT_OPT_TPM2_TPM2KEY,
+  PROTECT_OPT_TPM2_NVINDEX,
 } protect_opt_t;
 
 /* Option flags to keep track of specified arguments */
@@ -79,7 +80,8 @@ typedef enum protect_arg
   PROTECT_ARG_TPM2_KEYFILE    = 1 << 7,
   PROTECT_ARG_TPM2_OUTFILE    = 1 << 8,
   PROTECT_ARG_TPM2_EVICT      = 1 << 9,
-  PROTECT_ARG_TPM2_TPM2KEY    = 1 << 10
+  PROTECT_ARG_TPM2_TPM2KEY    = 1 << 10,
+  PROTECT_ARG_TPM2_NVINDEX    = 1 << 11
 } protect_arg_t;
 
 typedef enum protect_protector
@@ -111,6 +113,7 @@ typedef struct protect_args
   const char *tpm2_outfile;
   bool tpm2_evict;
   bool tpm2_tpm2key;
+  TPM_HANDLE_t tpm2_nvindex;
 } protect_args_t;
 
 static struct argp_option protect_options[] =
@@ -224,6 +227,15 @@ static struct argp_option protect_options[] =
 	N_("Use TPM 2.0 Key File format."),
       .group = 0
     },
+    {
+      .name = "tpm2-nvindex",
+      .key   = PROTECT_OPT_TPM2_NVINDEX,
+      .arg   = "NUM",
+      .flags = 0,
+      .doc   =
+	N_("Store the sealed key in a persistent or NV index handle."),
+      .group = 0
+    },
     /* End of list */
     { 0, 0, 0, 0, 0, 0 }
   };
@@ -668,8 +680,8 @@ extern asn1_static_node tpm2key_asn1_tab[];
 #define TPM2KEY_SEALED_KEY_OID "2.23.133.10.1.5"
 
 static grub_err_t
-protect_tpm2_export_tpm2key (const protect_args_t *args,
-			     tpm2_sealed_key_t *sealed_key)
+protect_tpm2_export_tpm2key (const protect_args_t *args, tpm2_sealed_key_t *sealed_key,
+			     void **der_buf, int *der_buf_size)
 {
   const char *sealed_key_oid = TPM2KEY_SEALED_KEY_OID;
   asn1_node asn1_def = NULL;
@@ -689,12 +701,13 @@ protect_tpm2_export_tpm2key (const protect_args_t *args,
   };
   struct grub_tpm2_buffer pub_buf;
   struct grub_tpm2_buffer priv_buf;
-  void *der_buf = NULL;
-  int der_buf_size = 0;
   int i;
   int ret;
   grub_err_t err;
 
+  if (der_buf == NULL)
+    return GRUB_ERR_BAD_ARGUMENT;
+
   for (i = 0; i < args->tpm2_pcr_count; i++)
     TPMS_PCR_SELECTION_SelectPCR (&pcr_sel.pcrSelections[0], args->tpm2_pcrs[i]);
 
@@ -844,8 +857,8 @@ protect_tpm2_export_tpm2key (const protect_args_t *args,
     }
 
   /* Create the DER binary */
-  der_buf_size = 0;
-  ret = asn1_der_coding (tpm2key, "", NULL, &der_buf_size, NULL);
+  *der_buf_size = 0;
+  ret = asn1_der_coding (tpm2key, "", NULL, der_buf_size, NULL);
   if (ret != ASN1_MEM_ERROR)
     {
       fprintf (stderr, "Failed to get DER size: 0x%x\n", ret);
@@ -853,15 +866,15 @@ protect_tpm2_export_tpm2key (const protect_args_t *args,
       goto error;
     }
 
-  der_buf = grub_malloc (der_buf_size);
-  if (der_buf == NULL)
+  *der_buf = grub_malloc (*der_buf_size);
+  if (*der_buf == NULL)
     {
       fprintf (stderr, "Failed to allocate memory for DER encoding\n");
       err = GRUB_ERR_OUT_OF_MEMORY;
       goto error;
     }
 
-  ret = asn1_der_coding (tpm2key, "", der_buf, &der_buf_size, NULL);
+  ret = asn1_der_coding (tpm2key, "", *der_buf, der_buf_size, NULL);
   if (ret != ASN1_SUCCESS)
     {
       fprintf (stderr, "DER coding error: 0x%x\n", ret);
@@ -869,13 +882,7 @@ protect_tpm2_export_tpm2key (const protect_args_t *args,
       goto error;
     }
 
-  err = protect_write_file (args->tpm2_outfile, der_buf, der_buf_size);
-  if (err != GRUB_ERR_NONE)
-    fprintf (stderr, N_("Could not write tpm2key file (%s).\n"), strerror (errno));
-
  error:
-  grub_free (der_buf);
-
   if (tpm2key)
     asn1_delete_structure (&tpm2key);
 
@@ -883,10 +890,8 @@ protect_tpm2_export_tpm2key (const protect_args_t *args,
 }
 
 static grub_err_t
-protect_tpm2_export_sealed_key (const char *filepath,
-				tpm2_sealed_key_t *sealed_key)
+protect_tpm2_export_raw (tpm2_sealed_key_t *sealed_key, void **out_buf, int *out_buf_size)
 {
-  grub_err_t err;
   struct grub_tpm2_buffer buf;
 
   grub_tpm2_buffer_init (&buf);
@@ -896,13 +901,98 @@ protect_tpm2_export_sealed_key (const char *filepath,
   if (buf.error != 0)
     return GRUB_ERR_BAD_ARGUMENT;
 
-  err = protect_write_file (filepath, buf.data, buf.size);
-  if (err != GRUB_ERR_NONE)
-    fprintf (stderr, N_("Could not write sealed key file (%s).\n"), strerror (errno));
+  *out_buf_size = buf.size;
+  *out_buf = grub_malloc (buf.size);
+
+  if (*out_buf == NULL)
+    {
+      fprintf (stderr, N_("Could not allocate memory for the raw format key.\n"));
+      return GRUB_ERR_OUT_OF_MEMORY;
+    }
+
+  grub_memcpy (*out_buf, buf.data, buf.size);
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+protect_tpm2_export_persistent (protect_args_t *args,
+				TPM_HANDLE_t srk_handle,
+				tpm2_sealed_key_t *sealed_key)
+{
+  TPMS_AUTH_COMMAND_t authCmd = {0};
+  TPM2B_NAME_t name = {0};
+  TPM_HANDLE_t sealed_handle;
+  TPM_RC_t rc;
+  grub_err_t err = GRUB_ERR_NONE;
+
+  /* Load the sealed key and associate it with the SRK */
+  authCmd.sessionHandle = TPM_RS_PW;
+  rc = grub_tpm2_load (srk_handle, &authCmd, &sealed_key->private, &sealed_key->public,
+		       &sealed_handle, &name, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, "Failed to load sealed key (TPM2_Load: %x).\n", rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  /* Make the sealed key object persistent */
+  authCmd.sessionHandle = TPM_RS_PW;
+  rc = grub_tpm2_evictcontrol (TPM_RH_OWNER, sealed_handle, &authCmd, args->tpm2_nvindex, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, "Failed to make sealed key persistent with handle 0x%x (TPM2_EvictControl: 0x%x).\n", args->tpm2_nvindex, rc);
+      err = GRUB_ERR_BAD_DEVICE;
+      goto exit;
+    }
+
+ exit:
+  grub_tpm2_flushcontext (sealed_handle);
 
   return err;
 }
 
+static grub_err_t
+protect_tpm2_export_nvindex (protect_args_t *args, void *data, int data_size)
+{
+  TPMS_AUTH_COMMAND_t authCmd = {0};
+  TPM2B_NV_PUBLIC_t pub_info = {0};
+  TPM2B_MAX_NV_BUFFER_t nv_data = {0};
+  TPM_RC_t rc;
+
+  if (data_size > TPM_MAX_NV_BUFFER_SIZE || data_size < 0)
+    {
+      fprintf (stderr, N_("Invalid tpm2key size for TPM NV buffer\n"));
+      return GRUB_ERR_OUT_OF_RANGE;
+    }
+
+  pub_info.nvPublic.nvIndex = args->tpm2_nvindex;
+  pub_info.nvPublic.nameAlg = TPM_ALG_SHA256;
+  pub_info.nvPublic.attributes = TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD;
+  pub_info.nvPublic.dataSize = (grub_uint16_t) data_size;
+
+  authCmd.sessionHandle = TPM_RS_PW;
+  rc = grub_tpm2_nv_definespace (TPM_RH_OWNER, &authCmd, NULL, &pub_info);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, "Failed to define NV space for 0x%x (TPM2_NV_DefineSpace: 0x%x)\n", args->tpm2_nvindex, rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  authCmd.sessionHandle = TPM_RS_PW;
+  grub_memcpy (nv_data.buffer, data, data_size);
+  nv_data.size = (grub_uint16_t) data_size;
+
+  rc = grub_tpm2_nv_write (TPM_RH_OWNER, args->tpm2_nvindex, &authCmd, &nv_data, 0);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, "Failed to write data into 0x%x (TPM2_NV_Write: 0x%x)\n", args->tpm2_nvindex, rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
 static grub_err_t
 protect_tpm2_add (protect_args_t *args)
 {
@@ -911,6 +1001,8 @@ protect_tpm2_add (protect_args_t *args)
   grub_size_t key_size;
   TPM_HANDLE_t srk;
   TPM2B_DIGEST_t policy_digest;
+  void *out_buf = NULL;
+  int out_buf_size;
   tpm2_sealed_key_t sealed_key;
 
   err = protect_tpm2_open_device (args->tpm2_device);
@@ -940,15 +1032,51 @@ protect_tpm2_add (protect_args_t *args)
   if (err != GRUB_ERR_NONE)
     goto exit3;
 
-  if (args->tpm2_tpm2key != 0)
-    err = protect_tpm2_export_tpm2key (args, &sealed_key);
+  if (args->tpm2_tpm2key == true)
+    {
+      err = protect_tpm2_export_tpm2key (args, &sealed_key, &out_buf, &out_buf_size);
+      if (err != GRUB_ERR_NONE)
+	{
+	  fprintf (stderr, N_("Could not export to TPM 2.0 Key File format\n"));
+	  goto exit3;
+	}
+    }
   else
-    err = protect_tpm2_export_sealed_key (args->tpm2_outfile, &sealed_key);
-  if (err != GRUB_ERR_NONE)
-    goto exit3;
+    {
+      err = protect_tpm2_export_raw (&sealed_key, &out_buf, &out_buf_size);
+      if (err != GRUB_ERR_NONE)
+	{
+	  fprintf (stderr, N_("Could not export to the raw format\n"));
+	  goto exit3;
+	}
+    }
+
+  if (args->tpm2_outfile != NULL)
+    {
+      err = protect_write_file (args->tpm2_outfile, out_buf, out_buf_size);
+      if (err != GRUB_ERR_NONE)
+	{
+	  fprintf (stderr, N_("Could not write key file (%s).\n"), strerror (errno));
+	  goto exit3;
+	}
+    }
+
+  if (TPM_HT_IS_NVINDEX (args->tpm2_nvindex) == true)
+    {
+      err = protect_tpm2_export_nvindex (args, out_buf, out_buf_size);
+      if (err != GRUB_ERR_NONE)
+	goto exit3;
+    }
+  else if (TPM_HT_IS_PERSISTENT (args->tpm2_nvindex) == true)
+    {
+      err = protect_tpm2_export_persistent (args, srk, &sealed_key);
+      if (err != GRUB_ERR_NONE)
+	goto exit3;
+    }
 
  exit3:
   grub_tpm2_flushcontext (srk);
+  grub_free (out_buf);
 
  exit2:
   grub_free (key);
@@ -960,14 +1088,66 @@ protect_tpm2_add (protect_args_t *args)
 }
 
 static grub_err_t
-protect_tpm2_remove (protect_args_t *args)
+protect_tpm2_evict (TPM_HANDLE_t handle)
 {
   TPM_RC_t rc;
   TPM2B_PUBLIC_t public;
-  TPMS_AUTH_COMMAND_t authCommand = {0};
+  TPMS_AUTH_COMMAND_t authCmd = {0};
+
+  /* Find the persistent handle */
+  rc = grub_tpm2_readpublic (handle, NULL, &public);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, "Handle 0x%x not found.\n", handle);
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  /* Evict the persistent handle */
+  authCmd.sessionHandle = TPM_RS_PW;
+  rc = grub_tpm2_evictcontrol (TPM_RH_OWNER, handle, &authCmd, handle, NULL);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, "Failed to evict handle 0x%x (TPM2_EvictControl: 0x%x).\n", handle, rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+protect_tpm2_nv_undefine (TPM_HANDLE_t handle)
+{
+  TPM_RC_t rc;
+  TPM2B_NV_PUBLIC_t nv_public;
+  TPMS_AUTH_COMMAND_t authCmd = {0};
+  TPM2B_NAME_t nv_name;
+
+  /* Find the nvindex handle */
+  rc = grub_tpm2_nv_readpublic (handle, NULL, &nv_public, &nv_name);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, "Handle 0x%x not found.\n", handle);
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  /* Undefine the nvindex handle */
+  authCmd.sessionHandle = TPM_RS_PW;
+  rc = grub_tpm2_nv_undefinespace (TPM_RH_OWNER, handle, &authCmd);
+  if (rc != TPM_RC_SUCCESS)
+    {
+      fprintf (stderr, "Failed to undefine handle 0x%x (TPM2_NV_UndefineSpace: 0x%x).\n", handle, rc);
+      return GRUB_ERR_BAD_DEVICE;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+protect_tpm2_remove (protect_args_t *args)
+{
   grub_err_t err;
 
-  if (args->tpm2_evict == 0)
+  if (args->tpm2_evict == false)
     {
       printf ("--tpm2-evict not specified, nothing to do.\n");
       return GRUB_ERR_NONE;
@@ -977,35 +1157,41 @@ protect_tpm2_remove (protect_args_t *args)
   if (err != GRUB_ERR_NONE)
     return err;
 
-  /* Find SRK */
-  rc = grub_tpm2_readpublic (args->tpm2_srk, NULL, &public);
-  if (rc != TPM_RC_SUCCESS)
+  if (args->tpm2_srk != 0)
     {
-      fprintf (stderr, "SRK with handle 0x%x not found.\n", args->tpm2_srk);
-      err = GRUB_ERR_BAD_ARGUMENT;
-      goto exit1;
+      err = protect_tpm2_evict (args->tpm2_srk);
+      if (err != GRUB_ERR_NONE)
+	goto exit;
     }
 
-  /* Evict SRK */
-  authCommand.sessionHandle = TPM_RS_PW;
-
-  rc = grub_tpm2_evictcontrol (TPM_RH_OWNER, args->tpm2_srk, &authCommand, args->tpm2_srk, NULL);
-  if (rc != TPM_RC_SUCCESS)
+  if (args->tpm2_nvindex != 0)
     {
-      fprintf (stderr, "Failed to evict SRK with handle 0x%x (TPM2_EvictControl: 0x%x).\n", args->tpm2_srk, rc);
-      err = GRUB_ERR_BAD_DEVICE;
-      goto exit2;
+      if (TPM_HT_IS_PERSISTENT (args->tpm2_nvindex) == true)
+	{
+	  err = protect_tpm2_evict (args->tpm2_nvindex);
+	  if (err != GRUB_ERR_NONE)
+	    goto exit;
+	}
+      else if (TPM_HT_IS_NVINDEX (args->tpm2_nvindex) == true)
+	{
+	  err = protect_tpm2_nv_undefine (args->tpm2_nvindex);
+	  if (err != GRUB_ERR_NONE)
+	    goto exit;
+	}
+      else
+	{
+	  fprintf (stderr, "Unsupported handle 0x%x\n", args->tpm2_nvindex);
+	  err = GRUB_ERR_BAD_ARGUMENT;
+	  goto exit;
+	}
     }
 
   err = GRUB_ERR_NONE;
 
- exit2:
-  grub_tpm2_flushcontext (args->tpm2_srk);
-
- exit1:
+ exit:
   protect_tpm2_close_device ();
 
-  return GRUB_ERR_NONE;
+  return err;
 }
 
 static grub_err_t
@@ -1045,9 +1231,36 @@ protect_tpm2_args_verify (protect_args_t *args)
 	  return GRUB_ERR_BAD_ARGUMENT;
 	}
 
-      if (args->tpm2_outfile == NULL)
+      if (args->tpm2_outfile == NULL && args->tpm2_nvindex == 0)
 	{
-	  fprintf (stderr, N_("--tpm2-outfile must be specified.\n"));
+	  fprintf (stderr, N_("--tpm2-outfile or --tpm2-nvindex must be specified.\n"));
+	  return GRUB_ERR_BAD_ARGUMENT;
+	}
+
+      if (args->tpm2_nvindex != 0)
+	{
+	  if (args->tpm2_tpm2key == true && TPM_HT_IS_PERSISTENT (args->tpm2_nvindex) == true)
+	    {
+	      fprintf (stderr, N_("Persistent handle does not support TPM 2.0 Key File format.\n"));
+	      return GRUB_ERR_BAD_ARGUMENT;
+	    }
+
+	  if (TPM_HT_IS_PERSISTENT (args->tpm2_nvindex) == false && TPM_HT_IS_NVINDEX (args->tpm2_nvindex) == false)
+	    {
+	      fprintf (stderr, N_("--tpm2-nvindex must be a persistent or NV index handle.\n"));
+	      return GRUB_ERR_BAD_ARGUMENT;
+	    }
+
+	  if (args->tpm2_nvindex == args->tpm2_srk)
+	    {
+	      fprintf (stderr, N_("--tpm2-nvindex and --tpm2-srk must be different.\n"));
+	      return GRUB_ERR_BAD_ARGUMENT;
+	    }
+	}
+
+      if (args->tpm2_srk != 0 && TPM_HT_IS_PERSISTENT(args->tpm2_srk) == false)
+	{
+	  fprintf (stderr, N_("--tpm2-srk must be a persistent handle, e.g. 0x81000000.\n"));
 	  return GRUB_ERR_BAD_ARGUMENT;
 	}
 
@@ -1099,9 +1312,9 @@ protect_tpm2_args_verify (protect_args_t *args)
 	  return GRUB_ERR_BAD_ARGUMENT;
 	}
 
-      if (args->tpm2_srk == 0)
+      if (args->tpm2_srk == 0 && args->tpm2_nvindex == 0)
 	{
-	  fprintf (stderr, N_("--tpm2-srk is not specified when --action is 'remove'.\n"));
+	  fprintf (stderr, N_("missing --tpm2-srk or --tpm2-nvindex for --action 'remove'.\n"));
 	  return GRUB_ERR_BAD_ARGUMENT;
 	}
 
@@ -1274,7 +1487,7 @@ protect_argp_parser (int key, char *arg, struct argp_state *state)
 	  return EINVAL;
 	}
 
-      args->tpm2_evict = 1;
+      args->tpm2_evict = true;
       args->args |= PROTECT_ARG_TPM2_EVICT;
       break;
 
@@ -1285,10 +1498,28 @@ protect_argp_parser (int key, char *arg, struct argp_state *state)
 	  return EINVAL;
 	}
 
-      args->tpm2_tpm2key = 1;
+      args->tpm2_tpm2key = true;
       args->args |= PROTECT_ARG_TPM2_TPM2KEY;
       break;
 
+    case PROTECT_OPT_TPM2_NVINDEX:
+      if (args->args & PROTECT_ARG_TPM2_NVINDEX)
+	{
+	  fprintf (stderr, N_("--tpm2-nvindex can only be specified once.\n"));
+	  return EINVAL;
+	}
+
+      err = grub_tpm2_protector_parse_tpm_handle (arg, &args->tpm2_nvindex);
+      if (err != GRUB_ERR_NONE)
+	{
+	  if (grub_errno != GRUB_ERR_NONE)
+	    grub_print_error ();
+	  return EINVAL;
+	}
+
+      args->args |= PROTECT_ARG_TPM2_NVINDEX;
+      break;
+
     default:
       return ARGP_ERR_UNKNOWN;
     }
Signature · 7 lines
2.43.0


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

Re: [PATCH v3 08/10] util/grub-protect: Support NV index mode

Quoted 9 lines · Gary Lin via Grub-devel

This commit implements the missing NV index mode support in 'grub-protect'. NV index mode stores the sealed key in the TPM non-volatile memory (NVRAM) instead of a file. There are two supported types of TPM handles.

1. Persistent handle (0x81000000~0x81FFFFFF)
TPM 2.0 Key File format (--tpm2key) is not supported due to the limitation of persistent handles. This 'grub-protect' command seals the key into the persistent handle 0x81000000.

It seems to me these two sentences are contradicting one another. I think at least one of them should be expanded or rephrased.

Quoted 43 lines
  # grub-protect \
      --protector=tpm2 \
      --action=add \
      --tpm2-bank=sha256 \
      --tpm2-pcrs=7,11 \
      --tpm2-keyfile=luks-key \
      --tpm2-nvindex=0x81000000

2. NV index handle (0x1000000~0x1FFFFFF)
Both TPM 2.0 Key File format and the raw format are supported by NV index handles. Here is the 'grub-protect' command to seal the key in TPM 2.0 Key File format into the NV index handle 0x1000000.

  # grub-protect \
      --protector=tpm2 \
      --action=add \
      --tpm2key \
      --tpm2-bank=sha256 \
      --tpm2-pcrs=7,11 \
      --tpm2-keyfile=luks-key \
      --tpm2-nvindex=0x1000000

Besides the 'add' action, the corresponding 'remove' action is also introduced. To remove the data from a persistent or NV index handle, just use '--tpm2-nvindex=HANDLE' combining with '--tpm2-evict'. This sample command removes the data from the NV index handle 0x1000000.

  # grub-protect \
      --protector=tpm2 \
      --action=remove \
      --tpm2-evict \
      --tpm2-nvindex=0x1000000
---
 util/grub-protect.c | 343 ++++++++++++++++++++++++++++++++++++--------
 1 file changed, 287 insertions(+), 56 deletions(-)
util/grub-protect.c +0 -0
index 5b7e952f4..40d4a3fc5 100644

[...]

util/grub-protect.c protect_tpm2_add (protect_args_t *args) · line 1150

Quoted 7 lines
util/grub-protect.c +4 -1
+static grub_err_t
+protect_tpm2_remove (protect_args_t *args)
+{
   grub_err_t err;
 
-  if (args->tpm2_evict == 0)
+  if (args->tpm2_evict == false)

I am OK with changes like this one but they should be documented in the commit message.

Daniel

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

#21 lore raw

Re: [PATCH v3 08/10] util/grub-protect: Support NV index mode

Quoted 6 lines · Daniel Kiper
Quoted 5 lines · Gary Lin via Grub-devel

This commit implements the missing NV index mode support in 'grub-protect'. NV index mode stores the sealed key in the TPM non-volatile memory (NVRAM) instead of a file. There are two supported types of TPM handles.

Quoted 8 lines
Quoted 4 lines

1. Persistent handle (0x81000000~0x81FFFFFF)
TPM 2.0 Key File format (--tpm2key) is not supported due to the limitation of persistent handles. This 'grub-protect' command seals the key into the persistent handle 0x81000000.

It seems to me these two sentences are contradicting one another. I think at least one of them should be expanded or rephrased.

I'll rephrase it like:

"Only the raw format is supported due to the limitation of persistent handles"

Quoted 51 lines
Quoted 43 lines
  # grub-protect \
      --protector=tpm2 \
      --action=add \
      --tpm2-bank=sha256 \
      --tpm2-pcrs=7,11 \
      --tpm2-keyfile=luks-key \
      --tpm2-nvindex=0x81000000

2. NV index handle (0x1000000~0x1FFFFFF)
Both TPM 2.0 Key File format and the raw format are supported by NV index handles. Here is the 'grub-protect' command to seal the key in TPM 2.0 Key File format into the NV index handle 0x1000000.

  # grub-protect \
      --protector=tpm2 \
      --action=add \
      --tpm2key \
      --tpm2-bank=sha256 \
      --tpm2-pcrs=7,11 \
      --tpm2-keyfile=luks-key \
      --tpm2-nvindex=0x1000000

Besides the 'add' action, the corresponding 'remove' action is also introduced. To remove the data from a persistent or NV index handle, just use '--tpm2-nvindex=HANDLE' combining with '--tpm2-evict'. This sample command removes the data from the NV index handle 0x1000000.

  # grub-protect \
      --protector=tpm2 \
      --action=remove \
      --tpm2-evict \
      --tpm2-nvindex=0x1000000
---
 util/grub-protect.c | 343 ++++++++++++++++++++++++++++++++++++--------
 1 file changed, 287 insertions(+), 56 deletions(-)
util/grub-protect.c +0 -0
index 5b7e952f4..40d4a3fc5 100644

[...]

Quoted 5 lines
util/grub-protect.c +3 -0
+static grub_err_t
+protect_tpm2_remove (protect_args_t *args)
+{
   grub_err_t err;
Quoted 6 lines

util/grub-protect.c protect_tpm2_add (protect_args_t *args) · line 1150

Quoted 2 lines
util/grub-protect.c +1 -1
-  if (args->tpm2_evict == 0)
+  if (args->tpm2_evict == false)

I am OK with changes like this one but they should be documented in the commit message.

Sure, I'll address such changes in the commit message.

Gary Lin

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

#22 lore raw

PATCH v3 9/10 tests/tpm2_key_protector_test: Amend the NV index mode test

In reply to Gary Lin via Grub-devel

Since 'grub-protect' already supports NV index mode, tpm2_seal_nv() is replaced with one 'grub-protect' command to simplify the test script.

Two more NV index test cases are also added to test key sealing and unsealing with the NV index handle 0x1000000.

Also, there is a minor fix to reset 'ret' to 0 when a test case fails so that the other test cases could continue.

---
 tests/tpm2_key_protector_test.in | 155 ++++++++++---------------------
 1 file changed, 51 insertions(+), 104 deletions(-)
tests/tpm2_key_protector_test.in +51 -104
index a92e5f498..1ba70a3d5 100644
@@ -225,112 +225,45 @@ EOF
     fi
 }
 
-tpm2_seal_nv () {
-    keyfile="$1"
-    nv_index="$2"
-    pcr_list="$3"
-
-    primary_file=${tpm2testdir}/primary.ctx
-    session_file=${tpm2testdir}/session.dat
-    policy_file=${tpm2testdir}/policy.dat
-    keypub_file=${tpm2testdir}/key.pub
-    keypriv_file=${tpm2testdir}/key.priv
-    name_file=${tpm2testdir}/sealing.name
-    sealing_ctx_file=${tpm2testdir}/sealing.ctx
-
-    # Since we don't run a resource manager on our swtpm instance, it has
-    # to flush the transient handles after tpm2_createprimary, tpm2_create
-    # and tpm2_load to avoid the potential out-of-memory (0x902) errors.
-    # Ref: https://github.com/tpm2-software/tpm2-tools/issues/1338#issuecomment-469689398
-
-    # Create the primary object
-    tpm2_createprimary -Q -C o -g sha256 -G ecc -c "${primary_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to create the primary object: ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext -t || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
-    fi
-
-    # Create the policy object
-    tpm2_startauthsession -S "${session_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to start auth session: ${ret}" >&2
-	return 1
-    fi
-    tpm2_policypcr -Q -S "${session_file}" -l "${pcr_list}" -L "${policy_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to create the policy object: ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext "${session_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
-    fi
+tpm2_seal_unseal_nv() {
+    handle_type="$1"
+    key_type="$2"
 
-    # Seal the key into TPM
-    tpm2_create -Q \
-	-C "${primary_file}" \
-	-u "${keypub_file}" \
-	-r "${keypriv_file}" \
-	-L "${policy_file}" \
-	-i "${keyfile}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to seal \"${keyfile}\": ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext -t || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
-    fi
+    extra_opt=""
+    extra_grub_opt=""
 
-    tpm2_load -Q \
-	-C "${primary_file}" \
-	-u "${keypub_file}" \
-	-r "${keypriv_file}" \
-	-n "${name_file}" \
-	-c "${sealing_ctx_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to load the sealed key into TPM: ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext -t || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
+    if [ "$handle_type" == "nvindex" ]; then
+	nv_index="0x1000000"
+    else
+	nv_index="0x81000000"
     fi
 
-    tpm2_evictcontrol -Q -C o -c "${sealing_ctx_file}" ${nv_index} || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to store the sealed key into ${nv_index}: ${ret}" >&2
-	return 1
+    if [ "$key_type" == "tpm2key" ]; then
+	extra_opt="--tpm2key"
+    else
+	extra_grub_opt="--pcrs=0,1"
     fi
 
-    return 0
-}
-
-tpm2_seal_unseal_nv() {
-    nv_index="0x81000000"
-    pcr_list="sha256:0,1"
-
     grub_cfg=${tpm2testdir}/testcase.cfg
 
     # Seal the key into a NV index guarded by PCR 0 and 1
-    tpm2_seal_nv "${lukskeyfile}" ${nv_index} ${pcr_list} || ret=$?
+    grub-protect ${extra_opt} \
+	--tpm2-device="${tpm2dev}" \
+	--action=add \
+	--protector=tpm2 \
+	--tpm2-bank=sha256 \
+	--tpm2-pcrs=0,1 \
+	--tpm2-keyfile="${lukskeyfile}" \
+	--tpm2-nvindex="${nv_index}" || ret=$?
     if [ "${ret}" -ne 0 ]; then
-	echo "Failed to seal the secret key into ${nv_index}" >&2
+	echo "Failed to seal the secret key into ${nv_index}: ${ret}" >&2
 	return 99
     fi
 
     # Write the TPM unsealing script
     cat > ${grub_cfg} <<EOF
 loopback luks (host)${luksfile}
-tpm2_key_protector_init --mode=nv --nvindex=${nv_index} --pcrs=0,1
+tpm2_key_protector_init --mode=nv --nvindex=${nv_index} ${extra_grub_opt}
 if cryptomount -a --protector tpm2; then
     cat (crypto0)+1
 fi
@@ -340,7 +273,12 @@ EOF
     ${grubshell} --timeout=${timeout} --emu-opts="-t ${tpm2dev}" < "${grub_cfg}" > "${testoutput}" || ret=$?
 
     # Remove the object from the NV index
-    tpm2_evictcontrol -Q -C o -c "${nv_index}" || :
+    grub-protect \
+	--tpm2-device="${tpm2dev}" \
+	--protector=tpm2 \
+	--action=remove \
+	--tpm2-nvindex=${nv_index} \
+	--tpm2-evict || :
 
     if [ "${ret}" -eq 0 ]; then
 	if ! grep -q "^${vtext}$" "${testoutput}"; then
@@ -366,24 +304,33 @@ srktests+=("ECC transient fallback_srk")
 for i in "${!srktests[@]}"; do
     tpm2_seal_unseal ${srktests[$i]} || ret=$?
     if [ "${ret}" -eq 0 ]; then
-        echo "TPM2 [${srktests[$i]}]: PASS"
+	echo "TPM2 [SRK][${srktests[$i]}]: PASS"
     elif [ "${ret}" -eq 1 ]; then
-        echo "TPM2 [${srktests[$i]}]: FAIL"
+	echo "TPM2 [SRK][${srktests[$i]}]: FAIL"
+	ret=0
     else
-	echo "Unexpected failure [${srktests[$i]}]" >&2
+	echo "Unexpected failure [SRK][${srktests[$i]}]" >&2
 	exit ${ret}
     fi
 done
 
-# Testcase for NV index mode
-tpm2_seal_unseal_nv || ret=$?
-if [ "${ret}" -eq 0 ]; then
-    echo "TPM2 [NV Index]: PASS"
-elif [ "${ret}" -eq 1 ]; then
-    echo "TPM2 [NV Index]: FAIL"
-else
-    echo "Unexpected failure [NV index]" >&2
-    exit ${ret}
-fi
+# Testcases for NV index mode
+declare -a nvtests=()
+nvtests+=("persistent raw")
+nvtests+=("nvindex raw")
+nvtests+=("nvindex tpm2key")
+
+for i in "${!nvtests[@]}"; do
+    tpm2_seal_unseal_nv ${nvtests[$i]} || ret=$?
+    if [ "${ret}" -eq 0 ]; then
+	echo "TPM2 [NV Index][${nvtests[$i]}]: PASS"
+    elif [ "${ret}" -eq 1 ]; then
+	echo "TPM2 [NV Index][${nvtests[$i]}]: FAIL"
+	ret=0
+    else
+	echo "Unexpected failure [NV index][${nvtests[$i]}]" >&2
+	exit ${ret}
+    fi
+done
 
 exit 0
Signature · 7 lines
2.43.0


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

Re: [PATCH v3 09/10] tests/tpm2_key_protector_test: Amend the NV index mode test

Quoted 8 lines · Gary Lin via Grub-devel

Since 'grub-protect' already supports NV index mode, tpm2_seal_nv() is replaced with one 'grub-protect' command to simplify the test script.

Two more NV index test cases are also added to test key sealing and unsealing with the NV index handle 0x1000000.

Also, there is a minor fix to reset 'ret' to 0 when a test case fails so that the other test cases could continue.

Please split this patch into three ones.

Daniel

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

#24 lore raw

Re: [PATCH v3 09/10] tests/tpm2_key_protector_test: Amend the NV index mode test

In reply to Gary Lin via Grub-devel
Quoted 8 lines · On Mon, 13 Jan 2025 11:07:12 +0800 Gary Lin via Grub-devel…

Since 'grub-protect' already supports NV index mode, tpm2_seal_nv() is replaced with one 'grub-protect' command to simplify the test script.

Two more NV index test cases are also added to test key sealing and unsealing with the NV index handle 0x1000000.

Also, there is a minor fix to reset 'ret' to 0 when a test case fails so that the other test cases could continue.

I missed the original patch for this test, so this should have been said earlier. This patch goes a long way in removing external dependencies for this test, but it doesn't remove all of them. Please document all debian packages needed to be installed to run this test in the INSTALL file and note that they are needed for the tpm test (as done for other documented packages). This should go under the section "Prerequisites for make-check".

Thanks,
Glenn

Quoted 198 lines
---
 tests/tpm2_key_protector_test.in | 155 ++++++++++---------------------
 1 file changed, 51 insertions(+), 104 deletions(-)
tests/tpm2_key_protector_test.in +43 -104
index a92e5f498..1ba70a3d5 100644
@@ -225,112 +225,45 @@ EOF
     fi
 }
 
-tpm2_seal_nv () {
-    keyfile="$1"
-    nv_index="$2"
-    pcr_list="$3"
-
-    primary_file=${tpm2testdir}/primary.ctx
-    session_file=${tpm2testdir}/session.dat
-    policy_file=${tpm2testdir}/policy.dat
-    keypub_file=${tpm2testdir}/key.pub
-    keypriv_file=${tpm2testdir}/key.priv
-    name_file=${tpm2testdir}/sealing.name
-    sealing_ctx_file=${tpm2testdir}/sealing.ctx
-
-    # Since we don't run a resource manager on our swtpm instance, it has
-    # to flush the transient handles after tpm2_createprimary, tpm2_create
-    # and tpm2_load to avoid the potential out-of-memory (0x902) errors.
-    # Ref: https://github.com/tpm2-software/tpm2-tools/issues/1338#issuecomment-469689398
-
-    # Create the primary object
-    tpm2_createprimary -Q -C o -g sha256 -G ecc -c "${primary_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to create the primary object: ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext -t || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
-    fi
-
-    # Create the policy object
-    tpm2_startauthsession -S "${session_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to start auth session: ${ret}" >&2
-	return 1
-    fi
-    tpm2_policypcr -Q -S "${session_file}" -l "${pcr_list}" -L "${policy_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to create the policy object: ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext "${session_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
-    fi
+tpm2_seal_unseal_nv() {
+    handle_type="$1"
+    key_type="$2"
 
-    # Seal the key into TPM
-    tpm2_create -Q \
-	-C "${primary_file}" \
-	-u "${keypub_file}" \
-	-r "${keypriv_file}" \
-	-L "${policy_file}" \
-	-i "${keyfile}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to seal \"${keyfile}\": ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext -t || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
-    fi
+    extra_opt=""
+    extra_grub_opt=""
 
-    tpm2_load -Q \
-	-C "${primary_file}" \
-	-u "${keypub_file}" \
-	-r "${keypriv_file}" \
-	-n "${name_file}" \
-	-c "${sealing_ctx_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to load the sealed key into TPM: ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext -t || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
+    if [ "$handle_type" == "nvindex" ]; then
+	nv_index="0x1000000"
+    else
+	nv_index="0x81000000"
     fi
 
-    tpm2_evictcontrol -Q -C o -c "${sealing_ctx_file}" ${nv_index} || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to store the sealed key into ${nv_index}: ${ret}" >&2
-	return 1
+    if [ "$key_type" == "tpm2key" ]; then
+	extra_opt="--tpm2key"
+    else
+	extra_grub_opt="--pcrs=0,1"
     fi
 
-    return 0
-}
-
-tpm2_seal_unseal_nv() {
-    nv_index="0x81000000"
-    pcr_list="sha256:0,1"
-
     grub_cfg=${tpm2testdir}/testcase.cfg
 
     # Seal the key into a NV index guarded by PCR 0 and 1
-    tpm2_seal_nv "${lukskeyfile}" ${nv_index} ${pcr_list} || ret=$?
+    grub-protect ${extra_opt} \
+	--tpm2-device="${tpm2dev}" \
+	--action=add \
+	--protector=tpm2 \
+	--tpm2-bank=sha256 \
+	--tpm2-pcrs=0,1 \
+	--tpm2-keyfile="${lukskeyfile}" \
+	--tpm2-nvindex="${nv_index}" || ret=$?
     if [ "${ret}" -ne 0 ]; then
-	echo "Failed to seal the secret key into ${nv_index}" >&2
+	echo "Failed to seal the secret key into ${nv_index}: ${ret}" >&2
 	return 99
     fi
 
     # Write the TPM unsealing script
     cat > ${grub_cfg} <<EOF
 loopback luks (host)${luksfile}
-tpm2_key_protector_init --mode=nv --nvindex=${nv_index} --pcrs=0,1
+tpm2_key_protector_init --mode=nv --nvindex=${nv_index} ${extra_grub_opt}
 if cryptomount -a --protector tpm2; then
     cat (crypto0)+1
 fi
@@ -340,7 +273,12 @@ EOF
     ${grubshell} --timeout=${timeout} --emu-opts="-t ${tpm2dev}" < "${grub_cfg}" > "${testoutput}" || ret=$?
 
     # Remove the object from the NV index
-    tpm2_evictcontrol -Q -C o -c "${nv_index}" || :
+    grub-protect \
+	--tpm2-device="${tpm2dev}" \
+	--protector=tpm2 \
+	--action=remove \
+	--tpm2-nvindex=${nv_index} \
+	--tpm2-evict || :
 
     if [ "${ret}" -eq 0 ]; then
 	if ! grep -q "^${vtext}$" "${testoutput}"; then
@@ -366,24 +304,33 @@ srktests+=("ECC transient fallback_srk")
 for i in "${!srktests[@]}"; do
     tpm2_seal_unseal ${srktests[$i]} || ret=$?
     if [ "${ret}" -eq 0 ]; then
-        echo "TPM2 [${srktests[$i]}]: PASS"
+	echo "TPM2 [SRK][${srktests[$i]}]: PASS"
     elif [ "${ret}" -eq 1 ]; then
-        echo "TPM2 [${srktests[$i]}]: FAIL"
+	echo "TPM2 [SRK][${srktests[$i]}]: FAIL"
+	ret=0
     else
-	echo "Unexpected failure [${srktests[$i]}]" >&2
+	echo "Unexpected failure [SRK][${srktests[$i]}]" >&2
 	exit ${ret}
     fi
 done
 
-# Testcase for NV index mode
-tpm2_seal_unseal_nv || ret=$?
-if [ "${ret}" -eq 0 ]; then
-    echo "TPM2 [NV Index]: PASS"
-elif [ "${ret}" -eq 1 ]; then
-    echo "TPM2 [NV Index]: FAIL"
-else
-    echo "Unexpected failure [NV index]" >&2
-    exit ${ret}
-fi
+# Testcases for NV index mode
+declare -a nvtests=()
+nvtests+=("persistent raw")
+nvtests+=("nvindex raw")
+nvtests+=("nvindex tpm2key")
+
+for i in "${!nvtests[@]}"; do
+    tpm2_seal_unseal_nv ${nvtests[$i]} || ret=$?
+    if [ "${ret}" -eq 0 ]; then
+	echo "TPM2 [NV Index][${nvtests[$i]}]: PASS"

tests/tpm2_key_protector_test.in srktests+=("ECC transient fallback_srk") · line 336

Quoted 10 lines
tests/tpm2_key_protector_test.in +8 -0
+    elif [ "${ret}" -eq 1 ]; then
+	echo "TPM2 [NV Index][${nvtests[$i]}]: FAIL"
+	ret=0
+    else
+	echo "Unexpected failure [NV index][${nvtests[$i]}]" >&2
+	exit ${ret}
+    fi
+done
 
 exit 0

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

#25 lore raw

Re: [PATCH v3 09/10] tests/tpm2_key_protector_test: Amend the NV index mode test

Quoted 12 lines · Glenn Washburn
Quoted 8 lines · On Mon, 13 Jan 2025 11:07:12 +0800 Gary Lin via Grub-devel…

Since 'grub-protect' already supports NV index mode, tpm2_seal_nv() is replaced with one 'grub-protect' command to simplify the test script.

Two more NV index test cases are also added to test key sealing and unsealing with the NV index handle 0x1000000.

Also, there is a minor fix to reset 'ret' to 0 when a test case fails so that the other test cases could continue.

Quoted 8 lines

I missed the original patch for this test, so this should have been said earlier. This patch goes a long way in removing external dependencies for this test, but it doesn't remove all of them. Please document all debian packages needed to be installed to run this test in the INSTALL file and note that they are needed for the tpm test (as done for other documented packages). This should go under the section "Prerequisites for make-check".

Sure. I'll add swtpm and tpm2-tools to the INSTALL file.

Thanks,

Gary Lin

Quoted 210 lines

Thanks,
Glenn

Quoted 207 lines
---
 tests/tpm2_key_protector_test.in | 155 ++++++++++---------------------
 1 file changed, 51 insertions(+), 104 deletions(-)
tests/tpm2_key_protector_test.in +51 -104
index a92e5f498..1ba70a3d5 100644
@@ -225,112 +225,45 @@ EOF
     fi
 }
 
-tpm2_seal_nv () {
-    keyfile="$1"
-    nv_index="$2"
-    pcr_list="$3"
-
-    primary_file=${tpm2testdir}/primary.ctx
-    session_file=${tpm2testdir}/session.dat
-    policy_file=${tpm2testdir}/policy.dat
-    keypub_file=${tpm2testdir}/key.pub
-    keypriv_file=${tpm2testdir}/key.priv
-    name_file=${tpm2testdir}/sealing.name
-    sealing_ctx_file=${tpm2testdir}/sealing.ctx
-
-    # Since we don't run a resource manager on our swtpm instance, it has
-    # to flush the transient handles after tpm2_createprimary, tpm2_create
-    # and tpm2_load to avoid the potential out-of-memory (0x902) errors.
-    # Ref: https://github.com/tpm2-software/tpm2-tools/issues/1338#issuecomment-469689398
-
-    # Create the primary object
-    tpm2_createprimary -Q -C o -g sha256 -G ecc -c "${primary_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to create the primary object: ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext -t || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
-    fi
-
-    # Create the policy object
-    tpm2_startauthsession -S "${session_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to start auth session: ${ret}" >&2
-	return 1
-    fi
-    tpm2_policypcr -Q -S "${session_file}" -l "${pcr_list}" -L "${policy_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to create the policy object: ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext "${session_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
-    fi
+tpm2_seal_unseal_nv() {
+    handle_type="$1"
+    key_type="$2"
 
-    # Seal the key into TPM
-    tpm2_create -Q \
-	-C "${primary_file}" \
-	-u "${keypub_file}" \
-	-r "${keypriv_file}" \
-	-L "${policy_file}" \
-	-i "${keyfile}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to seal \"${keyfile}\": ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext -t || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
-    fi
+    extra_opt=""
+    extra_grub_opt=""
 
-    tpm2_load -Q \
-	-C "${primary_file}" \
-	-u "${keypub_file}" \
-	-r "${keypriv_file}" \
-	-n "${name_file}" \
-	-c "${sealing_ctx_file}" || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to load the sealed key into TPM: ${ret}" >&2
-	return 1
-    fi
-    tpm2_flushcontext -t || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to flush the transient handles: ${ret}" >&2
-	return 1
+    if [ "$handle_type" == "nvindex" ]; then
+	nv_index="0x1000000"
+    else
+	nv_index="0x81000000"
     fi
 
-    tpm2_evictcontrol -Q -C o -c "${sealing_ctx_file}" ${nv_index} || ret=$?
-    if [ "${ret}" -ne 0 ]; then
-	echo "Failed to store the sealed key into ${nv_index}: ${ret}" >&2
-	return 1
+    if [ "$key_type" == "tpm2key" ]; then
+	extra_opt="--tpm2key"
+    else
+	extra_grub_opt="--pcrs=0,1"
     fi
 
-    return 0
-}
-
-tpm2_seal_unseal_nv() {
-    nv_index="0x81000000"
-    pcr_list="sha256:0,1"
-
     grub_cfg=${tpm2testdir}/testcase.cfg
 
     # Seal the key into a NV index guarded by PCR 0 and 1
-    tpm2_seal_nv "${lukskeyfile}" ${nv_index} ${pcr_list} || ret=$?
+    grub-protect ${extra_opt} \
+	--tpm2-device="${tpm2dev}" \
+	--action=add \
+	--protector=tpm2 \
+	--tpm2-bank=sha256 \
+	--tpm2-pcrs=0,1 \
+	--tpm2-keyfile="${lukskeyfile}" \
+	--tpm2-nvindex="${nv_index}" || ret=$?
     if [ "${ret}" -ne 0 ]; then
-	echo "Failed to seal the secret key into ${nv_index}" >&2
+	echo "Failed to seal the secret key into ${nv_index}: ${ret}" >&2
 	return 99
     fi
 
     # Write the TPM unsealing script
     cat > ${grub_cfg} <<EOF
 loopback luks (host)${luksfile}
-tpm2_key_protector_init --mode=nv --nvindex=${nv_index} --pcrs=0,1
+tpm2_key_protector_init --mode=nv --nvindex=${nv_index} ${extra_grub_opt}
 if cryptomount -a --protector tpm2; then
     cat (crypto0)+1
 fi
@@ -340,7 +273,12 @@ EOF
     ${grubshell} --timeout=${timeout} --emu-opts="-t ${tpm2dev}" < "${grub_cfg}" > "${testoutput}" || ret=$?
 
     # Remove the object from the NV index
-    tpm2_evictcontrol -Q -C o -c "${nv_index}" || :
+    grub-protect \
+	--tpm2-device="${tpm2dev}" \
+	--protector=tpm2 \
+	--action=remove \
+	--tpm2-nvindex=${nv_index} \
+	--tpm2-evict || :
 
     if [ "${ret}" -eq 0 ]; then
 	if ! grep -q "^${vtext}$" "${testoutput}"; then
@@ -366,24 +304,33 @@ srktests+=("ECC transient fallback_srk")
 for i in "${!srktests[@]}"; do
     tpm2_seal_unseal ${srktests[$i]} || ret=$?
     if [ "${ret}" -eq 0 ]; then
-        echo "TPM2 [${srktests[$i]}]: PASS"
+	echo "TPM2 [SRK][${srktests[$i]}]: PASS"
     elif [ "${ret}" -eq 1 ]; then
-        echo "TPM2 [${srktests[$i]}]: FAIL"
+	echo "TPM2 [SRK][${srktests[$i]}]: FAIL"
+	ret=0
     else
-	echo "Unexpected failure [${srktests[$i]}]" >&2
+	echo "Unexpected failure [SRK][${srktests[$i]}]" >&2
 	exit ${ret}
     fi
 done
 
-# Testcase for NV index mode
-tpm2_seal_unseal_nv || ret=$?
-if [ "${ret}" -eq 0 ]; then
-    echo "TPM2 [NV Index]: PASS"
-elif [ "${ret}" -eq 1 ]; then
-    echo "TPM2 [NV Index]: FAIL"
-else
-    echo "Unexpected failure [NV index]" >&2
-    exit ${ret}
-fi
+# Testcases for NV index mode
+declare -a nvtests=()
+nvtests+=("persistent raw")
+nvtests+=("nvindex raw")
+nvtests+=("nvindex tpm2key")
+
+for i in "${!nvtests[@]}"; do
+    tpm2_seal_unseal_nv ${nvtests[$i]} || ret=$?
+    if [ "${ret}" -eq 0 ]; then
+	echo "TPM2 [NV Index][${nvtests[$i]}]: PASS"
+    elif [ "${ret}" -eq 1 ]; then
+	echo "TPM2 [NV Index][${nvtests[$i]}]: FAIL"
+	ret=0
+    else
+	echo "Unexpected failure [NV index][${nvtests[$i]}]" >&2
+	exit ${ret}
+    fi
+done
 
Quoted 1 line

tests/tpm2_key_protector_test.in srktests+=("ECC transient fallback_srk") · line 336

Quoted 1 line
tests/tpm2_key_protector_test.in +0 -0
 exit 0

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

#26 lore raw

PATCH v3 10/10 docs: Update NV index mode of TPM2 key protector

In reply to Gary Lin via Grub-devel

This commit updates the NV index mode section and the grub-protect section to reflect the recent changes in TPM2 key protector and grub-protect.

---
 docs/grub.texi | 189 +++++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 167 insertions(+), 22 deletions(-)
docs/grub.texi +167 -22
index aba43e35e..8a8a23e44 100644
@@ -9044,46 +9044,121 @@ When/After the shim or GRUB are updated, it only requires to run the last
 @subsection NV index mode
 
 Instead of storing the sealed key in a file, NV index mode uses the TPM
-non-volatile memory to store the sealed key.
+non-volatile memory to store the sealed key and could be useful when accessing
+the file is not possible.
 
-The following sample commands use tpm2-tools (@url{https://github.com/tpm2-software/tpm2-tools})
-commands to seal @file{luks.key} into the specific NV index: @kbd{0x81000000}.
+However, the Linux root user must be careful who she/he gives access to the
+TPM (tss group) since those users will also be able to modify the NV index
+that's holding the key.
 
-First, we need to create the object file for the primary key, i.e. storage
-root key (SRK) with the default key settings in GRUB: SHA256 hash algorithm
-and ECC key algorithm.
+There are two types of TPM handles supported by NV index mode: persistent
+handle and NV index handle.
+
+@subsubsection Persistent handle
+
+The range of persistent handles is from @kbd{0x81000000} to @kbd{0x81FFFFFF}.
+The persistent handle is designed to make TPM objects persistent through
+power cycles, and only TPM objects, such as RSA or EC keys, are accepted.
+Thus, TPM 2.0 Key File format is not supported by persistent handles. The
+following shows the @command{grub-protect} command to seal the disk key
+@file{luks.key} into the persistent handle @kbd{0x81000000} with the PCRs
+@kbd{0,2,4,7}.
 
 @example
-# @kbd{tpm2_createprimary -C o -g sha256 -G ecc -c primary.ctx}
+@group
+# @kbd{grub-protect \
+             --protector=tpm2 \
+             --action=add \
+             --tpm2-bank=sha256 \
+             --tpm2-pcrs=0,2,4,7 \
+             --tpm2-keyfile=luks.key \
+             --tpm2-nvindex=0x81000000}
+@end group
 @end example
 
-The next commands collect the current values of PCR 0, 2, 4, and 7 and saves
-them in @file{pcr.dat}.
+To unseal the key, we have to specify the mode @kbd{nv}, the persistent handle
+@kbd{0x81000000}, and the PCRs @kbd{0,2,4,7} for the @command{tpm2_key_protector_init}
+command.
 
 @example
-# @kbd{tpm2_startauthsession -S session.dat}
-# @kbd{tpm2_policypcr -S session.dat -l sha256:0,2,4,7 -f pcrs.dat -L policy.dat}
-# @kbd{tpm2_flushcontext session.dat}
+grub> @kbd{tpm2_key_protector_init --mode=nv --nvindex=0x81000000 --pcrs=0,2,4,7}
+grub> @kbd{cryptomount -u <UUID> --protector tpm2}
 @end example
 
-The last commands seal @file{luks.key} with the primary key and stores the
-result in @kbd{0x81000000}.
+If the key in the persistent handle becomes unwanted, the following
+@command{grub-protect} command removes the specified persistent handle
+@kbd{0x81000000}.
 
 @example
-# @kbd{cat luks.key | tpm2_create -C primary.ctx -u key.pub -r key.priv -L policy.dat -i-}
-# @kbd{tpm2_load -C primary.ctx -u key.pub -r key.priv -n sealing.name -c sealing.ctx}
-# @kbd{tpm2_evictcontrol -C o -c sealing.ctx 0x81000000}
+@group
+# @kbd{grub-protect \
+             --protector=tpm2 \
+             --action=remove \
+             --tpm2-evict \
+             --tpm2-nvindex=0x81000000}
+@end group
 @end example
 
-To unseal the key, we have to specify the mode @kbd{nv}, the NV index
-@kbd{0x81000000}, and the PCRs @kbd{0,2,4,7} for the @command{tpm2_key_protector_init}
-command.
+@subsubsection NV index handle
+
+The range of NV index handles is from @kbd{0x1000000} to @kbd{0x1FFFFFF}.
+Unlike the persistent handle, the NV index handle allows user-defined data,
+so it can easily support both the TPM 2.0 Key File format as well as the raw
+format.
+
+The following @kbd{grub-protect} command seals the disk key @file{luks.key}
+into the NV index handle @kbd{0x1000000} with the PCRs @kbd{0,2,4,7} while
+using the TPM 2.0 Key File format.
 
 @example
-grub> @kbd{tpm2_key_protector_init --mode=nv --nvindex=0x81000000 --pcrs=0,2,4,7}
+@group
+# @kbd{grub-protect \
+             --protector=tpm2 \
+             --action=add \
+             --tpm2key \
+             --tpm2-bank=sha256 \
+             --tpm2-pcrs=0,2,4,7 \
+             --tpm2-keyfile=luks.key \
+             --tpm2-nvindex=0x1000000}
+@end group
+@end example
+
+Furthermore, it is also possible to insert an existing key file,
+@file{sealed.tpm}, into a specific NV index handle using the following
+tpm2-tools (@url{https://github.com/tpm2-software/tpm2-tools}) commands.
+
+@example
+@group
+# @kbd{tpm2_nvdefine -C o \
+             -a "ownerread|ownerwrite" \
+             -s $(stat -c %s sealed.tpm) \
+             0x1000000}
+@end group
+# @kbd{tpm2_nvwrite -C o -i sealed.tpm 0x1000000}
+@end example
+
+When unsealing the key in TPM 2.0 Key File format, only the mode @kbd{nv}
+and the NV index handle @kbd{0x1000000} have to be specified for the
+@command{tpm2_key_protector_init} command.
+
+@example
+grub> @kbd{tpm2_key_protector_init --mode=nv --nvindex=0x1000000}
 grub> @kbd{cryptomount -u <UUID> --protector tpm2}
 @end example
 
+The following @command{grub-protect} command allows to remove the specified
+NV index handle @kbd{0x1000000}.
+
+@example
+@group
+# @kbd{grub-protect \
+             --protector=tpm2 \
+             --action=remove \
+             --tpm2-evict \
+             --tpm2-nvindex=0x1000000}
+@end group
+@end example
+
 @subsection Setting up software TPM for EMU platform
 
 In order to test TPM2 key protector and TPM2 Software Stack (TSS2), it is
@@ -10008,11 +10083,16 @@ unsealing. (default: @samp{7})
 @item --tpm2-srk=@var{handle}
 Set the SRK handle, e.g. @samp{0x81000000}, if the SRK is to be made persistent.
 
+@item --tpm2-nvindex=@var{handle}
+Set the handle, e.g. @samp{0x81000000} or @samp{0x1000000}, for NV index mode.
+
 @item --tpm2key
 Use TPM 2.0 Key File format.
 
 @end table
 
+@subsection 'Add' action
+
 Before sealing the key, please check the TPM PCR usage
 (@pxref{TPM2 key protector, TPM PCR usage}) to choose a proper set of PCRs.
 
@@ -10038,12 +10118,77 @@ grub> @kbd{tpm2_key_protector_init -T (hd0,gpt1)/efi/grub/sealed.tpm}
 grub> @kbd{cryptomount -u <UUID> -P tpm2}
 @end example
 
+Besides writing the PCR-sealed key into a file, @command{grub-protect} can
+write the sealed key into TPM non-volatile memory. Here is the
+@command{grub-protect} command to write the sealed key into the NV index
+handle @samp{0x1000000}.
+
+@example
+@group
+# @kbd{grub-protect --action=add \
+               --protector=tpm2 \
+               --tpm2-pcrs=0,2,4,7 \
+               --tpm2key \
+               --tpm2-keyfile=luks.key \
+               --tpm2-nvindex=0x1000000}
+@end group
+@end example
+
+Later, GRUB can fetch the key from @samp{0x1000000}.
+
+@example
+grub> @kbd{tpm2_key_protector_init --mode=nv --nvindex=0x1000000}
+grub> @kbd{cryptomount -u <UUID> -P tpm2}
+@end example
+
 In most of cases, the user only needs to create the key with the `add' action.
 If auto-unlocking is unwanted, just remove the file and the
 @command{tpm2_key_protector_init} command and invoke the @command{cryptomount}
 command without @kbd{-P tpm2}.
 
-The only use case for the `remove' action is when the SRK is made persistent.
+@subsection 'Remove' action
+
+The `remove' action is used to remove the handles for NV index mode and the
+persistent SRK.
+
+@subsubsection Handles for NV index mode
+
+There are two types of TPM handles supported by NV index mode: persistent
+handles and NV index handles, and @command{tpm2_getcap} can be used to
+check the existing handles.
+
+To display the list of existing persistent handles:
+
+@example
+@group
+# @kbd{tpm2_getcap handles-persistent}
+- 0x81000000
+@end group
+@end example
+
+Similarly, to display the list of existing NV index handles:
+
+@example
+@group
+# @kbd{tpm2_getcap handles-nv-index}
+- 0x1000000
+@end group
+@end example
+
+If the sealed key at an NV index handle is not needed anymore, the user can
+remove the handle with @kbd{--tpm2-nvindex} and @kbd{--tpm2-evict}. For
+example, this command removes the data from NV index @samp{0x1000000}:
+
+@example
+@group
+# @kbd{grub-protect --action=remove \
+               --protector=tpm2 \
+               --tpm2-evict \
+               --tpm2-nvindex 0x1000000} \
+@end group
+@end example
+
+@subsubsection Persistent SRK
 
 There are two supported SRKs in @command{grub-protect}: @samp{RSA} and @samp{ECC}.
 Due to slower key generation, some users of the @samp{RSA} SRK may prefer
Signature · 7 lines
2.43.0


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v3 10/10
#27 lore raw

Re: [PATCH v3 10/10] docs: Update NV index mode of TPM2 key protector

Quoted 5 lines · Gary Lin via Grub-devel

This commit updates the NV index mode section and the grub-protect section to reflect the recent changes in TPM2 key protector and grub-protect.

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

#28 lore raw

Re: [PATCH v3 10/10] docs: Update NV index mode of TPM2 key protector

In reply to Gary Lin via Grub-devel
Quoted 32 lines · Gary Lin via Grub-devel

This commit updates the NV index mode section and the grub-protect section to reflect the recent changes in TPM2 key protector and grub-protect.

---
 docs/grub.texi | 189 +++++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 167 insertions(+), 22 deletions(-)
docs/grub.texi +7 -6
index aba43e35e..8a8a23e44 100644
@@ -9044,46 +9044,121 @@ When/After the shim or GRUB are updated, it only requires to run the last
 @subsection NV index mode
 
 Instead of storing the sealed key in a file, NV index mode uses the TPM
-non-volatile memory to store the sealed key.
+non-volatile memory to store the sealed key and could be useful when accessing
+the file is not possible.
 
-The following sample commands use tpm2-tools (@url{https://github.com/tpm2-software/tpm2-tools})
-commands to seal @file{luks.key} into the specific NV index: @kbd{0x81000000}.
+However, the Linux root user must be careful who she/he gives access to the
+TPM (tss group) since those users will also be able to modify the NV index
+that's holding the key.
 
-First, we need to create the object file for the primary key, i.e. storage
-root key (SRK) with the default key settings in GRUB: SHA256 hash algorithm
-and ECC key algorithm.
+There are two types of TPM handles supported by NV index mode: persistent
+handle and NV index handle.

docs/grub.texi When/After the shim or GRUB are updated, it only requires to run the last · line 9065

Quoted 10 lines
docs/grub.texi +10 -0
+
+@subsubsection Persistent handle
+
+The range of persistent handles is from @kbd{0x81000000} to @kbd{0x81FFFFFF}.
+The persistent handle is designed to make TPM objects persistent through
+power cycles, and only TPM objects, such as RSA or EC keys, are accepted.
+Thus, TPM 2.0 Key File format is not supported by persistent handles. The
+following shows the @command{grub-protect} command to seal the disk key
+@file{luks.key} into the persistent handle @kbd{0x81000000} with the PCRs
+@kbd{0,2,4,7}.

Again, this paragraph seems to contain contradicting sentences. I think the missing part is explanation what kind of format is used to store luks.key if the "TPM 2.0 Key File format is not supported".

Daniel

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

#29 lore raw

Re: [PATCH v3 10/10] docs: Update NV index mode of TPM2 key protector

Quoted 39 lines · Daniel Kiper
Quoted 38 lines · Gary Lin via Grub-devel

This commit updates the NV index mode section and the grub-protect section to reflect the recent changes in TPM2 key protector and grub-protect.

---
 docs/grub.texi | 189 +++++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 167 insertions(+), 22 deletions(-)
docs/grub.texi +13 -6
index aba43e35e..8a8a23e44 100644
@@ -9044,46 +9044,121 @@ When/After the shim or GRUB are updated, it only requires to run the last
 @subsection NV index mode
 
 Instead of storing the sealed key in a file, NV index mode uses the TPM
-non-volatile memory to store the sealed key.
+non-volatile memory to store the sealed key and could be useful when accessing
+the file is not possible.
 
-The following sample commands use tpm2-tools (@url{https://github.com/tpm2-software/tpm2-tools})
-commands to seal @file{luks.key} into the specific NV index: @kbd{0x81000000}.
+However, the Linux root user must be careful who she/he gives access to the
+TPM (tss group) since those users will also be able to modify the NV index
+that's holding the key.
 
-First, we need to create the object file for the primary key, i.e. storage
-root key (SRK) with the default key settings in GRUB: SHA256 hash algorithm
-and ECC key algorithm.
+There are two types of TPM handles supported by NV index mode: persistent
+handle and NV index handle.
+
+@subsubsection Persistent handle
+
+The range of persistent handles is from @kbd{0x81000000} to @kbd{0x81FFFFFF}.
+The persistent handle is designed to make TPM objects persistent through
+power cycles, and only TPM objects, such as RSA or EC keys, are accepted.
Quoted 9 lines

docs/grub.texi When/After the shim or GRUB are updated, it only requires to run the last · line 9065

Quoted 4 lines
docs/grub.texi +4 -0
+Thus, TPM 2.0 Key File format is not supported by persistent handles. The
+following shows the @command{grub-protect} command to seal the disk key
+@file{luks.key} into the persistent handle @kbd{0x81000000} with the PCRs
+@kbd{0,2,4,7}.

Again, this paragraph seems to contain contradicting sentences. I think the missing part is explanation what kind of format is used to store luks.key if the "TPM 2.0 Key File format is not supported".

I'll change it to "only the raw format is supported".

Gary Lin

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