Skip to contentSkip to conversation

Automatic Disk Unlock with TPM2

PATCH Superseded Gary Lin 2 participants 15 messages Apr 12, 2023 – Apr 17, 2023 Kbuild

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Gary Lin

author
#0 lore raw

v3 cover Automatic Disk Unlock with TPM2

GIT repo for v3: https://github.com/lcp/grub2/tree/tpm2-unlock-v3

This patch series is based on "Automatic TPM Disk Unlock"(*1) posted by Hernan Gatta to introduce the key protector framework and TPM2 stack to GRUB2, and this could be a useful feature for the systems to implement full disk encryption.

To support TPM 2.0 Key File format(*2), patch 1~6 are grabbed from Daniel Axtens's "appended signature secure boot support" (*3) to import libtasn1 into grub2. Besides, the libtasn1 version is upgraded to 4.19.0 instead of 4.16.0 in the original patch.

Patch 7 adds the document for libtasn1 and the steps to upgrade the library.

Patch 8~12 are Hernan Gatta's patches with the follow-up fixes and improvements:
- Converting 8 spaces into 1 tab
- Merging the minor build fix from Michael Chang
- Replacing "lu" with "PRIuGRUB_SIZE" for grub_dprintf
- Adding "enable = efi" to the tpm2 module in grub-core/Makefile.core.def
- Rebasing "cryptodisk: Support key protectors" to the git master
- Removing the measurement on the sealed key
- Based ont the patch from Olaf Kirch <[email protected]>
- Adjusting the input parameters of TPM2_EvictControl to match the order in "TCG TPM2 Part3 Commands"
- Declaring the input arguments of TPM2 functions as const
- Resending TPM2 commands on TPM_RC_RETRY
- Adding checks for the parameters of TPM2 commands
- Packing the missing authorization command for TPM2_PCR_Read
- Tweaking the TPM2 command functions to allow some parameters to be NULL so that we don't have to declare empty variables
- Only enabling grub-protect for "efi" since the TPM2 stack currently relies on the EFI TCG2 protocol to send TPM2 commands
- Using grub_cpu_to_be*() in the TPM2 stack instead of grub_swap_bytes*() which may cause problems in big-indian machines
- Changing the short name of "--protector" of "cryptomount" from "-k" to "-P" to avoid the conflict with "--key-file"
- Supporting TPM 2.0 Key File Format besides the raw sealed key
- Adding the external libtasn1 dependency to grub-protect to write the TPM 2.0 Key files

To utilize the TPM2 key protector to unlock the encrypted partition (sdb1), here are the sample steps:

1. Add an extra random key for LUKS (luks-key)

   $ dd if=/dev/urandom of=luks-key bs=1 count=32
   $ sudo cryptsetup luksAddKey /dev/sdb1 luks-key --pbkdf=pbkdf2

2. Seal the key

   $ sudo grub-protect --action=add \
                       --protector=tpm2 \
                       --tpm2key \
                       --tpm2-keyfile=luks-key \
                       --tpm2-outfile=/boot/efi/boot/grub2/sealed.tpm

3. Unseal the key with the proper commands in grub.cfg:
tpm2_key_protector_init --tpm2key=(hd0,gpt1)/boot/grub2/sealed.tpm cryptomount -u SDB1_UUID -P tpm2

(*1) https://lists.gnu.org/archive/html/grub-devel/2022-02/msg00006.html
(*2) https://www.hansenpartnership.com/draft-bottomley-tpm2-keys.html
(*3) https://lists.gnu.org/archive/html/grub-devel/2021-06/msg00044.html

v3:
- Adding the document for libtasn1
- Improving the error condition checks
ex: "if (!ptr)" ==> "if (ptr == NULL)"

      "if (err)" ==> "if (err != GRUB_ERR_NONE)"
      "if (rc)" ==> "if (rc != TPM_RC_SUCCESS)"

- Supporting the "TPMPolicy" and "TPMAuthPolicy" sequence in the TPM 2.0 key File
- Refactoring the key recover function to support "TPMPolicy" and "TPMAuthPolicy" sequence
- Using TPMS_PCR_SELECTION_SelectPCR() to set the PCR bit mask
- Also dropping TPM2_PCR_TO_SELECT() and TPM2_PCR_TO_BIT() which are not necessary anymore
- Removing the redundant variable, 'crd', from grub_cryptodisk_scan_device_real()
- Fixing the spaces/tabs in cryptodisk.c
- Fixing the comment format in cryptodisk.h
- Adding the defensive check for "cargs->protectors" in grub_cryptodisk_scan_device()
- Improving 'grub-protect' for the better support of TPM 2.0 Key File
- Adding more comments

Daniel Axtens (6):
posix_wrap: tweaks in preparation for libtasn1
libtasn1: import libtasn1-4.19.0
libtasn1: disable code not needed in grub
libtasn1: changes for grub compatibility
libtasn1: compile into asn1 module
test_asn1: test module for libtasn1

Gary Lin (1):
libtasn1: Add the documentation

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

 .gitignore                                    |    2 +
 Makefile.util.def                             |   29 +
 configure.ac                                  |    9 +
 docs/grub-dev.texi                            |   27 +
 grub-core/Makefile.am                         |    1 +
 grub-core/Makefile.core.def                   |   42 +
 grub-core/disk/cryptodisk.c                   |  172 +-
 grub-core/kern/protectors.c                   |   75 +
 ...asn1-disable-code-not-needed-in-grub.patch |  311 ++
 ...tasn1-changes-for-grub-compatibility.patch |  209 ++
 grub-core/lib/libtasn1/COPYING                |   16 +
 grub-core/lib/libtasn1/README.md              |   98 +
 grub-core/lib/libtasn1/lib/coding.c           | 1433 ++++++++++
 grub-core/lib/libtasn1/lib/decoding.c         | 2504 +++++++++++++++++
 grub-core/lib/libtasn1/lib/element.c          | 1110 ++++++++
 grub-core/lib/libtasn1/lib/element.h          |   42 +
 grub-core/lib/libtasn1/lib/errors.c           |  103 +
 grub-core/lib/libtasn1/lib/gstr.c             |   74 +
 grub-core/lib/libtasn1/lib/gstr.h             |   50 +
 grub-core/lib/libtasn1/lib/int.h              |  221 ++
 grub-core/lib/libtasn1/lib/parser_aux.c       | 1179 ++++++++
 grub-core/lib/libtasn1/lib/parser_aux.h       |  172 ++
 grub-core/lib/libtasn1/lib/structure.c        | 1227 ++++++++
 grub-core/lib/libtasn1/lib/structure.h        |   46 +
 .../tests/CVE-2018-1000654-1_asn1_tab.h       |   32 +
 .../tests/CVE-2018-1000654-2_asn1_tab.h       |   36 +
 .../libtasn1_wrap/tests/CVE-2018-1000654.c    |   61 +
 .../lib/libtasn1_wrap/tests/Test_overflow.c   |  138 +
 .../lib/libtasn1_wrap/tests/Test_simple.c     |  207 ++
 .../lib/libtasn1_wrap/tests/Test_strings.c    |  150 +
 .../libtasn1_wrap/tests/object-id-decoding.c  |  116 +
 .../libtasn1_wrap/tests/object-id-encoding.c  |  120 +
 .../lib/libtasn1_wrap/tests/octet-string.c    |  211 ++
 .../lib/libtasn1_wrap/tests/reproducers.c     |   81 +
 grub-core/lib/libtasn1_wrap/wrap.c            |   26 +
 grub-core/lib/libtasn1_wrap/wrap_tests.c      |   75 +
 grub-core/lib/libtasn1_wrap/wrap_tests.h      |   38 +
 grub-core/lib/posix_wrap/limits.h             |    1 +
 grub-core/lib/posix_wrap/stdlib.h             |    8 +
 grub-core/lib/posix_wrap/sys/types.h          |    1 +
 grub-core/tpm2/args.c                         |  131 +
 grub-core/tpm2/buffer.c                       |  145 +
 grub-core/tpm2/module.c                       | 1040 +++++++
 grub-core/tpm2/mu.c                           |  807 ++++++
 grub-core/tpm2/tcg2.c                         |  143 +
 grub-core/tpm2/tpm2.c                         |  761 +++++
 grub-core/tpm2/tpm2key.asn                    |   31 +
 grub-core/tpm2/tpm2key.c                      |  431 +++
 grub-core/tpm2/tpm2key_asn1_tab.c             |   41 +
 include/grub/cryptodisk.h                     |   16 +
 include/grub/libtasn1.h                       |  645 +++++
 include/grub/protector.h                      |   48 +
 include/grub/tpm2/buffer.h                    |   65 +
 include/grub/tpm2/internal/args.h             |   39 +
 include/grub/tpm2/internal/functions.h        |  117 +
 include/grub/tpm2/internal/structs.h          |  675 +++++
 include/grub/tpm2/internal/types.h            |  372 +++
 include/grub/tpm2/mu.h                        |  292 ++
 include/grub/tpm2/tcg2.h                      |   34 +
 include/grub/tpm2/tpm2.h                      |   34 +
 include/grub/tpm2/tpm2key.h                   |   83 +
 tests/test_asn1.in                            |   12 +
 util/grub-protect.c                           | 1508 ++++++++++
 63 files changed, 17892 insertions(+), 31 deletions(-)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 grub-core/lib/libtasn1-patches/0001-libtasn1-disable-code-not-needed-in-grub.patch
 create mode 100644 grub-core/lib/libtasn1-patches/0002-libtasn1-changes-for-grub-compatibility.patch
 create mode 100644 grub-core/lib/libtasn1/COPYING
 create mode 100644 grub-core/lib/libtasn1/README.md
 create mode 100644 grub-core/lib/libtasn1/lib/coding.c
 create mode 100644 grub-core/lib/libtasn1/lib/decoding.c
 create mode 100644 grub-core/lib/libtasn1/lib/element.c
 create mode 100644 grub-core/lib/libtasn1/lib/element.h
 create mode 100644 grub-core/lib/libtasn1/lib/errors.c
 create mode 100644 grub-core/lib/libtasn1/lib/gstr.c
 create mode 100644 grub-core/lib/libtasn1/lib/gstr.h
 create mode 100644 grub-core/lib/libtasn1/lib/int.h
 create mode 100644 grub-core/lib/libtasn1/lib/parser_aux.c
 create mode 100644 grub-core/lib/libtasn1/lib/parser_aux.h
 create mode 100644 grub-core/lib/libtasn1/lib/structure.c
 create mode 100644 grub-core/lib/libtasn1/lib/structure.h
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-1_asn1_tab.h
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-2_asn1_tab.h
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_overflow.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_simple.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_strings.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/object-id-decoding.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/object-id-encoding.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/octet-string.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/reproducers.c
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap.c
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap_tests.c
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap_tests.h
 create mode 100644 grub-core/tpm2/args.c
 create mode 100644 grub-core/tpm2/buffer.c
 create mode 100644 grub-core/tpm2/module.c
 create mode 100644 grub-core/tpm2/mu.c
 create mode 100644 grub-core/tpm2/tcg2.c
 create mode 100644 grub-core/tpm2/tpm2.c
 create mode 100644 grub-core/tpm2/tpm2key.asn
 create mode 100644 grub-core/tpm2/tpm2key.c
 create mode 100644 grub-core/tpm2/tpm2key_asn1_tab.c
 create mode 100644 include/grub/libtasn1.h
 create mode 100644 include/grub/protector.h
 create mode 100644 include/grub/tpm2/buffer.h
 create mode 100644 include/grub/tpm2/internal/args.h
 create mode 100644 include/grub/tpm2/internal/functions.h
 create mode 100644 include/grub/tpm2/internal/structs.h
 create mode 100644 include/grub/tpm2/internal/types.h
 create mode 100644 include/grub/tpm2/mu.h
 create mode 100644 include/grub/tpm2/tcg2.h
 create mode 100644 include/grub/tpm2/tpm2.h
 create mode 100644 include/grub/tpm2/tpm2key.h
 create mode 100644 tests/test_asn1.in
 create mode 100644 util/grub-protect.c

Range-diff against v2:

 -:  --------- >  1:  f2a39b639 posix_wrap: tweaks in preparation for libtasn1
 -:  --------- >  2:  493f2dc86 libtasn1: import libtasn1-4.19.0
 -:  --------- >  3:  c1c345915 libtasn1: disable code not needed in grub
 -:  --------- >  4:  5d84feb27 libtasn1: changes for grub compatibility
 -:  --------- >  5:  21441d802 libtasn1: compile into asn1 module
 -:  --------- >  6:  7064cf0bc test_asn1: test module for libtasn1
 -:  --------- >  7:  5485acfb8 libtasn1: Add the documentation
 1:  623072114 !  8:  327bb228f protectors: Add key protectors framework
    @@ grub-core/kern/protectors.c (new)
     +grub_err_t
     +grub_key_protector_register (struct grub_key_protector *protector)
     +{
    -+  if (!protector || !protector->name || !grub_strlen(protector->name))
    ++  if (protector == NULL || protector->name == NULL || grub_strlen(protector->name) == 0)
     +    return GRUB_ERR_BAD_ARGUMENT;
     +
     +  if (grub_key_protectors &&
    @@ grub-core/kern/protectors.c (new)
     +grub_err_t
     +grub_key_protector_unregister (struct grub_key_protector *protector)
     +{
    -+  if (!protector)
    ++  if (protector == NULL)
     +    return GRUB_ERR_BAD_ARGUMENT;
     +
     +  grub_list_remove (GRUB_AS_LIST (protector));
    @@ grub-core/kern/protectors.c (new)
     +{
     +  struct grub_key_protector *kp = NULL;
     +
    -+  if (!grub_key_protectors)
    ++  if (grub_key_protectors == NULL)
     +    return GRUB_ERR_OUT_OF_RANGE;
     +
    -+  if (!protector || !grub_strlen (protector))
    ++  if (protector == NULL || grub_strlen (protector) == 0)
     +    return GRUB_ERR_BAD_ARGUMENT;
     +
     +  kp = grub_named_list_find (GRUB_AS_NAMED_LIST (grub_key_protectors),
     +			     protector);
    -+  if (!kp)
    ++  if (kp == NULL)
     +    return grub_error (GRUB_ERR_OUT_OF_RANGE,
     +		       N_("A key protector with name '%s' could not be found. "
     +			  "Is the name spelled correctly and is the "
 2:  444c0038f !  9:  ced33130b tpm2: Add TPM Software Stack (TSS)
    @@ include/grub/tpm2/tpm2.h (new)
     +#include <grub/tpm2/internal/structs.h>
     +#include <grub/tpm2/internal/functions.h>
     +
    -+/* Defined in: TCG TPM Specification, v1.59, Part 2, Section 10.6.1. */
    -+#define TPM2_PCR_TO_SELECT(x)  ((x) / 8)
    -+#define TPM2_PCR_TO_BIT(x)     (1 << ((x) % 8))
    -+
     +/* Well-Known Windows SRK handle */
     +#define TPM2_SRK_HANDLE 0x81000001
     +
 3:  b579f35d3 ! 10:  2249db295 protectors: Add TPM2 Key Protector
    @@ Commit message
     
         The theory of operation is such that the module accepts various
         arguments, most of which are optional and therefore possess reasonable
    -    defaults. One of these arguments is the keyfile parameter, which is
    -    mandatory. There are two supported key formats:
    +    defaults. One of these arguments is the keyfile/tpm2key parameter, which
    +    is mandatory. There are two supported key formats:
     
         1. Raw Sealed Key (--keyfile)
    -       The raw sealed key glues TPM2B_PUBLIC and TPM2B_PRIVATE, which are
    -       returned from TPM2_Create, into one file, and is defined as a C
    -       struct:
    -
    -       typedef struct TPM2_SEALED_KEY {
    -         TPM2B_PUBLIC  public;
    -         TPM2B_PRIVATE private;
    -       } TPM2_SEALED_KEY;
    +       When sealing a key with TPM2_Create, the public portion of the sealed
    +       key is stored in TPM2B_PUBLIC, and the private portion is in
    +       TPM2B_PRIVATE. The raw sealed key glues the fully marshalled
    +       TPM2B_PUBLIC and TPM2B_PRIVATE into one file.
     
         2. TPM 2.0 Key (--tpm2key)
            The following is the ASN.1 definition of TPM 2.0 Key File:
     
    +       TPMPolicy ::= SEQUENCE {
    +         CommandCode   [0] EXPLICIT INTEGER
    +         CommandPolicy [1] EXPLICIT OCTET STRING
    +       }
    +
    +       TPMAuthPolicy ::= SEQUENCE {
    +         Name    [0] EXPLICIT UTF8STRING OPTIONAL
    +         Policy  [1] EXPLICIT SEQUENCE OF TPMPolicy
    +       }
    +
            TPMKey ::= SEQUENCE {
    -        type        OBJECT IDENTIFIER
    -        emptyAuth   [0] EXPLICIT BOOLEAN OPTIONAL
    -        policy      [1] EXPLICIT SEQUENCE OF TPMPolicy OPTIONAL
    -        secret      [2] EXPLICIT OCTET STRING OPTIONAL
    -        authPolicy  [3] EXPLICIT SEQUENCE OF TPMAuthPolicy OPTIONAL
    -        parent      INTEGER
    -        pubkey      OCTET STRING
    -        privkey     OCTET STRING
    -      }
    +         type        OBJECT IDENTIFIER
    +         emptyAuth   [0] EXPLICIT BOOLEAN OPTIONAL
    +         policy      [1] EXPLICIT SEQUENCE OF TPMPolicy OPTIONAL
    +         secret      [2] EXPLICIT OCTET STRING OPTIONAL
    +         authPolicy  [3] EXPLICIT SEQUENCE OF TPMAuthPolicy OPTIONAL
    +         parent      INTEGER
    +         pubkey      OCTET STRING
    +         privkey     OCTET STRING
    +       }
     
           The TPM2 key protector only expects a "sealed" key in DER encoding,
           so 'type' is always 2.23.133.10.1.5, 'emptyAuth' is 'TRUE', and
    -      'secret' is empty. TPM2B_PUBLIC is stored in 'pubkey' and
    -      TPM2B_PRIVATE is stored in 'privkey'. 'policy' and 'authPolicy' are
    -      ignored for the time being and will be used for the advanced features
    -      in the future.
    +      'secret' is empty. 'policy' and 'authPolicy' are the possible policy
    +      command sequences to construst the policy digest to unseal the key.
    +      Similar to the raw sealed key, the public portion (TPM2B_PUBLIC) of
    +      the sealed key is stored in 'pubkey', and the private portion
    +      (TPM2B_PRIVATE) is in 'privkey'.
     
           For more details: https://www.hansenpartnership.com/draft-bottomley-tpm2-keys.html
     
    @@ Commit message
         - tpm2_key_protector_clear: Clears any state set by tpm2_key_protector_init.
     
         The way this is expected to be used requires the user to, either
    -    interactively or, normally, via a boot script, initialize (i.e.,
    -    configure) the key protector and then specify that it be used by the
    -    'cryptomount' command (modifications to this command are in a different
    -    patch).
    +    interactively or, normally, via a boot script, initialize/configure
    +    the key protector and then specify that it be used by the 'cryptomount'
    +    command (modifications to this command are in a different patch).
     
         For instance, to unseal the raw sealed key file:
     
    @@ Commit message
         tpm2_key_protector_init --tpm2key=(hd0,gpt1)/efi/grub2/sealed-2.tpm --pcrs=7,11
         cryptomount DISK2 -P tpm2
     
    -    If a user does not initialize the key protector and attempts to use it anyway,
    -    the protector returns an error.
    +    If a user does not initialize the key protector and attempts to use it
    +    anyway, the protector returns an error.
    +
    +    Before unsealing the key, the TPM2 key protector follows the "TPMPolicy"
    +    sequences to enforce the TPM policy commands to construct a valid policy
    +    digest to unseal the key.
    +
    +    For the TPM 2.0 Key files, 'authPolicy' may contain multiple "TPMPolicy"
    +    sequences, the TPM2 key protector iterates 'authPolicy' to find a valid
    +    sequence to unseal key. If 'authPolicy' is empty or all sequences in
    +    'authPolicy' fail, the protector tries the one from 'policy'. In case
    +    'policy' is also empty, the protector creates a "TPMPolicy" sequence
    +    based on the given PCR selection.
    +
    +    For the raw sealed key, the TPM2 key protector treats the key file as a
    +    TPM 2.0 Key file without 'authPolicy' and 'policy', so the "TPMPolicy"
    +    sequence is always based on the PCR selection from the command
    +    parameters.
    +
    +    Currently, there is only one supported policy command: TPM2_PolicyPCR.
    +    The command set can be extended to support advanced features, such as
    +    as authorized policy, in the future.
     
         Signed-off-by: Hernan Gatta <[email protected]>
         Signed-off-by: Gary Lin <[email protected]>
    @@ grub-core/tpm2/args.c (new)
     +      pcrs[i] = (grub_uint8_t)pcr;
     +      *pcr_count += 1;
     +
    -+      if (!next_pcr)
    ++      if (next_pcr == NULL)
     +	break;
     +
     +      current_pcr = next_pcr + 1;
    @@ grub-core/tpm2/args.c (new)
     +    *bank = TPM_ALG_SHA256;
     +  else if (grub_strcasecmp (value, "SHA384") == 0)
     +    *bank = TPM_ALG_SHA384;
    ++  else if (grub_strcasecmp (value, "SHA512") == 0)
    ++    *bank = TPM_ALG_SHA512;
     +  else
     +    return grub_error (GRUB_ERR_OUT_OF_RANGE,
     +		       N_("Value '%s' is not a valid PCR bank"), value);
    @@ grub-core/tpm2/module.c (new)
     +#include <grub/extcmd.h>
     +#include <grub/file.h>
     +#include <grub/libtasn1.h>
    ++#include <grub/list.h>
     +#include <grub/misc.h>
     +#include <grub/mm.h>
     +#include <grub/protector.h>
     +#include <grub/tpm2/buffer.h>
     +#include <grub/tpm2/internal/args.h>
    ++#include <grub/tpm2/internal/types.h>
     +#include <grub/tpm2/mu.h>
     +#include <grub/tpm2/tpm2.h>
     +#include <grub/tpm2/tpm2key.h>
    @@ grub-core/tpm2/module.c (new)
     +  /* Using GRUB_FILE_TYPE_SIGNATURE ensures we do not hash the keyfile into PCR9
     +   * otherwise we'll never be able to predict the value of PCR9 at unseal time */
     +  file = grub_file_open (filepath, GRUB_FILE_TYPE_SIGNATURE);
    -+  if (!file)
    ++  if (file == NULL)
     +    {
     +      grub_dprintf ("tpm2", "Could not open file: %s\n", filepath);
     +      /* grub_file_open sets grub_errno on error, and if we do no unset it,
    @@ grub-core/tpm2/module.c (new)
     +    }
     +
     +  file_size = grub_file_size (file);
    -+  if (!file_size)
    ++  if (file_size == 0)
     +    {
     +      grub_dprintf ("tpm2", "Could not read file size: %s\n", filepath);
     +      grub_file_close (file);
    @@ grub-core/tpm2/module.c (new)
     +    }
     +
     +  read_buffer = grub_malloc (file_size);
    -+  if (!read_buffer)
    ++  if (read_buffer == NULL)
     +    {
     +      grub_dprintf ("tpm2", "Could not allocate buffer for %s.\n", filepath);
     +      grub_file_close (file);
    @@ grub-core/tpm2/module.c (new)
     +static grub_err_t
     +grub_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_uint32_t *parent,
     +					   TPM2_SEALED_KEY *sk)
     +{
    @@ grub-core/tpm2/module.c (new)
     +  struct grub_tpm2_buffer buf;
     +  grub_err_t err;
     +
    ++  /*
    ++   * Start to parse the tpm2key file
    ++   * TPMKey ::= SEQUENCE {
    ++   *     type        OBJECT IDENTIFIER,
    ++   *     emptyAuth   [0] EXPLICIT BOOLEAN OPTIONAL,
    ++   *     policy      [1] EXPLICIT SEQUENCE OF TPMPolicy OPTIONAL,
    ++   *     secret      [2] EXPLICIT OCTET STRING OPTIONAL,
    ++   *     authPolicy  [3] EXPLICIT SEQUENCE OF TPMAuthPolicy OPTIONAL,
    ++   *     parent      INTEGER,
    ++   *     pubkey      OCTET STRING,
    ++   *     privkey     OCTET STRING
    ++   * }
    ++   */
     +  err = grub_tpm2key_start_parsing (&tpm2key, sealed_key, sealed_key_size);
     +  if (err != GRUB_ERR_NONE)
     +    return err;
     +
    ++  /*
    ++   * Retrieve the policy sequence from 'policy'
    ++   * policy_seq will be NULL when 'policy' is not available
    ++   */
    ++  err = grub_tpm2key_get_policy_seq (tpm2key, policy_seq);
    ++  if (err != GRUB_ERR_NONE)
    ++    goto error;
    ++
    ++  /*
    ++   * Retrieve the authpolicy sequence from 'authPolicy'
    ++   * authpol_seq will be NULL when 'authPolicy' is not available
    ++   */
    ++  err = grub_tpm2key_get_authpolicy_seq (tpm2key, authpol_seq);
    ++  if (err != GRUB_ERR_NONE)
    ++    goto error;
    ++
    ++  /* Retrieve the parent handle */
     +  err = grub_tpm2key_get_parent (tpm2key, &parent_tmp);
     +  if (err != GRUB_ERR_NONE)
     +    goto error;
     +  *parent = parent_tmp;
     +
    ++  /* Retrieve the public part of the sealed key */
     +  err = grub_tpm2key_get_pubkey (tpm2key, &sealed_pub, &sealed_pub_size);
     +  if (err != GRUB_ERR_NONE)
     +    goto error;
     +
    ++  /* Retrieve the private part of the sealed key */
     +  err = grub_tpm2key_get_privkey (tpm2key, &sealed_priv, &sealed_priv_size);
     +  if (err != GRUB_ERR_NONE)
     +    goto error;
     +
    ++  /* Unmarshal the sealed key */
     +  grub_tpm2_buffer_init (&buf);
     +  if (sealed_pub_size + sealed_priv_size > buf.cap)
     +    {
    @@ grub-core/tpm2/module.c (new)
     +  err = GRUB_ERR_NONE;
     +
     +error:
    ++  /* End the parsing */
     +  grub_tpm2key_end_parsing (tpm2key);
     +  grub_free (sealed_pub);
     +  grub_free (sealed_priv);
    @@ grub-core/tpm2/module.c (new)
     +}
     +
     +static grub_err_t
    -+grub_tpm2_protector_srk_recover (const struct grub_tpm2_protector_context *ctx,
    -+				 grub_uint8_t **key, grub_size_t *key_size)
    ++grub_tpm2_protector_policypcr (TPMI_SH_AUTH_SESSION session,
    ++			       struct grub_tpm2_buffer *cmd_buf)
     +{
    ++  TPM2B_DIGEST pcr_digest;
    ++  TPML_PCR_SELECTION pcr_sel;
     +  TPM_RC rc;
    -+  TPM2_SEALED_KEY sealed_key;
    -+  void *file_bytes;
    -+  grub_size_t file_size;
    -+  TPM_HANDLE parent_handle = 0;
    -+  TPM_HANDLE srk_handle;
    -+  TPM2B_NONCE nonceCaller = { 0 };
    -+  TPMT_SYM_DEF symmetric = { 0 };
    -+  TPMI_SH_AUTH_SESSION session;
    -+  TPML_PCR_SELECTION pcrSel = {
    ++  grub_err_t err;
    ++
    ++  grub_tpm2_mu_TPM2B_DIGEST_Unmarshal (cmd_buf, &pcr_digest);
    ++  grub_tpm2_mu_TPML_PCR_SELECTION_Unmarshal (cmd_buf, &pcr_sel);
    ++  if (cmd_buf->error)
    ++    {
    ++      err = GRUB_ERR_BAD_ARGUMENT;
    ++      return grub_error (err, N_("Failed to unmarshal the buffer for "
    ++				 "TPM2_PolicyPCR"));
    ++    }
    ++
    ++  rc = TPM2_PolicyPCR (session, NULL, &pcr_digest, &pcr_sel, NULL);
    ++  if (rc != TPM_RC_SUCCESS)
    ++    {
    ++      err = GRUB_ERR_BAD_DEVICE;
    ++      grub_error (err, N_("Failed to submit PCR policy (TPM2_PolicyPCR "
    ++			  "failed with TSS/TPM error %u)"), rc);
    ++      return err;
    ++    }
    ++
    ++  return GRUB_ERR_NONE;
    ++}
    ++
    ++static grub_err_t
    ++grub_tpm2_protector_enforce_policy (tpm2key_policy_t policy, TPMI_SH_AUTH_SESSION session)
    ++{
    ++  struct grub_tpm2_buffer buf;
    ++  grub_err_t err;
    ++
    ++  grub_tpm2_buffer_init (&buf);
    ++  if (policy->cmd_policy_len > buf.cap)
    ++    {
    ++      return GRUB_ERR_BAD_ARGUMENT;
    ++    }
    ++
    ++  grub_memcpy (buf.data, policy->cmd_policy, policy->cmd_policy_len);
    ++  buf.size = policy->cmd_policy_len;
    ++
    ++  switch (policy->cmd_code)
    ++    {
    ++    case TPM_CC_PolicyPCR:
    ++      err = grub_tpm2_protector_policypcr (session, &buf);
    ++      break;
    ++    default:
    ++      err = GRUB_ERR_BAD_ARGUMENT;
    ++      grub_error (err, N_("Unknown TPM Command: %x"), policy->cmd_code);
    ++    }
    ++
    ++  return err;
    ++}
    ++
    ++static grub_err_t
    ++grub_tpm2_protector_enforce_policy_seq (tpm2key_policy_t policy_seq,
    ++					TPMI_SH_AUTH_SESSION session)
    ++{
    ++  tpm2key_policy_t policy;
    ++  grub_err_t err;
    ++
    ++  FOR_LIST_ELEMENTS (policy, policy_seq)
    ++    {
    ++      err = grub_tpm2_protector_enforce_policy (policy, session);
    ++      if (err != GRUB_ERR_NONE)
    ++	return err;
    ++    }
    ++
    ++  return GRUB_ERR_NONE;
    ++}
    ++
    ++static grub_err_t
    ++grub_tpm2_protector_simple_policy_seq (const struct grub_tpm2_protector_context *ctx,
    ++				       tpm2key_policy_t *policy_seq)
    ++{
    ++  tpm2key_policy_t policy = NULL;
    ++  struct grub_tpm2_buffer buf;
    ++  TPML_PCR_SELECTION pcr_sel = {
     +    .count = 1,
     +    .pcrSelections = {
     +      {
    @@ grub-core/tpm2/module.c (new)
     +      },
     +    }
     +  };
    ++  grub_uint8_t i;
    ++  grub_err_t err;
    ++
    ++  if (policy_seq == NULL)
    ++    return GRUB_ERR_BAD_ARGUMENT;
    ++
    ++  grub_tpm2_buffer_init (&buf);
    ++
    ++  for (i = 0; i < ctx->pcr_count; i++)
    ++    TPMS_PCR_SELECTION_SelectPCR (&pcr_sel.pcrSelections[0], ctx->pcrs[i]);
    ++
    ++  grub_tpm2_buffer_pack_u16 (&buf, 0);
    ++  grub_tpm2_mu_TPML_PCR_SELECTION_Marshal (&buf, &pcr_sel);
    ++
    ++  if (buf.error)
    ++    return GRUB_ERR_BAD_ARGUMENT;
    ++
    ++  policy = grub_malloc (sizeof(struct tpm2key_policy));
    ++  if (policy == NULL)
    ++    {
    ++      err = GRUB_ERR_OUT_OF_MEMORY;
    ++      goto error;
    ++    }
    ++  policy->cmd_code = TPM_CC_PolicyPCR;
    ++  policy->cmd_policy = grub_malloc (buf.size);
    ++  if (policy->cmd_policy == NULL)
    ++    {
    ++      err = GRUB_ERR_OUT_OF_MEMORY;
    ++      goto error;
    ++    }
    ++  grub_memcpy (policy->cmd_policy, buf.data, buf.size);
    ++  policy->cmd_policy_len = buf.size;
    ++
    ++  grub_list_push (GRUB_AS_LIST_P (policy_seq), GRUB_AS_LIST (policy));
    ++
    ++  return GRUB_ERR_NONE;
    ++
    ++error:
    ++  grub_free (policy);
    ++
    ++  return err;
    ++}
    ++
    ++static grub_err_t
    ++grub_tpm2_protector_unseal (tpm2key_policy_t policy_seq, TPM_HANDLE sealed_handle,
    ++			    grub_uint8_t **key, grub_size_t *key_size)
    ++{
     +  TPMS_AUTH_COMMAND authCmd = { 0 };
    -+  TPM_HANDLE sealed_key_handle;
    -+  TPM2B_NAME name;
     +  TPM2B_SENSITIVE_DATA data;
    ++  TPM2B_NONCE nonceCaller = { 0 };
    ++  TPMT_SYM_DEF symmetric = { 0 };
    ++  TPMI_SH_AUTH_SESSION session;
     +  grub_uint8_t *key_out;
    -+  grub_uint8_t i;
    ++  TPM_RC rc;
    ++  grub_err_t err;
    ++
    ++  err = GRUB_ERR_BAD_DEVICE;
    ++
    ++  /* Start Auth Session */
    ++  nonceCaller.size = TPM_SHA256_DIGEST_SIZE;
    ++  symmetric.algorithm = TPM_ALG_NULL;
    ++  rc = TPM2_StartAuthSession (TPM_RH_NULL, TPM_RH_NULL, NULL, &nonceCaller, NULL,
    ++			      TPM_SE_POLICY, &symmetric, TPM_ALG_SHA256,
    ++			      &session, NULL, NULL);
    ++  if (rc != TPM_RC_SUCCESS)
    ++    {
    ++      grub_error (err, N_("Failed to start auth session (TPM2_StartAuthSession "
    ++			  "failed with TSS/TPM error %u)"), rc);
    ++      goto error;
    ++    }
    ++
    ++  /* Enforce the policy command sequence */
    ++  err = grub_tpm2_protector_enforce_policy_seq (policy_seq, session);
    ++  if (err != GRUB_ERR_NONE)
    ++    goto error;
    ++
    ++  /* Unseal Sealed Key */
    ++  authCmd.sessionHandle = session;
    ++  rc = TPM2_Unseal (sealed_handle, &authCmd, &data, NULL);
    ++  if (rc != TPM_RC_SUCCESS)
    ++    {
    ++      grub_error (err, N_("Failed to unseal sealed key (TPM2_Unseal failed "
    ++			  "with TSS/TPM error %u)"), rc);
    ++      goto error;
    ++    }
    ++
    ++  /* Epilogue */
    ++  key_out = grub_malloc (data.size);
    ++  if (key_out == NULL)
    ++    {
    ++      err = GRUB_ERR_OUT_OF_MEMORY;
    ++      grub_error (err, N_("No memory left to allocate unlock key buffer"));
    ++      goto error;
    ++    }
    ++
    ++  grub_memcpy (key_out, data.buffer, data.size);
    ++
    ++  *key = key_out;
    ++  *key_size = data.size;
    ++
    ++  err = GRUB_ERR_NONE;
    ++
    ++error:
    ++  TPM2_FlushContext (session);
    ++
    ++  return err;
    ++}
    ++
    ++static grub_err_t
    ++grub_tpm2_protector_srk_recover (const struct grub_tpm2_protector_context *ctx,
    ++				 grub_uint8_t **key, grub_size_t *key_size)
    ++{
    ++  TPMS_AUTH_COMMAND authCmd = { 0 };
    ++  TPM2_SEALED_KEY sealed_key;
    ++  TPM2B_NAME name;
    ++  void *file_bytes;
    ++  grub_size_t file_size;
    ++  TPM_HANDLE parent_handle = 0;
    ++  TPM_HANDLE srk_handle;
    ++  TPM_HANDLE sealed_handle;
    ++  tpm2key_policy_t policy_seq = NULL;
    ++  tpm2key_authpolicy_t authpol = NULL;
    ++  tpm2key_authpolicy_t authpol_seq = NULL;
    ++  TPM_RC rc;
     +  grub_err_t err;
     +
    -+  /* Retrieve Sealed Key */
    ++  /*
    ++   * Retrieve sealed key, parent handle, policy sequence, and authpolicy
    ++   * sequence from the key file
    ++  */
     +  if (ctx->tpm2key)
     +    {
     +      err = grub_tpm2_protector_srk_read_file (ctx->tpm2key, &file_bytes,
     +					       &file_size);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	return grub_error (err, N_("Failed to read key file %s"), ctx->tpm2key);
     +
     +      err = grub_tpm2_protector_srk_unmarshal_tpm2key (file_bytes,
     +						       file_size,
    ++						       &policy_seq,
    ++						       &authpol_seq,
     +						       &parent_handle,
     +						       &sealed_key);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	{
     +	  grub_error (err, N_("Failed to unmarshal key, ensure the key file is in "
    -+		      "TPM wire format"));
    ++			      "TPM 2.0 Key File format"));
     +	  goto exit1;
     +	}
     +    }
    @@ grub-core/tpm2/module.c (new)
     +    {
     +      err = grub_tpm2_protector_srk_read_file (ctx->keyfile, &file_bytes,
     +					       &file_size);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	return grub_error (err, N_("Failed to read key file %s"), ctx->keyfile);
     +
     +      parent_handle = TPM_RH_OWNER;
     +      err = grub_tpm2_protector_srk_unmarshal_keyfile (file_bytes,
     +						       file_size,
     +						       &sealed_key);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	{
     +	  grub_error (err, N_("Failed to unmarshal key, ensure the key file is in "
    -+		      "TPM wire format"));
    ++			      "TPM wire format"));
     +	  goto exit1;
     +	}
     +    }
     +
    -+  /* Get SRK */
    -+  err = grub_tpm2_protector_srk_get (ctx, parent_handle, &srk_handle);
    -+  if (err)
    ++  /*
    ++   * Create a basic policy sequence based on the given PCR selection if the
    ++   * key file doesn't provide any policy or authpolicy sequence
    ++   */
    ++  if (policy_seq == NULL)
     +    {
    -+      grub_error (err, N_("Failed to retrieve the SRK"));
    -+      goto exit1;
    ++      err = grub_tpm2_protector_simple_policy_seq (ctx, &policy_seq);
    ++      if (err != GRUB_ERR_NONE)
    ++        goto exit1;
     +    }
     +
    -+  err = GRUB_ERR_BAD_DEVICE;
    -+
    -+  /* Start Auth Session */
    -+  nonceCaller.size = TPM_SHA256_DIGEST_SIZE;
    -+  symmetric.algorithm = TPM_ALG_NULL;
    -+
    -+  rc = TPM2_StartAuthSession (TPM_RH_NULL, TPM_RH_NULL, NULL, &nonceCaller, NULL,
    -+			      TPM_SE_POLICY, &symmetric, TPM_ALG_SHA256,
    -+			      &session, NULL, NULL);
    -+  if (rc)
    ++  /*
    ++   * Append the standalone policy sequence into the authpolicy sequence as
    ++   * the fallback
    ++   */
    ++  authpol = grub_malloc (sizeof (struct tpm2key_authpolicy));
    ++  if (authpol == NULL)
     +    {
    -+      grub_error (err, N_("Failed to start auth session (TPM2_StartAuthSession "
    -+			  "failed with TSS/TPM error %u)"), rc);
    -+      goto exit2;
    ++      /*
    ++       * Free policy_seq here since it's not included in authpol_seq
    ++       * yet, and grub_tpm2key_free_policy_seq() won't be able to
    ++       * free it.
    ++       */
    ++      grub_tpm2key_free_policy_seq (policy_seq);
    ++      err = GRUB_ERR_OUT_OF_MEMORY;
    ++      goto exit1;
     +    }
    ++  authpol->policy_seq = policy_seq;
    ++  grub_list_push (GRUB_AS_LIST_P (&authpol_seq), GRUB_AS_LIST (authpol));
     +
    -+  /* Policy PCR */
    -+  for (i = 0; i < ctx->pcr_count; i++)
    -+    pcrSel
    -+      .pcrSelections[0]
    -+      .pcrSelect[TPM2_PCR_TO_SELECT(ctx->pcrs[i])]
    -+	|= TPM2_PCR_TO_BIT(ctx->pcrs[i]);
    -+
    -+  rc = TPM2_PolicyPCR (session, NULL, NULL, &pcrSel, NULL);
    -+  if (rc)
    ++  /* Get the SRK to unseal the sealed key */
    ++  err = grub_tpm2_protector_srk_get (ctx, parent_handle, &srk_handle);
    ++  if (err != GRUB_ERR_NONE)
     +    {
    -+      grub_error (err, N_("Failed to submit PCR policy (TPM2_PolicyPCR failed "
    -+			  "with TSS/TPM error %u)"), rc);
    -+      goto exit3;
    ++      grub_error (err, N_("Failed to retrieve the SRK"));
    ++      goto exit1;
     +    }
     +
    -+  /* Load Sealed Key */
    ++  /* Load the sealed key and associate it with the SRK */
     +  authCmd.sessionHandle = TPM_RS_PW;
     +  rc = TPM2_Load (srk_handle, &authCmd, &sealed_key.private, &sealed_key.public,
    -+		  &sealed_key_handle, &name, NULL);
    -+  if (rc)
    -+    {
    -+      grub_error (err, N_("Failed to load sealed key (TPM2_Load failed with "
    -+			  "TSS/TPM error %u)"), rc);
    -+      goto exit3;
    -+    }
    -+
    -+  /* Unseal Sealed Key */
    -+  authCmd.sessionHandle = session;
    -+  rc = TPM2_Unseal (sealed_key_handle, &authCmd, &data, NULL);
    -+  if (rc)
    ++		  &sealed_handle, &name, NULL);
    ++  if (rc != TPM_RC_SUCCESS)
     +    {
    -+      grub_error (err, N_("Failed to unseal sealed key (TPM2_Unseal failed "
    ++      grub_error (err, N_("Failed to load sealed key (TPM2_Load failed "
     +			  "with TSS/TPM error %u)"), rc);
    -+      goto exit4;
    ++      goto exit2;
     +    }
     +
    -+  /* Epilogue */
    -+  key_out = grub_malloc (data.size);
    -+  if (!key_out)
    ++  /* Iterate the authpolicy sequence to find one that unseals the key */
    ++  FOR_LIST_ELEMENTS (authpol, authpol_seq)
     +    {
    -+      err = GRUB_ERR_OUT_OF_MEMORY;
    -+      grub_error (err, N_("No memory left to allocate unlock key buffer"));
    -+      goto exit4;
    ++      err = grub_tpm2_protector_unseal (authpol->policy_seq, sealed_handle,
    ++					key, key_size);
    ++      if (err == GRUB_ERR_NONE)
    ++        break;
     +    }
     +
    -+  grub_memcpy (key_out, data.buffer, data.size);
    -+
    -+  *key = key_out;
    -+  *key_size = data.size;
    -+
    -+  err = GRUB_ERR_NONE;
    -+
    -+exit4:
    -+  TPM2_FlushContext (sealed_key_handle);
    -+
    -+exit3:
    -+  TPM2_FlushContext (session);
    ++  TPM2_FlushContext (sealed_handle);
     +
     +exit2:
     +  TPM2_FlushContext (srk_handle);
     +
     +exit1:
    ++  grub_tpm2key_free_authpolicy_seq (authpol_seq);
     +  grub_free (file_bytes);
     +  return err;
     +}
    @@ grub-core/tpm2/module.c (new)
     +static grub_err_t
     +grub_tpm2_protector_recover_key (grub_uint8_t **key, grub_size_t *key_size)
     +{
    -+  grub_err_t err;
    -+
     +  /* Expect a call to tpm2_protector_init before anybody tries to use us */
     +  if (grub_tpm2_protector_ctx.mode == GRUB_TPM2_PROTECTOR_MODE_UNSET)
     +    return grub_error (GRUB_ERR_INVALID_COMMAND,
     +		       N_("Cannot use TPM2 key protector without initializing "
     +			  "it, call tpm2_protector_init first"));
     +
    -+  if (!key)
    ++  if (key == NULL || key_size == NULL)
     +    return GRUB_ERR_BAD_ARGUMENT;
     +
    -+  err = grub_tpm2_protector_recover (&grub_tpm2_protector_ctx, key, key_size);
    -+  if (err)
    -+    return err;
    -+
    -+  return GRUB_ERR_NONE;
    ++  return grub_tpm2_protector_recover (&grub_tpm2_protector_ctx, key, key_size);
     +}
     +
    -+
     +static grub_err_t
     +grub_tpm2_protector_check_args (struct grub_tpm2_protector_context *ctx)
     +{
    @@ grub-core/tpm2/module.c (new)
     +    ctx->mode = GRUB_TPM2_PROTECTOR_MODE_SRK;
     +
     +  /* Checks for SRK mode */
    -+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && !ctx->keyfile
    -+      && !ctx->tpm2key)
    ++  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && ctx->keyfile == NULL
    ++      && ctx->tpm2key == NULL)
     +    return grub_error (GRUB_ERR_BAD_ARGUMENT,
     +		       N_("In SRK mode, a key file must be specified: "
     +			  "--tpm2key/-T or --keyfile/-k"));
     +
    ++  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && ctx->keyfile
    ++      && ctx->tpm2key)
    ++    return grub_error (GRUB_ERR_BAD_ARGUMENT,
    ++		       N_("In SRK mode, please specify a key file with "
    ++			  "only --tpm2key/-T or --keyfile/-k"));
    ++
     +  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_SRK && ctx->nv)
     +    return grub_error (GRUB_ERR_BAD_ARGUMENT,
     +		       N_("In SRK mode, an NV Index cannot be specified"));
     +
     +  /* Checks for NV mode */
    -+  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && !ctx->nv)
    ++  if (ctx->mode == GRUB_TPM2_PROTECTOR_MODE_NV && ctx->nv == 0)
     +    return grub_error (GRUB_ERR_BAD_ARGUMENT,
     +		       N_("In NV Index mode, an NV Index must be specified: "
     +			   "--nvindex or -n"));
    @@ grub-core/tpm2/module.c (new)
     +			  "specified"));
     +
     +  /* Defaults assignment */
    -+  if (!ctx->bank)
    ++  if (ctx->bank == TPM_ALG_ERROR)
     +    ctx->bank = TPM_ALG_SHA256;
     +
    -+  if (!ctx->pcr_count)
    ++  if (ctx->pcr_count == 0)
     +    {
     +      ctx->pcrs[0] = 7;
     +      ctx->pcr_count = 1;
    @@ grub-core/tpm2/module.c (new)
     +    return GRUB_ERR_BAD_ARGUMENT;
     +
     +  *file = grub_strdup (value);
    -+  if (!*file)
    ++  if (*file == NULL)
     +    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
     +		       N_("No memory to duplicate file path"));
     +
    @@ grub-core/tpm2/module.c (new)
     +
     +static grub_err_t
     +grub_tpm2_protector_init_cmd_handler (grub_extcmd_context_t ctxt, int argc,
    -+				 char **args __attribute__ ((unused)))
    ++				      char **args __attribute__ ((unused)))
     +{
     +  struct grub_arg_list *state = ctxt->state;
     +  grub_err_t err;
    @@ grub-core/tpm2/module.c (new)
     +    {
     +      err = grub_tpm2_protector_parse_mode (state[OPTION_MODE].arg,
     +					    &grub_tpm2_protector_ctx.mode);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	return err;
     +    }
     +
    @@ grub-core/tpm2/module.c (new)
     +      err = grub_tpm2_protector_parse_pcrs (state[OPTION_PCRS].arg,
     +					    grub_tpm2_protector_ctx.pcrs,
     +					    &grub_tpm2_protector_ctx.pcr_count);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	return err;
     +    }
     +
    @@ grub-core/tpm2/module.c (new)
     +    {
     +      err = grub_tpm2_protector_parse_bank (state[OPTION_BANK].arg,
     +					    &grub_tpm2_protector_ctx.bank);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	return err;
     +    }
     +
    @@ grub-core/tpm2/module.c (new)
     +    {
     +      err = grub_tpm2_protector_parse_file (state[OPTION_TPM2KEY].arg,
     +					    &grub_tpm2_protector_ctx.tpm2key);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	return err;
     +    }
     +
    @@ grub-core/tpm2/module.c (new)
     +    {
     +      err = grub_tpm2_protector_parse_file (state[OPTION_KEYFILE].arg,
     +					    &grub_tpm2_protector_ctx.keyfile);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	return err;
     +    }
     +
    @@ grub-core/tpm2/module.c (new)
     +    {
     +      err = grub_tpm2_protector_parse_tpm_handle (state[OPTION_SRK].arg,
     +						  &grub_tpm2_protector_ctx.srk);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	return err;
     +    }
     +
    @@ grub-core/tpm2/module.c (new)
     +    {
     +      err = grub_tpm2_protector_parse_asymmetric (state[OPTION_ASYMMETRIC].arg,
     +						  &grub_tpm2_protector_ctx.asymmetric);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	return err;
     +    }
     +
    @@ grub-core/tpm2/module.c (new)
     +    {
     +      err = grub_tpm2_protector_parse_tpm_handle (state[OPTION_NVINDEX].arg,
     +						  &grub_tpm2_protector_ctx.nv);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	return err;
     +    }
     +
    @@ grub-core/tpm2/tpm2key.c (new)
     + *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
     + */
     +
    ++#include <grub/libtasn1.h>
    ++#include <grub/list.h>
     +#include <grub/misc.h>
     +#include <grub/mm.h>
    -+#include <grub/libtasn1.h>
    ++#include <grub/tpm2/buffer.h>
     +#include <grub/tpm2/tpm2key.h>
     +
     +extern asn1_static_node tpm2key_asn1_tab[];
    @@ grub-core/tpm2/tpm2key.c (new)
     +grub_tpm2key_get_privkey (asn1_node tpm2key, void **data, grub_size_t *size)
     +{
     +  return tpm2key_get_octstring (tpm2key, "privkey", data, size);
    ++}
    ++
    ++/*
    ++ * Expected strings for CommandCode and CommandPolicy:
    ++ *   policy.?XX.CommandCode
    ++ *   policy.?XX.CommandPolicy
    ++ *   authPolicy.?XX.Policy.?YY.CommandCode
    ++ *   authPolicy.?XX.Policy.?YY.CommandPolicy
    ++ */
    ++#define CMD_CODE_MAX (sizeof ("authPolicy.?XX.Policy.?YY.CommandCode"))
    ++#define CMD_POL_MAX (sizeof ("authPolicy.?XX.Policy.?YY.CommandPolicy"))
    ++
    ++static int
    ++tpm2key_get_policy_seq (asn1_node tpm2key, const char *prefix,
    ++			tpm2key_policy_t *policy_seq)
    ++{
    ++  tpm2key_policy_t tmp_seq = NULL;
    ++  tpm2key_policy_t policy = NULL;
    ++  int policy_n;
    ++  char cmd_code[CMD_CODE_MAX];
    ++  char cmd_pol[CMD_POL_MAX];
    ++  grub_size_t cmd_policy_len;
    ++  int i;
    ++  int ret;
    ++
    ++  ret = asn1_number_of_elements (tpm2key, prefix, &policy_n);
    ++  if (ret != ASN1_SUCCESS)
    ++    return ret;
    ++
    ++  /*
    ++   * Limit the number of policy commands to two digits (99)
    ++   * Although there is no upper bound for the number of policy commands,
    ++   * in practice, it takes one or two policy commands to unseal the key,
    ++   * so the 99 commands limit is more than enough.
    ++   */
    ++  if (policy_n > 100 || policy_n < 1)
    ++    return ASN1_VALUE_NOT_VALID;
    ++
    ++  /*
    ++   * Iterate the policy commands backwards since grub_list_push() prepends
    ++   * the item into the list.
    ++   */
    ++  for (i = policy_n; i >= 1; i--) {
    ++    policy = grub_zalloc (sizeof (struct tpm2key_policy));
    ++    if (policy == NULL)
    ++      {
    ++	ret = ASN1_MEM_ALLOC_ERROR;
    ++	goto error;
    ++      }
    ++    grub_snprintf (cmd_code, CMD_CODE_MAX, "%s.?%d.CommandCode", prefix, i);
    ++    grub_snprintf (cmd_pol, CMD_POL_MAX, "%s.?%d.CommandPolicy", prefix, i);
    ++
    ++    /* CommandCode   [0] EXPLICIT INTEGER */
    ++    ret = asn1_read_uint32 (tpm2key, cmd_code, &policy->cmd_code);
    ++    if (ret != ASN1_SUCCESS)
    ++      return ret;
    ++
    ++    /* CommandPolicy [1] EXPLICIT OCTET STRING */
    ++    ret = tpm2key_get_octstring (tpm2key, cmd_pol, &policy->cmd_policy,
    ++				 &cmd_policy_len);
    ++    if (ret != ASN1_SUCCESS)
    ++      {
    ++	goto error;
    ++      }
    ++    else if (cmd_policy_len > GRUB_TPM2_BUFFER_CAPACITY)
    ++      {
    ++	/*
    ++	 * CommandPolicy is the marshalled parameters for the TPM command so
    ++	 * it should not be larger than the maximum TPM2 buffer.
    ++	 */
    ++	ret = ASN1_VALUE_NOT_VALID;
    ++	goto error;
    ++      }
    ++    policy->cmd_policy_len = (grub_uint16_t)cmd_policy_len;
    ++
    ++    /* Prepend the policy command into the sequence */
    ++    grub_list_push (GRUB_AS_LIST_P (&tmp_seq), GRUB_AS_LIST (policy));
    ++  }
    ++
    ++  *policy_seq = tmp_seq;
    ++
    ++  return ASN1_SUCCESS;
    ++
    ++error:
    ++  if (policy)
    ++    {
    ++      grub_free (policy->cmd_policy);
    ++      grub_free (policy);
    ++    }
    ++  grub_tpm2key_free_policy_seq (tmp_seq);
    ++
    ++  return ret;
    ++}
    ++
    ++grub_err_t
    ++grub_tpm2key_get_policy_seq (asn1_node tpm2key, tpm2key_policy_t *policy_seq)
    ++{
    ++  int ret;
    ++
    ++  ret = tpm2key_get_policy_seq (tpm2key, "policy", policy_seq);
    ++  if (ret == ASN1_ELEMENT_NOT_FOUND)
    ++    {
    ++      /* "policy" is optional, so it may not be available */
    ++      *policy_seq = NULL;
    ++      return GRUB_ERR_NONE;
    ++    }
    ++  else if (ret != ASN1_SUCCESS)
    ++    {
    ++      return GRUB_ERR_READ_ERROR;
    ++    }
    ++
    ++  return GRUB_ERR_NONE;
    ++}
    ++
    ++void
    ++grub_tpm2key_free_policy_seq (tpm2key_policy_t policy_seq)
    ++{
    ++  tpm2key_policy_t policy;
    ++  tpm2key_policy_t next;
    ++
    ++  if (policy_seq == NULL)
    ++    return;
    ++
    ++  FOR_LIST_ELEMENTS_SAFE (policy, next, policy_seq)
    ++    {
    ++      grub_free (policy->cmd_policy);
    ++      grub_free (policy);
    ++    }
    ++}
    ++
    ++#define AUTHPOLICY_POL_MAX (sizeof ("authPolicy.?XX.Policy"))
    ++
    ++grub_err_t
    ++grub_tpm2key_get_authpolicy_seq (asn1_node tpm2key, tpm2key_authpolicy_t *authpol_seq)
    ++{
    ++  tpm2key_authpolicy_t tmp_seq = NULL;
    ++  tpm2key_authpolicy_t authpol = NULL;
    ++  int authpol_n;
    ++  char authpol_pol[AUTHPOLICY_POL_MAX];
    ++  int i;
    ++  int ret;
    ++  grub_err_t err;
    ++
    ++  ret = asn1_number_of_elements (tpm2key, "authPolicy", &authpol_n);
    ++  if (ret == ASN1_ELEMENT_NOT_FOUND)
    ++    {
    ++      /* "authPolicy" is optional, so it may not be available */
    ++      *authpol_seq = NULL;
    ++      return GRUB_ERR_NONE;
    ++    }
    ++  else if (ret != ASN1_SUCCESS)
    ++    {
    ++      return GRUB_ERR_READ_ERROR;
    ++    }
    ++
    ++  /* Limit the number of authPolicy elements to two digits (99) */
    ++  if (authpol_n > 100 || authpol_n < 1)
    ++    return GRUB_ERR_OUT_OF_RANGE;
    ++
    ++  /*
    ++   * Iterate the authPolicy elements backwards since grub_list_push() prepends
    ++   * the item into the list.
    ++   */
    ++  for (i = authpol_n; i >= 1; i--) {
    ++    authpol = grub_zalloc (sizeof (struct tpm2key_authpolicy));
    ++    if (authpol == NULL)
    ++      {
    ++	err = GRUB_ERR_OUT_OF_MEMORY;
    ++	goto error;
    ++      }
    ++    grub_snprintf (authpol_pol, AUTHPOLICY_POL_MAX, "authPolicy.?%d.Policy", i);
    ++
    ++    ret = tpm2key_get_policy_seq (tpm2key, authpol_pol, &authpol->policy_seq);
    ++    if (ret != ASN1_SUCCESS)
    ++      {
    ++        err = GRUB_ERR_READ_ERROR;
    ++        goto error;
    ++      }
    ++
    ++    /* Prepend the authPolicy element into the sequence */
    ++    grub_list_push (GRUB_AS_LIST_P (&tmp_seq), GRUB_AS_LIST (authpol));
    ++  }
    ++
    ++  *authpol_seq = tmp_seq;
    ++
    ++error:
    ++  if (authpol)
    ++    {
    ++      grub_tpm2key_free_policy_seq (authpol->policy_seq);
    ++      grub_free (authpol);
    ++    }
    ++
    ++  grub_tpm2key_free_authpolicy_seq (tmp_seq);
    ++
    ++  return err;
    ++}
    ++
    ++void
    ++grub_tpm2key_free_authpolicy_seq (tpm2key_authpolicy_t authpol_seq)
    ++{
    ++  tpm2key_authpolicy_t authpol;
    ++  tpm2key_authpolicy_t next;
    ++
    ++  if (authpol_seq == NULL)
    ++    return;
    ++
    ++  FOR_LIST_ELEMENTS_SAFE (authpol, next, authpol_seq)
    ++    {
    ++      grub_tpm2key_free_policy_seq (authpol->policy_seq);
    ++      grub_free (authpol);
    ++    }
     +}
     
      ## grub-core/tpm2/tpm2key_asn1_tab.c (new) ##
     @@
    ++/*
    ++ * This file is generated by 'asn1Parser tpm2key.asn' and the '#include'
    ++ * headers are replaced with the ones in grub2.
    ++ * - 'grub/mm.h' for the definition of 'NULL'
    ++ * - 'grub/libtasn1.h' for the definition of 'asn1_static_node'
    ++ */
    ++
     +#include <grub/mm.h>
     +#include <grub/libtasn1.h>
     +
    @@ include/grub/tpm2/tpm2key.h (new)
     +#include <grub/types.h>
     +#include <grub/libtasn1.h>
     +
    ++/*
    ++ * TPMPolicy ::= SEQUENCE {
    ++ *   CommandCode   [0] EXPLICIT INTEGER,
    ++ *   CommandPolicy [1] EXPLICIT OCTET STRING
    ++ * }
    ++ */
    ++struct tpm2key_policy {
    ++  struct tpm2key_policy *next;
    ++  struct tpm2key_policy **prev;
    ++  grub_uint32_t cmd_code;
    ++  void *cmd_policy;
    ++  grub_uint16_t cmd_policy_len;
    ++};
    ++typedef struct tpm2key_policy *tpm2key_policy_t;
    ++
    ++/*
    ++ * TPMAuthPolicy ::= SEQUENCE {
    ++ *   Name    [0] EXPLICIT UTF8String OPTIONAL,
    ++ *   Policy  [1] EXPLICIT SEQUENCE OF TPMPolicy
    ++ * }
    ++ *
    ++ * Name is not a necessary part to unseal the key. Ignore it.
    ++ */
    ++struct tpm2key_authpolicy {
    ++  struct tpm2key_authpolicy *next;
    ++  struct tpm2key_authpolicy **prev;
    ++  /* char *name; */
    ++  tpm2key_policy_t policy_seq;
    ++};
    ++typedef struct tpm2key_authpolicy *tpm2key_authpolicy_t;
    ++
     +grub_err_t
     +grub_tpm2key_start_parsing (asn1_node *parsed_tpm2key, void *data, grub_size_t size);
     +
    @@ include/grub/tpm2/tpm2key.h (new)
     +grub_err_t
     +grub_tpm2key_get_privkey (asn1_node tpm2key, void **data, grub_size_t *size);
     +
    ++grub_err_t
    ++grub_tpm2key_get_policy_seq (asn1_node tpm2key, tpm2key_policy_t *policy_seq);
    ++
    ++void
    ++grub_tpm2key_free_policy_seq (tpm2key_policy_t policy_seq);
    ++
    ++grub_err_t
    ++grub_tpm2key_get_authpolicy_seq (asn1_node tpm2key, tpm2key_authpolicy_t *authpol_seq);
    ++
    ++void
    ++grub_tpm2key_free_authpolicy_seq (tpm2key_authpolicy_t authpol_seq);
    ++
     +#endif /* GRUB_TPM2_TPM2KEY_HEADER */
 4:  609f2c6e4 ! 11:  9ad473fd8 cryptodisk: Support key protectors
    @@ grub-core/disk/cryptodisk.c: static const struct grub_arg_option options[] =
        };
      
     @@ grub-core/disk/cryptodisk.c: grub_cryptodisk_scan_device_real (const char *name,
    - {
        grub_err_t ret = GRUB_ERR_NONE;
        grub_cryptodisk_t dev;
    --  grub_cryptodisk_dev_t cr;
    -+  grub_cryptodisk_dev_t cr, crd = NULL;
    +   grub_cryptodisk_dev_t cr;
     +  int i;
        struct cryptodisk_read_hook_ctx read_hook_data = {0};
        int askpass = 0;
    @@ grub-core/disk/cryptodisk.c: grub_cryptodisk_scan_device_real (const char *name,
            goto error_no_close;
          if (!dev)
            continue;
    -+    crd = cr;
     +    break;
     +  }
      
    @@ grub-core/disk/cryptodisk.c: grub_cryptodisk_scan_device_real (const char *name,
     +  if (!dev)
     +    {
     +      grub_error (GRUB_ERR_BAD_MODULE,
    -+                  "no cryptodisk module can handle this device");
    ++		  "no cryptodisk module can handle this device");
     +      goto error_no_close;
     +    }
      
    @@ grub-core/disk/cryptodisk.c: grub_cryptodisk_scan_device_real (const char *name,
     +  if (cargs->protectors)
     +    {
     +      for (i = 0; cargs->protectors[i]; i++)
    -+        {
    -+          if (cargs->key_cache[i].invalid)
    -+            continue;
    -+
    -+          if (!cargs->key_cache[i].key)
    -+            {
    -+              ret = grub_key_protector_recover_key (cargs->protectors[i],
    -+                                                    &cargs->key_cache[i].key,
    -+                                                    &cargs->key_cache[i].key_len);
    -+              if (ret)
    -+                {
    -+                  if (grub_errno)
    -+                    {
    -+                      grub_print_error ();
    -+                      grub_errno = GRUB_ERR_NONE;
    -+                    }
    ++	{
    ++	  if (cargs->key_cache[i].invalid)
    ++	    continue;
     +
    -+                  grub_dprintf ("cryptodisk",
    -+                                "failed to recover a key from key protector "
    -+                                "%s, will not try it again for any other "
    -+                                "disks, if any, during this invocation of "
    -+                                "cryptomount\n",
    -+                                cargs->protectors[i]);
    ++	  if (!cargs->key_cache[i].key)
    ++	    {
    ++	      ret = grub_key_protector_recover_key (cargs->protectors[i],
    ++						    &cargs->key_cache[i].key,
    ++						    &cargs->key_cache[i].key_len);
    ++	      if (ret != GRUB_ERR_NONE)
    ++		{
    ++		  if (grub_errno)
    ++		    {
    ++		      grub_print_error ();
    ++		      grub_errno = GRUB_ERR_NONE;
    ++		    }
     +
    -+                  cargs->key_cache[i].invalid = 1;
    -+                  continue;
    -+                }
    -+            }
    ++		  grub_dprintf ("cryptodisk",
    ++				"failed to recover a key from key protector "
    ++				"%s, will not try it again for any other "
    ++				"disks, if any, during this invocation of "
    ++				"cryptomount\n",
    ++				cargs->protectors[i]);
     +
    -+          cargs->key_data = cargs->key_cache[i].key;
    -+          cargs->key_len = cargs->key_cache[i].key_len;
    ++		  cargs->key_cache[i].invalid = 1;
    ++		  continue;
    ++		}
    ++	    }
     +
    -+          ret = crd->recover_key (source, dev, cargs);
    -+          if (ret)
    -+            {
    -+              part = grub_partition_get_name (source->partition);
    -+              grub_dprintf ("cryptodisk",
    -+                            "recovered a key from key protector %s but it "
    -+                            "failed to unlock %s%s%s (%s)\n",
    -+                             cargs->protectors[i], source->name,
    -+                             source->partition != NULL ? "," : "",
    -+                             part != NULL ? part : N_("UNKNOWN"), dev->uuid);
    -+               grub_free (part);
    -+               continue;
    -+            }
    -+         else
    -+           {
    -+             ret = grub_cryptodisk_insert (dev, name, source);
    -+             if (ret != GRUB_ERR_NONE)
    -+               goto error;
    -+             goto cleanup;
    -+           }
    -+        }
    ++	  cargs->key_data = cargs->key_cache[i].key;
    ++	  cargs->key_len = cargs->key_cache[i].key_len;
      
     -    ret = grub_cryptodisk_insert (dev, name, source);
     -    if (ret != GRUB_ERR_NONE)
    ++	  ret = cr->recover_key (source, dev, cargs);
    ++	  if (ret != GRUB_ERR_NONE)
    ++	    {
    ++	      part = grub_partition_get_name (source->partition);
    ++	      grub_dprintf ("cryptodisk",
    ++			    "recovered a key from key protector %s but it "
    ++			    "failed to unlock %s%s%s (%s)\n",
    ++			     cargs->protectors[i], source->name,
    ++			     source->partition != NULL ? "," : "",
    ++			     part != NULL ? part : N_("UNKNOWN"), dev->uuid);
    ++	       grub_free (part);
    ++	       continue;
    ++	    }
    ++	 else
    ++	   {
    ++	     ret = grub_cryptodisk_insert (dev, name, source);
    ++	     if (ret != GRUB_ERR_NONE)
    ++	       goto error;
    ++	     goto cleanup;
    ++	   }
    ++	}
    ++
     +      part = grub_partition_get_name (source->partition);
     +      grub_error (GRUB_ERR_ACCESS_DENIED,
    -+                  N_("no key protector provided a usable key for %s%s%s (%s)"),
    -+                  source->name, source->partition != NULL ? "," : "",
    -+                  part != NULL ? part : N_("UNKNOWN"), dev->uuid);
    ++		  N_("no key protector provided a usable key for %s%s%s (%s)"),
    ++		  source->name, source->partition != NULL ? "," : "",
    ++		  part != NULL ? part : N_("UNKNOWN"), dev->uuid);
     +      grub_free (part);
            goto error;
     +    }
    @@ grub-core/disk/cryptodisk.c: grub_cryptodisk_scan_device_real (const char *name,
     +      askpass = 1;
     +      part = grub_partition_get_name (source->partition);
     +      grub_printf_ (N_("Enter passphrase for %s%s%s (%s): "), source->name,
    -+                    source->partition != NULL ? "," : "",
    -+                    part != NULL ? part : N_("UNKNOWN"), dev->uuid);
    ++		    source->partition != NULL ? "," : "",
    ++		    part != NULL ? part : N_("UNKNOWN"), dev->uuid);
     +      grub_free (part);
     +
     +      cargs->key_data = grub_malloc (GRUB_CRYPTODISK_MAX_PASSPHRASE);
     +      if (cargs->key_data == NULL)
    -+        goto error;
    ++	goto error;
     +
     +      if (!grub_password_get ((char *) cargs->key_data, GRUB_CRYPTODISK_MAX_PASSPHRASE))
    -+        {
    -+          grub_error (GRUB_ERR_BAD_ARGUMENT, "passphrase not supplied");
    -+          goto error;
    -+        }
    ++	{
    ++	  grub_error (GRUB_ERR_BAD_ARGUMENT, "passphrase not supplied");
    ++	  goto error;
    ++	}
     +      cargs->key_len = grub_strlen ((char *) cargs->key_data);
     +    }
     +
    -+  ret = crd->recover_key (source, dev, cargs);
    ++  ret = cr->recover_key (source, dev, cargs);
     +  if (ret != GRUB_ERR_NONE)
     +    goto error;
     +
    @@ grub-core/disk/cryptodisk.c: grub_cryptodisk_scan_device (const char *name,
     +{
     +  int i;
     +
    -+  if (!cargs->key_cache)
    ++  if (cargs->key_cache == NULL || cargs->protectors == NULL)
     +    return;
     +
     +  for (i = 0; cargs->protectors[i]; i++)
    @@ grub-core/disk/cryptodisk.c: grub_cmd_cryptomount (grub_extcmd_context_t ctxt, i
      
     +  if (state[OPTION_PASSWORD].set && state[OPTION_PROTECTOR].set) /* password and key protector */
     +    return grub_error (GRUB_ERR_BAD_ARGUMENT,
    -+                       "a password and a key protector cannot both be set");
    ++		       "a password and a key protector cannot both be set");
     +
        if (state[OPTION_PASSWORD].set) /* password */
          {
    @@ grub-core/disk/cryptodisk.c: grub_cmd_cryptomount (grub_extcmd_context_t ctxt, i
     +    {
     +      cargs.key_cache = grub_zalloc (state[OPTION_PROTECTOR].set * sizeof (*cargs.key_cache));
     +      if (!cargs.key_cache)
    -+        return grub_error (GRUB_ERR_OUT_OF_MEMORY,
    -+                           "no memory for key protector key cache");
    ++	return grub_error (GRUB_ERR_OUT_OF_MEMORY,
    ++			   "no memory for key protector key cache");
     +      cargs.protectors = state[OPTION_PROTECTOR].args;
     +    }
     +
    @@ grub-core/disk/cryptodisk.c: grub_cmd_cryptomount (grub_extcmd_context_t ctxt, i
            dev = grub_cryptodisk_get_by_uuid (args[0]);
            if (dev)
      	{
    -+          grub_cryptodisk_clear_key_cache (&cargs);
    ++	  grub_cryptodisk_clear_key_cache (&cargs);
      	  grub_dprintf ("cryptodisk",
      			"already mounted as crypto%lu\n", dev->id);
      	  return GRUB_ERR_NONE;
    @@ grub-core/disk/cryptodisk.c: grub_cmd_cryptomount (grub_extcmd_context_t ctxt, i
            disk = grub_disk_open (diskname);
            if (!disk)
      	{
    -+          grub_cryptodisk_clear_key_cache (&cargs);
    ++	  grub_cryptodisk_clear_key_cache (&cargs);
      	  if (disklast)
      	    *disklast = ')';
      	  return grub_errno;
    @@ grub-core/disk/cryptodisk.c: grub_cmd_cryptomount (grub_extcmd_context_t ctxt, i
      	{
      	  grub_dprintf ("cryptodisk", "already mounted as crypto%lu\n", dev->id);
      	  grub_disk_close (disk);
    -+          grub_cryptodisk_clear_key_cache (&cargs);
    ++	  grub_cryptodisk_clear_key_cache (&cargs);
      	  if (disklast)
      	    *disklast = ')';
      	  return GRUB_ERR_NONE;
    @@ include/grub/cryptodisk.h: typedef gcry_err_code_t
     +  grub_uint8_t *key;
     +  grub_size_t key_len;
     +
    -+  /* The key protector associated with this cache entry failed, so avoid it
    -+   * even if the cached entry (an instance of this structure) is empty. */
    ++  /*
    ++   * The key protector associated with this cache entry failed, so avoid it
    ++   * even if the cached entry (an instance of this structure) is empty.
    ++   */
     +  int invalid;
     +};
     +
 5:  8547f130d ! 12:  aa6210c44 util/grub-protect: Add new tool
    @@ util/grub-protect.c (new)
     +  void *buf;
     +
     +  f = fopen (filepath, "rb");
    -+  if (!f)
    ++  if (f == NULL)
     +    return GRUB_ERR_FILE_NOT_FOUND;
     +
     +  if (fseek (f, 0, SEEK_END))
    @@ util/grub-protect.c (new)
     +    }
     +
     +  len = ftell (f);
    -+  if (!len)
    ++  if (len == 0)
     +    {
     +       err = GRUB_ERR_FILE_READ_ERROR;
     +       goto exit1;
    @@ util/grub-protect.c (new)
     +  rewind (f);
     +
     +  buf = grub_malloc (len);
    -+  if (!buf)
    ++  if (buf == NULL)
     +    {
     +       err = GRUB_ERR_OUT_OF_MEMORY;
     +       goto exit1;
    @@ util/grub-protect.c (new)
     +  FILE *f;
     +
     +  f = fopen (filepath, "wb");
    -+  if (!f)
    ++  if (f == NULL)
     +    return GRUB_ERR_FILE_NOT_FOUND;
     +
     +  if (fwrite (buffer, buffer_size, 1, f) != 1)
    @@ util/grub-protect.c (new)
     +  int n;
     +
     +  grub_path = grub_canonicalize_file_name (filepath);
    -+  if (!grub_path)
    ++  if (grub_path == NULL)
     +    goto exit1;
     +
     +  devices = grub_guess_root_devices (grub_path);
    -+  if (!devices || !devices[0])
    ++  if (devices == NULL || devices[0] == NULL)
     +    goto exit2;
     +
     +  disk = devices[0];
    @@ util/grub-protect.c (new)
     +  grub_util_pull_device (disk);
     +
     +  grub_dev = grub_util_get_grub_dev (disk);
    -+  if (!grub_dev)
    ++  if (grub_dev == NULL)
     +    goto exit3;
     +
     +  dev = grub_device_open (grub_dev);
    -+  if (!dev)
    ++  if (dev == NULL)
     +    goto exit4;
     +
     +  efi_drive = grub_util_guess_efi_drive (disk);
    -+  if (!efi_drive)
    ++  if (efi_drive == NULL)
     +    goto exit5;
     +
     +  partition = grub_partition_get_name (dev->disk->partition);
    -+  if (!partition)
    ++  if (partition == NULL)
     +    goto exit6;
     +
     +  grub_drive_len = grub_strlen (efi_drive) + grub_strlen (partition) + 3;
     +  grub_drive = grub_malloc (grub_drive_len + 1);
    -+  if (!grub_drive)
    ++  if (grub_drive == NULL)
     +    goto exit7;
     +
     +  n = grub_snprintf (grub_drive, grub_drive_len + 1, "(%s,%s)", efi_drive,
    @@ util/grub-protect.c (new)
     +grub_err_t
     +grub_tcg2_get_max_output_size (grub_size_t *size)
     +{
    -+  if (!size)
    ++  if (size == NULL)
     +    return GRUB_ERR_BAD_ARGUMENT;
     +
     +  *size = GRUB_TPM2_BUFFER_CAPACITY;
    @@ util/grub-protect.c (new)
     +    return GRUB_ERR_NONE;
     +
     +  err = close (grub_protector_tpm2_fd);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +  {
     +    fprintf (stderr, _("Could not close TPM device (Error: %u).\n"), errno);
     +    return GRUB_ERR_IO;
    @@ util/grub-protect.c (new)
     +
     +  /* PCR Read */
     +  for (i = 0; i < args->tpm2_pcr_count; i++)
    -+    pcr_sel
    -+      .pcrSelections[0]
    -+      .pcrSelect[TPM2_PCR_TO_SELECT(args->tpm2_pcrs[i])]
    -+	|= TPM2_PCR_TO_BIT(args->tpm2_pcrs[i]);
    ++    TPMS_PCR_SELECTION_SelectPCR (&pcr_sel.pcrSelections[0], args->tpm2_pcrs[i]);
     +
     +  rc = TPM2_PCR_Read (NULL, &pcr_sel, NULL, &pcr_sel_out, &pcr_values, NULL);
     +  if (rc != TPM_RC_SUCCESS)
    @@ util/grub-protect.c (new)
     +
     +  pcr_concat_len = pcr_digest_len * args->tpm2_pcr_count;
     +  pcr_concat = grub_malloc (pcr_concat_len);
    -+  if (!pcr_concat)
    ++  if (pcr_concat == NULL)
     +    {
     +      err = GRUB_ERR_OUT_OF_MEMORY;
     +      fprintf (stderr, _("Failed to allocate PCR concatenation buffer.\n"));
    @@ util/grub-protect.c (new)
     +extern asn1_static_node tpm2key_asn1_tab[];
     +
     +static grub_err_t
    -+grub_protect_tpm2_export_tpm2key (const char *filepath,
    ++grub_protect_tpm2_export_tpm2key (const struct grub_protect_args *args,
     +				  TPM2_SEALED_KEY *sealed_key)
     +{
     +  const char *sealed_key_oid = "2.23.133.10.1.5";
     +  asn1_node asn1_def = NULL;
     +  asn1_node tpm2key = NULL;
     +  grub_uint32_t parent;
    ++  grub_uint32_t cmd_code;
    ++  struct grub_tpm2_buffer pol_buf;
    ++  TPML_PCR_SELECTION pcr_sel = {
    ++    .count = 1,
    ++    .pcrSelections = {
    ++      {
    ++	.hash = args->tpm2_bank,
    ++	.sizeOfSelect = 3,
    ++	.pcrSelect = { 0 }
    ++      },
    ++    }
    ++  };
     +  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;
     +
    ++  for (i = 0; i < args->tpm2_pcr_count; i++)
    ++    TPMS_PCR_SELECTION_SelectPCR (&pcr_sel.pcrSelections[0], args->tpm2_pcrs[i]);
    ++
    ++  /*
    ++   * Prepare the parameters for TPM_CC_PolicyPCR:
    ++   * empty pcrDigest and the user selected PCRs
    ++   */
    ++  grub_tpm2_buffer_init (&pol_buf);
    ++  grub_tpm2_buffer_pack_u16 (&pol_buf, 0);
    ++  grub_tpm2_mu_TPML_PCR_SELECTION_Marshal (&pol_buf, &pcr_sel);
    ++
     +  grub_tpm2_buffer_init (&pub_buf);
     +  grub_tpm2_mu_TPM2B_PUBLIC_Marshal (&pub_buf, &sealed_key->public);
     +  grub_tpm2_buffer_init (&priv_buf);
     +  grub_tpm2_mu_TPM2B_Marshal (&priv_buf, sealed_key->private.size,
     +			      sealed_key->private.buffer);
    -+  if (pub_buf.error || priv_buf.error)
    ++  if (pub_buf.error != 0 || priv_buf.error != 0)
     +    return GRUB_ERR_BAD_ARGUMENT;
     +
     +  ret = asn1_array2tree (tpm2key_asn1_tab, &asn1_def, NULL);
    @@ util/grub-protect.c (new)
     +      goto error;
     +    }
     +
    -+  /* Remove 'policy' */
    -+  ret = asn1_write_value (tpm2key, "policy", NULL, 0);
    ++  /* Set 'policy' */
    ++  ret = asn1_write_value (tpm2key, "policy", "NEW", 1);
    ++  if (ret != ASN1_SUCCESS)
    ++    {
    ++      err = GRUB_ERR_BAD_ARGUMENT;
    ++      goto error;
    ++    }
    ++  cmd_code = grub_cpu_to_be32 (TPM_CC_PolicyPCR);
    ++  ret = asn1_write_value (tpm2key, "policy.?LAST.CommandCode", &cmd_code,
    ++			  sizeof (cmd_code));
    ++  if (ret != ASN1_SUCCESS)
    ++    {
    ++      err = GRUB_ERR_BAD_ARGUMENT;
    ++      goto error;
    ++    }
    ++  ret = asn1_write_value (tpm2key, "policy.?LAST.CommandPolicy", &pol_buf.data,
    ++			  pol_buf.size);
     +  if (ret != ASN1_SUCCESS)
     +    {
     +      err = GRUB_ERR_BAD_ARGUMENT;
    @@ util/grub-protect.c (new)
     +      goto error;
     +    }
     +
    -+  err = grub_protect_write_file (filepath, der_buf, der_buf_size);
    -+  if (err)
    ++  err = grub_protect_write_file (args->tpm2_outfile, der_buf, der_buf_size);
    ++  if (err != GRUB_ERR_NONE)
     +    fprintf (stderr, _("Could not write tpm2key file (Error: %u).\n"),
     +	     errno);
     +
    @@ util/grub-protect.c (new)
     +  grub_tpm2_mu_TPM2B_PUBLIC_Marshal (&buf, &sealed_key->public);
     +  grub_tpm2_mu_TPM2B_Marshal (&buf, sealed_key->private.size,
     +			      sealed_key->private.buffer);
    -+  if (buf.error)
    ++  if (buf.error != 0)
     +    return GRUB_ERR_BAD_ARGUMENT;
     +
     +  err = grub_protect_write_file (filepath, buf.data, buf.size);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +    fprintf (stderr, _("Could not write sealed key file (Error: %u).\n"),
     +	     errno);
     +
    @@ util/grub-protect.c (new)
     +  grub_protect_get_grub_drive_for_file (args->tpm2_outfile, &grub_drive);
     +
     +  err = grub_protect_tpm2_open_device (args->tpm2_device);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +    return err;
     +
     +  err = grub_protect_read_file (args->tpm2_keyfile, (void **)&key, &key_size);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +    goto exit1;
     +
     +  if (key_size > TPM_MAX_SYM_DATA)
    @@ util/grub-protect.c (new)
     +  }
     +
     +  err = grub_protect_tpm2_get_srk (args, &srk);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +    goto exit2;
     +
     +  err = grub_protect_tpm2_get_policy_digest (args, &policy_digest);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +    goto exit3;
     +
     +  err = grub_protect_tpm2_seal (&policy_digest, srk, key, key_size,
     +				&sealed_key);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +    goto exit3;
     +
     +  if (args->tpm2_tpm2key)
    -+    err = grub_protect_tpm2_export_tpm2key (args->tpm2_outfile, &sealed_key);
    ++    err = grub_protect_tpm2_export_tpm2key (args, &sealed_key);
     +  else
     +    err = grub_protect_tpm2_export_sealed_key (args->tpm2_outfile, &sealed_key);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +    goto exit3;
     +
     +  if (grub_drive)
    @@ util/grub-protect.c (new)
     +  TPMS_AUTH_COMMAND authCommand = { 0 };
     +  grub_err_t err;
     +
    -+  if (!args->tpm2_evict)
    ++  if (args->tpm2_evict == 0)
     +    {
     +      printf (_("--tpm2-evict not specified, nothing to do.\n"));
     +      return GRUB_ERR_NONE;
     +    }
     +
     +  err = grub_protect_tpm2_open_device (args->tpm2_device);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +    return err;
     +
     +  /* Find SRK */
    @@ util/grub-protect.c (new)
     +	  return GRUB_ERR_BAD_ARGUMENT;
     +	}
     +
    -+      if (!args->tpm2_keyfile)
    ++      if (args->tpm2_keyfile == NULL)
     +	{
     +	  fprintf (stderr, _("--tpm2-keyfile must be specified.\n"));
     +	  return GRUB_ERR_BAD_ARGUMENT;
     +	}
     +
    -+      if (!args->tpm2_outfile)
    ++      if (args->tpm2_outfile == NULL)
     +	{
     +	  fprintf (stderr, _("--tpm2-outfile must be specified.\n"));
     +	  return GRUB_ERR_BAD_ARGUMENT;
     +	}
     +
    -+      if (!args->tpm2_device)
    ++      if (args->tpm2_device == NULL)
     +	args->tpm2_device = "/dev/tpm0";
     +
    -+      if (!args->tpm2_pcr_count)
    ++      if (args->tpm2_pcr_count == 0)
     +	{
     +	  args->tpm2_pcrs[0] = 7;
     +	  args->tpm2_pcr_count = 1;
     +	}
     +
    -+      if (!args->tpm2_srk)
    ++      if (args->tpm2_srk == 0)
     +	args->tpm2_srk = TPM2_SRK_HANDLE;
     +
    -+      if (!args->tpm2_asymmetric)
    ++      if (args->tpm2_asymmetric == TPM_ALG_ERROR)
     +	args->tpm2_asymmetric = TPM_ALG_RSA;
     +
    -+      if (!args->tpm2_bank)
    ++      if (args->tpm2_bank == TPM_ALG_ERROR)
     +	args->tpm2_bank = TPM_ALG_SHA256;
     +
     +      break;
    @@ util/grub-protect.c (new)
     +	  return GRUB_ERR_BAD_ARGUMENT;
     +	}
     +
    -+      if (!args->tpm2_device)
    ++      if (args->tpm2_device == NULL)
     +	args->tpm2_device = "/dev/tpm0";
     +
    -+      if (!args->tpm2_srk)
    ++      if (args->tpm2_srk == 0)
     +	args->tpm2_srk = TPM2_SRK_HANDLE;
     +
     +      break;
    @@ util/grub-protect.c (new)
     +
     +      err = grub_tpm2_protector_parse_pcrs (arg, args->tpm2_pcrs,
     +					    &args->tpm2_pcr_count);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	{
    -+	  if (grub_errno)
    ++	  if (grub_errno != GRUB_ERR_NONE)
     +	    grub_print_error ();
     +	  return EINVAL;
     +	}
    @@ util/grub-protect.c (new)
     +	}
     +
     +      err = grub_tpm2_protector_parse_tpm_handle (arg, &args->tpm2_srk);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	{
    -+	  if (grub_errno)
    ++	  if (grub_errno != GRUB_ERR_NONE)
     +	    grub_print_error ();
     +	  return EINVAL;
     +	}
    @@ util/grub-protect.c (new)
     +	}
     +
     +      err = grub_tpm2_protector_parse_asymmetric (arg, &args->tpm2_asymmetric);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	{
    -+	  if (grub_errno)
    ++	  if (grub_errno != GRUB_ERR_NONE)
     +	    grub_print_error ();
     +	  return EINVAL;
     +	}
    @@ util/grub-protect.c (new)
     +	}
     +
     +      err = grub_tpm2_protector_parse_bank (arg, &args->tpm2_bank);
    -+      if (err)
    ++      if (err != GRUB_ERR_NONE)
     +	{
    -+	  if (grub_errno)
    ++	  if (grub_errno != GRUB_ERR_NONE)
     +	    grub_print_error ();
     +	  return EINVAL;
     +	}
    @@ util/grub-protect.c (new)
     +  grub_protect_init (&argc, &argv);
     +
     +  err = grub_protect_args_verify (&args);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +    goto exit;
     +
     +  err = grub_protect_dispatch (&args);
    -+  if (err)
    ++  if (err != GRUB_ERR_NONE)
     +    goto exit;
     +
     +exit:
Signature · 1 line
2.35.3
author
#1 lore raw

PATCH v3 1/12 posix_wrap: tweaks in preparation for libtasn1

From: Daniel Axtens <[email protected]>

- Define SIZEOF_UNSIGNED_LONG_INT, it's the same as SIZEOF_UNSIGNED_LONG.

- Define WORD_BIT, the size in bits of an int. This is a defined in the Single Unix Specification and in gnulib's limits.h. gnulib assumes it's 32 bits on all our platforms, including 64 bit platforms, so we also use that value.

- Provide strto[u]l[l] preprocessor macros that resolve to grub_strto[u]l[l]. To avoid gcrypt redefining strtoul, we also define HAVE_STRTOUL here.

---
 grub-core/lib/posix_wrap/limits.h    | 1 +
 grub-core/lib/posix_wrap/stdlib.h    | 8 ++++++++
 grub-core/lib/posix_wrap/sys/types.h | 1 +
 3 files changed, 10 insertions(+)
grub-core/lib/posix_wrap/limits.h +1 -0
index 26918c8a0..4be7b4080 100644
@@ -41,5 +41,6 @@
 #define LONG_MAX GRUB_LONG_MAX
 
 #define CHAR_BIT 8
+#define WORD_BIT 32
 
 #endif
grub-core/lib/posix_wrap/stdlib.h +8 -0
index f5279756a..14e4efdd0 100644
@@ -64,4 +64,12 @@ abort (void)
   grub_abort ();
 }
 
+#define strtol grub_strtol
+
+/* for libgcrypt */
+#define HAVE_STRTOUL
+#define strtoul grub_strtoul
+
+#define strtoull grub_strtoull
+
 #endif
grub-core/lib/posix_wrap/sys/types.h +1 -0
index eeda543c4..2f3e86549 100644
@@ -50,6 +50,7 @@ typedef grub_uint8_t byte;
 typedef grub_addr_t uintptr_t;
 
 #define SIZEOF_UNSIGNED_LONG GRUB_CPU_SIZEOF_LONG
+#define SIZEOF_UNSIGNED_LONG_INT GRUB_CPU_SIZEOF_LONG
 #define SIZEOF_UNSIGNED_INT 4
 #define SIZEOF_UNSIGNED_LONG_LONG 8
 #define SIZEOF_UNSIGNED_SHORT 2
Signature · 1 line
2.35.3
author
#2 lore raw

PATCH v3 2/12 libtasn1: import libtasn1-4.19.0

In reply to Gary Lin

From: Daniel Axtens <[email protected]>

Import a very trimmed-down set of libtasn1 files:

pushd /tmp
wget https://ftp.gnu.org/gnu/libtasn1/libtasn1-4.19.0.tar.gz
tar -xf libtasn1-4.19.0.tar.gz
popd
pushd grub-core/lib
rm -rf libtasn1
mkdir libtasn1
cp /tmp/libtasn1-4.19.0/{README.md,COPYING} libtasn1/
mkdir libtasn1/lib
cp /tmp/libtasn1-4.19.0/lib/{coding.c,decoding.c,element.c,element.h,errors.c,gstr.c,gstr.h,int.h,parser_aux.c,parser_aux.h,structure.c,structure.h} libtasn1/lib cp /tmp/libtasn1-4.19.0/lib/includes/libtasn1.h ../../include/grub/
git add libtasn1/ ../../include/grub/libtasn1.h
popd

---
 grub-core/lib/libtasn1/COPYING          |   16 +
 grub-core/lib/libtasn1/README.md        |   98 +
 grub-core/lib/libtasn1/lib/coding.c     | 1425 +++++++++++++
 grub-core/lib/libtasn1/lib/decoding.c   | 2501 +++++++++++++++++++++++
 grub-core/lib/libtasn1/lib/element.c    | 1109 ++++++++++
 grub-core/lib/libtasn1/lib/element.h    |   42 +
 grub-core/lib/libtasn1/lib/errors.c     |  100 +
 grub-core/lib/libtasn1/lib/gstr.c       |   74 +
 grub-core/lib/libtasn1/lib/gstr.h       |   50 +
 grub-core/lib/libtasn1/lib/int.h        |  221 ++
 grub-core/lib/libtasn1/lib/parser_aux.c | 1178 +++++++++++
 grub-core/lib/libtasn1/lib/parser_aux.h |  172 ++
 grub-core/lib/libtasn1/lib/structure.c  | 1225 +++++++++++
 grub-core/lib/libtasn1/lib/structure.h  |   46 +
 include/grub/libtasn1.h                 |  643 ++++++
 15 files changed, 8900 insertions(+)
 create mode 100644 grub-core/lib/libtasn1/COPYING
 create mode 100644 grub-core/lib/libtasn1/README.md
 create mode 100644 grub-core/lib/libtasn1/lib/coding.c
 create mode 100644 grub-core/lib/libtasn1/lib/decoding.c
 create mode 100644 grub-core/lib/libtasn1/lib/element.c
 create mode 100644 grub-core/lib/libtasn1/lib/element.h
 create mode 100644 grub-core/lib/libtasn1/lib/errors.c
 create mode 100644 grub-core/lib/libtasn1/lib/gstr.c
 create mode 100644 grub-core/lib/libtasn1/lib/gstr.h
 create mode 100644 grub-core/lib/libtasn1/lib/int.h
 create mode 100644 grub-core/lib/libtasn1/lib/parser_aux.c
 create mode 100644 grub-core/lib/libtasn1/lib/parser_aux.h
 create mode 100644 grub-core/lib/libtasn1/lib/structure.c
 create mode 100644 grub-core/lib/libtasn1/lib/structure.h
 create mode 100644 include/grub/libtasn1.h
grub-core/lib/libtasn1/COPYING new file +16 -0
new file mode 100644
index 000000000..e8b3628db
@@ -0,0 +1,16 @@
+LICENSING
+=========
+
+The libtasn1 library is released under the GNU Lesser General Public
+License (LGPL) version 2.1 or later; see [COPYING.LESSER](doc/COPYING.LESSER)
+for the license terms.
+
+The GNU LGPL applies to the main libtasn1 library, while the
+included applications library are under the GNU GPL version 3.
+The libtasn1 library is located in the lib directory, while the applications
+in src/.
+
+The documentation in doc/ is under the GNU FDL license 1.3.
+
+For any copyright year range specified as YYYY-ZZZZ in this package
+note that the range specifies every single year in that closed interval.
grub-core/lib/libtasn1/README.md new file +98 -0

98 lines not on this page · raw message

grub-core/lib/libtasn1/lib/coding.c new file +1425 -0

1,425 lines not on this page · raw message

grub-core/lib/libtasn1/lib/decoding.c new file +2501 -0

1,461 lines not on this page · raw message

grub-core/lib/libtasn1/lib/element.c new file +1109 -0

1,109 lines not on this page · raw message

grub-core/lib/libtasn1/lib/element.h new file +42 -0

42 lines not on this page · raw message

grub-core/lib/libtasn1/lib/errors.c new file +100 -0

100 lines not on this page · raw message

grub-core/lib/libtasn1/lib/gstr.c new file +74 -0

74 lines not on this page · raw message

grub-core/lib/libtasn1/lib/gstr.h new file +50 -0

50 lines not on this page · raw message

grub-core/lib/libtasn1/lib/int.h new file +221 -0

221 lines not on this page · raw message

grub-core/lib/libtasn1/lib/parser_aux.c new file +1178 -0

1,178 lines not on this page · raw message

grub-core/lib/libtasn1/lib/parser_aux.h new file +172 -0

172 lines not on this page · raw message

grub-core/lib/libtasn1/lib/structure.c new file +1225 -0

1,225 lines not on this page · raw message

grub-core/lib/libtasn1/lib/structure.h new file +46 -0

46 lines not on this page · raw message

include/grub/libtasn1.h new file +643 -0

643 lines not on this page · raw message

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

Signature · 1 line
2.35.3

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

author
#3 lore raw

PATCH v3 3/12 libtasn1: disable code not needed in grub

In reply to Gary Lin

From: Daniel Axtens <[email protected]>

We don't expect to be able to write ASN.1, only read it, so we can disable some code.

Do that with #if 0/#endif, rather than deletion. This means that the difference between upstream and grub is smaller, which should make updating libtasn1 easier in the future.

With these exclusions we also avoid the need for minmax.h, which is convenient because it means we don't have to import it from gnulib.

---
 grub-core/lib/libtasn1/lib/coding.c    | 12 ++++++++++--
 grub-core/lib/libtasn1/lib/decoding.c  |  2 ++
 grub-core/lib/libtasn1/lib/element.c   |  4 ++--
 grub-core/lib/libtasn1/lib/errors.c    |  3 +++
 grub-core/lib/libtasn1/lib/structure.c | 10 ++++++----
 include/grub/libtasn1.h                | 15 +++++++++++++++
 6 files changed, 38 insertions(+), 8 deletions(-)
grub-core/lib/libtasn1/lib/coding.c +10 -2
index ea5bc370e..841fe47a9 100644
@@ -30,11 +30,11 @@
 #include "parser_aux.h"
 #include <gstr.h>
 #include "element.h"
-#include "minmax.h"
 #include <structure.h>
 
 #define MAX_TAG_LEN 16
 
+#if 0
 /******************************************************/
 /* Function : _asn1_error_description_value_not_found */
 /* Description: creates the ErrorDescription string   */
@@ -58,6 +58,7 @@ _asn1_error_description_value_not_found (asn1_node node,
   Estrcat (ErrorDescription, "' not found");
 
 }
+#endif
 
 /**
  * asn1_length_der:
@@ -244,6 +245,7 @@ asn1_encode_simple_der (unsigned int etype, const unsigned char *str,
   return ASN1_SUCCESS;
 }
 
+#if 0
 /******************************************************/
 /* Function : _asn1_time_der                          */
 /* Description: creates the DER coding for a TIME     */
@@ -278,7 +280,7 @@ _asn1_time_der (unsigned char *str, int str_len, unsigned char *der,
 
   return ASN1_SUCCESS;
 }
-
+#endif
 
 /*
 void
@@ -519,6 +521,7 @@ asn1_bit_der (const unsigned char *str, int bit_len,
 }
 
 
+#if 0
 /******************************************************/
 /* Function : _asn1_complete_explicit_tag             */
 /* Description: add the length coding to the EXPLICIT */
@@ -595,6 +598,7 @@ _asn1_complete_explicit_tag (asn1_node node, unsigned char *der,
 
   return ASN1_SUCCESS;
 }
+#endif
 
 const tag_and_class_st _asn1_tags[] = {
   [ASN1_ETYPE_GENERALSTRING] =
@@ -647,6 +651,8 @@ const tag_and_class_st _asn1_tags[] = {
 
 unsigned int _asn1_tags_size = sizeof (_asn1_tags) / sizeof (_asn1_tags[0]);
 
+
+#if 0
 /******************************************************/
 /* Function : _asn1_insert_tag_der                    */
 /* Description: creates the DER coding of tags of one */
@@ -1423,3 +1429,5 @@ error:
   asn1_delete_structure (&node);
   return err;
 }
+
+#endif
\ No newline at end of file
grub-core/lib/libtasn1/lib/decoding.c +2 -0
index b9245c486..92fc87c23 100644
@@ -1620,6 +1620,7 @@ asn1_der_decoding (asn1_node * element, const void *ider, int ider_len,
   return asn1_der_decoding2 (element, ider, &ider_len, 0, errorDescription);
 }
 
+#if 0
 /**
  * asn1_der_decoding_element:
  * @structure: pointer to an ASN1 structure
@@ -1650,6 +1651,7 @@ asn1_der_decoding_element (asn1_node * structure, const char *elementName,
 {
   return asn1_der_decoding (structure, ider, len, errorDescription);
 }
+#endif
 
 /**
  * asn1_der_decoding_startEnd:
grub-core/lib/libtasn1/lib/element.c +2 -2
index d4c558e10..5c7941e53 100644
@@ -191,7 +191,7 @@ _asn1_append_sequence_set (asn1_node node, struct node_tail_cache_st *pcache)
   return ASN1_SUCCESS;
 }
 
-
+#if 0
 /**
  * asn1_write_value:
  * @node_root: pointer to a structure
@@ -646,7 +646,7 @@ asn1_write_value (asn1_node node_root, const char *name,
 
   return ASN1_SUCCESS;
 }
-
+#endif
 
 #define PUT_VALUE( ptr, ptr_size, data, data_size) \
 	*len = data_size; \
grub-core/lib/libtasn1/lib/errors.c +3 -0
index aef5dfe6f..0175ddedb 100644
@@ -57,6 +57,8 @@ static const libtasn1_error_entry error_algorithms[] = {
   {0, 0}
 };
 
+
+#if 0
 /**
  * asn1_perror:
  * @error: is an error returned by a libtasn1 function.
@@ -73,6 +75,7 @@ asn1_perror (int error)
   const char *str = asn1_strerror (error);
   fprintf (stderr, "LIBTASN1 ERROR: %s\n", str ? str : "(null)");
 }
+#endif
 
 /**
  * asn1_strerror:
grub-core/lib/libtasn1/lib/structure.c +6 -4
index 512dd601f..3e1e35ba5 100644
@@ -76,7 +76,7 @@ _asn1_find_left (asn1_node_const node)
   return node->left;
 }
 
-
+#if 0
 int
 _asn1_create_static_structure (asn1_node_const pointer,
 			       char *output_file_name, char *vector_name)
@@ -155,7 +155,7 @@ _asn1_create_static_structure (asn1_node_const pointer,
 
   return ASN1_SUCCESS;
 }
-
+#endif
 
 /**
  * asn1_array2tree:
@@ -721,7 +721,7 @@ asn1_create_element (asn1_node_const definitions, const char *source_name,
   return res;
 }
 
-
+#if 0
 /**
  * asn1_print_structure:
  * @out: pointer to the output file (e.g. stdout).
@@ -1062,7 +1062,7 @@ asn1_print_structure (FILE * out, asn1_node_const structure, const char *name,
 	}
     }
 }
-
+#endif
 
 
 /**
@@ -1158,6 +1158,7 @@ asn1_find_structure_from_oid (asn1_node_const definitions,
   return NULL;			/* ASN1_ELEMENT_NOT_FOUND; */
 }
 
+#if 0
 /**
  * asn1_copy_node:
  * @dst: Destination asn1 node.
@@ -1207,6 +1208,7 @@ asn1_copy_node (asn1_node dst, const char *dst_name,
 
   return result;
 }
+#endif
 
 /**
  * asn1_dup_node:
include/grub/libtasn1.h +15 -0
index 51cc7879f..507e0679e 100644
@@ -318,6 +318,8 @@ extern "C"
 /*  Functions definitions          */
 /***********************************/
 
+/* These functions are not used in grub and should not be referenced. */
+# if 0
   extern ASN1_API int
     asn1_parser2tree (const char *file,
 		      asn1_node * definitions, char *error_desc);
@@ -326,14 +328,17 @@ extern "C"
     asn1_parser2array (const char *inputFileName,
 		       const char *outputFileName,
 		       const char *vectorName, char *error_desc);
+# endif
 
   extern ASN1_API int
     asn1_array2tree (const asn1_static_node * array,
 		     asn1_node * definitions, char *errorDescription);
 
+# if 0
   extern ASN1_API void
     asn1_print_structure (FILE * out, asn1_node_const structure,
 			  const char *name, int mode);
+# endif
 
   extern ASN1_API int
     asn1_create_element (asn1_node_const definitions,
@@ -347,9 +352,11 @@ extern "C"
   extern ASN1_API int
     asn1_delete_element (asn1_node structure, const char *element_name);
 
+# if 0
   extern ASN1_API int
     asn1_write_value (asn1_node node_root, const char *name,
 		      const void *ivalue, int len);
+# endif
 
   extern ASN1_API int
     asn1_read_value (asn1_node_const root, const char *name,
@@ -366,9 +373,11 @@ extern "C"
     asn1_number_of_elements (asn1_node_const element, const char *name,
 			     int *num);
 
+# if 0
   extern ASN1_API int
     asn1_der_coding (asn1_node_const element, const char *name,
 		     void *ider, int *len, char *ErrorDescription);
+# endif
 
   extern ASN1_API int
     asn1_der_decoding2 (asn1_node * element, const void *ider,
@@ -379,6 +388,7 @@ extern "C"
     asn1_der_decoding (asn1_node * element, const void *ider,
 		       int ider_len, char *errorDescription);
 
+# if 0
 /* Do not use. Use asn1_der_decoding() instead. */
   extern ASN1_API int
     asn1_der_decoding_element (asn1_node * structure,
@@ -386,6 +396,7 @@ extern "C"
 			       const void *ider, int len,
 			       char *errorDescription)
     _ASN1_GCC_ATTR_DEPRECATED;
+# endif
 
   extern ASN1_API int
     asn1_der_decoding_startEnd (asn1_node element,
@@ -411,12 +422,16 @@ extern "C"
 							    const char
 							    *oidValue);
 
+# if 0
     __LIBTASN1_PURE__
     extern ASN1_API const char *asn1_check_version (const char *req_version);
+# endif
 
   __LIBTASN1_PURE__ extern ASN1_API const char *asn1_strerror (int error);
 
+# if 0
   extern ASN1_API void asn1_perror (int error);
+# endif
 
 # define ASN1_MAX_TAG_SIZE 4
 # define ASN1_MAX_LENGTH_SIZE 9
Signature · 1 line
2.35.3
author
#4 lore raw

PATCH v3 4/12 libtasn1: changes for grub compatibility

In reply to Gary Lin

From: Daniel Axtens <[email protected]>

Do a few things to make libtasn1 compile as part of grub:

- redefine _asn1_strcat. grub removed strcat so replace it with the appropriate calls to memcpy and strlen. Use this internally where strcat was used.

- replace c_isdigit with grub_isdigit (and don't import c-ctype from gnulib) grub_isdigit provides the same functionality as c_isdigit: it determines if the input is an ASCII digit without regard for locale.

- replace GL_ATTRIBUTE_PURE with __attribute__((pure)) which been supported since gcc-2.96. This avoids messing around with gnulib.

- adjust libtasn1.h: drop the ASN1_API logic, it's not needed for our modules. Unconditionally support const and pure attributes and adjust header paths.

- adjust header paths to "grub/libtasn1.h".

- replace a 64 bit division with a call to grub_divmod64, preventing creation of __udivdi3 calls on 32 bit platforms.

---
 grub-core/lib/libtasn1/lib/decoding.c   | 11 +++++-----
 grub-core/lib/libtasn1/lib/element.c    |  3 ++-
 grub-core/lib/libtasn1/lib/gstr.c       |  4 ++--
 grub-core/lib/libtasn1/lib/int.h        |  4 ++--
 grub-core/lib/libtasn1/lib/parser_aux.c |  7 +++---
 include/grub/libtasn1.h                 | 29 +++++++------------------
 6 files changed, 24 insertions(+), 34 deletions(-)
grub-core/lib/libtasn1/lib/decoding.c +6 -5
index 92fc87c23..4fd5f0ce6 100644
@@ -32,7 +32,8 @@
 #include <element.h>
 #include <limits.h>
 #include <intprops.h>
-#include "c-ctype.h"
+
+#define c_isdigit grub_isdigit
 
 #ifdef DEBUG
 # define warn() fprintf(stderr, "%s: %d\n", __func__, __LINE__)
@@ -2016,8 +2017,8 @@ asn1_expand_octet_string (asn1_node_const definitions, asn1_node * element,
 	  (p2->type & CONST_ASSIGN))
 	{
 	  strcpy (name, definitions->name);
-	  strcat (name, ".");
-	  strcat (name, p2->name);
+	  _asn1_strcat (name, ".");
+	  _asn1_strcat (name, p2->name);
 
 	  len = sizeof (value);
 	  result = asn1_read_value (definitions, name, value, &len);
@@ -2034,8 +2035,8 @@ asn1_expand_octet_string (asn1_node_const definitions, asn1_node * element,
 	      if (p2)
 		{
 		  strcpy (name, definitions->name);
-		  strcat (name, ".");
-		  strcat (name, p2->name);
+		  _asn1_strcat (name, ".");
+		  _asn1_strcat (name, p2->name);
 
 		  result = asn1_create_element (definitions, name, &aux);
 		  if (result == ASN1_SUCCESS)
grub-core/lib/libtasn1/lib/element.c +2 -1
index 5c7941e53..822a1b6ab 100644
@@ -30,9 +30,10 @@
 #include "parser_aux.h"
 #include <gstr.h>
 #include "structure.h"
-#include "c-ctype.h"
 #include "element.h"
 
+#define c_isdigit grub_isdigit
+
 void
 _asn1_hierarchical_name (asn1_node_const node, char *name, int name_size)
 {
grub-core/lib/libtasn1/lib/gstr.c +2 -2
index eef419554..bc507d3d8 100644
@@ -36,13 +36,13 @@ _asn1_str_cat (char *dest, size_t dest_tot_size, const char *src)
 
   if (dest_tot_size - dest_size > str_size)
     {
-      strcat (dest, src);
+      _asn1_strcat (dest, src);
     }
   else
     {
       if (dest_tot_size > dest_size)
 	{
-	  strncat (dest, src, (dest_tot_size - dest_size) - 1);
+	  memcpy (dest + dest_size, src, (dest_tot_size - dest_size) - 1);
 	  dest[dest_tot_size - 1] = 0;
 	}
     }
grub-core/lib/libtasn1/lib/int.h +2 -2
index d94d51c8c..07dd669ac 100644
@@ -35,7 +35,7 @@
 #  include <sys/types.h>
 # endif
 
-# include <libtasn1.h>
+# include "grub/libtasn1.h"
 
 # define ASN1_SMALL_VALUE_SIZE 16
 
@@ -115,7 +115,7 @@ extern const tag_and_class_st _asn1_tags[];
 # define _asn1_strtoul(n,e,b) strtoul((const char *) n, e, b)
 # define _asn1_strcmp(a,b) strcmp((const char *)a, (const char *)b)
 # define _asn1_strcpy(a,b) strcpy((char *)a, (const char *)b)
-# define _asn1_strcat(a,b) strcat((char *)a, (const char *)b)
+# define _asn1_strcat(a,b) memcpy((char *)a + strlen((const char *)a), (const char *)b, strlen((const char *)b) + 1)
 
 # if SIZEOF_UNSIGNED_LONG_INT == 8
 #  define _asn1_strtou64(n,e,b) strtoul((const char *) n, e, b)
grub-core/lib/libtasn1/lib/parser_aux.c +4 -3
index c05bd2339..8bdc42ae3 100644
@@ -26,7 +26,8 @@
 #include "gstr.h"
 #include "structure.h"
 #include "element.h"
-#include "c-ctype.h"
+
+#define c_isdigit grub_isdigit
 
 char _asn1_identifierMissing[ASN1_MAX_NAME_SIZE + 1];	/* identifier name not found */
 
@@ -40,7 +41,7 @@ char _asn1_identifierMissing[ASN1_MAX_NAME_SIZE + 1];	/* identifier name not fou
 #ifdef __clang__
 __attribute__((no_sanitize ("integer")))
 #endif
-     _GL_ATTRIBUTE_PURE static unsigned int _asn1_hash_name (const char *x)
+     __attribute__((__pure__)) static unsigned int _asn1_hash_name (const char *x)
 {
   const unsigned char *s = (unsigned char *) x;
   unsigned h = 0;
@@ -632,7 +633,7 @@ _asn1_ltostr (int64_t v, char str[LTOSTR_MAX_SIZE])
   count = 0;
   do
     {
-      d = val / 10;
+      d = grub_divmod64(val, 10, NULL);
       r = val - d * 10;
       temp[start + count] = '0' + (char) r;
       count++;
include/grub/libtasn1.h +8 -21
index 507e0679e..201089c11 100644
@@ -34,29 +34,16 @@
 #ifndef LIBTASN1_H
 # define LIBTASN1_H
 
-# ifndef ASN1_API
-#  if defined ASN1_BUILDING && defined HAVE_VISIBILITY && HAVE_VISIBILITY
-#   define ASN1_API __attribute__((__visibility__("default")))
-#  elif defined ASN1_BUILDING && defined _MSC_VER && ! defined ASN1_STATIC
-#   define ASN1_API __declspec(dllexport)
-#  elif defined _MSC_VER && ! defined ASN1_STATIC
-#   define ASN1_API __declspec(dllimport)
-#  else
-#   define ASN1_API
-#  endif
-# endif
+/* grub: ASN1_API is not used */
+# define ASN1_API
+
+/* grub: all our supported compilers support these attributes */
+# define __LIBTASN1_CONST__  __attribute__((const))
+# define __LIBTASN1_PURE__  __attribute__((pure))
 
-# ifdef __GNUC__
-#  define __LIBTASN1_CONST__  __attribute__((const))
-#  define __LIBTASN1_PURE__  __attribute__((pure))
-# else
-#  define __LIBTASN1_CONST__
-#  define __LIBTASN1_PURE__
-# endif
 
-# include <sys/types.h>
-# include <time.h>
-# include <stdio.h>		/* for FILE* */
+# include <grub/types.h>
+# include <grub/time.h>
 
 # ifdef __cplusplus
 extern "C"
Signature · 1 line
2.35.3
author
#5 lore raw

PATCH v3 5/12 libtasn1: compile into asn1 module

In reply to Gary Lin

From: Daniel Axtens <[email protected]>

Create a wrapper file that specifies the module license. Set up the makefile so it is built.

---
 grub-core/Makefile.core.def        | 15 +++++++++++++++
 grub-core/lib/libtasn1_wrap/wrap.c | 26 ++++++++++++++++++++++++++
 2 files changed, 41 insertions(+)
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap.c
grub-core/Makefile.core.def +15 -0
index 501cb008d..859776c91 100644
@@ -2561,3 +2561,18 @@ module = {
   common = commands/memtools.c;
   condition = COND_MM_DEBUG;
 };
+
+module = {
+  name = asn1;
+  common = lib/libtasn1/lib/decoding.c;
+  common = lib/libtasn1/lib/coding.c;
+  common = lib/libtasn1/lib/element.c;
+  common = lib/libtasn1/lib/structure.c;
+  common = lib/libtasn1/lib/parser_aux.c;
+  common = lib/libtasn1/lib/gstr.c;
+  common = lib/libtasn1/lib/errors.c;
+  common = lib/libtasn1_wrap/wrap.c;
+  cflags = '$(CFLAGS_POSIX) $(CFLAGS_GNULIB)';
+  // -Wno-type-limits comes from libtasn1's configure.ac
+  cppflags = '$(CPPFLAGS_POSIX) $(CPPFLAGS_GNULIB) -I$(srcdir)/lib/libtasn1/lib -Wno-type-limits';
+};
grub-core/lib/libtasn1_wrap/wrap.c new file +26 -0
new file mode 100644
index 000000000..622ba942e
@@ -0,0 +1,26 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020 IBM Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/dl.h>
+
+/*
+ * libtasn1 is provided under LGPL2.1+, which is compatible
+ * with GPL3+. As Grub as a whole is under GPL3+, this module
+ * is therefore under GPL3+ also.
+ */
+GRUB_MOD_LICENSE ("GPLv3+");
Signature · 1 line
2.35.3
author
#6 lore raw

PATCH v3 6/12 test_asn1: test module for libtasn1

In reply to Gary Lin

From: Daniel Axtens <[email protected]>

Import tests from libtasn1 that don't use functionality we don't import. I have put them here rather than in the libtasn1 directory because:

- They need much more significant changes to run in the grub context.

- I don't expect they will need to be changed when updating
libtasn1: I expect the old tests will usually continue to pass on new versions.

This doesn't test the full decoder but that will be exercised in test suites for coming patch sets.

Add testcase target in accordance with
5e10be48e5 tests: Add check-native and check-nonnative make targets

---
 Makefile.util.def                             |   6 +
 grub-core/Makefile.core.def                   |  13 ++
 .../tests/CVE-2018-1000654-1_asn1_tab.h       |  32 +++
 .../tests/CVE-2018-1000654-2_asn1_tab.h       |  36 +++
 .../libtasn1_wrap/tests/CVE-2018-1000654.c    |  61 +++++
 .../lib/libtasn1_wrap/tests/Test_overflow.c   | 138 ++++++++++++
 .../lib/libtasn1_wrap/tests/Test_simple.c     | 207 +++++++++++++++++
 .../lib/libtasn1_wrap/tests/Test_strings.c    | 150 +++++++++++++
 .../libtasn1_wrap/tests/object-id-decoding.c  | 116 ++++++++++
 .../libtasn1_wrap/tests/object-id-encoding.c  | 120 ++++++++++
 .../lib/libtasn1_wrap/tests/octet-string.c    | 211 ++++++++++++++++++
 .../lib/libtasn1_wrap/tests/reproducers.c     |  81 +++++++
 grub-core/lib/libtasn1_wrap/wrap_tests.c      |  75 +++++++
 grub-core/lib/libtasn1_wrap/wrap_tests.h      |  38 ++++
 tests/test_asn1.in                            |  12 +
 15 files changed, 1296 insertions(+)
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-1_asn1_tab.h
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-2_asn1_tab.h
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_overflow.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_simple.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_strings.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/object-id-decoding.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/object-id-encoding.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/octet-string.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/reproducers.c
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap_tests.c
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap_tests.h
 create mode 100644 tests/test_asn1.in
Makefile.util.def +6 -0
index beaef1168..c3b7df96d 100644
@@ -1237,6 +1237,12 @@ script = {
   common = tests/luks2_test.in;
 };
 
+script = {
+  testcase = native;
+  name = test_asn1;
+  common = tests/test_asn1.in;
+};
+
 program = {
   testcase = native;
   name = example_unit_test;
grub-core/Makefile.core.def +13 -0
index 859776c91..9b4423d47 100644
@@ -2576,3 +2576,16 @@ module = {
   // -Wno-type-limits comes from libtasn1's configure.ac
   cppflags = '$(CPPFLAGS_POSIX) $(CPPFLAGS_GNULIB) -I$(srcdir)/lib/libtasn1/lib -Wno-type-limits';
 };
+
+module = {
+  name = test_asn1;
+  common = lib/libtasn1_wrap/tests/CVE-2018-1000654.c;
+  common = lib/libtasn1_wrap/tests/object-id-decoding.c;
+  common = lib/libtasn1_wrap/tests/object-id-encoding.c;
+  common = lib/libtasn1_wrap/tests/octet-string.c;
+  common = lib/libtasn1_wrap/tests/reproducers.c;
+  common = lib/libtasn1_wrap/tests/Test_overflow.c;
+  common = lib/libtasn1_wrap/tests/Test_simple.c;
+  common = lib/libtasn1_wrap/tests/Test_strings.c;
+  common = lib/libtasn1_wrap/wrap_tests.c;
+};
grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-1_asn1_tab.h new file +32 -0
new file mode 100644
index 000000000..1e7d3d64f
@@ -0,0 +1,32 @@
+#if HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <grub/libtasn1.h>
+
+const asn1_static_node CVE_2018_1000654_1_asn1_tab[] = {
+  { "TEST_TREE", 536875024, NULL },
+  { NULL, 1610612748, NULL },
+  { "iso", 1073741825, "1"},
+  { "identified-organization", 1073741825, "3"},
+  { "dod", 1073741825, "6"},
+  { "internet", 1073741825, "1"},
+  { "security", 1073741825, "5"},
+  { "mechanisms", 1073741825, "5"},
+  { "pkix", 1073741825, "7"},
+  { "id-mod", 1073741825, "0"},
+  { "id-pkix1-implicit-88", 1, "2"},
+  { "id-xnyTest", 1879048204, NULL },
+  { NULL, 1073741825, "id-ix"},
+  { NULL, 1073741825, "29"},
+  { NULL, 1, "1"},
+  { "id-ix", 1880096780, "OBJECR"},
+  { NULL, 1073741825, "id-ix"},
+  { NULL, 1073741825, "29"},
+  { NULL, 1, "2"},
+  { "id-xnyTest", 805306380, NULL },
+  { NULL, 1073741825, "id-ix"},
+  { NULL, 1073741825, "29"},
+  { NULL, 1, "1"},
+  { NULL, 0, NULL }
+};
grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-2_asn1_tab.h new file +36 -0
new file mode 100644
index 000000000..e2561e5ec
@@ -0,0 +1,36 @@
+#if HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <grub/libtasn1.h>
+
+const asn1_static_node CVE_2018_1000654_2_asn1_tab[] = {
+  { "TEST_TREE", 536875024, NULL },
+  { NULL, 1610612748, NULL },
+  { "iso", 1073741825, "1"},
+  { "identified-organization", 1073741825, "3"},
+  { "dod", 1073741825, "6"},
+  { "internet", 1073741825, "1"},
+  { "security", 1073741825, "5"},
+  { "mechanisms", 1073741825, "5"},
+  { "pkix", 1073741825, "7"},
+  { "id-mod", 1073741825, "0"},
+  { "id-pkix1-implicit-88", 1, "2"},
+  { "id-oneTest", 1879048204, NULL },
+  { NULL, 1073741825, "id-two"},
+  { NULL, 1073741825, "9"},
+  { NULL, 1, "1"},
+  { "id-two", 1879048204, NULL },
+  { NULL, 1073741825, "id-three"},
+  { NULL, 1073741825, "2"},
+  { NULL, 1, "2"},
+  { "id-three", 1879048204, NULL },
+  { NULL, 1073741825, "id-four"},
+  { NULL, 1073741825, "3"},
+  { NULL, 1, "3"},
+  { "id-four", 805306380, NULL },
+  { NULL, 1073741825, "id-two"},
+  { NULL, 1073741825, "3"},
+  { NULL, 1, "3"},
+  { NULL, 0, NULL }
+};
grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654.c new file +61 -0

61 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/Test_overflow.c new file +138 -0

138 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/Test_simple.c new file +207 -0

207 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/Test_strings.c new file +150 -0

150 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/object-id-decoding.c new file +116 -0

116 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/object-id-encoding.c new file +120 -0

120 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/octet-string.c new file +211 -0

211 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/reproducers.c new file +81 -0

81 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/wrap_tests.c new file +75 -0

75 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/wrap_tests.h new file +38 -0
new file mode 100644
index 000000000..555e56dd2
@@ -0,0 +1,38 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020 IBM Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef LIBTASN1_WRAP_TESTS_H
+#define LIBTASN1_WRAP_TESTS_H
+
+void test_CVE_2018_1000654 (void);
+
+void test_object_id_encoding (void);
+
+void test_object_id_decoding (void);
+
+void test_octet_string (void);
+
+void test_overflow (void);
+
+void test_reproducers (void);
+
+void test_simple (void);
+
+void test_strings (void);
+
+#endif
tests/test_asn1.in new file +12 -0
new file mode 100644
index 000000000..8173c5c27
@@ -0,0 +1,12 @@
+#! @BUILD_SHEBANG@
+set -e
+
+. "@builddir@/grub-core/modinfo.sh"
+
+out=`echo test_asn1 | @builddir@/grub-shell`
+
+if [ "$(echo "$out" | tail -n 1)" != "ASN.1 self-tests passed" ]; then
+  echo "ASN.1 test failure: $out"
+  exit 1
+fi
+
Signature · 1 line
2.35.3
author
#7 lore raw

PATCH v3 7/12 libtasn1: Add the documentation

In reply to Gary Lin

Document libtasn1 in docs/grub-dev.texi and add the upgrade steps. Also add the patches to make libtasn1 compatible with grub code.

---
 docs/grub-dev.texi                            |  27 ++
 ...asn1-disable-code-not-needed-in-grub.patch | 311 ++++++++++++++++++
 ...tasn1-changes-for-grub-compatibility.patch | 209 ++++++++++++
 3 files changed, 547 insertions(+)
 create mode 100644 grub-core/lib/libtasn1-patches/0001-libtasn1-disable-code-not-needed-in-grub.patch
 create mode 100644 grub-core/lib/libtasn1-patches/0002-libtasn1-changes-for-grub-compatibility.patch
docs/grub-dev.texi +27 -0
index 31eb99ea2..702fe84f7 100644
@@ -595,6 +595,33 @@ cp minilzo-2.10/*.[hc] grub-core/lib/minilzo
 rm -r minilzo-2.10*
 @end example
 
+@node libtasn1
+@section libtasn1
+
+libtasn1 is a library providing Abstract Syntax Notation One (ASN.1, as
+specified by the X.680 ITU-T recommendation) parsing and structures management,
+and Distinguished Encoding Rules (DER, as per X.690) encoding and decoding
+functions.
+
+To upgrade to a new version of the libtasn1 library, download the release
+tarball and copy the files into the target directory:
+
+@example
+curl -L -O https://ftp.gnu.org/gnu/libtasn1/libtasn1-4.19.0.tar.gz
+tar -zxf libtasn1-4.19.0.tar.gz
+rm -r grub-core/lib/libtasn1/
+mkdir libtasn1/lib
+mkdir -p grub-core/lib/libtasn1/lib/
+cp libtasn1-4.19.0/{README.md,COPYING} grub-core/lib/libtasn1/
+cp libtasn1-4.19.0/lib/{coding.c,decoding.c,element.c,element.h,errors.c,gstr.c,gstr.h,int.h,parser_aux.c,parser_aux.h,structure.c,structure.h} grub-core/lib/libtasn1/lib/
+cp libtasn1-4.19.0/lib/includes/libtasn1.h include/grub/
+rm -rf libtasn1-4.19.0
+@end example
+
+After upgrading the library, it is necessary to apply the patches in
+@file{grub-core/lib/libtasn1-patches/} to adjust the code to be compatible with
+grub.
+
 @node Porting
 @chapter Porting
 
grub-core/lib/libtasn1-patches/0001-libtasn1-disable-code-not-needed-in-grub.patch new file +311 -0

311 lines not on this page · raw message

grub-core/lib/libtasn1-patches/0002-libtasn1-changes-for-grub-compatibility.patch new file +209 -0

209 lines not on this page · raw message

Signature · 1 line
2.35.3
author
#8 lore raw

PATCH v3 8/12 protectors: Add key protectors framework

In reply to Gary Lin

From: Hernan Gatta <[email protected]>

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

The key protectors framework, besides offering registration and unregistration functions, also offers a one-stop routine for finding and invoking a key protector by name. If a key protector with the specified name exists and if an unlocking key is successfully retrieved by it, the function returns to the caller the retrieved key and its length.

---
 grub-core/Makefile.am       |  1 +
 grub-core/Makefile.core.def |  1 +
 grub-core/kern/protectors.c | 75 +++++++++++++++++++++++++++++++++++++
 include/grub/protector.h    | 48 ++++++++++++++++++++++++
 4 files changed, 125 insertions(+)
 create mode 100644 grub-core/kern/protectors.c
 create mode 100644 include/grub/protector.h
grub-core/Makefile.am +1 -0
index 80e7a83ed..79d17a3d2 100644
@@ -90,6 +90,7 @@ endif
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/mm.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/parser.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/partition.h
+KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/protector.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/stack_protector.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/term.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/time.h
grub-core/Makefile.core.def +1 -0
index 9b4423d47..53b680a77 100644
@@ -144,6 +144,7 @@ kernel = {
   common = kern/misc.c;
   common = kern/parser.c;
   common = kern/partition.c;
+  common = kern/protectors.c;
   common = kern/rescue_parser.c;
   common = kern/rescue_reader.c;
   common = kern/term.c;
grub-core/kern/protectors.c new file +75 -0

75 lines not on this page · raw message

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

48 lines not on this page · raw message

Signature · 1 line
2.35.3
author
#9 lore raw

PATCH v3 9/12 tpm2: Add TPM Software Stack (TSS)

In reply to Gary Lin

From: Hernan Gatta <[email protected]>

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

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

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

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

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

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

807 lines not on this page · raw message

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

143 lines not on this page · raw message

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

761 lines not on this page · raw message

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

65 lines not on this page · raw message

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

117 lines not on this page · raw message

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

675 lines not on this page · raw message

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

287 lines not on this page · raw message

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

292 lines not on this page · raw message

include/grub/tpm2/tcg2.h new file +34 -0
new file mode 100644
index 000000000..553b3fd93

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

include/grub/tpm2/tpm2.h new file +34 -0
new file mode 100644
index 000000000..cfdc9edcd

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

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

Signature · 1 line
2.35.3

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

author
#10 lore raw

PATCH v3 10/12 protectors: Add TPM2 Key Protector

In reply to Gary Lin

From: Hernan Gatta <[email protected]>

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

The theory of operation is such that the module accepts various arguments, most of which are optional and therefore possess reasonable defaults. One of these arguments is the keyfile/tpm2key parameter, which is mandatory. There are two supported key formats:

1. Raw Sealed Key (--keyfile)
When sealing a key with TPM2_Create, the public portion of the sealed key is stored in TPM2B_PUBLIC, and the private portion is in TPM2B_PRIVATE. The raw sealed key glues the fully marshalled TPM2B_PUBLIC and TPM2B_PRIVATE into one file.

2. TPM 2.0 Key (--tpm2key)
The following is the ASN.1 definition of TPM 2.0 Key File:

   TPMPolicy ::= SEQUENCE {
     CommandCode   [0] EXPLICIT INTEGER
     CommandPolicy [1] EXPLICIT OCTET STRING
   }

   TPMAuthPolicy ::= SEQUENCE {
     Name    [0] EXPLICIT UTF8STRING OPTIONAL
     Policy  [1] EXPLICIT SEQUENCE OF TPMPolicy
   }

TPMKey ::= SEQUENCE {

     type        OBJECT IDENTIFIER
     emptyAuth   [0] EXPLICIT BOOLEAN OPTIONAL
     policy      [1] EXPLICIT SEQUENCE OF TPMPolicy OPTIONAL
     secret      [2] EXPLICIT OCTET STRING OPTIONAL
     authPolicy  [3] EXPLICIT SEQUENCE OF TPMAuthPolicy OPTIONAL
     parent      INTEGER
     pubkey      OCTET STRING
     privkey     OCTET STRING

}

The TPM2 key protector only expects a "sealed" key in DER encoding, so 'type' is always 2.23.133.10.1.5, 'emptyAuth' is 'TRUE', and 'secret' is empty. 'policy' and 'authPolicy' are the possible policy command sequences to construst the policy digest to unseal the key. Similar to the raw sealed key, the public portion (TPM2B_PUBLIC) of the sealed key is stored in 'pubkey', and the private portion (TPM2B_PRIVATE) is in 'privkey'.

For more details: https://www.hansenpartnership.com/draft-bottomley-tpm2-keys.html

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

The TPM2 key protector registers two commands:

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

- tpm2_key_protector_clear: Clears any state set by tpm2_key_protector_init.

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

For instance, to unseal the raw sealed key file:

tpm2_key_protector_init --keyfile=(hd0,gpt1)/efi/grub2/sealed-1.key cryptomount DISK1 -P tpm2

tpm2_key_protector_init --keyfile=(hd0,gpt1)/efi/grub2/sealed-2.key --pcrs=7,11 cryptomount DISK2 -P tpm2

Or, to unseal the TPM 2.0 Key file:

tpm2_key_protector_init --tpm2key=(hd0,gpt1)/efi/grub2/sealed-1.tpm cryptomount DISK1 -P tpm2

tpm2_key_protector_init --tpm2key=(hd0,gpt1)/efi/grub2/sealed-2.tpm --pcrs=7,11 cryptomount DISK2 -P tpm2

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

Before unsealing the key, the TPM2 key protector follows the "TPMPolicy" sequences to enforce the TPM policy commands to construct a valid policy digest to unseal the key.

For the TPM 2.0 Key files, 'authPolicy' may contain multiple "TPMPolicy" sequences, the TPM2 key protector iterates 'authPolicy' to find a valid sequence to unseal key. If 'authPolicy' is empty or all sequences in 'authPolicy' fail, the protector tries the one from 'policy'. In case 'policy' is also empty, the protector creates a "TPMPolicy" sequence based on the given PCR selection.

For the raw sealed key, the TPM2 key protector treats the key file as a TPM 2.0 Key file without 'authPolicy' and 'policy', so the "TPMPolicy" sequence is always based on the PCR selection from the command parameters.

Currently, there is only one supported policy command: TPM2_PolicyPCR. The command set can be extended to support advanced features, such as as authorized policy, in the future.

---
 grub-core/Makefile.core.def       |   13 +
 grub-core/tpm2/args.c             |  131 ++++
 grub-core/tpm2/module.c           | 1040 +++++++++++++++++++++++++++++
 grub-core/tpm2/tpm2key.asn        |   31 +
 grub-core/tpm2/tpm2key.c          |  431 ++++++++++++
 grub-core/tpm2/tpm2key_asn1_tab.c |   41 ++
 include/grub/tpm2/internal/args.h |   39 ++
 include/grub/tpm2/tpm2key.h       |   83 +++
 8 files changed, 1809 insertions(+)
 create mode 100644 grub-core/tpm2/args.c
 create mode 100644 grub-core/tpm2/module.c
 create mode 100644 grub-core/tpm2/tpm2key.asn
 create mode 100644 grub-core/tpm2/tpm2key.c
 create mode 100644 grub-core/tpm2/tpm2key_asn1_tab.c
 create mode 100644 include/grub/tpm2/internal/args.h
 create mode 100644 include/grub/tpm2/tpm2key.h
grub-core/Makefile.core.def +13 -0
index 53b680a77..d8c4e92a2 100644
@@ -2525,6 +2525,19 @@ module = {
   enable = efi;
 };
 
+module = {
+  name = tpm2;
+  common = tpm2/args.c;
+  common = tpm2/buffer.c;
+  common = tpm2/module.c;
+  common = tpm2/mu.c;
+  common = tpm2/tpm2.c;
+  common = tpm2/tpm2key.c;
+  common = tpm2/tpm2key_asn1_tab.c;
+  efi = tpm2/tcg2.c;
+  enable = efi;
+};
+
 module = {
   name = tr;
   common = commands/tr.c;
grub-core/tpm2/args.c new file +131 -0

131 lines not on this page · raw message

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

1,040 lines not on this page · raw message

grub-core/tpm2/tpm2key.asn new file +31 -0
new file mode 100644
index 000000000..e3b6a03e0
@@ -0,0 +1,31 @@
+--
+-- TPM 2.0 key file format
+--  To generate tpm2key_asn1_tab.c: asn1Parser tpm2key.asn
+--
+TPM2KEY {}
+DEFINITIONS IMPLICIT TAGS ::=
+
+BEGIN
+
+TPMPolicy ::= SEQUENCE {
+    CommandCode   [0] EXPLICIT INTEGER,
+    CommandPolicy [1] EXPLICIT OCTET STRING
+}
+
+TPMAuthPolicy ::= SEQUENCE {
+    Name    [0] EXPLICIT UTF8String OPTIONAL,
+    Policy  [1] EXPLICIT SEQUENCE OF TPMPolicy
+}
+
+TPMKey ::= SEQUENCE {
+    type        OBJECT IDENTIFIER,
+    emptyAuth   [0] EXPLICIT BOOLEAN OPTIONAL,
+    policy      [1] EXPLICIT SEQUENCE OF TPMPolicy OPTIONAL,
+    secret      [2] EXPLICIT OCTET STRING OPTIONAL,
+    authPolicy  [3] EXPLICIT SEQUENCE OF TPMAuthPolicy OPTIONAL,
+    parent      INTEGER,
+    pubkey      OCTET STRING,
+    privkey     OCTET STRING
+}
+
+END
grub-core/tpm2/tpm2key.c new file +431 -0

431 lines not on this page · raw message

grub-core/tpm2/tpm2key_asn1_tab.c new file +41 -0

41 lines not on this page · raw message

include/grub/tpm2/internal/args.h new file +39 -0
new file mode 100644
index 000000000..df3341913
@@ -0,0 +1,39 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2022 Microsoft Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef GRUB_TPM2_INTERNAL_ARGS_HEADER
+#define GRUB_TPM2_INTERNAL_ARGS_HEADER 1
+
+#include <grub/err.h>
+#include <grub/tpm2/tpm2.h>
+
+grub_err_t
+grub_tpm2_protector_parse_pcrs (char *value, grub_uint8_t *pcrs,
+				grub_uint8_t *pcr_count);
+
+grub_err_t
+grub_tpm2_protector_parse_asymmetric (const char *value,
+				      TPM_ALG_ID *asymmetric);
+
+grub_err_t
+grub_tpm2_protector_parse_bank (const char *value, TPM_ALG_ID *bank);
+
+grub_err_t
+grub_tpm2_protector_parse_tpm_handle (const char *value, TPM_HANDLE *handle);
+
+#endif /* ! GRUB_TPM2_INTERNAL_ARGS_HEADER */
include/grub/tpm2/tpm2key.h new file +83 -0

83 lines not on this page · raw message

Signature · 1 line
2.35.3
author
#11 lore raw

PATCH v3 11/12 cryptodisk: Support key protectors

In reply to Gary Lin

From: Hernan Gatta <[email protected]>

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

---
 Makefile.util.def           |   1 +
 grub-core/disk/cryptodisk.c | 172 +++++++++++++++++++++++++++++-------
 include/grub/cryptodisk.h   |  16 ++++
 3 files changed, 158 insertions(+), 31 deletions(-)
Makefile.util.def +1 -0
index c3b7df96d..7d8db722e 100644
@@ -35,6 +35,7 @@ library = {
   common = grub-core/kern/list.c;
   common = grub-core/kern/misc.c;
   common = grub-core/kern/partition.c;
+  common = grub-core/kern/protectors.c;
   common = grub-core/lib/crypto.c;
   common = grub-core/lib/json/json.c;
   common = grub-core/disk/luks.c;
grub-core/disk/cryptodisk.c +141 -31

267 lines not on this page · raw message

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

Re: [PATCH v3 11/12] cryptodisk: Support key protectors

Quoted 11 lines · Gary Lin

From: Hernan Gatta <[email protected]>

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

Except for some trivial changes below.

Quoted 77 lines
---
  Makefile.util.def           |   1 +
  grub-core/disk/cryptodisk.c | 172 +++++++++++++++++++++++++++++-------
  include/grub/cryptodisk.h   |  16 ++++
  3 files changed, 158 insertions(+), 31 deletions(-)
Makefile.util.def +1 -0
index c3b7df96d..7d8db722e 100644
@@ -35,6 +35,7 @@ library = {
    common = grub-core/kern/list.c;
    common = grub-core/kern/misc.c;
    common = grub-core/kern/partition.c;
+  common = grub-core/kern/protectors.c;
    common = grub-core/lib/crypto.c;
    common = grub-core/lib/json/json.c;
    common = grub-core/disk/luks.c;
grub-core/disk/cryptodisk.c +8 -14
index 34b67a705..8fdae74cf 100644
@@ -26,6 +26,7 @@
  #include <grub/file.h>
  #include <grub/procfs.h>
  #include <grub/partition.h>
+#include <grub/protector.h>
 
  #ifdef GRUB_UTIL
  #include <grub/emu/hostdisk.h>
@@ -44,7 +45,8 @@ enum
      OPTION_KEYFILE,
      OPTION_KEYFILE_OFFSET,
      OPTION_KEYFILE_SIZE,
-    OPTION_HEADER
+    OPTION_HEADER,
+    OPTION_PROTECTOR
    };
 
  static const struct grub_arg_option options[] =
@@ -58,6 +60,8 @@ static const struct grub_arg_option options[] =
      {"keyfile-offset", 'O', 0, N_("Key file offset (bytes)"), 0, ARG_TYPE_INT},
      {"keyfile-size", 'S', 0, N_("Key file data size (bytes)"), 0, ARG_TYPE_INT},
      {"header", 'H', 0, N_("Read header from file"), 0, ARG_TYPE_STRING},
+    {"protector", 'P', GRUB_ARG_OPTION_REPEATABLE,
+     N_("Unlock volume(s) using key protector(s)."), 0, ARG_TYPE_STRING},
      {0, 0, 0, 0, 0, 0}
    };
 
@@ -1061,6 +1065,7 @@ grub_cryptodisk_scan_device_real (const char *name,
    grub_err_t ret = GRUB_ERR_NONE;
    grub_cryptodisk_t dev;
    grub_cryptodisk_dev_t cr;
+  int i;
    struct cryptodisk_read_hook_ctx read_hook_data = {0};
    int askpass = 0;
    char *part = NULL;
@@ -1113,41 +1118,112 @@ grub_cryptodisk_scan_device_real (const char *name,
        goto error_no_close;
      if (!dev)
        continue;
+    break;
+  }
 
-    if (!cargs->key_len)
-      {
-	/* Get the passphrase from the user, if no key data. */
-	askpass = 1;
-	part = grub_partition_get_name (source->partition);
-	grub_printf_ (N_("Enter passphrase for %s%s%s (%s): "), source->name,
-		     source->partition != NULL ? "," : "",
-		     part != NULL ? part : N_("UNKNOWN"),
-		     dev->uuid);
-	grub_free (part);
-
-	cargs->key_data = grub_malloc (GRUB_CRYPTODISK_MAX_PASSPHRASE);
-	if (cargs->key_data == NULL)

grub-core/disk/cryptodisk.c grub_cryptodisk_scan_device_real (const char *name, · line 1124

Quoted 10 lines
grub-core/disk/cryptodisk.c +1 -9
-	  goto error_no_close;
-
-	if (!grub_password_get ((char *) cargs->key_data, GRUB_CRYPTODISK_MAX_PASSPHRASE))
-	  {
-	    grub_error (GRUB_ERR_BAD_ARGUMENT, "passphrase not supplied");
-	    goto error;
-	  }
-	cargs->key_len = grub_strlen ((char *) cargs->key_data);
-      }
+  if (!dev)

Daniel like to NULL pointer checks to be dev == NULL.

Quoted 7 lines
grub-core/disk/cryptodisk.c +5 -1
+    {
+      grub_error (GRUB_ERR_BAD_MODULE,
+		  "no cryptodisk module can handle this device");
+      goto error_no_close;
+    }
 
-    ret = cr->recover_key (source, dev, cargs);

grub-core/disk/cryptodisk.c grub_cryptodisk_scan_device_real (const char *name, · line 1138

Quoted 10 lines
grub-core/disk/cryptodisk.c +8 -2
-    if (ret != GRUB_ERR_NONE)
-      goto error;
+  if (cargs->protectors)
+    {
+      for (i = 0; cargs->protectors[i]; i++)
+	{
+	  if (cargs->key_cache[i].invalid)
+	    continue;
+
+	  if (!cargs->key_cache[i].key)

cargs->key_cache[i].key == NULL

Quoted 129 lines
grub-core/disk/cryptodisk.c +103 -5
+	    {
+	      ret = grub_key_protector_recover_key (cargs->protectors[i],
+						    &cargs->key_cache[i].key,
+						    &cargs->key_cache[i].key_len);
+	      if (ret != GRUB_ERR_NONE)
+		{
+		  if (grub_errno)
+		    {
+		      grub_print_error ();
+		      grub_errno = GRUB_ERR_NONE;
+		    }
+
+		  grub_dprintf ("cryptodisk",
+				"failed to recover a key from key protector "
+				"%s, will not try it again for any other "
+				"disks, if any, during this invocation of "
+				"cryptomount\n",
+				cargs->protectors[i]);
+
+		  cargs->key_cache[i].invalid = 1;
+		  continue;
+		}
+	    }
+
+	  cargs->key_data = cargs->key_cache[i].key;
+	  cargs->key_len = cargs->key_cache[i].key_len;
 
-    ret = grub_cryptodisk_insert (dev, name, source);
-    if (ret != GRUB_ERR_NONE)
+	  ret = cr->recover_key (source, dev, cargs);
+	  if (ret != GRUB_ERR_NONE)
+	    {
+	      part = grub_partition_get_name (source->partition);
+	      grub_dprintf ("cryptodisk",
+			    "recovered a key from key protector %s but it "
+			    "failed to unlock %s%s%s (%s)\n",
+			     cargs->protectors[i], source->name,
+			     source->partition != NULL ? "," : "",
+			     part != NULL ? part : N_("UNKNOWN"), dev->uuid);
+	       grub_free (part);
+	       continue;
+	    }
+	 else
+	   {
+	     ret = grub_cryptodisk_insert (dev, name, source);
+	     if (ret != GRUB_ERR_NONE)
+	       goto error;
+	     goto cleanup;
+	   }
+	}
+
+      part = grub_partition_get_name (source->partition);
+      grub_error (GRUB_ERR_ACCESS_DENIED,
+		  N_("no key protector provided a usable key for %s%s%s (%s)"),
+		  source->name, source->partition != NULL ? "," : "",
+		  part != NULL ? part : N_("UNKNOWN"), dev->uuid);
+      grub_free (part);
        goto error;
+    }
+
+  if (!cargs->key_len)
+    {
+      /* Get the passphrase from the user, if no key data. */
+      askpass = 1;
+      part = grub_partition_get_name (source->partition);
+      grub_printf_ (N_("Enter passphrase for %s%s%s (%s): "), source->name,
+		    source->partition != NULL ? "," : "",
+		    part != NULL ? part : N_("UNKNOWN"), dev->uuid);
+      grub_free (part);
+
+      cargs->key_data = grub_malloc (GRUB_CRYPTODISK_MAX_PASSPHRASE);
+      if (cargs->key_data == NULL)
+	goto error;
+
+      if (!grub_password_get ((char *) cargs->key_data, GRUB_CRYPTODISK_MAX_PASSPHRASE))
+	{
+	  grub_error (GRUB_ERR_BAD_ARGUMENT, "passphrase not supplied");
+	  goto error;
+	}
+      cargs->key_len = grub_strlen ((char *) cargs->key_data);
+    }
+
+  ret = cr->recover_key (source, dev, cargs);
+  if (ret != GRUB_ERR_NONE)
+    goto error;
+
+  ret = grub_cryptodisk_insert (dev, name, source);
+  if (ret != GRUB_ERR_NONE)
+    goto error;
 
-    goto cleanup;
-  }
-  grub_error (GRUB_ERR_BAD_MODULE, "no cryptodisk module can handle this device");
    goto cleanup;
 
   error:
@@ -1258,6 +1334,20 @@ grub_cryptodisk_scan_device (const char *name,
    return ret;
  }
 
+static void
+grub_cryptodisk_clear_key_cache (struct grub_cryptomount_args *cargs)
+{
+  int i;
+
+  if (cargs->key_cache == NULL || cargs->protectors == NULL)
+    return;
+
+  for (i = 0; cargs->protectors[i]; i++)
+    grub_free (cargs->key_cache[i].key);
+
+  grub_free (cargs->key_cache);
+}
+
  static grub_err_t
  grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
  {
@@ -1270,6 +1360,10 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
    if (grub_cryptodisk_list == NULL)
      return grub_error (GRUB_ERR_BAD_MODULE, "no cryptodisk modules loaded");
 
+  if (state[OPTION_PASSWORD].set && state[OPTION_PROTECTOR].set) /* password and key protector */
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+		       "a password and a key protector cannot both be set");
+
    if (state[OPTION_PASSWORD].set) /* password */
      {
        cargs.key_data = (grub_uint8_t *) state[OPTION_PASSWORD].arg;

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

Quoted 7 lines
grub-core/disk/cryptodisk.c +4 -0
@@ -1362,6 +1456,15 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
  	return grub_errno;
      }
 
+  if (state[OPTION_PROTECTOR].set) /* key protector(s) */
+    {
+      cargs.key_cache = grub_zalloc (state[OPTION_PROTECTOR].set * sizeof (*cargs.key_cache));
+      if (!cargs.key_cache)

cargs.key_cache == NULL

Glenn

Quoted 97 lines
grub-core/disk/cryptodisk.c +12 -0
+	return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			   "no memory for key protector key cache");
+      cargs.protectors = state[OPTION_PROTECTOR].args;
+    }
+
    if (state[OPTION_UUID].set) /* uuid */
      {
        int found_uuid;
@@ -1370,6 +1473,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
        dev = grub_cryptodisk_get_by_uuid (args[0]);
        if (dev)
  	{
+	  grub_cryptodisk_clear_key_cache (&cargs);
  	  grub_dprintf ("cryptodisk",
  			"already mounted as crypto%lu\n", dev->id);
  	  return GRUB_ERR_NONE;
@@ -1378,6 +1482,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
        cargs.check_boot = state[OPTION_BOOT].set;
        cargs.search_uuid = args[0];
        found_uuid = grub_device_iterate (&grub_cryptodisk_scan_device, &cargs);
+      grub_cryptodisk_clear_key_cache (&cargs);
 
        if (found_uuid)
  	return GRUB_ERR_NONE;
@@ -1397,6 +1502,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
      {
        cargs.check_boot = state[OPTION_BOOT].set;
        grub_device_iterate (&grub_cryptodisk_scan_device, &cargs);
+      grub_cryptodisk_clear_key_cache (&cargs);
        return GRUB_ERR_NONE;
      }
    else
@@ -1420,6 +1526,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
        disk = grub_disk_open (diskname);
        if (!disk)
  	{
+	  grub_cryptodisk_clear_key_cache (&cargs);
  	  if (disklast)
  	    *disklast = ')';
  	  return grub_errno;
@@ -1430,12 +1537,14 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
  	{
  	  grub_dprintf ("cryptodisk", "already mounted as crypto%lu\n", dev->id);
  	  grub_disk_close (disk);
+	  grub_cryptodisk_clear_key_cache (&cargs);
  	  if (disklast)
  	    *disklast = ')';
  	  return GRUB_ERR_NONE;
  	}
 
        dev = grub_cryptodisk_scan_device_real (diskname, disk, &cargs);
+      grub_cryptodisk_clear_key_cache (&cargs);
 
        grub_disk_close (disk);
        if (disklast)
@@ -1576,6 +1685,7 @@ GRUB_MOD_INIT (cryptodisk)
    cmd = grub_register_extcmd ("cryptomount", grub_cmd_cryptomount, 0,
  			      N_("[ [-p password] | [-k keyfile"
  				 " [-O keyoffset] [-S keysize] ] ] [-H file]"
+				 " [-P protector [-P protector ...]]"
  				 " <SOURCE|-u UUID|-a|-b>"),
  			      N_("Mount a crypto device."), options);
    grub_procfs_register ("luks_script", &luks_script);
include/grub/cryptodisk.h +16 -0
index d94df68b6..0b41e249e 100644
@@ -70,6 +70,18 @@ typedef gcry_err_code_t
  (*grub_cryptodisk_rekey_func_t) (struct grub_cryptodisk *dev,
  				 grub_uint64_t zoneno);
 
+struct grub_cryptomount_cached_key
+{
+  grub_uint8_t *key;
+  grub_size_t key_len;
+
+  /*
+   * The key protector associated with this cache entry failed, so avoid it
+   * even if the cached entry (an instance of this structure) is empty.
+   */
+  int invalid;
+};
+
  struct grub_cryptomount_args
  {
    /* scan: Flag to indicate that only bootable volumes should be decrypted */
@@ -81,6 +93,10 @@ struct grub_cryptomount_args
    /* recover_key: Length of key_data */
    grub_size_t key_len;
    grub_file_t hdr_file;
+  /* recover_key: Names of the key protectors to use (NULL-terminated) */
+  char **protectors;
+  /* recover_key: Key cache to avoid invoking the same key protector twice */
+  struct grub_cryptomount_cached_key *key_cache;
  };
  typedef struct grub_cryptomount_args *grub_cryptomount_args_t;
 
author
#13 lore raw

Re: [PATCH v3 11/12] cryptodisk: Support key protectors

Quoted 9 lines · Glenn Washburn
Quoted 8 lines · Gary Lin

From: Hernan Gatta <[email protected]>

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

Quoted 8 lines
Quoted 3 lines

Except for some trivial changes below.

Thanks! I'm working on v4 for some improvements. Will fix them in v4 and gratefully add your "Reviewed-by" :)

Gary Lin

Quoted 333 lines
Quoted 73 lines
---
  Makefile.util.def           |   1 +
  grub-core/disk/cryptodisk.c | 172 +++++++++++++++++++++++++++++-------
  include/grub/cryptodisk.h   |  16 ++++
  3 files changed, 158 insertions(+), 31 deletions(-)
Makefile.util.def +1 -0
index c3b7df96d..7d8db722e 100644
@@ -35,6 +35,7 @@ library = {
    common = grub-core/kern/list.c;
    common = grub-core/kern/misc.c;
    common = grub-core/kern/partition.c;
+  common = grub-core/kern/protectors.c;
    common = grub-core/lib/crypto.c;
    common = grub-core/lib/json/json.c;
    common = grub-core/disk/luks.c;
grub-core/disk/cryptodisk.c +8 -14
index 34b67a705..8fdae74cf 100644
@@ -26,6 +26,7 @@
  #include <grub/file.h>
  #include <grub/procfs.h>
  #include <grub/partition.h>
+#include <grub/protector.h>
  #ifdef GRUB_UTIL
  #include <grub/emu/hostdisk.h>
@@ -44,7 +45,8 @@ enum
      OPTION_KEYFILE,
      OPTION_KEYFILE_OFFSET,
      OPTION_KEYFILE_SIZE,
-    OPTION_HEADER
+    OPTION_HEADER,
+    OPTION_PROTECTOR
    };
  static const struct grub_arg_option options[] =
@@ -58,6 +60,8 @@ static const struct grub_arg_option options[] =
      {"keyfile-offset", 'O', 0, N_("Key file offset (bytes)"), 0, ARG_TYPE_INT},
      {"keyfile-size", 'S', 0, N_("Key file data size (bytes)"), 0, ARG_TYPE_INT},
      {"header", 'H', 0, N_("Read header from file"), 0, ARG_TYPE_STRING},
+    {"protector", 'P', GRUB_ARG_OPTION_REPEATABLE,
+     N_("Unlock volume(s) using key protector(s)."), 0, ARG_TYPE_STRING},
      {0, 0, 0, 0, 0, 0}
    };
@@ -1061,6 +1065,7 @@ grub_cryptodisk_scan_device_real (const char *name,
    grub_err_t ret = GRUB_ERR_NONE;
    grub_cryptodisk_t dev;
    grub_cryptodisk_dev_t cr;
+  int i;
    struct cryptodisk_read_hook_ctx read_hook_data = {0};
    int askpass = 0;
    char *part = NULL;
@@ -1113,41 +1118,112 @@ grub_cryptodisk_scan_device_real (const char *name,
        goto error_no_close;
      if (!dev)
        continue;
+    break;
+  }
-    if (!cargs->key_len)
-      {
-	/* Get the passphrase from the user, if no key data. */
-	askpass = 1;
-	part = grub_partition_get_name (source->partition);
-	grub_printf_ (N_("Enter passphrase for %s%s%s (%s): "), source->name,
-		     source->partition != NULL ? "," : "",
-		     part != NULL ? part : N_("UNKNOWN"),
-		     dev->uuid);
-	grub_free (part);
-
-	cargs->key_data = grub_malloc (GRUB_CRYPTODISK_MAX_PASSPHRASE);
-	if (cargs->key_data == NULL)

grub-core/disk/cryptodisk.c grub_cryptodisk_scan_device_real (const char *name, · line 1123

Quoted 10 lines
grub-core/disk/cryptodisk.c +1 -9
-	  goto error_no_close;
-
-	if (!grub_password_get ((char *) cargs->key_data, GRUB_CRYPTODISK_MAX_PASSPHRASE))
-	  {
-	    grub_error (GRUB_ERR_BAD_ARGUMENT, "passphrase not supplied");
-	    goto error;
-	  }
-	cargs->key_len = grub_strlen ((char *) cargs->key_data);
-      }
+  if (!dev)

Daniel like to NULL pointer checks to be dev == NULL.

Quoted 6 lines
grub-core/disk/cryptodisk.c +5 -1
+    {
+      grub_error (GRUB_ERR_BAD_MODULE,
+		  "no cryptodisk module can handle this device");
+      goto error_no_close;
+    }
-    ret = cr->recover_key (source, dev, cargs);

grub-core/disk/cryptodisk.c grub_cryptodisk_scan_device_real (const char *name, · line 1138

Quoted 10 lines
grub-core/disk/cryptodisk.c +8 -2
-    if (ret != GRUB_ERR_NONE)
-      goto error;
+  if (cargs->protectors)
+    {
+      for (i = 0; cargs->protectors[i]; i++)
+	{
+	  if (cargs->key_cache[i].invalid)
+	    continue;
+
+	  if (!cargs->key_cache[i].key)

cargs->key_cache[i].key == NULL

Quoted 124 lines
grub-core/disk/cryptodisk.c +103 -5
+	    {
+	      ret = grub_key_protector_recover_key (cargs->protectors[i],
+						    &cargs->key_cache[i].key,
+						    &cargs->key_cache[i].key_len);
+	      if (ret != GRUB_ERR_NONE)
+		{
+		  if (grub_errno)
+		    {
+		      grub_print_error ();
+		      grub_errno = GRUB_ERR_NONE;
+		    }
+
+		  grub_dprintf ("cryptodisk",
+				"failed to recover a key from key protector "
+				"%s, will not try it again for any other "
+				"disks, if any, during this invocation of "
+				"cryptomount\n",
+				cargs->protectors[i]);
+
+		  cargs->key_cache[i].invalid = 1;
+		  continue;
+		}
+	    }
+
+	  cargs->key_data = cargs->key_cache[i].key;
+	  cargs->key_len = cargs->key_cache[i].key_len;
-    ret = grub_cryptodisk_insert (dev, name, source);
-    if (ret != GRUB_ERR_NONE)
+	  ret = cr->recover_key (source, dev, cargs);
+	  if (ret != GRUB_ERR_NONE)
+	    {
+	      part = grub_partition_get_name (source->partition);
+	      grub_dprintf ("cryptodisk",
+			    "recovered a key from key protector %s but it "
+			    "failed to unlock %s%s%s (%s)\n",
+			     cargs->protectors[i], source->name,
+			     source->partition != NULL ? "," : "",
+			     part != NULL ? part : N_("UNKNOWN"), dev->uuid);
+	       grub_free (part);
+	       continue;
+	    }
+	 else
+	   {
+	     ret = grub_cryptodisk_insert (dev, name, source);
+	     if (ret != GRUB_ERR_NONE)
+	       goto error;
+	     goto cleanup;
+	   }
+	}
+
+      part = grub_partition_get_name (source->partition);
+      grub_error (GRUB_ERR_ACCESS_DENIED,
+		  N_("no key protector provided a usable key for %s%s%s (%s)"),
+		  source->name, source->partition != NULL ? "," : "",
+		  part != NULL ? part : N_("UNKNOWN"), dev->uuid);
+      grub_free (part);
        goto error;
+    }
+
+  if (!cargs->key_len)
+    {
+      /* Get the passphrase from the user, if no key data. */
+      askpass = 1;
+      part = grub_partition_get_name (source->partition);
+      grub_printf_ (N_("Enter passphrase for %s%s%s (%s): "), source->name,
+		    source->partition != NULL ? "," : "",
+		    part != NULL ? part : N_("UNKNOWN"), dev->uuid);
+      grub_free (part);
+
+      cargs->key_data = grub_malloc (GRUB_CRYPTODISK_MAX_PASSPHRASE);
+      if (cargs->key_data == NULL)
+	goto error;
+
+      if (!grub_password_get ((char *) cargs->key_data, GRUB_CRYPTODISK_MAX_PASSPHRASE))
+	{
+	  grub_error (GRUB_ERR_BAD_ARGUMENT, "passphrase not supplied");
+	  goto error;
+	}
+      cargs->key_len = grub_strlen ((char *) cargs->key_data);
+    }
+
+  ret = cr->recover_key (source, dev, cargs);
+  if (ret != GRUB_ERR_NONE)
+    goto error;
+
+  ret = grub_cryptodisk_insert (dev, name, source);
+  if (ret != GRUB_ERR_NONE)
+    goto error;
-    goto cleanup;
-  }
-  grub_error (GRUB_ERR_BAD_MODULE, "no cryptodisk module can handle this device");
    goto cleanup;
   error:
@@ -1258,6 +1334,20 @@ grub_cryptodisk_scan_device (const char *name,
    return ret;
  }
+static void
+grub_cryptodisk_clear_key_cache (struct grub_cryptomount_args *cargs)
+{
+  int i;
+
+  if (cargs->key_cache == NULL || cargs->protectors == NULL)
+    return;
+
+  for (i = 0; cargs->protectors[i]; i++)
+    grub_free (cargs->key_cache[i].key);
+
+  grub_free (cargs->key_cache);
+}
+
  static grub_err_t
  grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
  {
@@ -1270,6 +1360,10 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
    if (grub_cryptodisk_list == NULL)
      return grub_error (GRUB_ERR_BAD_MODULE, "no cryptodisk modules loaded");
+  if (state[OPTION_PASSWORD].set && state[OPTION_PROTECTOR].set) /* password and key protector */
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+		       "a password and a key protector cannot both be set");
+
    if (state[OPTION_PASSWORD].set) /* password */
      {
        cargs.key_data = (grub_uint8_t *) state[OPTION_PASSWORD].arg;

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

Quoted 6 lines
grub-core/disk/cryptodisk.c +4 -0
@@ -1362,6 +1456,15 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
  	return grub_errno;
      }
+  if (state[OPTION_PROTECTOR].set) /* key protector(s) */
+    {
+      cargs.key_cache = grub_zalloc (state[OPTION_PROTECTOR].set * sizeof (*cargs.key_cache));
+      if (!cargs.key_cache)

cargs.key_cache == NULL

Glenn

Quoted 92 lines
grub-core/disk/cryptodisk.c +12 -0
+	return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			   "no memory for key protector key cache");
+      cargs.protectors = state[OPTION_PROTECTOR].args;
+    }
+
    if (state[OPTION_UUID].set) /* uuid */
      {
        int found_uuid;
@@ -1370,6 +1473,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
        dev = grub_cryptodisk_get_by_uuid (args[0]);
        if (dev)
  	{
+	  grub_cryptodisk_clear_key_cache (&cargs);
  	  grub_dprintf ("cryptodisk",
  			"already mounted as crypto%lu\n", dev->id);
  	  return GRUB_ERR_NONE;
@@ -1378,6 +1482,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
        cargs.check_boot = state[OPTION_BOOT].set;
        cargs.search_uuid = args[0];
        found_uuid = grub_device_iterate (&grub_cryptodisk_scan_device, &cargs);
+      grub_cryptodisk_clear_key_cache (&cargs);
        if (found_uuid)
  	return GRUB_ERR_NONE;
@@ -1397,6 +1502,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
      {
        cargs.check_boot = state[OPTION_BOOT].set;
        grub_device_iterate (&grub_cryptodisk_scan_device, &cargs);
+      grub_cryptodisk_clear_key_cache (&cargs);
        return GRUB_ERR_NONE;
      }
    else
@@ -1420,6 +1526,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
        disk = grub_disk_open (diskname);
        if (!disk)
  	{
+	  grub_cryptodisk_clear_key_cache (&cargs);
  	  if (disklast)
  	    *disklast = ')';
  	  return grub_errno;
@@ -1430,12 +1537,14 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
  	{
  	  grub_dprintf ("cryptodisk", "already mounted as crypto%lu\n", dev->id);
  	  grub_disk_close (disk);
+	  grub_cryptodisk_clear_key_cache (&cargs);
  	  if (disklast)
  	    *disklast = ')';
  	  return GRUB_ERR_NONE;
  	}
        dev = grub_cryptodisk_scan_device_real (diskname, disk, &cargs);
+      grub_cryptodisk_clear_key_cache (&cargs);
        grub_disk_close (disk);
        if (disklast)
@@ -1576,6 +1685,7 @@ GRUB_MOD_INIT (cryptodisk)
    cmd = grub_register_extcmd ("cryptomount", grub_cmd_cryptomount, 0,
  			      N_("[ [-p password] | [-k keyfile"
  				 " [-O keyoffset] [-S keysize] ] ] [-H file]"
+				 " [-P protector [-P protector ...]]"
  				 " <SOURCE|-u UUID|-a|-b>"),
  			      N_("Mount a crypto device."), options);
    grub_procfs_register ("luks_script", &luks_script);
include/grub/cryptodisk.h +16 -0
index d94df68b6..0b41e249e 100644
@@ -70,6 +70,18 @@ typedef gcry_err_code_t
  (*grub_cryptodisk_rekey_func_t) (struct grub_cryptodisk *dev,
  				 grub_uint64_t zoneno);
+struct grub_cryptomount_cached_key
+{
+  grub_uint8_t *key;
+  grub_size_t key_len;
+
+  /*
+   * The key protector associated with this cache entry failed, so avoid it
+   * even if the cached entry (an instance of this structure) is empty.
+   */
+  int invalid;
+};
+
  struct grub_cryptomount_args
  {
    /* scan: Flag to indicate that only bootable volumes should be decrypted */
@@ -81,6 +93,10 @@ struct grub_cryptomount_args
    /* recover_key: Length of key_data */
    grub_size_t key_len;
    grub_file_t hdr_file;
+  /* recover_key: Names of the key protectors to use (NULL-terminated) */
+  char **protectors;
+  /* recover_key: Key cache to avoid invoking the same key protector twice */
+  struct grub_cryptomount_cached_key *key_cache;
  };
  typedef struct grub_cryptomount_args *grub_cryptomount_args_t;
author
#14 lore raw

PATCH v3 12/12 util/grub-protect: Add new tool

In reply to Gary Lin

From: Hernan Gatta <[email protected]>

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

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

Sample usage:

$ dd if=/dev/urandom of=luks-key bs=1 count=32
$ sudo cryptsetup luksAddKey /dev/sdb1 luks-key --pbkdf=pbkdf2 --hash=sha512

To seal the key with TPM 2.0 Key File (recommended):

$ sudo grub-protect --action=add \
                    --protector=tpm2 \
                    --tpm2key \
                    --tpm2-keyfile=luks-key \
                    --tpm2-outfile=/boot/efi/boot/grub2/sealed.tpm

Or, to seal the key with the raw sealed key:

$ sudo grub-protect --action=add \
                    --protector=tpm2 \
                    --tpm2-keyfile=luks-key \
                    --tpm2-outfile=/boot/efi/boot/grub2/sealed.key

Then, in the boot script, for TPM 2.0 Key File:

tpm2_key_protector_init --tpm2key=(hd0,gpt1)/boot/grub2/sealed.tpm cryptomount -u b20f95d0834842bc9197bd78b36732f8 -P tpm2

Or, for the raw sealed key:

tpm2_key_protector_init --keyfile=(hd0,gpt1)/boot/grub2/sealed.key cryptomount -u b20f95d0834842bc9197bd78b36732f8 -P tpm2

where the UUID corresponds to /dev/sdb1.

---
 .gitignore          |    2 +
 Makefile.util.def   |   22 +
 configure.ac        |    9 +
 util/grub-protect.c | 1508 +++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 1541 insertions(+)
 create mode 100644 util/grub-protect.c
.gitignore +2 -0
index 4064d3d1e..7298886c3 100644
@@ -167,6 +167,8 @@ widthspec.bin
 /grub-ofpathname.exe
 /grub-probe
 /grub-probe.exe
+/grub-protect
+/grub-protect.exe
 /grub-reboot
 /grub-render-label
 /grub-render-label.exe
Makefile.util.def +22 -0
index 7d8db722e..88626516c 100644
@@ -206,6 +206,28 @@ program = {
   ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
 };
 
+program = {
+  name = grub-protect;
+
+  common = grub-core/osdep/init.c;
+  common = grub-core/tpm2/args.c;
+  common = grub-core/tpm2/buffer.c;
+  common = grub-core/tpm2/mu.c;
+  common = grub-core/tpm2/tpm2.c;
+  common = grub-core/tpm2/tpm2key_asn1_tab.c;
+  common = util/grub-protect.c;
+  common = util/probe.c;
+
+  ldadd = libgrubmods.a;
+  ldadd = libgrubgcry.a;
+  ldadd = libgrubkern.a;
+  ldadd = grub-core/lib/gnulib/libgnu.a;
+  ldadd = '$(LIBTASN1)';
+  ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
+
+  enable = efi;
+};
+
 program = {
   name = grub-mkrelpath;
   mansection = 1;
configure.ac +9 -0
index ca42ff8f7..70919627c 100644
@@ -76,6 +76,7 @@ grub_TRANSFORM([grub-mkpasswd-pbkdf2])
 grub_TRANSFORM([grub-mkrelpath])
 grub_TRANSFORM([grub-mkrescue])
 grub_TRANSFORM([grub-probe])
+grub_TRANSFORM([grub-protect])
 grub_TRANSFORM([grub-reboot])
 grub_TRANSFORM([grub-script-check])
 grub_TRANSFORM([grub-set-default])
@@ -1922,6 +1923,14 @@ fi
 AC_SUBST([LIBZFS])
 AC_SUBST([LIBNVPAIR])
 
+LIBTASN1=
+if test x"$platform" = xefi; then
+  AC_CHECK_LIB([tasn1], [asn1_write_value], [],
+               [AC_MSG_ERROR([Your platform requires libtasn1])])
+  LIBTASN1="-ltasn1"
+fi
+AC_SUBST([LIBTASN1])
+
 LIBS=""
 
 AC_SUBST([FONT_SOURCE])
util/grub-protect.c new file +1508 -0

1,508 lines not on this page · raw message

Signature · 1 line
2.35.3