Compare commits

..
682 Commits
Author SHA1 Message Date
Nicholas Vinson 3dce38eb19 conf/i386-cygwin-img.lds: Update to use _grub_text_base symbol
This patch updates conf/i386-cygwin-img.lds to use the _grub_text_base
symbol just like conf/i386-pc-kernel.lds. It also updates configure.ac
to account for this change.

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-03-05 15:08:00 +01:00
Nicholas Vinson 7d0a4c07a8 build: i386-cygwin-img-ld.sc -> i386-cygwin-img.lds
Rename i386-cygwin-img-ld.sc to i386-cygwin-img.lds as "lds" is the
preferred extension for linker scripts.

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-03-05 15:03:57 +01:00
Nicholas Vinson ab6f735174 configure: Add --image-base check for non-i386
Configure check grub_PROG_OBJCOPY_ABSOLUTE is run for all non-Apple
targets. With ld.lld-21, the check fails for addresses below image base
address (which ld.lld-21 assumes is 0x200000).

Fix by checking if linker support --image-base flag, and if it does,
include "--image-base 0" to TARGET_IMG_BASE_LDOPT.

The AX_CHECK_LINK_FLAG macro has been added to avoid a dependency on
autoconf-archive.

Note: I tried this approach with i386-pc, but I ended up with a GRUB
image that failed to boot correctly.

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-03-05 14:59:22 +01:00
Nicholas Vinson 86283bfd4e configure: Drop -Ttext checks for i386-pc
The i386-pc target now uses a linker script, so -Ttext is no longer
required. However, a new variable TARGET_IMG_BASE_LDOPT_ARG_SEP is
introduced to handle the fact that when using --defsym the argument
separator must be "=". The space character is a syntax error.

Finally, EXTRA_DIST is updated to track the linker script used.

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-03-05 14:49:16 +01:00
Nicholas Vinson 935e889ab5 Revert "INSTALL: Add note that the GNU Autoconf Archive may be needed"
This reverts commit a90ccbac6 (INSTALL: Add note that the GNU Autoconf
Archive may be needed).

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-03-05 14:38:55 +01:00
Nicholas Vinson 1dc2986c7e Revert "configure: Check linker for --image-base support"
This reverts commit 1a5417f39 (configure: Check linker for --image-base support).

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-03-05 14:36:54 +01:00
Nicholas Vinson 7b72d6cbd5 Revert "configure: Print a more helpful error if autoconf-archive is not installed"
This reverts commit ac042f3f5 (configure: Print a more helpful error if
autoconf-archive is not installed).

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-03-05 14:34:48 +01:00
Nicholas Vinson ba2f351145 build/i386-pc: Update kernel image generation
The i386-pc kernel image fails to build because of changes made to
address ld.lld-21 and newer linking issues. Specifically, with
ld.lld-21, if you try to set the text section address below image base
address when linking a non-relocatable binary, ld.lld wil fail to link.

Switching to using a customized linker script solves the issue and is
a more robust solution to supporting multiple linkers than attempting to
find a set of command-line flags that satisfied all supported linkers
and links the kernel properly. In the worst case, continued use of
command-line flags could result in having to create code branches to
support various linkers.

For example, when dealing with just ld.bfd and ld.lld, the behavioral
differences between the two made finding a proper subset of flags that
worked impossible. The previous attempt dropped -Ttext for --image-base,
which has been proven not to work. The simplest correction,
"-Wl,--image-base=0 -Wl,-Ttext", did not work because that option resulted
in a GRUB kernel that entered into a tight infinite refresh loop.

Moreover, ld.lld does not order the sections the same way ld.bfd does,
and that results in object files with gaps or holes when sections are
stripped. I suspect, but did not investigate, that this plays a role in
the infinite refresh loop I mentioned earlier.

The easiest way to resolve all this is to use customized linker scripts.
These scripts, by default, override any default configuration the linker
would otherwise impose, allow for complete control in aligning sections,
and allows GRUB to specify where in the load segment each section goes.

This patch series does require linkers to support the --defsym flag,
which requires its argument to be of the form "sym=address" as
"sym address" is not supported.

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-03-05 14:22:49 +01:00
Nicholas Vinson 9922ed133c include/grub/i386/pc/int.h: Move GRUB_MACHINE_PCBIOS ifdef
Modern compilers are becoming more strict and starting to warn when
certain attributes are ignored. The regparam attribute is such an
attribute.

Moreover, the function

  void EXPORT_FUNC (grub_bios_interrupt) (grub_uint8_t intno, struct grub_bios_int_registers *regs) __attribute__ ((regparm(3)));

is only defined with the i386-pc target.

Update include/grub/i386/pc/int.h so grub_bios_interrupt() is only
declared when GRUB_MACHINE_PCBIOS is defined. This addresses the issue
of declaring a function that is not defined for non-i386-pc targets and
prevents the "attribute ignored" diagnostic message.

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-03-05 14:14:56 +01:00
Nicholas Vinson ce6f2b57f5 util/resolve: Save str[r]chr() ret val to const data ptr
With glibc-2.43 implementing the C23 standard, strrchr() and strchr()
now return "const char *" when its first argument is "const char *".

The fix is update all pointers receiving strrchr() and strchr()'s return
values so that they are now "const char *" instead of "char *".

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-02-26 15:59:23 +01:00
Nicholas Vinson 9f4a586f12 util/probe: Save strrchr() ret val to const data ptr
With glibc-2.43 implementing the C23 standard, strrchr() now returns
"const char *" when its first argument is "const char *".

The fix is update all pointers receiving strrchr()'s return value so
that they are now "const char *" instead of "char *".

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-02-26 15:54:04 +01:00
Nicholas Vinson b71ae6db28 osdep/linux/ofpath: Correct path_size calculation
path_size is computed in part by taking the size of the format string.
However, the format string contains conversion specifiers. These
conversion specifiers are included in the size calculation resulting in
a size calculation that is larger than it needs to be. This patch
corrects that error by removing the conversion specifiers when computing
path_size.

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-02-26 15:51:56 +01:00
Nicholas Vinson 675d858103 osdep/linux/ofpath: Update strstr() calls
With C23, strstr() returns a "const char *" if its first argument is
"const char *", and these changes are implemented in glibc-2.43.

As a result, the first strstr() call in check_sas() now returns a "const
char *" instead of "char *" because sysfs_path is a "const char *". This
triggers a "discards qualifiers" warning, that is later promoted to an
error and ultimately causes the build to fail.

To fix the issue, this patch converts "ed", the pointer that stores
strstr()'s return value, to a "const char *". Removes the xstrdup()
call and cleans up the rest of the function by updating the *printf()
calls and using pointer arithmetic to compute lengths instead of strlen().

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-02-26 15:43:11 +01:00
Wanda Phinode 170221b355 mmap/mmap: Fix integer overflow in binary search
The integer overflow triggered for simple masks in the "badram"
command, such as "badram 0x0000000012340000,0xfffffffffffffff8".
This resulted in an infinite loop, locking up the machine.

Signed-off-by: Wanda Phinode <wanda@phinode.net>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-02-11 17:24:34 +01:00
Daniel Kiper eaa3b8f0f9 Bump version to 2.15
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-01-14 20:05:13 +01:00
Daniel Kiper d38d6a1a9b Release 2.14
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-01-14 16:46:57 +01:00
Daniel Kiper 35bfd6c478 build: Add grub-core/tests/crypto_cipher_mode_vectors.h file to EXTRA_DIST
This file was not added to EXTRA_DIST during test creation.

Fixes: 51ebc6f67 (tests: Add functional tests for ecb/cbc helpers)

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Srish Srinivasan <ssrish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2026-01-14 14:28:37 +01:00
Radoslav Kolev ac042f3f58 configure: Print a more helpful error if autoconf-archive is not installed
... because an undefined macro receives another macro as parameter and
autoconf is not smart enough to produce a useful error message.

Signed-off-by: Radoslav Kolev <radoslav.kolev@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-01-13 15:37:09 +01:00
Avnish Chouhan e37d021583 kern/ieee1275/openfw: Add a check for invalid partition number
The grub_strtoul() may fail in several scenarios like invalid input,
overflow, etc. Lack of proper check may lead to unexpected failures
in the code further.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-01-13 15:35:23 +01:00
Sudhakar Kuppusamy f94eae0f8d grub-mkimage: Do not generate empty SBAT metadata
When creating core.elf with SBAT the grub-mkimage does not check if
an SBAT metadata file contains at least an SBAT header or not. It leads to
adding an empty SBAT ELF note for PowerPC and the .sbat section for EFI.
Fix this by checking the SBAT metadata file size against the SBAT header
size before adding SBAT contents to the ELF note or .sbat section.

Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-01-08 19:51:29 +01:00
Yao Zi 1aa0dd0c04 configure: Defer check for -mcmodel=large until PIC/PIE checks are done
On RISC-V, large code model is only compatible with position-depedent
code. However, the configure script checks availability of -mcmodel=large
before determining whether PIC/PIE is enabled, and disable them.

This is problematic with toolchains that enable PIE by default, where
check for -mcmodel=large will always fail with,

  cc1: sorry, unimplemented: code model 'large' with '-fPIC'

and -mcmodel=medany will be silently used instead, causing relocation
failures at runtime with some memory layouts since -mcmodel=medany
requires all data and code to stay within a contiguous 4 GiB range.

Let's defer the check for -mcmodel=large until PIC/PIE is ensured disabled.

Fixes: f1957dc8a3 (RISC-V: Add to build system)

Reported-by: Han Gao <gaohan@iscas.ac.cn>
Signed-off-by: Yao Zi <me@ziyao.cc>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-01-08 19:48:59 +01:00
Sudhakar Kuppusamy ff1edd9752 util/grub-mkimagexx: Stop generating unaligned appended signatures
When creating the core image with an unaligned appended signature size,
e.g. 479, for PowerPC, the grub-mkimage aligns the appended signature
size to a multiple of 4 bytes, but it does not add a padding needed to
align to multiple of 4 bytes appended signature size in the appended
signature ELF note. Therefore, after signing and installing this core
image, the firmware tries to read the magic string "~Module signature
appended~" from the appended signature ELF note but gets the partial
magic string like "Module signature appended~". It leads to the appended
signature magic string match failure.

Example:
  grub-mkimage -O powerpc-ieee1275 -o core.elf -p /grub -x \
    kernel.der --appended-signature-size 479 ...

  sign-file SHA256 ./grub.key ./grub.pem ./core.elf ./core.elf.signed

Without padding: hexdump -C ./core.elf.signed
  ...
  00383550  00 00 00 13 00 00 01 e0  41 53 69 67 41 70 70 65  |........ASigAppe|
  00383560  6e 64 65 64 2d 53 69 67  6e 61 74 75 72 65 00 00  |nded-Signature..|
  ...
  003836f0  dd 47 cd ed 02 8e 15 af  5b 09 2e 44 6f da 67 88  |.G......[..Do.g.|
  00383700  4d 94 17 31 26 9d 47 95  d8 7c ad 36 00 d2 9c 53  |M..1&.G..|.6...S|
  00383710  20 e0 af 60 78 cd 22 e6  ed 45 1e b1 e7 7e cf b5  | ..`x."..E...~..|
  00383720  fc 58 ec df 1b ab 7a 00  00 02 00 00 00 00 00 00  |.X....z.........|
  00383730  00 01 b7 7e 4d 6f 64 75  6c 65 20 73 69 67 6e 61  |...~Module signa|
  00383740  74 75 72 65 20 61 70 70  65 6e 64 65 64 7e 0a     |ture appended~.|

Fix this by adding a padding required to align appended signature size in the
appended signature ELF note to multiple of 4 bytes.

Example:
  grub-mkimage -O powerpc-ieee1275 -o core.elf -p /grub -x \
    kernel.der --appended-signature-size 479 ...

  sign-file SHA256 ./grub.key ./grub.pem ./core.elf ./core.elf.signed

With padding: hexdump -C ./core.elf.signed
  ...
  00137460  62 00 00 00 00 00 00 13  00 00 01 ec 41 53 69 67  |b...........ASig|
  00137470  41 70 70 65 6e 64 65 64  2d 53 69 67 6e 61 74 75  |Appended-Signatu|
  ...
  00137610  b7 07 cd b6 c8 ca 9a 5b  7c 13 8c 75 1d 1c 54 81  |.......[|..u..T.|
  00137620  7f c4 9a 8b bd d7 73 8d  2f 7d d2 e6 d1 3c 52 a9  |......s./}...<R.|
  00137630  4e 0b e5 24 ba 0a 82 aa  8e c5 86 fa e1 19 50 ec  |N..$..........P.|
  00137640  9f a7 9a ed e5 ed 13 35  00 00 02 00 00 00 00 00  |.......5........|
  00137650  00 00 01 c2 7e 4d 6f 64  75 6c 65 20 73 69 67 6e  |....~Module sign|
  00137660  61 74 75 72 65 20 61 70  70 65 6e 64 65 64 7e 0a  |ature appended~.|

Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-01-08 19:31:37 +01:00
Srish Srinivasan 51ebc6f677 tests: Add functional tests for ecb/cbc helpers
Test the following helper functions using AES with 128, 192, and
256 bit keys:
  - grub_crypto_ecb_encrypt(),
  - grub_crypto_ecb_decrypt(),
  - grub_crypto_cbc_encrypt(),
  - grub_crypto_cbc_decrypt().

Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Glenn Washburn <development@efficientek.com>
2026-01-08 19:28:50 +01:00
Srish Srinivasan caaf50b9af osdep/aros/hostdisk: Fix use-after-free bug during MsgPort deletion
... in function grub_util_fd_open() when creation of an I/O request or
opening a device fails. The "ret", the file descriptor, will be freed
before its associated MsgPort is deleted resulting in a use-after-free
condition.

Fix this issue by freeing "ret" after its associated MsgPort has been
deleted.

Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2026-01-08 19:12:20 +01:00
Ingo Breßler 18f08826f9 kern/efi/sb: Enable loading GRUB_FILE_TYPE_CRYPTODISK_ENCRYPTION_KEY and GRUB_FILE_TYPE_CRYPTODISK_DETACHED_HEADER
... file types when UEFI Secure Boot is enabled. Otherwise it is not
possible to load cryptodisk encryption key or detached header.

Fixes: https://savannah.gnu.org/bugs/?65889

Signed-off-by: Ingo Breßler <dev@ingobressler.net>
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2026-01-08 19:09:26 +01:00
Radoslav Kolev 25b7f6b934 blsuki: Error out if unexpected arguments are supplied
This can be especially helpful, as the Fedora version of the blscfg
actually made use of positional arguments, but current implementation
switched to parameters. For example what used to be "blscfg (hd0,gpt2)/..."
now should be "blscfg --path (hd0,gpt2)/...)". In case of old configs/scripts
still supplying positional arguments we will now error out instead of just
ignoring them and falling back to defaults silently.

Signed-off-by: Radoslav Kolev <radoslav.kolev@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:47 +01:00
Radoslav Kolev cfeff5e071 blsuki: Fix default location in comment to /loader/entries
Signed-off-by: Radoslav Kolev <radoslav.kolev@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:47 +01:00
Radoslav Kolev d19a74a17f blsuki: Use specified device in case of fallback
Currently if the fallback option is enabled and no files are found in
the specified directory it searches the default (loader/conf) directory
but always in the device set by the root environment variable. It makes
more sense and also the comment in the code implies, that the default
directory on the current device should be searched.

Signed-off-by: Radoslav Kolev <radoslav.kolev@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
Radoslav Kolev 242816e93f blsuki: Fix position of DIR parameter in blscfg command summary
The DIR parameter in the example should be specified after the -p|--path option
instead of after -f|fallback.

Signed-off-by: Radoslav Kolev <radoslav.kolev@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
Radoslav Kolev b733d9d6dc blsuki: Fix typo in entry parameter description
Change "specificUKII entries" to "specific UKI entries".

Signed-off-by: Radoslav Kolev <radoslav.kolev@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
Khalid Ali 0f0899c329 efi: Fix several memory leaks of UEFI handles
Fix possible and absolute memory leaks of "handles"
returned by grub_efi_locate_handle() using grub_malloc().

Signed-off-by: Khalid Ali <khaliidcaliy@gmail.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
Andreas K. Hüttel c477a95519 util/grub-install: Allow recursive copying of theme dirs
grub-install allows to pass a parameter to install a theme in the boot partition.
This works fine for the default starfield theme. However, in general themes can
contain subdirectories, as, e.g. "icons", and these are not copied by grub-install.
As a result, the icons are missing on the screen.

Fix this by simple recursive copying.

Signed-off-by: Andreas K. Hüttel <dilfridge@gentoo.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
Heinrich Schuchardt f551d3de24 commands/efi/lsefisystab: Recognize EFI_MEMORY_ATTRIBUTES_TABLE_GUID and EFI_TCG2_FINAL_EVENTS_TABLE_GUID
Let the lsefisystab command recognize the following table GUIDs:
  - EFI_MEMORY_ATTRIBUTES_TABLE_GUID,
  - EFI_TCG2_FINAL_EVENTS_TABLE_GUID.

Signed-off-by: Heinrich Schuchardt <heinrich.schuchardt@canonical.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
Glenn Washburn ee283b14ae tests/util/grub-fs-tester: Use CSMACINTOSH encoding instead of macroman
From Debian 12 to 13, recode had a major overhaul and now does not support
the macroman encoding. Its unclear if this is a bug or intentional.
Regardless, use the CSMACINTOSH encoding instead as MacRoman and it are
aliases and CSMACINTOSH is supported on both Debian 12 and 13.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
Luca Boccassi 9b2c8ae5d2 commands/bli: Set UINT32_MAX in LoaderTpm2ActivePcrBanks if TPM2 present but no banks protocol
The implementation in sd-boot was changed to return UINT32_MAX when
the EFI environment detects a working TPM2, but with an older firmware
that doesn't implement the protocol to get the list of active banks.
This allows distinguishing with the case where there is no working TPM2,
in which case userspace just gives up, and instead lets userspace try to
figure it out later.

Fixes: f326c5c47 (commands/bli: Set LoaderTpm2ActivePcrBanks runtime variable)

Signed-off-by: Luca Boccassi <luca.boccassi@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
Sridhar Markonda c0669af6a8 script/execute: Add a NULL check after grub_calloc() call
... in gettext_append() to handle allocation errors. This prevents NULL
pointer dereference and stops crashes during string translation.

Signed-off-by: Sridhar Markonda <sridharm@linux.ibm.com>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
Avnish Chouhan 02cae1a357 disk/ieee1275/ofdisk: Fix memory leaks
In case of an overflow "p" and "p->grub_devpath" will not be freed.
Fix both issues.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-12-21 16:41:46 +01:00
Avnish Chouhan 09c512b8fa efiemu/loadcore: Add grub_calloc() failure check
Add a failure check after grub_calloc() call. If grub_calloc()
fails, e.g., due to memory allocation failure, it returns NULL.
Then using grub_efiemu_elfsyms, which will be NULL, later will
result in a NULL pointer dereference.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
George Hu 641646376b lib/x86_64/setjmp: Use 32-bit zero idiom for shorter encoding
Switch from "xorq %rax, %rax" to "xorl %eax, %eax". In 64-bit mode
zeroing EAX implicitly clears RAX and the 32-bit form encodes are one
byte smaller while keeping identical semantics.

Signed-off-by: George Hu <integral@archlinux.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:46 +01:00
Glenn Washburn d07ebd11d6 tests: Fix nonnative tests labeled as native
The tests asn1_test and tpm2_key_protector_test should be labelled as
nonnative tests because they run tests on the target. A clue that
indicates a nonnative test is the usage of the grub-shell script.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:45 +01:00
Glenn Washburn a90ccbac67 INSTALL: Add note that the GNU Autoconf Archive may be needed
As of 1a5417f39a (configure: Check linker for --image-base support),
the GNU Autoconf Archive is now required to bootstrap GRUB.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-12-21 16:41:45 +01:00
Glenn Washburn 29f3131a36 INSTALL: Fix a grammatical error
Also, add more documentation mentioning that the tests require
a "specially crafted environment" to run. Just running as root
is not enough.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-21 20:35:13 +01:00
Glenn Washburn 0a31df119d bootstrap: Condense and simplify LINGUAS generation
Remove unnecessary subshells. Loop over autogenerated po files only once.
Use existing LINGUAS created by bootstrap instead of finding po files
again.

Add wget as a soft requirement now that we are using bootstrap's code
for updating translation files. This should only be needed if updated
translations are desired, which is the default. There should be older
translation files already, and wget is not necessary if those will
suffice.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-21 20:31:55 +01:00
Glenn Washburn 0dfec2945a bootstrap: Migrate linguas.sh into bootstrap.conf
Bootstrap has infrastructure for downloading/updating project po files
and generating the LINGUAS file. It uses wget instead of rsync, but
provides the same functionality, namely that only po files that have
a modification date before the corresponding one on the server will get
redownloaded. Bootstrap creates a pristine copy of the po files in
po/.reference, so update .gitignore to ignore that directory.

Bootstrap also creates the po/LINGUAS file, but it does not know to add
in GRUB's autogenerated po files. So move that code from linguas.sh into
the bootstrap epilogue.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-21 20:30:11 +01:00
Glenn Washburn 8a6ea7ab7b bootstrap: Run linguas.sh in bootstrap epilogue
Heretofore, linguas.sh had to be run by the user and a common mistake
made when building GRUB was to not run the command. By adding it to
the bootstrap epilogue it will by default get run at the end of the
bootstrap script. The user no longer needs to remember to run it.
If the --skip-po option is passed to bootstrap, do not run linguas.sh.
This allows for bootstrap to be run without updating the translations,
which might be desired in the future if we track po files so that
translations can be used as they were at time of release.

Update INSTALL file to reflect that it is no longer necessary to run
linguas.sh. Also, fix a list numbering error.

Fixes: 9f73ebd49b (* INSTALL: Document linguas.sh.)

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-21 20:27:25 +01:00
Avnish Chouhan cb811bdf05 normal/cmdline: Add grub_calloc() failure check and fix hist_lines state loss
If grub_calloc() fails hist_lines becomes NULL. It means we loose the
reference to the previously allocated hist_lines and leak memory. With
this change on failure hist_lines still points to the old memory. So,
no leak, no state corruption.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-21 20:15:38 +01:00
Michael Chang 8a850f47d0 blsuki: Fix grub_errno leakage in blsuki_is_default_entry()
The grub_strtol() call in blsuki_is_default_entry() can set grub_errno
to either GRUB_ERR_BAD_NUMBER or GRUB_ERR_OUT_OF_RANGE if the input
string is invalid or out of range.

This grub_errno value is currently left uncleared, which can lead to
unexpected behavior in subsequent functions that rely on checking
current state of grub_errno.

Clear grub_errno unconditionally when grub_strtol() reports error so
that we can plug the leak.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 17:46:08 +01:00
Glenn Washburn a8b2beedf6 Revert "tests: Remove -w param from mkfs.hfsplus command"
The original commit removes testing of GRUB's support for HFS+
wrapping and replaces it with testing that is an exact duplicate of
another test, namely HFS+ without wrapping. To start, the change is
misleading in that it suggests that the testing of HFS+ wrapping is
still taking place, when it is not. If it was desired to remove support
for testing the HFS+ wrapping, then the test should have been removed
entirely. Second, having a series of tests that are exactly the same is
just a waste of testing resources. And third, the justification for the
change is nonsensical. Just because a required program may not have
a required feature on a particular distro is not a reason that a test
should be removed. Reducing test coverage because some distros do not
have the tools GRUB needs to run certain tests goes against the testing
priority to have test coverage be as broad as possible. The fact is
that Debian, the officially supported distro for running the tests, does
have a mkfs.hfsplus that supports the -w parameter.

This reverts commit 2bc0929a2 (tests: Remove -w param from mkfs.hfsplus command).

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 17:41:05 +01:00
Glenn Washburn 1437647052 Revert "tests: Skip tests if required tools are not available"
As explained in commit a21618c8a (tests: Test aborts due to missing
requirements should be marked as error instead of skipped) and in the
Automake manual[1], skipped tests are tests that should not be run, e.g.
running the ohci test on the powerpc-ieee1275 as there are no native ohci
drivers for that platform. Test that fail for reasons other than there is
a bug in GRUB code that is causing the test to fail are hard errors.
Commonly this is because the test is run in an improperly configured
environment, like required programs are missing. If a hard error condition
is identified with a SKIP return code, the person running the tests can not
know without investigating every skip if a SKIP in the tests was because
the test does not apply to the target being tested or because the user had
a misconfigured environment that was causing the test not to run. By
ensuring that a test is skipped only when it should not run, the person
running the test can be sure that there is no need to investigate why the
test was skipped.

This reverts commit bf13fed5f (tests: Skip tests if required tools are not available).

[1] https://www.gnu.org/software/automake/manual/automake.html#Generalities-about-Testing

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 17:38:15 +01:00
Sudhakar Kuppusamy 07c250487f osdep/linux/ofpath: Add missing strdup() failure checks
Segmentation faults or undefined behaviour may result from a NULL pointer
dereference in strip_trailing_digits() and grub_util_devname_to_ofpath()
if strdup() fails. Therefore, I added a NULL check to fix this.

Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Srish Srinivasan <ssrish@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 17:37:32 +01:00
Vladimir Serbinenko ae69b464be lib/relocator: Fix dereference after NULL check
In the function free_subchunk(), after checking that subchu->post isn't NULL,
grub_memset() is called on subchu->pre->freebytes but it should be called on
subchu->post->freebytes. If subchu->pre is NULL but subchu->post isn't NULL,
then this could lead to a NULL pointer dereference.

Fixes: CID 473882

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 17:28:00 +01:00
Nicholas Vinson 1a5417f39a configure: Check linker for --image-base support
In several scenarios, configure tests assume it's safe to use
"-Wl,-Ttext,<address>", but starting with ld.lld-21, blindly using that
flag may result in configure-test failures due to ld.lld failing to
link. The failure is because ld.lld-21 no longer allows the specified
address is less than the base address.

However, ld.lld-21+ and ld.bfd-2.44+ both provide support for the
--image-base flag making it preferable over the older -Ttext flag.

Fixes: https://savannah.gnu.org/bugs/?67662

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 17:03:27 +01:00
Glenn Washburn f41c896d23 INSTALL: Make note that Linux kernel 6.12.x or earlier is needed for reiserfs testing
Also, remove wording suggesting that tests may be skipped if prerequisites
are not installed. Tests should never be skipped because of an environment
misconfiguration, instead they should return a hard error (code 99).

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 16:54:27 +01:00
Glenn Washburn 591e02bc6e docs: Reorganize test section and add section on writing tests
Rename the main section to Tests and put the existing test section into
a subsection. A new subsection called "Writing tests" is added to give
a brief overview and make clear the difference in returning a SKIP code
versus a HARD ERROR code.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 16:50:25 +01:00
Glenn Washburn db16859e8e docs: Add note and explanation that the privileged user is required for properly running the tests
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 16:46:52 +01:00
Glenn Washburn 7d885513ff docs: Fix spelling, grammatical and usage issues with new Porting section
There are some other fixes outside of this section as well.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 16:43:30 +01:00
Glenn Washburn 56ecdfc1a5 util/grub-mkrescue: Fix spelling mistakes
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-20 16:41:05 +01:00
Jamie 7debdce1e9 commands/usbtest: Ensure string length is sufficient in usb string processing
If descstrp->length is less than 2 this will result in underflow in
"descstrp->length / 2 - 1" math. Let's fix the check to make sure the
value is sufficient.

Signed-off-by: Jamie <volticks@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:44 +01:00
Jamie 549a9cc372 commands/usbtest: Use correct string length field
An incorrect length field is used for buffer allocation. This leads to
grub_utf16_to_utf8() receiving an incorrect/different length and possibly
causing OOB write. This makes sure to use the correct length.

Fixes: CVE-2025-61661

Reported-by: Jamie <volticks@gmail.com>
Signed-off-by: Jamie <volticks@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:44 +01:00
Alec Brown 9df1e693e7 tests/lib/functional_test: Unregister commands on module unload
When the functional_test module is loaded, both the functional_test and
all_functional_test commands are registered but only the all_functional_test
command is being unregistered since it was the last to set the cmd variable
that gets unregistered when the module is unloaded. To unregister both
commands, we need to create an additional grub_extcmd_t variable.

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:44 +01:00
Alec Brown 05d3698b8b normal/main: Unregister commands on module unload
When the normal module is loaded, the normal and normal_exit commands
are registered but aren't unregistered when the module is unloaded. We
need to add calls to grub_unregister_command() when unloading the module
for these commands.

Fixes: CVE-2025-61663
Fixes: CVE-2025-61664

Reported-by: Alec Brown <alec.r.brown@oracle.com>
Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:44 +01:00
Alec Brown 8ed78fd9f0 gettext/gettext: Unregister gettext command on module unload
When the gettext module is loaded, the gettext command is registered but
isn't unregistered when the module is unloaded. We need to add a call to
grub_unregister_command() when unloading the module.

Fixes: CVE-2025-61662

Reported-by: Alec Brown <alec.r.brown@oracle.com>
Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:44 +01:00
Thomas Frauendorfer | Miray Software 10e58a14db net/net: Unregister net_set_vlan command on unload
The commit 954c48b9c (net/net: Add net_set_vlan command) added command
net_set_vlan to the net module. Unfortunately the commit only added the
grub_register_command() call on module load but missed the
grub_unregister_command() on unload. Let's fix this.

Fixes: CVE-2025-54770
Fixes: 954c48b9c (net/net: Add net_set_vlan command)

Reported-by: Thomas Frauendorfer | Miray Software <tf@miray.de>
Signed-off-by: Thomas Frauendorfer | Miray Software <tf@miray.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:44 +01:00
Thomas Frauendorfer | Miray Software c4fb4cbc94 kern/file: Call grub_dl_unref() after fs->fs_close()
With commit 16f196874 (kern/file: Implement filesystem reference
counting) files hold a reference to their file systems.

When closing a file in grub_file_close() we should not expect
file->fs to stay valid after calling grub_dl_unref() on file->fs->mod.
So, grub_dl_unref() should be called after file->fs->fs_close().

Fixes: CVE-2025-54771
Fixes: 16f196874 (kern/file: Implement filesystem reference counting)

Reported-by: Thomas Frauendorfer | Miray Software <tf@miray.de>
Signed-off-by: Thomas Frauendorfer | Miray Software <tf@miray.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:44 +01:00
Thomas Frauendorfer | Miray Software cc9d621dd0 commands/test: Fix error in recursion depth calculation
The commit c68b7d236 (commands/test: Stack overflow due to unlimited
recursion depth) added recursion depth tests to the test command. But in
the error case it decrements the pointer to the depth value instead of
the value itself. Fix it.

Fixes: c68b7d236 (commands/test: Stack overflow due to unlimited recursion depth)

Signed-off-by: Thomas Frauendorfer | Miray Software <tf@miray.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:44 +01:00
Alec Brown 95e614a11b fs/zfs/zfs: Avoid pointer downcasting in dnode_get()
Coverity marks multiple issues in grub-core/fs/zfs/zfs.c as either "Untrusted
value as argument", "Untrusted pointer read", or "Untrusted loop bound". Each
of these issues share a common cause where Coverity finds that data->dnode_buf
gets tainted by dnbuf since it is downcasting from (void *) to (dnode_phys_t *)
and could imply that the data the pointer points to is tainted. However, the
function zio_read(), which reads this data from disk, sanitizes this data by
verifying its checksum. To resolve the issues for Coverity, setting dnbuf to
(dnode_phys_t *) at the start of the function dnode_get() seems to do the trick.

Fixes: CID 314020
Fixes: CID 896330
Fixes: CID 896331
Fixes: CID 896334
Fixes: CID 896336
Fixes: CID 896340
Fixes: CID 897337

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:44 +01:00
Alec Brown 2464d43829 mmap/mmap: Fix resource leak
In the function grub_mmap_iterate(), memory is allocated to
"ctx.scanline_events" and "present" but isn't freed when error handling
grub_malloc(). Prior to returning grub_errno, these variables should be
freed to prevent a resource leak.

Fixes: CID 96655

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:44 +01:00
Glenn Washburn f7bcca3168 linguas: Ensure that linguas.sh runs from the directory that it resides
The script assumes that it is run from the root of the source tree,
which is where it is located. So this should be enforced to prevent
accidental misuses.

realpath is used instead of readlink as that is recommended in Debian's
readlink manpage since at least Debian 11. Also, use the shell variable's
parameter expansion for removing a suffix pattern to get the directory
in which the script resides. This is preferable to using the dirname binary
as it avoids creating a new process.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:43 +01:00
Glenn Washburn 8b5d3bdf87 gitignore: Remove po/*.po and po/LINGUAS
po files will now be tracked. This has the following benefits as listed
by Colin Watson:

  * Build processes would no longer be vulnerable to an external server
    potentially going down for an extended period of time; they'd be
    stuck with outdated translations until the server was fixed or came
    up with a workaround, but that's better than nothing.

  * It would be easier to manage branches of stable releases, rather than
    assuming that translations downloaded for master will match the POT
    files for a stable release.

  * Tests would be able to pass from a clean git checkout without relying
    on an external server, improving QA reliability.

  * It would be easier to make and test branches while offline.

  * The translations shipped with a release tarball could be tagged in
    git so that it's easy to investigate bugs in them.

  * Downstream distributors would be able to use git branches without
    having to fill in additional files.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 14:34:43 +01:00
Glenn Washburn 445549c898 tests/grub_cmd_cryptomount: Use builddir shell variable and quote
Using a shell variable instead of an autoconf macro creates less changes
to the file, which can be desirable when modifying by hand later and
then diffing with the unexpanded file. It also makes it simpler to
change the builddir after expansion, which may need to happen when
moving the build dir to a different path and not being able to rerun
the autoconf expansion.

Also, add quoting around the builddir variable as there may be spaces
in the path.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-11-18 13:08:01 +01:00
Glenn Washburn 6ae8fd0ee5 tests/grub_cmd_cryptomount: Expect test success, now that GRUB supports Argon2
This test was included to verify that, while GRUB did not have Argon2
support, trying to open a LUKS2 volume with an Argon2 keyslot would fail
Now that Argon2 support is included, the test is failing because it
expected a failure, but is now getting success. Change the test to expect
success.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-11-18 13:07:22 +01:00
Glenn Washburn de8961314f tests/erofs_test: Improve accuracy of FSTIME check
On resource constrained test runs, the last modification time on the
image is an unreliable date to check against the filesystem creation
time. Use dump.erofs to get the filesystem creation time from the
superblock. This should get the timestamp as shown by GRUB's "ls -l".

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-11-18 12:49:32 +01:00
Glenn Washburn a94d3ab7fc tests/erofs_test: Disable filetime check for erofs_compact
Compact EROFS inodes do not allow for modification times that are
different from FS creation times. The file modification time check is
done between the EROFS image and the file system where test temporary
files are written to, not the files as seen from the mounted EROFS image.
So its likely that the file modification time will be different, more
so when run on slower systems.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-11-18 12:49:32 +01:00
Glenn Washburn b6aceba7fb tests/erofs_test: Remove root check
The erofs tests do not ever mount the generated erofs image. So root is
not needed, as with the squashfs and iso9660 filesystems.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-11-18 12:49:32 +01:00
Glenn Washburn 0879ff7bc6 tests/erofs_test: Fix mkfs.erofs version test to not use process substitution bashism
The shell used to run the tests is generally /bin/sh, which does not
support process substitution.

Fixes: b990df0bef (tests/util/grub-fs-tester: Fix EROFS label tests in grub-fs-tester)

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-11-18 12:49:32 +01:00
Andrew Hamilton e4e99a8f84 tests: Support changed mkfs.ext2 behavior for -r flag
Correct nuisance ext234_test failure on newer Linux distros.

Recently, the mkfs.ext2 utility removed support for the -r flag to
specify old (version 0) formats of ext2. A new flag was added to allow
the same behavior. Support both ways of specifying version 0 ext2 file
systems when testing ext2 in GRUB.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Glenn Washburn <development@efficientek.com>
2025-11-18 12:49:32 +01:00
Andrew Hamilton a377cd67d0 tests: Avoid test failure in erofs for label length
Recently, mkfs.erofs began to enforce that the file system
label is 15 characters or less (excluding NUL terminator).
This causes the current erofs test in GRUB to fail. Reduce
the test label used to fit in this limit allowing the test
to work as expected.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Glenn Washburn <development@efficientek.com>
2025-11-18 12:49:32 +01:00
Andrew Hamilton a04171b4d2 tests: Split ZFS ZSTD test into new file
Split ZFS ZSTD test into its own test script. Add a check to the new
test script to see if the zfs utility installed on the host supports
"zstd" compression before running the test and fail the test if not. It
seems at least some zfs-fuse binaries do not support zstd compression
and the current test will fail in that case. Splitting into a new file
will avoid masking other test failures due to missing zstd support.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Glenn Washburn <development@efficientek.com>
2025-11-18 12:49:32 +01:00
Andrew Hamilton ea0b76dc4a util/grub.d/00_header.in: Disable loading all_video for EFI
Loading all_video for EFI can cause video issues in some cases
since GRUB Bochs/Cirrus drivers may conflict with native EFI drivers.
Change default behavior for EFI to only load EFI specific video
modules. Also include a new environment variable to restore the old
behavior if needed.

Fixes: https://savannah.gnu.org/bugs/?66200

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 12:49:31 +01:00
Glenn Washburn 73dee610b1 util/grub-mkrescue: Fix copy/paste issue referencing mdadm
The check_xorriso() function appears to have been copy/pasted from
somewhere that was originally checking the mdadm command. So the file
handle to the output of the xorriso command is named "mdadm". Instead
rename it to the more generic "fout". Also change a comment referencing
mdadm to reference xorriso.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 12:49:31 +01:00
Avnish Chouhan 72b4c99376 osdep/linux/getroot: Add missing strdup() failure checks
If strdup() fails, it returns NULL and passing NULL further down to
the code can lead to segmentation fault or an undefined behavior.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 12:49:31 +01:00
Avnish Chouhan f8c48cbedc kern/mips/arc/init: Add missing grub_strdup() failure check
If grub_strdup() fails, it returns NULL and passing NULL further down to
the code can lead to segmentation fault or an undefined behavior.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 12:49:31 +01:00
Avnish Chouhan 9eebd67744 script/execute: Add missing grub_strdup() failure check
If grub_strdup() fails, it returns NULL and passing NULL further down to
the code can lead to segmentation fault or an undefined behavior.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 12:49:31 +01:00
Avnish Chouhan f0170c2177 kern/ieee1275/openfw: Add missing grub_strdup() failure checks
If grub_strdup() fails, it returns NULL and passing NULL further down to
the code can lead to segmentation fault or an undefined behavior.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 12:49:31 +01:00
Andrew Hamilton 3a66437054 docs: Add security hardening suggestions
Add some suggestions to the security section on maximizing the
security hardening of GRUB.

This change reveals sectioning issues introduced by commit 0b59d379f
(docs/grub: Document signing GRUB under UEFI) and commit 0f2dda8cf
(docs/grub: Document signing GRUB with an appended signature). Fix them
on the occasion.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-18 12:40:02 +01:00
Leo Sandoval 2bc0929a2f tests: Remove -w param from mkfs.hfsplus command
Apparently the man page is outdated because the option "-w" is shown
but not on "mkfs.hfsplus --usage". According to Gemini:

  The -w option is used to add an HFS wrapper around an HFS Plus file
  system, which is sometimes required for compatibility with older
  Mac OS 9 systems. However, this is not a standard or commonly used
  option and may not be available in all versions of the hfsprogs package,
  especially on Linux.

Signed-off-by: Leo Sandoval <lsandova@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-06 21:22:34 +01:00
Leo Sandoval cdbc6ffbb8 tests: Increase verbosity in *_test.in checks
In this case it does not hurt to increase bash execution verbosity so
we can get more insight in case of issues.

Signed-off-by: Leo Sandoval <lsandova@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-06 20:50:54 +01:00
Leo Sandoval bf13fed5fe tests: Skip tests if required tools are not available
There is no reason to fail a test if the required testing tool is not
present on the system, so skip the test instead of failing it.

Signed-off-by: Leo Sandoval <lsandova@redhat.com>
Reviewed-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-06 19:27:06 +01:00
Srish Srinivasan d9b7b23d2d tests: Extend pbkdf2_test to cover HMAC-SHA{256,512}
HMAC-SHA1 is the only HMAC variant tested in the existing vectors.
Add vectors to test HMAC-SHA{256,512} as well.

Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-06 17:29:39 +01:00
Avnish Chouhan d4f476f08e lib/legacy_parse: Add missing grub_malloc() failure check
This patch adds a NULL check after grub_malloc() call. Missing a failure
check after calling grub_malloc() can lead to undefined behavior. If the
allocation fails and returns NULL subsequent dereferencing or writing to
the pointer will likely result in a runtime error such as a segmentation
fault.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-06 17:21:18 +01:00
Avnish Chouhan 77e2ceb79a mmap/mmap: Add missing grub_malloc() failure check
This patch adds a NULL check after grub_malloc() call. Missing a failure
check after calling grub_malloc() can lead to undefined behavior. If the
allocation fails and returns NULL subsequent dereferencing or writing to
the pointer will likely result in a runtime error such as a segmentation
fault.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-06 16:56:06 +01:00
Avnish Chouhan 4cc22937e7 partmap/msdos: Add missing grub_malloc() failure check
This patch adds a NULL check after grub_malloc() call. Missing a failure
check after calling grub_malloc() can lead to undefined behavior. If the
allocation fails and returns NULL subsequent dereferencing or writing to
the pointer will likely result in a runtime error such as a segmentation
fault.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-06 16:25:53 +01:00
Avnish Chouhan c0d2f76d55 normal/completion: Add missing grub_malloc() failure check
This patch adds a NULL check after grub_malloc() call. Missing a failure
check after calling grub_malloc() can lead to undefined behavior. If the
allocation fails and returns NULL subsequent dereferencing or writing to
the pointer will likely result in a runtime error such as a segmentation
fault.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-06 15:37:40 +01:00
Avnish Chouhan 5f0ffd7f57 term/ieee1275/serial: Fix memory leak
The grub_zalloc() allocates memory for port. If the allocation for
port->name fails the function returns NULL without freeing the
previously allocated port memory. This results in a memory leak.
To avoid this we must free port before return.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-06 15:31:43 +01:00
Lars Wendler cc36d0f088 configure: Avoid bashisms
or else configure check doesn't succeed with non-bash shell (e.g. dash):

  checking whether to enable AMD64 as(1) feature detection... /var/tmp/portage/sys-boot/grub-2.14_rc1/work/grub-2.14~rc1/configure: 39176: test: xx86_64: unexpected operator
  no

and later build fails with

  /var/tmp/portage/sys-boot/grub-2.14_rc1/work/grub-2.14~rc1/grub-core/lib/libgcrypt-grub/src/hwf-x86.c: In function ‘detect_x86_gnuc’:
  /var/tmp/portage/sys-boot/grub-2.14_rc1/work/grub-2.14~rc1/grub-core/lib/libgcrypt-grub/src/hwf-x86.c:252:17: error: ‘HWF_INTEL_CPU’ undeclared (first use in this function)
    252 |       result |= HWF_INTEL_CPU;
        |                 ^~~~~~~~~~~~~

and other corresponding HWF_INTEL_* definitions because HAVE_CPU_ARCH_X86 was
erroneously not defined by configure script.

Signed-off-by: Lars Wendler <polynomial-c@gmx.de>
Reviewed-by: Gary Lin <glin@suse.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-11-06 15:29:52 +01:00
Daniel Kiper 280715ec63 Release 2.14~rc1
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-28 13:19:47 +01:00
Daniel Kiper e549317e15 windows: Fix symbol table generation during module conversion from PE to ELF
According to the System V Application Binary Interface specification [1]
the sections holding a symbol table, SHT_SYMTAB and SHT_DYNSYM, have to
have sh_info set to "One greater than the symbol table index of the last
local symbol (binding STB_LOCAL)". Current code converting PE images to
ELF files does not do that and readelf complains in following way:

  ...

  Section Headers:
    [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
    [ 0]                   NULL            00000000 000000 000000 00      0   0  0
    [ 1] .text             PROGBITS        00000000 000034 0014d4 00  AX  0   0  4
    [ 2] .data             PROGBITS        00000000 001508 000040 00  WA  0   0 32
    [ 3] .rdata            PROGBITS        00000000 001548 0006b8 00   A  0   0  4
    [ 4] .module_license   PROGBITS        00000000 001c00 000010 00      0   0  4
    [ 5] .bss              NOBITS          00000000 000000 000008 00  WA  0   0  4
    [ 6] .moddeps          PROGBITS        00000000 001c10 000010 00      0   0  4
    [ 7] .modname          PROGBITS        00000000 001c20 000008 00      0   0  4
    [ 8] .rel.text         REL             00000000 001c28 0008c8 08     11   1  4
    [ 9] .rel.data         REL             00000000 0024f0 000040 08     11   2  4
    [10] .rel.rdata        REL             00000000 002530 000070 08     11   3  4
    [11] .symtab           SYMTAB          00000000 0025a0 0001d0 10     12   0  4
    [12] .strtab           STRTAB          00000000 002770 000237 00      0   0  1

  ...

  Symbol table '.symtab' contains 29 entries:
     Num:    Value  Size Type    Bind   Vis      Ndx Name
       0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND
  readelf: Warning: local symbol 0 found at index >= .symtab's sh_info value of 0
       1: 0000144a     0 FUNC    LOCAL  DEFAULT    1 grub_mod_init
  readelf: Warning: local symbol 1 found at index >= .symtab's sh_info value of 0
       2: 000014aa     0 FUNC    LOCAL  DEFAULT    1 grub_mod_fini
  readelf: Warning: local symbol 2 found at index >= .symtab's sh_info value of 0
       3: 00000000     0 SECTION LOCAL  DEFAULT    1 .text
  readelf: Warning: local symbol 3 found at index >= .symtab's sh_info value of 0
       4: 00000000     0 SECTION LOCAL  DEFAULT    2 .data
  readelf: Warning: local symbol 4 found at index >= .symtab's sh_info value of 0
       5: 00000000     0 SECTION LOCAL  DEFAULT    5 .bss
  readelf: Warning: local symbol 5 found at index >= .symtab's sh_info value of 0
       6: 00000000     0 SECTION LOCAL  DEFAULT    3 .rdata
  readelf: Warning: local symbol 6 found at index >= .symtab's sh_info value of 0
       7: 00000000     0 NOTYPE  GLOBAL DEFAULT  UND grub_dma_get_phys
       8: 00000000     0 NOTYPE  GLOBAL DEFAULT  UND grub_cs5536_write_msr
       9: 00000000     0 NOTYPE  GLOBAL DEFAULT  UND grub_dma_free

  ...

Let's fix it...

[1] https://www.sco.com/developers/gabi/2012-12-31/contents.html

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-10-28 12:19:35 +01:00
Daniel Kiper a340750f9e windows: Fix relocation sections generation during module conversion from PE to ELF
The commit 98ad84328 (kern/dl: Check for the SHF_INFO_LINK flag in
grub_dl_relocate_symbols()) revealed a bug in the code converting PE
module images to ELF files. The missing SHF_INFO_LINK flag for SHT_REL
and SHT_RELA sections lead to hangs during GRUB load. This only happens
for the GRUB images generated on Windows platforms. The *NIX platforms
are not affected due to lack of PE to ELF conversion step.

This patch fixes the issue...

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-10-28 12:19:35 +01:00
Andrew Hamilton c602035a9f loader/efi/linux: Fix compile error with Clang
Clang will produce a warning, which is treated as an error, that
"vendor_defined_data" is uninitialized. This is a "zero length" array
member of this struct. Add conditional compile pragma to allow this to
compile with Clang.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-28 12:19:34 +01:00
Andrew Hamilton f62269767e build: Add tpm2key.asn file for reference to dist archive
Add the tpm2key.asn file to the dist archive for reference by end users.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-28 12:19:34 +01:00
Andrew Hamilton 46be4488fd build: Include new zstd test support files in dist archive
Include the two new zstd test support files in the dist archive
so end users can successfully run this test.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-28 12:19:34 +01:00
Andrew Hamilton fa79d5ea9c build: Include MAINTAINERS and SECURITY files in dist archive
Include the MAINTAINERS and SECURITY files in the dist archive
for reference in distributed archives by end users.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-28 12:19:34 +01:00
Daniel Kiper 8271bcc130 build: Add appended signatures header file to EXTRA_DIST
This file was not added to EXTRA_DIST during the appended signatures merge.

Fixes: 3e4ff6ffb (appended signatures: Parse ASN1 node)

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-10-24 20:18:18 +02:00
Daniel Kiper 11845da2b1 lib/xzembed/xz_dec_stream: Replace grub_memcpy() call with memcpy()
Make the code consistent.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-10-24 20:05:08 +02:00
Daniel Kiper 7ded35feaa bootstrap: Fix patching warnings
Currently bootstrap complains in the following way when
patching gnulib files:

  patching file regcomp.c
  Hunk #2 succeeded at 1029 with fuzz 2.
  Hunk #5 succeeded at 1716 with fuzz 2.
  patching file regexec.c
  patching file base64.c
  patching file regexec.c
  Hunk #1 succeeded at 807 (offset -21 lines).

Let's fix it by adding missing "\f" and amending line
numbers in the patches.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-10-24 20:05:07 +02:00
Yann Diorcet 4129e9ad6f tss2: Always init out buffer before calling tpm2_submit_command_real()
When tpm2_submit_command_real() is called for a retry, the content of
out buffer can already be set with previous tpm2_submit_command_real()
call's reply. Add a call to grub_tpm2_buffer_init() before tpm2_submit_command_real().

This solves the issues occurring during TPM_CC_Load command on the
integrated TPM 2.0 in Intel Elkhart Lake chip.

Signed-off-by: Yann Diorcet <diorcet.yann@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 20:05:07 +02:00
Andrew Hamilton 000e48b42c fs/ntfs: Correct next_attribute validation
Improved ad-hoc fuzzing coverage revealed a possible access violation
around line 342 of grub-core/fs/ntfs.c when accessing the attr_cur
pointer due to possibility of moving pointer "next" beyond of the end of
the valid buffer inside next_attribute. Prevent this for cases where
full attribute validation is not performed (such as on attribute lists)
by performing a sanity check on the newly calculated next pointer.

Fixes: 06914b614 (fs/ntfs: Correct attribute vs attribute list validation)

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 20:05:07 +02:00
Michael Chang 5ff9c43cfe kern/ieee1275/init: Use net config for boot location instead of firmware bootpath
On network boots grub_ieee1275_net_config() is used to determine the
boot device but the path continues to be taken from the Open Firmware
/chosen/bootpath property. This assumes the device node follows the
generic IEEE 1275 syntax which is not always the case. Different drivers
may extend or redefine the format and GRUB may then misinterpret the
argument as a filename and set $prefix incorrectly.

The generic Open Firmware device path format is:

  device-name[:device-argument]
  device-argument := [partition][,[filename]]

For example, a bootpath such as:

  /vdevice/l-lan@30000002:speed=auto,duplex=auto,1.2.243.345,,9.8.76.543,1.2.34.5,5,5,255.255.255.0,512

does not follow this form. The section after the colon (the device-argument)
contains driver-specific options and network parameters, not a valid filename.
The GRUB interprets this string as a filename which results in $prefix being
set to "/", effectively losing the intended boot directory.

The firmware is not at fault here since interpretation of device nodes
is driver-specific. Instead, GRUB should use the filename provided in
the cached DHCP packet which is consistent and reliable. This is also
the same mechanism already used on UEFI and legacy BIOS platforms.

This patch updates grub_machine_get_bootlocation() to prefer the result
from grub_ieee1275_net_config() when complete and only fall back to the
firmware bootpath otherwise.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 20:05:07 +02:00
Lidong Chen c2cae77abe net/tftp: Fix NULL pointer dereference in grub_net_udp_close()
A NULL pointer dereference can occur in grub_net_udp_close(data->sock)
when handling a malformed TFTP OACK packet.

This issue was discovered via fuzzing. When a malformed OACK packet
contains an invalid file size, "tsize", value tftp_receive() detects
the error and saves it via grub_error_save(&data->save_err). Later,
tftp_open() restores this error and calls grub_net_udp_close(data->sock)
assuming the socket is still valid.

However, the socket may have already been closed and set to NULL after
processing the final data block in tftp_receive() leading to a NULL
pointer dereference when attempting to close it again.

Fix it by checking if the socket is non-NULL before closing.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-10-24 20:05:07 +02:00
Lidong Chen fadc94b919 net/dns: Prevent UAF and double free
In recv_hook(), *data->addresses is freed without being set to NULL.
Since *data->addresses can be cached in dns_cache[h].addresses, this
can lead to UAF or double free if dns_cache[h].addresses is accessed
or cleared later.

The fix sets *data->addresses to NULL after freeing to avoid dangling
pointer.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 20:05:07 +02:00
Lidong Chen cd24e25910 net/bootp: Prevent a UAF in network interface unregister
A UAF occurs in grub_net_network_level_interface_unregister()
when inter->name is accessed after being freed in grub_cmd_bootp().
Fix it by deferring grub_free(ifaces[j].name) until after
grub_net_network_level_interface_unregister() completes.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 20:05:07 +02:00
Andrew Hamilton fca6c0afda docs: Document lsmemregions and memtools commands
Add documentation of the new lsmemregions command as well as
documenting the existing memtools module commands.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 20:02:36 +02:00
Leo Sandoval 42c0997864 commands/memtools: Add lsmemregions command
Prints memory regions general information including size, number of
blocks, total free and total allocated memory per region. The reason
behind is to have a tool that shows general information about regions
and how fragmented the memory is at some particular time.

Below is an example showing how this tool before and after memory stress.

    grub> lsmemregions

    Region 0x78f6e000 (size 33554368 blocks 1048574 free 27325472 alloc 6232768)

    > stress_big_allocations
    ...

    grub> lsmemregions

    Region 0x7af8e000 (size 4032 blocks 126 free 2720 alloc 1312)
    Region 0x80c000 (size 81856 blocks 2558 free 81856 alloc 0)
    Region 0x7d165000 (size 167872 blocks 5246 free 167872 alloc 0)
    Region 0x7d0bf000 (size 655296 blocks 20478 free 655296 alloc 0)
    Region 0x7ee00000 (size 1331136 blocks 41598 free 1331136 alloc 0)
    Region 0x100000 (size 7385024 blocks 230782 free 7385024 alloc 0)
    Region 0x7af95000 (size 25382848 blocks 793214 free 25382848 alloc 0)
    Region 0x1780000 (size 2038357952 blocks 63698686 free 2077517536 alloc 5445568)

Signed-off-by: Leo Sandoval <lsandova@redhat.com>
Reviewed-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 19:39:51 +02:00
Logan Gunthorpe 20211246a8 tests/file_filter: Add zstd tests
Test zstd decompression in the same way that other decompressors are tested.

Signed-off-by: Logan Gunthorpe <logang@deltatee.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 19:39:51 +02:00
Logan Gunthorpe 092449f63c tests/file_filter: Add zstd test file
Add a file.zstd similar to the other compression methods and generate
a gpg signature with "gpg --detach-sign".

Signed-off-by: Logan Gunthorpe <logang@deltatee.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 19:39:51 +02:00
Logan Gunthorpe 356dcac9af tests/file_filter: Regenerate gpg keys
The "keys" file is not a valid GPG secret key so it is not possible to
generate new signatures.

Create a new key and use "gpg --export-secret-key" to export the key
and "gpg --export" to export the public key. Then resign all the
signatures with "gpg --detach-sign".

Signed-off-by: Logan Gunthorpe <logang@deltatee.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 19:39:51 +02:00
Logan Gunthorpe 8ea83c3ee2 io/zstdio: Implement zstdio decompression
Add zstd based io decompression.

Based largely on the existing xzio, implement the same features using
the zstd library already included in the project.

Signed-off-by: Logan Gunthorpe <logang@deltatee.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-24 19:37:55 +02:00
Michael Chang 7c22c1000c fs/btrfs: Update doc link for bootloader support
The old wiki link is obsolete and no longer updated. Change it to the
current documentation.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:02 +02:00
Michael Chang 6435551a66 docs: Add Btrfs env block and special env vars
Update grub.texi to describe the external environment block in the
reserved area of Btrfs header used for grub-reboot and savedefault, and
add a section documenting the saved_entry, next_entry, and env_block
variables.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:01 +02:00
Michael Chang b634477481 util/grub.d/00_header.in: Wire grub.cfg to use env_block when present
This patch extends the generated grub.cfg so that it can use the
external environment block when the variable env_block is defined.
During boot, if env_block is set, grub.cfg builds a device path for it,
exports the variable, and then loads its contents in addition to the
normal grubenv file.

When GRUB writes variables such as next_entry or saved_entry, the save
commands are changed to write into env_block if it is set, and to fall
back to the grubenv file otherwise. In this way the external environment
block is used automatically, and existing commands like savedefault or
save_env do not need to change.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:01 +02:00
Michael Chang e4e1776613 fs/btrfs: Add environment block to reserved header area
This patch reserves space for the GRUB environment block inside the
Btrfs header. The block is placed at an offset of GRUB_ENV_BTRFS_OFFSET,
256 KiB from the start of the device, and occupies one sector. To
protect the space, overflow guard sectors are placed before and after
the reserved block.

The Btrfs header already defines regions for bootloader use. By adding
this entry, GRUB gains a fixed and safe location to store the environment
block without conflicting with other structures in the header.

Add Btrfs and its reserved area information to the fs_envblk_spec table.
With the groundworks done in previous patches, the function is now
complete and working in grub-editenv.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:01 +02:00
Michael Chang d6525f0e65 util/grub-editenv: Add probe call for external envblk
This patch adds the probe_fs_envblk() function to identify the root
filesystem and invoke fs_envblk_init() with the probed filesystem type
and device. This checks if the feature is available and initializes the
handle, fs_envblk, to access the external environment block. It avoids
configurations with diskfilter or cryptodisk where filesystem blocks may
be remapped or encrypted.

The probe is only invoked when grub-editenv is working on the default
environment file path. This restriction ensures that probing and
possible raw device access are not triggered for arbitrary user supplied
paths, but only for the standard grubenv file. In that case the code
checks if the filename equals DEFAULT_ENVBLK_PATH and then calls
probe_fs_envblk with fs_envblk_spec. The result is stored in the global
fs_envblk handle. At this stage the external environment block is only
detected and recorded, and the behavior of grub-editenv is unchanged.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:01 +02:00
Michael Chang 4b5ea8dca6 util/grub-editenv: Wire list_variables() to optional fs_envblk
This patch updates list_variables() so that it also prints entries from
the external environment block when one is present. The function first
lists all variables from the file based envblk, then iterates over the
external envblk and prints those as well.

The output format remains the same as before. The change makes it
possible to inspect variables regardless of whether they are stored in
the file envblk or in the reserved block.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:01 +02:00
Michael Chang 84e2bc2f1e util/grub-editenv: Wire unset_variables() to optional fs_envblk
This patch updates unset_variables() so that removals are also applied
to the external environment block when it is present. The code opens the
external block, deletes the same named keys there, and then writes the
external block back using fs_envblk_write(). The file based envblk is
still updated and written as before.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:01 +02:00
Michael Chang c7c9019165 util/grub-editenv: Wire set_variables() to optional fs_envblk
This patch changes set_variables() so that it can use an external
environment block when one is present. The variable next_entry is
written into the external block, env_block is treated as read only, and
all other variables are written into the normal file based envblk.

A cleanup step is added to handle cases where GRUB at runtime writes
variables into the external block because file based updates are not
safe on a copy on write filesystem such as Btrfs. For example, the
savedefault command can update saved_entry, and on Btrfs GRUB will place
that update in the external block instead of the file envblk. If an
older copy remains in the external block, it would override the newer
value from the file envblk when GRUB first loads the file and then
applies the external block on top of it. To avoid this, whenever
a variable is updated in the file envblk, any same named key in
the external block is deleted.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:01 +02:00
Michael Chang 2abdd8cd21 util/grub-editenv: Add fs_envblk write helper
This patch adds the function fs_envblk_write to update the reserved
environment block on disk. The helper takes an in memory envblk buffer
and writes it back to the device at the location defined by the
fs_envblk specification. It performs size checks and uses file sync to
ensure that the updated data is flushed.

The helper is also added into the fs_envblk ops table, together with the
open helper from the previous patch. With this change the basic input
and output path for an external environment block is complete. The
choice of which variables should be written externally will be handled
by later patches.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:01 +02:00
Michael Chang e4d684cc42 util/grub-editenv: Add fs_envblk open helper
This patch adds the logic to locate and open an environment block that
is stored in a reserved area on the device. It introduces the function
fs_envblk_open() together with helper routines to read the block pointed
to by the env_block variable, and to create the block on disk when it
does not exist yet. When a block is created, the code records its
location inside the file based envblk by setting env_block in block list
syntax of offset plus size in sectors.

The env_block variable acts as a link from the file envblk to the raw
disk region so that later runs of grub-editenv can follow it and access
the external block. The helper is exposed through a small ops table
attached to fs_envblk so that later patches can call
fs_envblk->ops->open() without touching core code again. At this stage
variables are still stored in the file envblk and no redirection has
been applied.

In relation to this, the fs_envblk_spec table defines the file-system
specific layout of the reserved raw blocks used for environment storage.
It is prepared to facilitate integration in grub-editenv, with Btrfs to
be added in the future once its reserved area is defined.

An fs_envblk_init() helper is added to prepare it for using the ops with
its associated data context if the feature is available. It is not used
yet, but will be used later when a filesystem and its device are probed
to initialize the fs_envblk handle and enable access to the feature.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:01 +02:00
Michael Chang 512e33ec7c tests: Add "z" length modifier printf tests
Add unit tests for %zd, %zu and %zx to verify size_t and ssize_t
formatting matches system snprintf().

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Michael Chang 3c9762b12f kern/misc: Add the "z" length modifier support
Add support for the "z" length modifier in the printf code. This allows
printing of size_t and ssize_t values using %zu, %zd and related
formats. The parser maps "z" to the correct integer width based on
sizeof(size_t).

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Gary Lin 91ddada642 disk/cryptodisk: Add --hw-accel to enable hardware acceleration
The --hw-accel option has been added to cryptomount to speed up
decryption by temporarily enabling hardware-specific instruction
sets (e.g., AVX, SSE) in libgcrypt.

A new feature, "feature_gcry_hw_accel", is also introduced to mark the
availability of the new option.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Gary Lin f8f68f14ae libgcrypt: Add hardware acceleration for gcry_sha512
Enable hardware acceleration for the gcry_sha512 module when building
for the x86_64 EFI target.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Gary Lin 70b2f5f08d libgcrypt: Add hardware acceleration for gcry_sha256
Enable hardware acceleration for the gcry_sha256 module when building
for the x86_64 EFI target.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Gary Lin 2158d8e8a7 libgcrypt: Declare the sha256 shaext function
There is no prototype of _gcry_sha256_transform_intel_shaext() defined
in the header or libgcrypt-grub/cipher/sha256.c, and gcc may complain
the missing-prototypes error when compiling sha256-intel-shaext.c.

Declare the prototype in sha256-intel-shaext.c to avoid the error.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Gary Lin 0ff5faf8cd libgcrypt: Implement _gcry_get_hw_features()
Implement _gcry_get_hw_features() and enable hardware feature detection
for x86_64.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Gary Lin 8123561911 libgcrypt: Copy sha512 x86_64 assembly files
Copy the selected x86_64 assembly files to support hardware
acceleration for sha512.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Gary Lin 7f9c590aff libgcrypt: Copy sha256 x86_64 assembly files
Copy the selected x86_64 assembly files to support hardware
acceleration for sha256.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Gary Lin 8423176f1f lib/hwfeatures-gcry: Enable SSE and AVX for x86_64 EFI
Implement the necessary functions to dynamically enable SSE and AVX
on x86_64 EFI systems when the hardware is capable.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Gary Lin 06a5b88baf lib/hwfeatures-gcry: Introduce functions to manage hardware features
This commit introduces the generic functions to manage the hardware
features in libgcrypt. These functions are stubs for future
platform-specific implementations:
  - grub_gcry_hwf_enabled() returns __gcry_use_hwf which indicates if
    the hardware features are enabled specifically by grub_enable_gcry_hwf(),
  - grub_enable_gcry_hwf() invokes the architecture specific enablement
    functions and sets __gcry_use_hwf to true,
  - grub_reset_gcry_hwf() invokes the architecture specific reset
    functions and sets __gcry_use_hwf to false.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:15:00 +02:00
Gary Lin d01abd7131 configure: Tweak autoconf/automake files to detect x86_64 features
To enable hardware acceleration, this commit ports the feature detection
logic from libgcrypt. This allows us to check if the compiler supports
specific assembly instructions, including SSSE3, Intel SHA extensions,
SSE4.1, AVX, AVX2, AVX512, and BMI2.

To simplify the initial implementation, support for x86_64 feature
detection is currently limited to the x86_64 EFI target.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:14:59 +02:00
Gary Lin a122e02623 lib/pbkdf2: Optimize PBKDF2 by reusing HMAC handle
The previous PBKDF2 implementation used grub_crypto_hmac_buffer() which
allocates and frees an HMAC handle on every call. This approach caused
significant performance overhead slowing down the boot process considerably.

This commit refactors the PBKDF2 code to use the new HMAC functions
allowing the HMAC handle and its buffers to be allocated once and reused
across multiple operations. This change significantly reduces disk
unlocking time.

In a QEMU/OVMF test environment this patch reduced the time to unlock
a LUKS2 (*) partition from approximately 15 seconds to 4 seconds.

  (*) PBKDF2 SHA256 with 3454944 iterations.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:14:59 +02:00
Gary Lin 961e38b2b0 lib/crypto: Introduce new HMAC functions to reuse buffers
To enable more efficient buffer reuse for HMAC operations three new
functions have been introduced. This change prevents the need to
reallocate memory for each HMAC operation:
  - grub_crypto_hmac_reset(): reinitializes the hash contexts in the HMAC handle,
  - grub_crypto_hmac_final(): provides the final HMAC result without freeing the
    handle allowing it to be reused immediately,
  - grub_crypto_hmac_free(): deallocates the HMAC handle and its associated memory.

To further facilitate buffer reuse ctx2 is now included within the HMAC handle
struct and the initialization of ctx2 is moved to grub_crypto_hmac_init().

The intermediate hash states, ctx and ctx2, for the inner and outer padded
keys are now cached. The grub_crypto_hmac_reset() restores these cached
states for new operations which avoids redundant hashing of the keys.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:14:59 +02:00
Gary Lin 59304a7b51 docs: Document argon2 and argon2_test modules
Signed-off-by: Gary Lin <glin@suse.com>
Tested-By: Waldemar Brodkorb <wbx@openadk.org>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:14:59 +02:00
Gary Lin 28dbe8a3b6 kern/misc: Implement faster grub_memcpy() for aligned buffers
When both "dest" and "src" are aligned, copying the data in grub_addr_t
sized chunks is more efficient than a byte-by-byte copy.

Also tweak __aeabi_memcpy(), __aeabi_memcpy4(), and __aeabi_memcpy8(),
since grub_memcpy() is not inline anymore.

Optimization for unaligned buffers was omitted to maintain code
simplicity and readability. The current chunk-copy optimization
for aligned buffers already provides a noticeable performance
improvement (*) for Argon2 keyslot decryption.

  (*) On my system, for a LUKS2 keyslot configured with a 1 GB Argon2
      memory requirement, this patch reduces the decryption time from
      22 seconds to 12 seconds.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-23 19:12:22 +02:00
Gary Lin da01eb0c55 tests/util/grub-fs-tester: Use Argon2id for LUKS2 test
Given that the LUKS1 test already covers PBKDF2, the default KDF for the
LUKS2 test has been switched to Argon2id to ensure both algorithms are
validated.

Signed-off-by: Gary Lin <glin@suse.com>
Tested-By: Waldemar Brodkorb <wbx@openadk.org>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 14:09:02 +02:00
Gary Lin c1bd9fc829 tests: Integrate Argon2 tests into functional_test
Refactor the Argon2 tests to enable the module build and integrate the
tests into function_test.

Signed-off-by: Gary Lin <glin@suse.com>
Tested-By: Waldemar Brodkorb <wbx@openadk.org>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 14:05:50 +02:00
Gary Lin 6a525ee64f tests: Import Argon2 tests from libgcrypt
Copy the Argon2 test function, check_argon2(), from t-kdf.c in libgcrypt
to grub-core/tests/argon2_test.c.

Signed-off-by: Gary Lin <glin@suse.com>
Tested-By: Waldemar Brodkorb <wbx@openadk.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 14:01:21 +02:00
Gary Lin 6052fc2cf6 disk/luks2: Add Argon2 support
Leverage the new grub_crypto_argon2() function to add support for the
Argon2i and Argon2id KDFs in LUKS2.

Signed-off-by: Gary Lin <glin@suse.com>
Tested-By: Waldemar Brodkorb <wbx@openadk.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 13:59:12 +02:00
Gary Lin 66b8718f93 argon2: Introduce grub_crypto_argon2()
This commit introduces grub_crypto_argon2() which leverages the
_gcry_kdf_*() functions from libgcrypt to provide Argon2 support.

Due to the dependency of the _gcry_kdf_*() functions, the order of
"ldadd" entries have to be tweaked in Makefile.util.def so that the
linker can discover these functions.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 13:50:09 +02:00
Gary Lin de201105d4 libgcrypt/kdf: Fix 64-bit modulus on 32-bit platforms
Use grub_divmod64() for the 64-bit modulus to prevent creation of
special division calls such as __umoddi3() and __aeabi_uldivmod() on
32-bit platforms.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 13:48:29 +02:00
Gary Lin 93544861bc libgcrypt/kdf: Remove unsupported KDFs
Clean up _gcry_kdf_*() to remove unsupported KDFs.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 13:47:50 +02:00
Gary Lin 1ff7206417 libgcrypt/kdf: Get rid of gpg_err_code_from_errno()
gpg_err_code_from_errno() requires libgcrypt_wrap/mem.c which is not in
Makefile.utilgcry.def. This commit replaces gpg_err_code_from_errno()
with GPG_ERR_* to avoid the build errors.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 13:47:25 +02:00
Gary Lin 0c06a454fc libgcrypt/kdf: Implement hash_buffers() for BLAKE2b-512
The hash_buffers() functions are disabled in GRUB by default but the
Argon2 implementation requires hash_buffers() for BLAKE2b-512.

This commit implements argon2_blake2b_512_hash_buffers() as the
replacement of _gcry_digest_spec_blake2b_512.hash_buffers().

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 13:46:22 +02:00
Gary Lin bc94dfd541 crypto: Update crypto.h for libgcrypt KDF functions
This commit introduces the necessary changes to crypto.h in preparation
for implementing Argon2 support via the generic KDF functions, _gcry_kdf_*():
  - add new GPG error types required by kdf.c,
  - declare _gcry_digest_spec_blake2b_512 to enable BLAKE2b-512 digest calculations,
  - define the gcrypt KDF algorithm IDs for Argon2,
  - add the prototypes of _gcry_kdf_*() functions.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 13:46:16 +02:00
Gary Lin 5b81f490c4 util/import_gcry: Import kdf.c for Argon2
The import_gcry.py script now imports kdf.c from libgcrypt. To isolate
the Argon2 implementation, all unrelated functions have been removed.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-21 13:45:58 +02:00
Sudhakar Kuppusamy 6b5c671d35 commands/menuentry: Fix for out of bound access
A menu entry with an empty title leads to an out-of-bounds access at
"ch = src[len - 1]", i.e., "src" is empty and "len" is zero. So, fixing
this by checking the menu entry title length and throwing an error if
the length is zero.

Signed-off-by: Sridhar Markonda <sridharm@linux.ibm.com>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:43:59 +02:00
Gary Lin 21cdcb125c tests/tpm2_key_protector_test: Add a test for PCR Capping
A test is introduced to cap PCR 1 and track the PCR 1 value before and
after key unsealing.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:43:59 +02:00
Gary Lin afddba0127 tpm2_key_protector: Support PCR capping
To prevent a sealed key from being unsealed again, a common and
straightforward method is to "cap" the key by extending the associated
PCRs. When the PCRs associated with the sealed key are extended, TPM will
be unable to unseal the key, as the PCR values required for unsealing no
longer match, effectively rendering the key unusable until the next
system boot or a state where the PCRs are reset to their expected values.

To cap a specific set of PCRs, simply append the argument '-c pcr_list'
to the tpm2_key_protector command. Upon successfully unsealing the key,
the TPM2 key protector will then invoke tpm2_protector_cap_pcrs(). This
function extends the selected PCRs with an EV_SEPARATOR event,
effectively "capping" them. Consequently, the associated key cannot be
unsealed in any subsequent attempts until these PCRs are reset to their
original, pre-capped state, typically occurring upon the next system
boot.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:43:58 +02:00
Gary Lin ae7a399005 tss2: Implement grub_tcg2_cap_pcr() for emu
Since there is no system firmware for grub-emu, the TPM2_PCR_Event
command becomes the only choice to implement grub_tcg2_cap_pcr().

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:43:58 +02:00
Gary Lin 7b39970e90 tss2: Implement grub_tcg2_cap_pcr() for ieee1275
This commit implements grub_tcg2_cap_pcr() for ieee1275 with the
firmware function, 2hash-ext-log, to extend the target PCR with an
EV_SEPARATOR event and record the event into the TPM event log.

To avoid duplicate code, ibmvtpm_2hash_ext_log() is moved to tcg2.c
and exported as a global function.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:43:58 +02:00
Gary Lin 39f98e4719 tss2: Implement grub_tcg2_cap_pcr() for EFI
This commit implements grub_tcg2_cap_pcr() for EFI by using the UEFI
TCG2 protocol, HashLogExtendEvent, to extend the specified PCR with an
EV_SEPARATOR event and ensure the event will be recorded properly in the
TPM event log.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:43:58 +02:00
Gary Lin d47d261ecd tss2: Introduce grub_tcg2_cap_pcr()
This commit introduces the definition of grub_tcg2_cap_pcr(), a new
function designed to enhance the security of sealed keys. Its primary
purpose is to "cap" a specific PCR by extending it with an EV_SEPARATOR
event. This action cryptographically alters the PCR value, making it
impossible to unseal any key that was previously sealed to the original
PCR state. Consequently, the sealed key remains protected against
unauthorized unsealing attempts until the associated PCRs are reset to
their initial configuration, typically occurring during a subsequent
system boot.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:43:58 +02:00
Gary Lin b2549b4d34 tss2: Add TPM2_PCR_Event command
The TPM2_PCR_Event command is introduced to tss2 to allow the user to
extend a specific PCR. The related data structure and unmarshal function
are also introduced.

However, simply invoking TPM2_PCR_Event does not automatically record
the event into the TPM event log. The TPM event log is primarily
maintained by the system firmware (e.g., BIOS/UEFI). Therefore, for most
standard use cases, the recommended method for extending PCRs and
ensuring proper event logging is to utilize the system firmware
functions.

There are specific scenarios where direct use of TPM2_PCR_Event becomes
necessary. For instance, in environments lacking system firmware support
for PCR extension, such as the grub-emu, TPM2_PCR_Event serves as the
only available method to extend PCRs.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:43:58 +02:00
Thomas Zimmermann e1b9d92a8b loader/i386/linux: Transfer EDID information to kernel
The Linux kernel's struct bootparams provides a field at offset 0x140
for storing an EDID header. Copy the video adapter's data to the field.

The edid_info field was added in 2003 (see "[FBDEV] EDID support from
OpenFirmware on PPC platoforms and from the BIOS on intel platforms."),
but only got useable in 2004 (see "[PATCH] Fix EDID_INFO in zero-page").
The boot protocol was at version 2.03 at that time.

The field was never used much, but with the recent addition of the efidrm
and vesadrm drivers to the kernel, it becomes much more useful. As with
the initial screen setup, these drivers can make use of the provided
EDID information for basic display output.

Signed-off-by: Thomas Zimmermann <tzimmermann@suse.de>
Reviewed-by: Neal Gompa <ngompa13@gmail.com>
Reviewed-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:43:58 +02:00
Dave Vasilevsky a8379e693b fs/hfsplus: Allow reading files created by Mac OS 9
The "permissions" field of hfsplus files is only used by Mac OS X. This
causes GRUB to skip reading files created by Mac OS 9, since their
file mode is read as unknown. Instead, assume files with zero mode
are regular files.

From Technote 1150:

  The traditional Mac OS implementation of HFS Plus does not use the
  permissions field. Files created by traditional Mac OS have the
  entire field set to 0.

Signed-off-by: Dave Vasilevsky <dave@vasilevsky.ca>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:43:58 +02:00
Sridhar Markonda c5ff0d616f docs: Fix build warnings in libgcrypt and blsuki doc
Following warnings are thrown during libgrcypt and bluski doc build:

  grub.texi:4744: warning: node next pointer for `gcry_arcfour_module' is `gcry_blake2_module' but next is `gcry_aria_module' in menu
  grub.texi:4744: warning: node prev pointer for `gcry_arcfour_module' is `gcry_aria_module' but prev is `functional_test_module' in menu
  grub.texi:4751: warning: node prev pointer for `gcry_blake2_module' is `gcry_arcfour_module' but prev is `gcry_aria_module' in menu
  grub.texi:8532: warning: node next pointer for `trust' is `unset' but next is `uki' in menu
  grub.texi:8549: warning: node next pointer for `unset' is `uki' but next is `verify_detached' in menu
  grub.texi:8549: warning: node prev pointer for `unset' is `trust' but prev is `uki' in menu
  grub.texi:8557: warning: node next pointer for `uki' is `verify_detached' but next is `unset' in menu
  grub.texi:8557: warning: node prev pointer for `uki' is `unset' but prev is `trust' in menu
  grub.texi:8600: warning: node prev pointer for `verify_detached' is `uki' but prev is `unset' in menu

Fix order of gcry_aria_module and unset nodes.

Signed-off-by: Sridhar Markonda <sridharm@linux.ibm.com>
Reviewed-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:41:14 +02:00
Srish Srinivasan fa93f2412b kern/command,commands/extcmd: Perform explicit NULL check in both the unregister helpers
During command registration, grub_register_command_prio() returns
a 0 when there is a failure in memory allocation. In such a situation,
calls to grub_unregister_{command(), extcmd()} during command
unregistration will result in dereferencing a NULL pointer.

Perform explicit NULL check in both unregister helpers to prevent
undefined behaviour due to a NULL pointer dereference.

Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:54 +02:00
Luca Boccassi 9a725391f1 commands/efi/tpm: Call get_active_pcr_banks() only with TCG2 1.1 or newer
The call was added in the 1.1 revision of the spec, 1.0 does
not have it, and there are some machines out there with a TPM2
and a UEFI firmware that only supports version 1.0, so the
call fails in those cases. Check the reported version before
calling get_active_pcr_banks().

See Table 4 in section 6.2 of the TCG EFI Protocol Specification:

  https://trustedcomputinggroup.org/wp-content/uploads/EFI-Protocol-Specification-rev13-160330final.pdf

Fixes: f326c5c47 (commands/bli: Set LoaderTpm2ActivePcrBanks runtime variable)

Signed-off-by: Luca Boccassi <luca.boccassi@gmail.com>
Reviewed-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:54 +02:00
Leo Sandoval 894241c854 kern: Include function name on debug and error print functions
With the following change, we see standard (grub_dprintf) and
error (grub_error) logs with the function name embedded (see below)
into the log which is particular useful when debugging:

  commands/efi/tpm.c:grub_tpm_measure:281:tpm: log_event, pcr = 8, size = 0xb,

Including one more field on the print log impacts the binary sizes
and in turn their respective distro packages. For Fedora rpm packages
the increase is 20k approximately.

Signed-off-by: Leo Sandoval <lsandova@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:53 +02:00
Peter Jones 75a20cc144 kern: Make grub_error() more verbose
Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:53 +02:00
Michael Chang 8abbafa493 net/tcp: Fix TCP port number reused on reboot
GRUB's TCP stack assigns source ports for outgoing connections starting
at 21550 and increments sequentially by 1 (e.g., 21550, 21551, ...).
While this generally works, it can lead to failures if the system
reboots rapidly and reuses the same source port too soon.

This issue was observed on powerpc-ieee1275 platforms using CAS (Client
Architecture Support) reboot. In such cases, loading the initrd over
HTTP may fail with connection timeouts. Packet captures show the failed
connections are flagged as "TCP Port Number Reused" by Wireshark.

The root cause is that GRUB reuses the same port shortly after reboot,
while the server may still be tracking the previous connection in
TIME_WAIT. This can result in the server rejecting the connection
attempt or responding with a stale ACK or RST, leading to handshake
failure.

This patch fixes the issue by introducing a time based source port
selection strategy. Instead of always starting from port 21550, GRUB now
computes an initial base port based on the current RTC time, divided
into 5 minute windows. The purpose of this time based strategy is to
ensure that GRUB avoids reusing the same source port within a 5 minute
window, thereby preventing collisions with stale server side connection
tracking that could interfere with a new TCP handshake.

A step size of 8 ensures that the same port will not be reused across
reboots unless GRUB opens more than 8 TCP connections per second on
average, something that is highly unlikely. In typical usage, a GRUB
boot cycle lasts about 15 seconds and may open fewer than 100
connections total, well below the reuse threshold. This makes the
approach robust against short reboot intervals while keeping the logic
simple and deterministic.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:53 +02:00
Sudhakar Kuppusamy 3dff10a979 docs/grub: Document appended signature
This explains how appended signatures can be used to form part of
a secure boot chain, and documents the commands and variables
introduced.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:53 +02:00
Sudhakar Kuppusamy 0f2dda8cf6 docs/grub: Document signing GRUB with an appended signature
Signing GRUB for firmware that verifies an appended signature is a
bit fiddly. I don't want people to have to figure it out from scratch
so document it here.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:53 +02:00
Daniel Axtens 0b59d379fc docs/grub: Document signing GRUB under UEFI
Before adding information about how GRUB is signed with an appended
signature scheme, it's worth adding some information about how it
can currently be signed for UEFI.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:53 +02:00
Sudhakar Kuppusamy dbfa3d7d7e appended signatures: Verification tests
These tests are run through all_functional_test and test a range
of commands and behaviours.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:53 +02:00
Sudhakar Kuppusamy 7f68c71952 appended signatures: GRUB commands to manage the hashes
Introducing the following GRUB commands to manage certificate/binary
hashes.

  1. append_list_dbx:
      Show the list of distrusted certificates and binary/certificate
      hashes from the dbx list.
  2. append_add_db_hash:
      Add the trusted binary hash to the db list.
  3. append_add_dbx_hash:
      Add the distrusted certificate/binary hash to the dbx list.

Note that if signature verification (check_appended_signatures) is set to yes,
the append_add_db_hash and append_add_dbx_hash commands only accept the file
‘hash_file’ that is signed with an appended signature.

Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Tested-by: Sridhar Markonda <sridharm@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:53 +02:00
Sudhakar Kuppusamy 6cb58b1c9e appended signatures: GRUB commands to manage the certificates
Introducing the following GRUB commands to manage the certificates.

 1. append_list_db:
      Show the list of trusted certificates from the db list
 2. append_add_db_cert:
      Add the trusted certificate to the db list
 3. append_add_dbx_cert:
      Add the distrusted certificate to the dbx list
 4. append_verify:
      Verify the signed file using db list

Note that if signature verification (check_appended_signatures) is set to yes,
the append_add_db_cert and append_add_dbx_cert commands only accept the file
‘X509_certificate’ that is signed with an appended signature.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Tested-by: Sridhar Markonda <sridharm@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:53 +02:00
Sudhakar Kuppusamy ab7b177178 appended signatures: Using db and dbx lists for signature verification
Signature verification: verify the kernel against lists of hashes that are
either in dbx or db list. If it is not in the dbx list then the trusted keys
from the db list are used to verify the signature.

Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:53 +02:00
Sudhakar Kuppusamy 97f7001e19 appended signatures: Create db and dbx lists
If secure boot is enabled with static key management mode, the trusted
certificates will be extracted from the GRUB ELF Note and added to db list.

If secure boot is enabled with dynamic key management mode, the trusted
certificates and certificate/binary hash will be extracted from the PKS
and added to db list. The distrusted certificates, certificate/binary hash
are read from the PKS and added to dbx list. Both dbx and db lists usage is
added by a subsequent patch.

Note:
- If db does not exist in the PKS storage, then read the static keys as a db
  default keys from the GRUB ELF Note and add them into the db list.
- If the certificate or the certificate hash exists in the dbx list, then do not
  add that certificate/certificate hash to the db list.

Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:52 +02:00
Sudhakar Kuppusamy b5e872417d appended signatures: Introducing key management environment variable
Introducing the appended signature key management environment variable. It is
automatically set to either "static" or "dynamic" based on the Platform KeyStore.

"static": Enforce static key management signature verification. This is the
          default. When the GRUB is locked down, user cannot change the value
          by setting the appendedsig_key_mgmt variable back to "dynamic".

"dynamic": Enforce dynamic key management signature verification. When the GRUB
           is locked down, user cannot change the value by setting the
           appendedsig_key_mgmt variable back to "static".

Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:52 +02:00
Sudhakar Kuppusamy 76158ed1ad powerpc/ieee1275: Read the db and dbx secure boot variables
Enhancing the infrastructure to enable the Platform Keystore (PKS) feature,
which provides access to the SB_VERSION, db, and dbx secure boot variables
from PKS.

If PKS is enabled, it will read secure boot variables such as db and dbx
from PKS and extract EFI Signature List (ESL) from it. The ESLs would be
saved in the Platform Keystore buffer, and the appendedsig module would
read it later to extract the certificate's details from ESL.

In the following scenarios, static key management mode will be activated:
 1. When Secure Boot is enabled with static key management mode
 2. When SB_VERSION is unavailable but Secure Boot is enabled
 3. When PKS support is unavailable but Secure Boot is enabled

Note:

 SB_VERSION: Key Management Mode
 1 - Enable dynamic key management mode. Read the db and dbx variables from PKS,
     and use them for signature verification.
 0 - Enable static key management mode. Read keys from the GRUB ELF Note and
     use it for signature verification.

Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:46 +02:00
Sudhakar Kuppusamy 069f3614e6 appended signatures: Support verifying appended signatures
Building on the parsers and the ability to embed X.509 certificates, as well
as the existing gcrypt functionality, add a module for verifying appended
signatures.

This includes a signature verifier that requires that the Linux kernel and
GRUB modules have appended signatures for verification.

Signature verification must be enabled by setting check_appended_signatures.
If secure boot is enabled with enforce mode when the appendedsig module is
loaded, signature verification will be enabled, and trusted keys will be
extracted from the GRUB ELF Note and stored in the db and locked automatically.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:44 +02:00
Sudhakar Kuppusamy f8e8779d8e powerpc/ieee1275: Enter lockdown based on /ibm, secure-boot
Read secure boot mode from 'ibm,secure-boot' property and if the secure boot
mode is set to 2 (enforce), enter lockdown. Else it is considered as disabled.
There are three secure boot modes. They are

0 - disabled
     No signature verification is performed. This is the default.
1 - audit
     Signature verification is performed and if signature verification fails,
     display the errors and allow the boot to continue.
2 - enforce
     Lockdown the GRUB. Signature verification is performed and if signature
     verification fails, display the errors and stop the boot.

Now, only support disabled and enforce.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:37 +02:00
Sudhakar Kuppusamy e95c52f1f4 appended signatures: Parse X.509 certificates
This code allows us to parse:

 - X.509 certificates: at least enough to verify the signatures on the PKCS#7
   messages. We expect that the certificates embedded in GRUB will be leaf
   certificates, not CA certificates. The parser enforces this.

 - X.509 certificates support the Extended Key Usage extension and handle it by
   verifying that the certificate has a Code Signing usage.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com> # EKU support
Reported-by: Michal Suchanek <msuchanek@suse.com> # key usage issue
Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:35 +02:00
Sudhakar Kuppusamy a337549797 appended signatures: Parse PKCS#7 signed data
This code allows us to parse:

 - PKCS#7 signed data messages. Only a single signer info is supported, which
   is all that the Linux sign-file utility supports creating out-of-the-box.
   Only RSA, SHA-256 and SHA-512 are supported. Any certificate embedded in
   the PKCS#7 message will be ignored.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:35 +02:00
Sudhakar Kuppusamy 3e4ff6ffb3 appended signatures: Parse ASN1 node
This code allows us to parse ASN1 node and allocating memory to store it.
It will work for anything where the size libtasn1 returns is right:
 - Integers
 - Octet strings
 - DER encoding of other structures

It will _not_ work for things where libtasn1 size requires adjustment:
 - Strings that require an extra NULL byte at the end
 - Bit strings because libtasn1 returns the length in bits, not bytes.

If the function returns a non-NULL value, the caller must free it.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:34 +02:00
Sudhakar Kuppusamy 7d28bdb0b2 appended signatures: Import GNUTLS's ASN.1 description files
In order to parse PKCS#7 messages and X.509 certificates with libtasn1, we need
some information about how they are encoded. We get these from GNUTLS, which has
the benefit that they support the features we need and are well tested.

The GNUTLS files are from:

- https://github.com/gnutls/gnutls/blob/master/lib/gnutls.asn
- https://github.com/gnutls/gnutls/blob/master/lib/pkix.asn

The GNUTLS license is LGPLv2.1+, which is GPLv3 compatible, allowing us to import
it without issue.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:34 +02:00
Sudhakar Kuppusamy 1fca5f397a grub-install: Support embedding x509 certificates
To support verification of appended signatures, we need a way to embed the
necessary public keys. Existing appended signature schemes in the Linux kernel
use X.509 certificates, so allow certificates to be embedded in the GRUB core
image in the same way as PGP keys.

Signed-off-by: Alastair D'Silva <alastair@d-silva.org>
Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:34 +02:00
Sudhakar Kuppusamy aefe0de22e pgp: Rename OBJ_TYPE_PUBKEY to OBJ_TYPE_GPG_PUBKEY
Prior to the addition of the X.509 public key support for appended signature,
current PGP signature relied on the GPG public key. Changing the enum name
from "OBJ_TYPE_PUBKEY" to "OBJ_TYPE_GPG_PUBKEY" to differentiate between x509
certificate based appended signature and GPG certificate based PGP signature.

Signed-off-by: Alastair D'Silva <alastair@d-silva.org>
Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:34 +02:00
Daniel Axtens f826cc8b0e crypto: Move storage for grub_crypto_pk_* to crypto.c
The way gcry_rsa and friends (the asymmetric ciphers) are loaded for the
pgp module is a bit quirky.

include/grub/crypto.h contains:
  extern struct gcry_pk_spec *grub_crypto_pk_rsa;

commands/pgp.c contains the actual storage:
  struct gcry_pk_spec *grub_crypto_pk_rsa;

And the module itself saves to the storage in pgp.c:
  GRUB_MOD_INIT(gcry_rsa)
  {
    grub_crypto_pk_rsa = &_gcry_pubkey_spec_rsa;
  }

This is annoying: gcry_rsa now has a dependency on pgp!

We want to be able to bring in gcry_rsa without bringing in PGP, so move the
storage to crypto.c.

Previously, gcry_rsa depended on pgp and mpi. Now it depends on crypto and mpi.
As pgp depends on crypto, this doesn't add any new module dependencies using
the PGP verfier.

[FWIW, the story is different for the symmetric ciphers. cryptodisk and friends
(zfs encryption etc) use grub_crypto_lookup_cipher_by_name() to get a cipher
handle. That depends on grub_ciphers being populated by people calling
grub_cipher_register. import_gcry.py ensures that the symmetric ciphers call it.]

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:34 +02:00
Sudhakar Kuppusamy 31cc7dfe50 powerpc/ieee1275: Add support for signing GRUB with an appended signature
Add infrastructure to allow firmware to verify the integrity of GRUB
by use of a Linux-kernel-module-style appended signature. We initially
target powerpc-ieee1275, but the code should be extensible to other
platforms.

Usually these signatures are appended to a file without modifying the
ELF file itself. (This is what the 'sign-file' tool does, for example.)
The verifier loads the signed file from the file system and looks at the
end of the file for the appended signature. However, on powerpc-ieee1275
platforms, the bootloader is often stored directly in the PReP partition
as raw bytes without a file-system. This makes determining the location
of an appended signature more difficult.

To address this, we add a new ELF Note.

The name field of shall be the string "Appended-Signature", zero-padded
to 4 byte alignment. The type field shall be 0x41536967 (the ASCII values
for the string "ASig"). It must be the final section in the ELF binary.

The description shall contain the appended signature structure as defined
by the Linux kernel. The description will also be padded to be a multiple
of 4 bytes. The padding shall be added before the appended signature
structure (not at the end) so that the final bytes of a signed ELF file
are the appended signature magic.

A subsequent patch documents how to create a GRUB core.img validly signed
under this scheme.

Signed-off-by: Rashmica Gupta <rashmica.g@gmail.com>
Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-10-11 15:36:25 +02:00
Anaëlle Cazuc ee789e1a62 lib/b64dec: Use grub_size_t instead of size_t for _gpgrt_b64dec_proc() function definition
On some targets, size_t and grub_size_t may not be the same type
(unsigned long / unsigned int). This breaks the compilation because the
definition of _gpgrt_b64dec_proc() differs from gpgrt_b64dec_proc()
declaration. Fix it by using grub_size_t in the _gpgrt_b64dec_proc()
definition.

Signed-off-by: Anaëlle Cazuc <acazuc@acazuc.fr>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-10 01:12:17 +02:00
Anaëlle Cazuc abb8fb6d1a util/grub-mkimagexx: Fix riscv32 relocation offset
When using grub-mkrescue for a riscv32 target, an invalid implicit cast
on the offset calculation produces an error during the relocation process:

  grub-mkrescue: error: target XXX not reachable from pc=fc.

This patch adds an explicit grub_int64_t cast to compute the offset
as a 64-bit subtraction.

Signed-off-by: Anaëlle Cazuc <acazuc@acazuc.fr>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-10 01:12:17 +02:00
Andrew Hamilton 1f9092bfd5 libgcrypt: Allow GRUB to build with Clang
Attempts to build GRUB with Clang were failing due to errors such as:

  error: redefinition of typedef 'gcry_md_hd_t' is a C11 feature

Correct this by adding a compiler pragma to disable the Clang
"typedef-redefinition" warnings. This required an update to
include/grub/crypto.h and the util/import_gcry.py script to add the
pragma to libgcrypt-grub's types.h due to u16 and similar types.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-10 01:12:17 +02:00
Andrew Hamilton 1d2ee8f8b3 tests: Add test ISO files to dist package
Add test ISO files to dist package to allow ISO test to pass.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-10 01:12:17 +02:00
Vladimir Serbinenko dfa3dbf61e tests: Test dates outside of 32-bit Unix range
Add tests outside the date range possible with 32-bit time calculation.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-10 01:12:17 +02:00
Vladimir Serbinenko 6837293b87 lib/datetime: Support dates outside of 1901..2038 range
Fixes: https://savannah.gnu.org/bugs/?63894
Fixes: https://savannah.gnu.org/bugs/?66301

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-10 01:09:47 +02:00
Andrew Hamilton 02788bfdf9 bootstrap: Ensure shallow gnulib clone works on newer git
Update the bootstrap script to be compatible with newer versions of git
that changed the "git clone -h" output from containing:

  --depth

to:

  --[no-]depth

This bootstrap script is pulled the latest gnulib version from gnulib
git, commit 9a1a6385 (Silence 'time-stamp' warnings with bleeding-edge
Emacs.). This change avoids a full clone on gnulib, saving something
like 50 MB.

Fixes: https://savannah.gnu.org/bugs/?66357

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:21 +02:00
Andrew Hamilton 4e42199f35 docs: Correct some URLs
Correct some outdated links to various websites and change
http to https in a few places.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:21 +02:00
Andrew Hamilton 733cc28eb6 docs: Update Future section to reflect current release
Update the Future section of the GRUB manual to reflect
current work on the 2.x series.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:21 +02:00
Andrew Hamilton 54c8573ef4 docs: Document new libgrypt modules
Add documentation for new libgcrypt modules imported into GRUB.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:21 +02:00
Andrew Hamilton 1562dee692 docs: Clarify section heading and fix wording
Update chapter name from "Outline" to "Platform-specific operations" to
improve readability. Also slightly improve some wording in this section.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:21 +02:00
Andrew Hamilton cf1b75a144 BUGS: Update to point to bug tracking system
Update the BUGS file to just point to the GRUB bug tracking system.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:21 +02:00
Andrew Hamilton 236663dfbe INSTALL: Document libtasn1 needed for grub-protect
Update INSTALL documentation to note that the optional grub-protect
utility requires libtasn1 to build.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:21 +02:00
Andrew Hamilton 7bfb38627b po: Update translations to build with gettext 0.26
Gettext 0.26 validates format strings. In some cases before
the GRUB build process was converting newlines sequences (\n)
to (\<translated character>) which is invalid. Update the
impacted language sed script files to ensure newlines use
the correct escape sequence.

This avoids build errors such as:

  de@hebrew.po:8192: 'msgstr' is not a valid Shell printf format string, unlike 'msgid'. Reason: This escape sequence is invalid.

Fixes: https://savannah.gnu.org/bugs/?67353

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:21 +02:00
Kancy Joe 49e76ad16f term/efi/console: Treat key.scan_code 0x0102 (suspend) as Enter
Some Qualcomm-based UEFI platforms only provide volume up, volume down,
and power keys. The volume keys are already mapped to SCAN_UP and SCAN_DOWN,
while the power key is mapped to SCAN_SUSPEND (key.scan_code 0x0102).

On such devices, the power key is commonly used as the Enter (confirm)
button, since no dedicated Enter key exists. This patch treats key.scan_code
0x0102 as Enter to improve usability on these platforms.

Signed-off-by: Kancy Joe <kancy2333@outlook.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:20 +02:00
Mate Kukri de72f39985 util/bash-completion.d/Makefile.am: s/mkrescure/mkrescue/g
This is a typo that was stopping this bash-completion from being installed.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:20 +02:00
Alec Brown 14c2966c72 blsuki: Add uki command to load Unified Kernel Image entries
A Unified Kernel Image (UKI) is a single UEFI PE file that combines
a UEFI boot stub, a Linux kernel image, an initrd, and further resources.
The uki command will locate where the UKI file is and create a GRUB menu
entry to load it.

The Unified Kernel Image Specification: https://uapi-group.org/specifications/specs/unified_kernel_image/

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:20 +02:00
Robbie Harwood 5190df8510 blsuki: Check for mounted /boot in emu
Irritatingly, BLS defines paths relative to the mountpoint of the
filesystem which contains its snippets, not / or any other fixed
location. So grub-emu needs to know whether /boot is a separate
filesystem from / and conditionally prepend a path.

Signed-off-by: Robbie Harwood <rharwood@redhat.com>
Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:20 +02:00
Alec Brown 51b9601320 util/misc.c: Change offset type for grub_util_write_image_at()
Adding filevercmp support to grub-core/commands/blsuki.c from gnulib will cause
issues with the type of the offset parameter for grub_util_write_image_at() for
emu builds. To fix this issue, we can change the type from off_t to grub_off_t.

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:20 +02:00
Peter Jones 8cee1c284b blsuki: Add blscfg command to parse Boot Loader Specification snippets
The BootLoaderSpec (BLS) defines a scheme where different bootloaders can
share a format for boot items and a configuration directory that accepts
these common configurations as drop-in files.

The BLS Specification: https://uapi-group.org/specifications/specs/boot_loader_specification/

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Signed-off-by: Will Thompson <wjt@endlessm.com>
Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:20 +02:00
Alec Brown e016d6d60a kern/misc: Implement grub_strtok()
Add the functions grub_strtok() and grub_strtok_r() to help parse strings into
tokens separated by characters in the "delim" parameter. These functions are
present in gnulib but calling them directly from the gnulib code is quite
challenging since the call "#include <string.h>" would include the header file
grub-core/lib/posix_wrap/string.h instead of grub-core/lib/gnulib/string.h,
where strtok() and strtok_r() are declared. Since this overlap is quite
problematic, the simpler solution was to implement the code in the GRUB based
on gnulib's implementation. For more information on these functions, visit the
Linux Programmer's Manual, man strtok.

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:37:20 +02:00
Aaron Rainbolt 587db89afc kern/xen: Add Xen command line parsing
Xen traditionally allows customizing guest behavior by passing arguments
to the VM kernel via the kernel command line. This is no longer possible
when using GRUB with Xen, as the kernel command line is decided by the
GRUB configuration file within the guest, not data passed to the guest
by Xen.

To work around this limitation, enable GRUB to parse a command line
passed to it by Xen, and expose data from the command line to the GRUB
configuration as environment variables. These variables can be used in
the GRUB configuration for any desired purpose, such as extending the
kernel command line passed to the guest. The command line format is
inspired by the Linux kernel's command line format.

To reduce the risk of misuse, abuse, or accidents in production, the
command line will only be parsed if it consists entirely of 7-bit ASCII
characters, only alphabetical characters and underscores are permitted
in variable names, and all variable names must start with the string
"xen_grub_env_". This also allows room for expanding the command line
arguments accepted by GRUB in the future, should other arguments end up
becoming desirable in the future.

Signed-off-by: Aaron Rainbolt <arraybolt3@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-04 14:34:31 +02:00
Aaron Rainbolt b2a975bc5d include/xen/xen.h: Add warning comment for cmd_line
The cmd_line field of the start_info struct is not guaranteed to be
NUL-terminated, even though it is intended to contain a NUL-terminated
string. Add a warning about this in a comment so future consumers of
this field know to check it for a NUL terminator before using it.

Signed-off-by: Aaron Rainbolt <arraybolt3@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-09-03 17:44:26 +02:00
Doug Goldstein 19c698d123 zfs: Fix LINUX_ROOT_DEVICE when grub-probe fails
When grub-probe fails, the current code is to just stuff an empty result
in which causes the user to not knowingly have a system that no longer
boots. grub-probe can fail because the ZFS pool that contains the root
filesystem might have features that GRUB does not yet support which is
a common configuration for people with a rpool and a bpool. This behavior
uses the zdb utility to dump the same value as the filesystem label
would print.

Signed-off-by: Doug Goldstein <cardoe@cardoe.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-08-15 00:27:02 +02:00
Vladimir Serbinenko 6898fcf74d relocator: Switch to own page table while moving chunks
We need to avoid clobbering existing table between starting of chunk movers
and the moment we install target page table. Generate temporary table for
this rather than hoping that we don't clobber existing one.

Fixes 64-bit GhostBSD on 64-bit EFI.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-08-15 00:23:45 +02:00
Mate Kukri 67a95527b5 configure: Generate tar-ustar tarball instead of tar-v7
Some of our paths are too long for tar-v7 at this point but tar-ustar
is supported by essentially everything. So, let's use that.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-08-14 21:21:42 +02:00
Mate Kukri 29d515b4cc build: Add new libgcrypt and libtasn1 related files to EXTRA_DISTS
These files were not added to EXTRA_DISTS during the libgcrypt
and libtasn1 imports but are required for autogen.sh to work.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-08-14 21:21:42 +02:00
Mate Kukri eb76b064d2 build: Add util/import_gcrypt_inth.sed to EXTRA_DISTS
This new file was not added to the distribution tarball during the last
libgcrypt import.

Fixes: 0739d24cd1 (libgcrypt: Adjust import script, definitions and API users for libgcrypt 1.11)

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-08-14 21:21:42 +02:00
Aaron Rainbolt eb56a6af9a include/xen/xen.h: Rename MAX_GUEST_CMDLINE to GRUB_XEN_MAX_GUEST_CMDLINE
The include/xen/xen.h header was using an overly generic name to refer
to the maximum length of the command line passed from Xen to a guest.
Rename it to avoid confusion or conflicts in the future.

Signed-off-by: Aaron Rainbolt <arraybolt3@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-08-14 21:21:42 +02:00
Frediano Ziglio 80df5e1327 loader/arm64/xen_boot: Set correctly bootargs property for modules
The cmdline_size already account for NUL terminator, you can see
this in xen_boot_binary_load(). The same property is set correctly
for Xen command line.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-08-14 21:21:42 +02:00
Frediano Ziglio 6831d242ad loader/efi/linux: Return correct size from LoadFile2
From UEFI specifications 2.10, section 13.2.2, EFI_LOAD_FILE2_PROTOCOL.LoadFile
(see https://uefi.org/specs/UEFI/2.10/13_Protocols_Media_Access.html), for BufferSize:

  On input the size of Buffer in bytes. On output with a return code
  of EFI_SUCCESS, the amount of data transferred to Buffer. On output
  with a return code of EFI_BUFFER_TOO_SMALL, the size of Buffer
  required to retrieve the requested file.

So, set *buffer_size correctly.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-08-14 21:21:41 +02:00
Luca Boccassi f326c5c475 commands/bli: Set LoaderTpm2ActivePcrBanks runtime variable
It turns out checking from userspace is not 100% reliable to figure out
whether the firmware had TPM2 support enabled or not. For example with
EDK2 arm64, the default upstream build config bundles TPM2 support with
SecureBoot support, so if the latter is disabled, TPM2 is also unavailable.
But still, the ACPI TPM2 table is created just as if it was enabled. So,
/sys/firmware/acpi/tables/TPM2 exists and looks correct but there are no
measurements, neither the firmware nor the loader/stub can do them, and
/sys/kernel/security/tpm0/binary_bios_measurements does not exist.
So, userspace cannot really tell what was going on in UEFI mode.

The loader can use the apposite UEFI protocol to check, which is a more
definitive answer. Export the bitmask with the list of active banks as-is.
If it's not 0, then in userspace we can be sure a working TPM2 was available
in UEFI mode.

systemd-boot and systemd-stub v258 (current main) set this variable and
userspace portion consumes it to be able to tell what was available in
the firmware context.

Signed-off-by: Luca Boccassi <luca.boccassi@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-08-14 21:20:01 +02:00
Vladimir Serbinenko 0e367796c0 docs: Write how to import new libgcrypt
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:51 +02:00
Vladimir Serbinenko b930bfa377 libgcrypt: Fix a memory leak
Fixes: CID 468917

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:51 +02:00
Vladimir Serbinenko d48c277c49 libgcrypt: Don't use 64-bit division on platforms where it's slow
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:51 +02:00
Vladimir Serbinenko de49514c9e util/import_gcry: Fix pylint warnings
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:51 +02:00
Vladimir Serbinenko 334353a977 util/import_gcry: Make compatible with Python 3.4
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:51 +02:00
Vladimir Serbinenko 2a6de42093 libgcrypt: Import blake family of hashes
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:51 +02:00
Vladimir Serbinenko e541879123 libgcrypt: Ignore sign-compare warnings
libgcrypt itself is compiled with -Wno-sign-compare. Do the same for consistency.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:51 +02:00
Vladimir Serbinenko e3b78e49cd libgcrypt: Remove now unneeded compilation flag
HAVE_STRTOUL is now defined in stdlib.h. Include it in g10lib.h rather
than defining on command line.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:51 +02:00
Vladimir Serbinenko e23704ad48 libgcrypt: Fix Coverity warnings
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:51 +02:00
Vladimir Serbinenko d65810b01c keccak: Disable acceleration with SSE asm
Libgcrypt code assumes that on x64 all SSE registers are fair game.
While it's true that CPUs in question support it, we disable it in
our compilation options. Disable the offending optimization.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:51 +02:00
Vladimir Serbinenko f808ef0d28 tests: Add DSA and RSA SEXP tests
This allows us to test purely the integration of the implementation of
DSA and RSA from libgcrypt without concerning with additional code.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:50 +02:00
Vladimir Serbinenko 0739d24cd1 libgcrypt: Adjust import script, definitions and API users for libgcrypt 1.11
This patches modifies the GRUB-libgcrypt API to match new libgcrypt 1.11.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:50 +02:00
Vladimir Serbinenko 3e1c2890b8 b64dec: Add harness for compilation in GRUB environment
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:50 +02:00
Vladimir Serbinenko 5ca0d5e412 b64dec: Import b64dec from gpg-error
Imported from libgpg-error 1.51.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:50 +02:00
Vladimir Serbinenko 3312af6e07 libgcrypt: Import libgcrypt 1.11
We currently use an old version of libgcrypt which results in us having
fewer ciphers and missing on many other improvements.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:12:50 +02:00
Mate Kukri a0d4c94ef6 loader/efi/linux: Use shim loader image handle where available
Not reusing these handles will result in image measurements showing up
twice in the event log.

On the occasion add missing grub_free() call.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 23:11:35 +02:00
Mate Kukri 1b9a84e63b loader/efi/chainloader: Use shim loader image handle where available
Not reusing these handles will result in image measurements showing up
twice in the event log.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 17:46:19 +02:00
Mate Kukri e31d0cd7fb efi/sb: Add API for retrieving shim loader image handles
Not reusing these handles will result in image measurements showing up
twice in the event log.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 17:46:19 +02:00
Mate Kukri ed7e053a36 efi/sb: Add support for the shim loader protocol
Use loader protocol for image verification where available, otherwise
fall back to the old shim lock protocol.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 17:46:14 +02:00
Julian Andres Klode 70897d3d3e efi: Provide wrappers for load_image, start_image and unload_image
These can be used to register a different implementation later,
for example, when shim provides a protocol with those functions.

Signed-off-by: Julian Andres Klode <julian.klode@canonical.com>
Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 17:12:24 +02:00
Frediano Ziglio 030a70fcad loader/arm64/xen_boot: Consider alignment calling grub_arch_efi_linux_boot_image()
The Xen image is loaded with an alignment, not always at "start".

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-07-11 16:47:34 +02:00
Frediano Ziglio e82609a476 loader/arm64/xen_boot: Use bool instead of int
More readable, could consume less space.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 16:40:31 +02:00
Frediano Ziglio d1a470b694 loader/arm64/xen_boot: Remove correctly all modules loaded by xen_module command
We need to use FOR_LIST_ELEMENTS_SAFE() instead of FOR_LIST_ELEMENTS()
as single_binary_unload(), called during the loop, is changing the list
using grub_list_remove(). Given the environment probably the old code
simply removed only the first module on the list not freeing all the others.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-07-11 16:33:08 +02:00
Gary Lin cf5e52fa85 dl: Fix grub_dl_is_persistent() for emu
When attempting to build grub-emu the compilation failed with the
following error message:

  include/grub/dl.h: In function ‘grub_dl_is_persistent’:
  include/grub/dl.h:262:1: error: no return statement in function returning non-void [-Werror=return-type]

To avoid the error make the function always return 0.

Fixes: ba8eadde6b (dl: Provide a fake grub_dl_set_persistent() and grub_dl_is_persistent() for the emu target)

Signed-off-by: Gary Lin <glin@suse.com>
Cc: Daniel Axtens <dja@axtens.net>
Cc: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-07-11 16:25:14 +02:00
Lidong Chen a68a7dece4 loader/i386/pc/linux: Fix resource leak
In grub_cmd_initrd(), memory is allocated for variable initrd_ctx
before calling grub_relocator_alloc_chunk_align_safe(). When the
function call fails, initrd_ctx should be freed before exiting
grub_cmd_initrd().

Fixes: CID 473852

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 20:02:05 +02:00
Adriano Cordova de80acf368 loader/efi/linux: Unload previous Linux kernel/initrd before updating kernel size
Unload previous Linux kernel/initrd before updating the global variable
kernel_size. Otherwise the previous Linux kernel gets deallocated with
the kernel_size of the Linux kernel that is being currently loaded.

Signed-off-by: Adriano Cordova <adriano.cordova@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 18:05:08 +02:00
Frediano Ziglio 249db11d8f loader/efi/linux: Correctly terminate load_options member
If a simple string for arguments are passed it should be NUL terminated.
This is true for other code but not for "linux" command.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 18:05:08 +02:00
Frediano Ziglio f3b339af11 loader/efi/linux: Use sizeof() instead of constant
This is more consistent with the above code using sizeof(grub_efi_char16_t).

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 18:05:08 +02:00
Frediano Ziglio c2b2e0dcf5 loader/efi/linux: Use proper type for len variable
Although the length should not exceed 2^31 grub_size_t is more
suitable for that variable. len is used to compute the size
of buffers which in C is a size_t, not a int. It is used
for GRUB_EFI_BYTES_TO_PAGES which expects unsigned values.
It is assigned to load_options_size which is unsigned, not signed.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 18:05:08 +02:00
Frediano Ziglio de4e8e2aa6 loader/efi/linux: Do not pass excessive size for source string
The size passed to grub_utf8_to_utf16() for the source string is
used as a limit for the string if NUL character is not encountered.
However, len, which is "strlen(src) * 2 + 2" is surely greater than
strlen(src). Pass the exact correct length.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 18:05:08 +02:00
Frediano Ziglio 8c8f966643 loader/efi/linux: Remove useless assignment
If the following allocation fails this would leave load_options NULL
while load_options_size not valid. If the allocation succeed
load_options_size is overwritten.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 18:05:08 +02:00
Frediano Ziglio 8ebf155af3 include/grub/charset.h: Update documentation
(grub_size_t) -1 is never returned, the function always return
a not negative values. This is important for overflows considerations.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 18:05:08 +02:00
Lidong Chen 2f2ed28d5a Revert "lzma: Make sure we don't dereference past array"
Commit 40e261b89b (lib/LzmaEnc: Validate "len" before subtracting)
ensures that the variable len is at least 2. As a result, GetLenToPosState(len)
never returns a value greater than or equal to kNumLenToPosStates,
making the changes introduced in the commit 16c0dbf4bc (lzma: Make
sure we don't dereference past array) unreachable and no longer necessary.

This reverts commit 16c0dbf4bc (lzma: Make sure we don't dereference past array).

Fixes: CID 481982

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 18:05:08 +02:00
Andrew Hamilton 2539ede82a tests/util/grub-shell: Correct netboot and file_filter test failure
Correct a test failure in netboot_test and file_filter_test caused by an
issue cleaning up the tmp directory created for netboot. Netboot creates
a subdirectory in the tmp folder that causes the rmdir to fail - so
cleanup the subdirectory first.

Fixes: 1d59f39b5f (tests/util/grub-shell: Remove the work directory on successful run and debug is not on)

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Tested-by: Leo Sandoval <lsandova@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 17:24:39 +02:00
Lidong Chen 8c2d4e64ff normal/charset: Fix underflow and overflow in loop init
In bidi_line_wrap(), "kk - 1" in the for loop init, "i = kk - 1",
underflows when "kk" (unsigned int) is 0. Assigning the result of
"kk - 1" to signed int "i" may cause overflow. To address both
issues, cast "kk" to a signed type before subtraction to ensure
safe arithmetic and assignment.

Fixed: CID 473874

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-06-26 17:19:25 +02:00
Daniel Axtens ba8eadde6b dl: Provide a fake grub_dl_set_persistent() and grub_dl_is_persistent() for the emu target
Trying to start grub-emu with a module that calls grub_dl_set_persistent()
and grub_dl_is_persistent() will crash because grub-emu fakes modules and
passes NULL to the module init function.

Provide an empty function for the emu case.

Fixes: ee7808e219 (dl: Add support for persistent modules)

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 17:19:25 +02:00
Andrew Hamilton 409e72cedf util/grub-protect: Correct uninit "err" variable
In function protect_tpm2_export_tpm2key(), the "err" variable
is uninitialized in the normal (error free) path, so ensure this
defaults to GRUB_ERR_NONE.

This causes the GRUB build to fail with clang (observed with clang-14).

Fixes: 5934bf51c (util/grub-protect: Support NV index mode)

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 17:19:25 +02:00
Lidong Chen 5eca564b19 gnulib: Bring back the fix for resolving unused variable issue
This patch resolved a minor issue spotted by Coverity:
  a983d36bd9 (gnulib/regexec: Resolve unused variable)

But, it was removed by the Gnulib update:
  2b79024598 (Update gnulib version and drop most gnulib patches)

It caused Coverity to continue to flag the issue. Daniel Kiper
suggested to bring back the patch a983d36bd9 (gnulib/regexec: Resolve
unused variable).

Fixes: CID 292459

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 17:19:25 +02:00
Andrew Hamilton ac1512b872 gnulib: Add patch to allow GRUB w/GCC-15 compile
Pull in Gnulib fix to allow lib/base64.c to compile using GCC 15 or newer.

Pulled from Gnulib commit 25df6dc425 (Silence some
-Wunterminated-string-initialization warnings.)

GCC 15 adds a new compiler warning "-Wunterminated-string-initialization"
that will trigger what is considered a false-positive in lib/base64.c as
this array is not treated as a string but an array of characters so the
lack of NUL string terminator is expected.

GCC team has added ability to flag such instances of arrays that the
compiler may think are strings as "nonstring" arrays to avoid this
warning: __attribute__((nonstring)).

Fixes: https://savannah.gnu.org/bugs/?66470

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-26 17:02:21 +02:00
Alec Brown db506b3b83 gnulib/regexec: Fix resource leak
In the function merge_state_with_log(), memory is allocated for the variable
next_nodes when creating a union of the variables table_nodes and log_nodes.
However, if next_state->entrance_nodes is NULL, then table_nodes becomes NULL
and we still allocate memory to copy the content of log_nodes. This can cause
a resource leak since we only free the memory for next_nodes if table_nodes
isn't NULL. To prevent this, we need to check that next_state->entrance_nodes
isn't NULL before allocating memory for the union.

This issue has been fixed in the latest version of gnulib and I've backported
this change to maintain consistency.

This issue was found by a Coverity scan of GRUB2 under the CID 473887.

Fixes: CID 473887

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-17 14:29:29 +02:00
Alec Brown bba7dd7363 gnulib/regcomp: Fix resource leak
In the functions create_initial_state() and calc_eclosure_iter(), memory
is allocated for the elems member of a re_node_set structure but that
memory isn't freed on error. Before returning an error, a call to
re_node_set_free() should be made to prevent the resource leak.

This issue has been fixed in the latest version of gnulib and I've
backported this change to maintain consistency.

This issue was found by a Coverity scan of GRUB2 under the following
CIDs: 473869, 473888.

Fixes: CID 473869
Fixes: CID 473888

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-17 14:17:56 +02:00
Gary Lin 91cb7ff6bb tests/tpm2_key_protector_test: Add tests for SHA-384 PCR bank
Add a few more tests to seal and unseal the key with the SHA-384 PCR
bank instead of the default SHA-256 PCR bank.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-17 14:13:42 +02:00
Gary Lin 451e227e53 tpm2_key_protector: Dump the PCR bank for key unsealing
TPM 2.0 Key File format stores the PCR selection in the parameters
for TPM2_PolicyPCR and it already contains the selected PCR bank.
Currently, tpm2_key_protector dumped the PCR bank specified by the
--bank option, and it may not be the PCR bank for key unsealing.

To dump the real PCR bank for key unsealing, this commit records the PCR
bank used by TPM2_PolicyPCR and dumps PCR values from that bank when
necessary.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-17 14:12:50 +02:00
Gary Lin 11caacdb22 util/grub-protect: Fix the hash algorithm of PCR digest
For tpm2_key_protector and grub-protect, SHA-256 is chosen as the hash
algorithm for the TPM session. However, grub-protect mistakenly used the
hash algorithm of the PCR bank to calculate PCR digest. If the user
chose a PCR bank other than SHA-256, grub-protect created a non-SHA-256
PCR digest to seal the key. But, tpm2_key_protector expects a SHA-256
PCR digest to the TPM unsealing session, so it would fail due to digest
mismatch.

This commit fixes the hash algorithm of PCR digest in grub-protect to
avoid the potential unsealing failure.

Fixes: https://github.com/lcp/grub2/issues/4

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-17 14:10:37 +02:00
Andrew Hamilton ce23919cac build: Add new header files to dist to allow building from tar
Several new header files have been added to GRUB which need
to be manually added to the dist archive. This allows building
from the tar archive created by "make dist".

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-17 13:51:46 +02:00
Andrew Hamilton e3b15bafd1 build: Remove extra_deps.lst from EXTRA_DIST
This file is auto-generated based on the selected platform and should
not be included in the source tarball.

Fixes: 6744840b (build: Track explicit module dependencies in Makefile.core.def)

Signed-off-by: Mike Gilbert <floppym@gentoo.org>
Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-17 13:47:21 +02:00
Lidong Chen 40e261b89b lib/LzmaEnc: Validate "len" before subtracting
In LzmaEnc_CodeOneBlock(), both GetOptimumFast() and GetOptimum()
returns a value of greater or equal to 1, which is assigned to
"len". But since LZMA_MATCH_LEN_MIN == 2, "len" should be validated
before performing "len - LZMA_MATCH_LEN_MIN" to avoid underflow
when "len" equals to 1.

Fixes: CID 51508

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
2025-06-17 13:37:31 +02:00
Lidong Chen 86e8f2c4b0 osdep/unix/hostdisk: Fix signed integer overflow
The potential overflow issue arises at "size += ret;" because "size"
is of type ssize_t (signed) while "len" is size_t (unsigned). Repeatedly
adding read sizes, "ret", to "size" can potentially exceed the maximum
value of ssize_t, causing it to overflow into a negative or incorrect value.
The fix is to ensure "len" is within the range of SSIZE_MAX.

Fixes: CID 473850
Fixes: CID 473863

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-06-12 18:56:24 +02:00
Egor Ignatov 438f055819 disk/luks2: Add attempting to decrypt message to align with luks and geli modules
Signed-off-by: Egor Ignatov <egori@altlinux.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-29 15:45:24 +02:00
Renaud Métrich 20e6d0c4a4 osdep/linux/getroot: Detect DDF container similar to IMSM
Similarly to Intel IMSM, there are BIOS and UEFI implementations that
support DDF containers natively.

DDF and IMSM are very similar in handling, especially these should not
be considered as RAID abstraction. This fixes the requirement of having
a device map when probing DDF containers.

Fixes: https://issues.redhat.com/browse/RHEL-44336

Signed-off-by: Renaud Métrich <rmetrich@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-29 15:45:24 +02:00
Andrew Hamilton b71bc0f8b4 fs/fshelp: Avoid possible NULL pointer deference
Avoid attempting to defererence a NULL pointer to call read_symlink() when
the given filesystem does not provide a read_symlink() function. This could
be triggered if the calling filesystem had a file marked as a symlink.
This appears possible for HFS and was observed during fuzzing of NTFS.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-29 15:45:24 +02:00
Andrew Hamilton 272ff81cb2 fs/ntfs: Correct possible infinite loops/hangs
Correct several infinite loops/hangs found during fuzzing. The issues
fixed here could occur if certain specific malformed NTFS file systems
were presented to GRUB. Currently, GRUB does not allow NTFS file system
access when lockdown mode is enforced, so these should be of minimal
impact.

The changes made in this commit generally correct issues such as attempting
to iterate through a buffer using a length read from the NTFS file system
without confirming the length is larger than 0.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-29 15:45:24 +02:00
Andrew Hamilton 8c95307a0b fs/ntfs: Correct possible access violations
Correct several memory access violations found during fuzzing.
The issues fixed here could occur if certain specific malformed NTFS
file systems were presented to GRUB. Currently, GRUB does not allow NTFS
file system access when lockdown mode is enforced, so these should be of
minimal impact.

The changes made in this commit generally correct issues where pointers
into data buffers were being calculated using lengths read from the
NTFS file system without sufficient bounds/sanity checking; or
attempting to access elements of a structure to free them, when the
structure pointer is NULL.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-29 15:45:24 +02:00
Andrew Hamilton 06914b6141 fs/ntfs: Correct attribute vs attribute list validation
Correct ntfs_test test failures around attempting to validate attribute
list entries as attributes. The NTFS code uses common logic in some
places to parse both attributes and attribute_lists which complicates
validation. Attribute lists contain different headers including a
different size of the length field (2 bytes) at offset 4 instead of the
4 byte length field used in attributes at offset 4. There are other
differences as well, but attempting to validate attribute list types
using attribute header validation was causing failure of the NTFS test
suite. This change restores some of the validation logic which may be
shared between attributes and attribute lists to be closer to the
original logic prior to fixes for previous CVEs. A following commit will
address some of the implications of removing this validation logic by
correcting some fuzzer failures (some which are exposed by removing the
validation in some of the cases).

Fixes: 067b6d225 (fs/ntfs: Implement attribute verification)

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-29 15:45:24 +02:00
Andrew Hamilton 0e1762c8a0 fs/ntfs: Correct regression with run list calculation
Correct ntfs_test test failures around attempting to validate attribute
run list values. The calculation was incorrect for the "curr" variable.
With previous calculation, some file systems would fail validation
despite being well-formed and valid. This was caused by incrementing
"curr" by min_size which included both the (already accounted for)
min_size as well as the size of the run list. Correct by making a new
variable "run_size" to denote the current run list size to increment
both "curr" and "min_size" separately.

Fixes: 067b6d225 (fs/ntfs: Implement attribute verification)

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-29 15:45:24 +02:00
Shreenidhi Shedi be303f8c18 lib/envblk: Ignore empty new lines while parsing env files
Environment files may contain empty lines, which should be ignored
during parsing. Currently, these lines are not skipped and resulting in
incorrect behavior. This patch adds a check to skip empty lines along
with those starting with "#".

Signed-off-by: Shreenidhi Shedi <shreenidhi.shedi@broadcom.com>
Reviewed-by: Alexey Makhalov <alexey.makhalov@broadcom.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-29 15:45:09 +02:00
Glenn Washburn 34bd00ee26 fs/zfs: Fix another memory leak in ZFS code
Commit b66c6f918 (fs/zfs: Fix a number of memory leaks in ZFS code)
fixes many of the same leaks detected in bug #63846 except one, which
is fixed here.

Fixes: https://savannah.gnu.org/bugs/?63846
Fixes: b66c6f918 (fs/zfs: Fix a number of memory leaks in ZFS code)

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-29 14:53:09 +02:00
Glenn Washburn ca2a91f43b tests: Disable gfxterm_menu and cmdline_cat tests
Those tests fail depending on the version of unifont. As we don't distribute
our own unifont it fails for most users. Disable them so that they don't mask
real failures. They can be reinstated once we solve unifont problem.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-29 14:48:31 +02:00
Michael Chang 73d1c959ea cryptocheck: Add --quiet option
The option can be used to suppress output if we only want to test the
return value of the command.

Also, mention this option in the documentation.

Signed-off-by: Michael Chang <mchang@suse.com>
Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-06 17:14:04 +02:00
Maxim Suhanov dbc0eb5bd1 disk/cryptodisk: Wipe the passphrase from memory
Switching to another EFI boot application while there are secrets in
RAM is dangerous, because not all firmware is wiping memory on free.

To reduce the attack surface, wipe the passphrase acquired when
unlocking an encrypted volume.

Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-06 17:14:03 +02:00
Maxim Suhanov 301b4ef25a disk/cryptodisk: Add the "erase secrets" function
This commit adds the grub_cryptodisk_erasesecrets() function to wipe
master keys from all cryptodisks. This function is EFI-only.

Since there is no easy way to "force unmount" a given encrypted disk,
this function renders all mounted cryptodisks unusable. An attempt to
read them will return garbage.

This is why this function must be used in "no way back" conditions.

Currently, it is used when unloading the cryptodisk module and when
performing the "exit" command (it is often used to switch to the next
EFI application). This function is not called when performing the
"chainloader" command, because the callee may return to GRUB. For this
reason, users are encouraged to use "exit" instead of "chainloader" to
execute third-party boot applications.

This function does not guarantee that all secrets are wiped from RAM.
Console output, chunks from disk read requests and other may remain.

This function does not clear the IV prefix and rekey key for geli disks.

Also, this commit adds the relevant documentation improvements.

Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-06 17:14:03 +02:00
Maxim Suhanov 23ec4535f4 docs: Document available crypto disks checks
Document the --cryptodisk-only argument. Also, document the
"cryptocheck" command invoked when that argument is processed.

Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-06 17:14:03 +02:00
Maxim Suhanov 10d778c4b4 commands/search: Add the diskfilter support
When the --cryptodisk-only argument is given, also check the target
device using the "cryptocheck" command, if available.

This extends the checks to common layouts like LVM-on-LUKS, so the
--cryptodisk-only argument transparently handles such setups.

Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-06 17:14:03 +02:00
Maxim Suhanov 7a584fbde0 disk/diskfilter: Introduce the "cryptocheck" command
This command examines a given diskfilter device, e.g., an LVM disk,
and checks if underlying disks, physical volumes, are cryptodisks,
e.g., LUKS disks, this layout is called "LVM-on-LUKS".

The return value is 0 when all underlying disks (of a given device)
are cryptodisks (1 if at least one disk is unencrypted or in an
unknown state).

Users are encouraged to include the relevant check before loading
anything from an LVM disk that is supposed to be encrypted.

This further supports the CLI authentication, blocking bypass
attempts when booting from an encrypted LVM disk.

Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-06 17:14:03 +02:00
Maxim Suhanov ed691c0e0e commands/search: Introduce the --cryptodisk-only argument
This allows users to restrict the "search" command's scope to
encrypted disks only.

Typically, this command is used to "rebase" $root and $prefix
before loading additional configuration files via "source" or
"configfile". Unfortunately, this leads to security problems,
like CVE-2023-4001, when an unexpected, attacker-controlled
device is chosen by the "search" command.

The --cryptodisk-only argument allows users to ensure that the
file system picked is encrypted.

This feature supports the CLI authentication, blocking bypass
attempts.

Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-06 17:14:02 +02:00
Maxim Suhanov c448f511e7 kern/rescue_reader: Block the rescue mode until the CLI authentication
This further mitigates potential misuse of the CLI after the
root device has been successfully unlocked via TPM.

Fixes: CVE-2025-4382

Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-05-06 17:13:00 +02:00
Eric Sandeen 4abac0ad5a fs/xfs: Fix large extent counters incompat feature support
When large extent counter / NREXT64 support was added to GRUB, it missed
a couple of direct reads of nextents which need to be changed to the new
NREXT64-aware helper as well. Without this, we'll have mis-reads of some
directories with this feature enabled.

The large extent counter fix likely raced on merge with commit 07318ee7e
(fs/xfs: Fix XFS directory extent parsing) which added the new direct
nextents reads just prior, causing this issue.

Fixes: aa7c132267 (fs/xfs: Add large extent counters incompat feature support)

Signed-off-by: Eric Sandeen <sandeen@redhat.com>
Reviewed-by: Anthony Iliopoulos <ailiop@suse.com>
Reviewed-by: Jon DeVree <nuxi@vault24.org>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-23 18:10:53 +02:00
Egor Ignatov a4da71dafe util/grub-install: Include raid5rec module for RAID 4 as well
RAID 4 requires the same recovery module as RAID 5. Extend the condition to
cover both RAID levels.

Signed-off-by: Egor Ignatov <egori@altlinux.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 19:40:50 +02:00
Vladimir Serbinenko 223fcf8084 loader/ia64/efi/linux: Reset grub_errno on failure to allocate
The code goes on to allocate memory in another region on failure, hence
it should discard the error.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 19:39:27 +02:00
Vladimir Serbinenko 6504a8d4bd lib/datetime: Specify license in emu module
Other platforms specify license in platform-specific files but corresponding
code for emu is in kernel, so datetime ends up without license section.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 19:37:16 +02:00
Vladimir Serbinenko 8fef533cf6 configure: Add -mno-relax on riscv*
Without this option compiler sometimes emits R_RISCV_ALIGN relocs.
Unlike other relocs this one requires the linker to do NOP deletions
and we can't ignore them. Just instruct compiler not to emit them.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 19:34:59 +02:00
Gary Lin 1fe0948558 docs: Document the long options of tpm2_key_protect_init
Add the long options of tpm2_key_protect_init along with the short options.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 19:32:29 +02:00
Gary Lin 6252eb97ca INSTALL: Document the packages needed for TPM2 key protector tests
The TPM2 key protector tests require two external packages: swtpm-tools
and tpm2-tools. Add those two packages to the INSTALL file to inform
the user to install those packages before starting the TPM2 key protector
tests.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
2025-04-10 19:32:12 +02:00
Gary Lin 9d4b382aa0 docs: Update NV index mode of TPM2 key protector
This commit updates the NV index mode section and the grub-protect
section to reflect the recent changes in TPM2 key protector and
grub-protect.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 19:29:03 +02:00
Gary Lin 2043b6899b tests/tpm2_key_protector_test: Add more NV index mode tests
Two more NV index test cases are added to test key sealing and
unsealing with the NV index handle 0x1000000.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 19:28:02 +02:00
Gary Lin 9f66a4719b tests/tpm2_key_protector_test: Reset "ret" on fail
Reset "ret" to 0 when a test case fails so that the other test cases
could continue.

Also set the exit status to 1 when encountering a failure to reflect the
test result.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 19:25:41 +02:00
Gary Lin b7d89e6671 tests/tpm2_key_protector_test: Simplify the NV index mode test
Since grub-protect already supports NV index mode, tpm2_seal_nv() is
replaced with one grub-protect command to simplify the test script.

"tpm2_evictcontrol" is also replaced with "grub-protect --tpm2-evict".

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 18:15:31 +02:00
Gary Lin 5934bf51cb util/grub-protect: Support NV index mode
This commit implements the missing NV index mode support in grub-protect.
NV index mode stores the sealed key in the TPM non-volatile memory (NVRAM)
instead of a file. There are two supported types of TPM handles.

1. Persistent handle (0x81000000~0x81FFFFFF)
   Only the raw format is supported due to the limitation of persistent
   handles. This grub-protect command seals the key into the
   persistent handle 0x81000000.

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

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

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

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

  # grub-protect \
      --protector=tpm2 \
      --action=remove \
      --tpm2-evict \
      --tpm2-nvindex=0x1000000

Also set and check the boolean variables with true/false instead of 1/0.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 18:12:57 +02:00
Gary Lin cd9cb944d9 tpm2_key_protector: Support NV index handles
Previously, NV index mode only supported persistent handles which are
only for TPM objects.

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

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

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

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

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

To remove the NV index handle:

  # tpm2_nvundefine -C o 0x1000000

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 18:10:33 +02:00
Gary Lin fa69deac56 tpm2_key_protector: Unseal key from a buffer
Extract the logic to handle the file buffer from the SRK recover
function to prepare to load the sealed key from the NV index handle,
so the NV index mode can share the same code path in the later patch.
The SRK recover function now only reads the file and sends the file
buffer to the new function.

Besides this, to avoid introducing more options for the NV index mode,
the file format is detected automatically before unmarshaling the data,
so there is no need to use the command option to specify the file format
anymore. In other words, "-T" and "-k" are the same now.

Also update grub.text to address the change.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 18:05:58 +02:00
Gary Lin 75c480885a tss2: Add TPM 2.0 NV index commands
The following TPM 2.0 commands are introduced to tss2 to access the
TPM non-volatile memory associated with the NV index handles:
  - TPM2_NV_DefineSpace,
  - TPM2_NV_UndefineSpace,
  - TPM2_NV_ReadPublic,
  - TPM2_NV_Read,
  - TPM2_NV_Write.

The related marshal/unmarshal functions are also introduced.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 18:04:48 +02:00
Gary Lin 041164d00e tss2: Fix the missing authCommand
grub_tpm2_readpublic() and grub_tpm2_testparms() didn't check
authCommand when marshaling the input data buffer. Currently, there is
no caller using non-NULL authCommand. However, to avoid the potential
issue, the conditional check is added to insert authCommand into the
input buffer if necessary.

Also fix a few pointer checks.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 18:04:01 +02:00
Gary Lin 46c9f3a8da tpm2_key_protector: Add tpm2_dump_pcr command
The user may need to inspect the TPM 2.0 PCR values with the GRUB shell,
so the new tpm2_dump_pcr command is added to print all PCRs of the
specified bank.

Also update the document for the new command.

Signed-off-by: Gary Lin <glin@suse.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 18:03:55 +02:00
Gary Lin 617dab9e47 tpm2_key_protector: Dump PCRs on policy fail
PCR mismatch is one common cause of TPM key unsealing fail. Since the
system may be compromised, it is not safe to boot into OS to get the PCR
values and TPM eventlog for the further investigation.

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

The sample output:

PCR Mismatch! Check firmware and bootloader before typing passphrase!
TPM PCR [sha256]:
  00: 17401f37710984c1d8a03a81fff3ab567ae9291bac61e21715b890ee28879738
  01: 7a114329ba388445a96e8db2a072785937c1b7a8803ed7cc682b87f3ff3dd7a8
  02: 11c2776849e8e24b7d80c926cbc4257871bffa744dadfefd3ed049ce25143e05
  03: 6c33b362073e28e30b47302bbdd3e6f9cee4debca3a304e646f8c68245724350
  04: 62d38838483ecfd2484ee3a2e5450d8ca3b35fc72cda6a8c620f9f43521c37d1
  05: d8a85cb37221ab7d1f2cc5f554dbe0463acb6784b5b8dc3164ccaa66d8fff0e1
  06: 9262e37cbe71ed4daf815b4a4881fb7251c9d371092dde827557d5368121e10e
  07: 219d542233be492d62b079ffe46cf13396a8c27e520e88b08eaf2e6d3b7e70f5
  08: de1f61c973b673e505adebe0d7e8fb65fde6c24dd4ab4fbaff9e28b18df6ecd3
  09: c1de7274fa3e879a16d7e6e7629e3463d95f68adcfd17c477183846dccc41c89
  10: 0000000000000000000000000000000000000000000000000000000000000000
  11: 0000000000000000000000000000000000000000000000000000000000000000
  12: 0000000000000000000000000000000000000000000000000000000000000000
  13: 0000000000000000000000000000000000000000000000000000000000000000
  14: 9ab9ebe4879a7f4dd00c04f37e79cfd69d0dd7a8bcc6b01135525b67676a3e40
  15: 0000000000000000000000000000000000000000000000000000000000000000
  16: 0000000000000000000000000000000000000000000000000000000000000000
  17: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  18: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  19: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  20: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  21: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  22: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  23: 0000000000000000000000000000000000000000000000000000000000000000
error: failed to unseal sealed key (TPM2_Unseal: 0x99d).
error: no key protector provided a usable key for luks (af16e48f-746b-4a12-aae1-c14dcee429e0).

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

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

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-10 18:03:38 +02:00
Patrick Colp 204a6ddfb3 loader/i386/linux: Update linux_kernel_params to match upstream
Update linux_kernel_params to match the v6.13.7 upstream version of boot_params.
Refactor most things out into structs, as the Linux kernel does.

edid_info should be a struct with "unsigned char dummy[128]" and efi_info should
be a struct as well, starting at 0x1c0. However, for backwards compatibility,
GRUB can have efi_systab at 0x1b8 and padding at 0x1bc (or padding at both spots).
This cuts into the end of edid_info. Make edid_info inline and only make it go
up to 0x1b8.

Signed-off-by: Patrick Colp <patrick.colp@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-04 21:57:05 +02:00
Lidong Chen 6b64f297e5 loader/xnu: Fix memory leak
In grub_xnu_load_kext_from_dir(), when the call to grub_device_open()
failed, it simply cleaned up previously allocated memory and returned
GRUB_ERR_NONE. However, it neglected to free ctx->newdirname which is
allocated before the call to grub_device_open().

Fixes: CID 473859

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-04 19:37:34 +02:00
Lidong Chen f94d257e8c fs/btrfs: Fix memory leaks
Fix memory leaks in grub_btrfs_extent_read() and grub_btrfs_dir().

Fixes: CID 473842
Fixes: CID 473871

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-04 19:35:51 +02:00
Lidong Chen 81146fb623 loader/i386/linux: Fix resource leak
In grub_cmd_initrd(), initrd_ctx is allocated before calling
grub_relocator_alloc_chunk_align(). When that function fails,
initrd_ctx should be freed before exiting grub_cmd_initrd().

Fixes: CID 473852

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-04 19:33:50 +02:00
Lidong Chen 1d00594475 lib/reloacator: Fix memory leaks
Fix memory leaks in grub_relocator_alloc_chunk_align().

Fixes: CID 473844

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-04 19:31:05 +02:00
Lidong Chen f3f1fcecdc disk/ldm: Fix memory leaks
Fix memory leaks in make_vg() with new helper functions, free_pv()
and free_lv(). Additionally, correct a check after allocating
comp->segments->nodes that mistakenly checked lv->segments->nodes
instead, likely due to a copy-paste error.

Fixes: CID 473878
Fixes: CID 473884
Fixes: CID 473889
Fixes: CID 473890

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-04-04 19:27:25 +02:00
Andrew Hamilton aae2ea619e fs/ntfs: Fix NULL pointer dereference and possible infinite loop
A regression was introduced recently as a part of the series of
filesystem related patches to address some CVEs found in GRUB.

This issue may cause either an infinite loop at startup when
accessing certain valid NTFS filesystems, or may cause a crash
due to a NULL pointer dereference on systems where NULL address
is invalid (such as may happen when calling grub-mount from
the operating system level).

Correct this issue by checking that at->attr_cur is within bounds
inside find_attr().

Fixes: https://savannah.gnu.org/bugs/?66855
Fixes: aff263187 (fs/ntfs: Fix out-of-bounds read)

Signed-off-by: B Horn <b@horn.uk>
Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
2025-03-26 15:33:02 +01:00
Nicolas Frayer 3b25e494d4 net/drivers/ieee1275/ofnet: Add missing grub_malloc()
The grub_malloc() has been inadvertently removed from the code after it
has been modified to use safe math functions.

Fixes: 4beeff8a (net: Use safe math macros to prevent overflows)

Signed-off-by: Nicolas Frayer <nfrayer@redhat.com>
Tested-by: Marta Lewandowska <mlewando@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 15:15:22 +01:00
Avnish Chouhan fee6081ec7 kern/ieee1275/init: Increase MIN_RMA size for CAS negotiation on PowerPC machines
Change RMA size from 512 MB to 768 MB which will result in more memory
at boot time for PowerPC. When vTPM, Secure Boot or FADump are enabled
on PowerPC the 512 MB RMA memory is not sufficient for boot. With this
512 MB RMA, GRUB runs out of memory and fails to boot the machine.
Sometimes even usage of CDROM requires more memory for installation and
along with the options mentioned above exhausts the boot memory which
results in boot failures. Increasing the RMA size will resolves multiple
out of memory issues observed on PowerPC machines.

Failure details (GRUB debug console dump):

  kern/ieee1275/init.c:550: mm requested region of size 8513000, flags 1
  kern/ieee1275/init.c:563: Cannot satisfy allocation and retain minimum runtime space
  kern/ieee1275/init.c:550: mm requested region of size 8513000, flags 0
  kern/ieee1275/init.c:563: Cannot satisfy allocation and retain minimum runtime space
  kern/file.c:215: Closing `/ppc/ppc64/initrd.img' ...
  kern/disk.c:297: Closing `ieee1275//vdevice/v-scsi@30000067/disk@8300000000000000'...
  kern/disk.c:311: Closing `ieee1275//vdevice/v-scsi@30000067/disk@8300000000000000' succeeded.
  kern/file.c:225: Closing `/ppc/ppc64/initrd.img' failed with 3.
  kern/file.c:148: Opening `/ppc/ppc64/initrd.img' succeeded.
  error: ../../grub-core/kern/mm.c:552:out of memory.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 14:56:59 +01:00
Stuart Hayes b66c6f9182 fs/zfs: Fix a number of memory leaks in ZFS code
Without this fix the GRUB failed to boot linux with "out of memory" after
trying to run a "search --fs-uuid..." on a system that has 7 ZFS pools
across about 80 drives.

Signed-off-by: Stuart Hayes <stuart.w.hayes@gmail.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 14:34:44 +01:00
Glenn Washburn 1d59f39b5f tests/util/grub-shell: Remove the work directory on successful run and debug is not on
This removes a lot of empty grub-shell working directories in the TMPDIR directory.

Signed-off-by: Thomas Schmitt <scdbackup@gmx.net>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Tested-by: Thomas Schmitt <scdbackup@gmx.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 14:30:56 +01:00
Thomas Schmitt e0116f3bd5 tests/grub_cmd_cryptomount: Remove temporary directories if successful and debug is not on
grub_cmd_cryptomount creates a directory per subtest. If a subtest is
successful and debugging is not on, the directory should be empty.
So, it can be deleted.

Signed-off-by: Thomas Schmitt <scdbackup@gmx.net>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Tested-by: Thomas Schmitt <scdbackup@gmx.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 14:29:21 +01:00
Glenn Washburn e6e2b73db8 tests/grub_cmd_cryptomount: Default TMPDIR to /tmp
This fixes behavior where grub_cmd_cryptomount temporary files, which are
some times not cleaned up, are left in the / directory. Set TMPDIR if your
system does not have /tmp or it can not be used for some reason.

Reported-by: Thomas Schmitt <scdbackup@gmx.net>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Tested-by: Thomas Schmitt <scdbackup@gmx.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 14:23:42 +01:00
Glenn Washburn 32b02bb92e tests/grub_cmd_cryptomount: Cleanup the cryptsetup script unless debug is enabled
This fixes an issue where the grub_cmd_cryptomount test leaves a file
with an ambiguous name in the / directory when TMPDIR is not set.

Reported-by: Thomas Schmitt <scdbackup@gmx.net>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Tested-by: Thomas Schmitt <scdbackup@gmx.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 14:22:29 +01:00
Glenn Washburn c188ca5d5e tests: Cleanup generated files on expected failure in grub_cmd_cryptomount
grub-shell-luks-tester only cleans up generated files when the test it
runs returns success. Sometimes tests are run that should fail. Add
a --xfail argument to grub-shell-luks-tester and pass it from
grub_cmd_cryptomount when invoking a test that is expected to fail.

Reported-by: Thomas Schmitt <scdbackup@gmx.net>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Tested-by: Thomas Schmitt <scdbackup@gmx.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 14:18:46 +01:00
Glenn Washburn 50320c093a tests/util/grub-shell-luks-tester: Add missing line to create RET variable in cleanup
Set the RET variable to the exit status of the script, as was assumed in
the cleanup() function.

Reported-by: Thomas Schmitt <scdbackup@gmx.net>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Tested-by: Thomas Schmitt <scdbackup@gmx.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 14:16:39 +01:00
Glenn Washburn bb6d3199b3 tests/util/grub-shell-luks-tester: Find cryptodisk by UUID
GRUB has the capability to search all the disks for a cryptodisk of a
given UUID. Use this instead of hardcoding which disk is the cryptodisk,
which can change when devices are added or removed, or potentially when
QEMU is upgraded. This can not be done for the detached header tests
because the header contains the UUID.

Also, capitalize comment lines for consistency.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 14:08:49 +01:00
Glenn Washburn 3fd163e453 tests/util/grub-shell: Default qemuopts to envvar $GRUB_QEMU_OPTS
Fix a regression where qemuopts was mistakenly defaulted to the empty
string. This prevents the sending of arbitrary QEMU options to tests,
which may be desirable for overriding the machine type. There was a
concern that allowing the tester to accept arbitrary options would add
headaches for another developer trying to diagnose why a test failed on
the testers machine because he could not be sure if any additional
options were passed to make the test fail. However, all the options are
recorded in the run.sh generated script, so this concern is unwarranted.

Fixes: 6d729ced70 (tests/util/grub-shell: Add $GRUB_QEMU_OPTS to run.sh to easily see unofficial QEMU arguments)

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-26 14:04:49 +01:00
Patrick Plenefisch ff7f553071 disk/lvm: Add informational messages in error cases of ignored features
Signed-off-by: Patrick Plenefisch <simonpatp@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:28:03 +01:00
Patrick Plenefisch a16b4304a2 disk/lvm: Add support for cachevol LV
Mark cachevol LV's as ignored features, which is true only if they are
configured as "writethrough". This patch does not let GRUB boot from
"writeback" cache-enabled LV's.

Signed-off-by: Patrick Plenefisch <simonpatp@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:27:54 +01:00
Patrick Plenefisch 9a37d61145 disk/lvm: Add support for integrity LV
The LV matching must be done after processing the ignored feature
indirections, as integrity volumes & caches may have several levels
of indirection that the segments must be shifted through.

Signed-off-by: Patrick Plenefisch <simonpatp@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:27:37 +01:00
Patrick Plenefisch 6c14b87d6f lvm: Match all LVM segments before validation
The PV matching must be completely finished before validating a volume,
otherwise referenced RAID stripes may not have PV data applied yet.

This change is required for integrity & cachevol support.

Signed-off-by: Patrick Plenefisch <simonpatp@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:48 +01:00
Patrick Plenefisch d34b9120e7 disk/lvm: Remove unused cache_pool
The cache_pool is never read or used, remove it.

Signed-off-by: Patrick Plenefisch <simonpatp@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:48 +01:00
Patrick Plenefisch 90848a1f7c disk/lvm: Make cache_lv more generic as ignored_feature_lv
This patch isn't necessary by itself, but when combined with subsequent
patches it enhances readability as ignored_features_lv is then used for
multiple types of extra LV's, not just cache LV's.

Signed-off-by: Patrick Plenefisch <simonpatp@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:48 +01:00
Glenn Washburn 488ac8bda9 commands/ls: Add directory header for dir args
Like the GNU ls, first print a line with the directory path before printing
files in the directory, which will not have a directory component, but only
if there is more than one argument.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:48 +01:00
Glenn Washburn 096bf59e4c commands/ls: Print full paths for file args
For arguments that are paths to files, print the full path of the file.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:48 +01:00
Glenn Washburn 90288fc48d commands/ls: Output path for single file arguments given with path
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:48 +01:00
Glenn Washburn 6337d84afa commands/ls: Show modification time for file paths
The modification time for paths to files was not being printed because
the grub_dirhook_info, which contains the mtime, was initialized to NULL.
Instead of calling print_file() directly, use fs->fs_dir() to call
print_file() with a properly filled in grub_dirhook_info. This has the
added benefit of reducing code complexity.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:48 +01:00
Glenn Washburn cbfb031b14 commands/ls: Merge print_files_long() and print_files() into print_file()
Simplify the code by removing logic around which file printer to call.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:47 +01:00
Glenn Washburn 112d2069cf commands/ls: Return proper GRUB_ERR_* for functions returning type grub_err_t
Also, remove unused code.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:47 +01:00
Glenn Washburn da9740cd52 commands/acpi: Use options enum to index command options
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:47 +01:00
Andrew Hamilton 1acf11fe4c docs: Capture additional commands restricted by lockdown
Update documentation to capture that all memrw commands, the minicmd
dump command, and raw memory dumping via hexdump are restricted when
lockdown is enabled. This aligns to recent GRUB code updates.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:47 +01:00
Andrew Hamilton 6a168afd32 docs: Document restricted filesystems in lockdown
Document which filesystems are not allowed when lockdown
is enabled to align to recent GRUB changes.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:47 +01:00
Vladimir Serbinenko be0ae9583e loader/i386/bsd: Fix type passed for the kernel
FreeBSD loader always passes "elf kernel". We currently pass "elf64 kernel"
when loading 64-bit kernel. The -CURRENT, HEAD, kernel accepts only
"elf kernel". Older kernel accepts either.

Tested with FreeBSD and DragonFlyBSD.

Reference: https://cgit.freebsd.org/src/commit/?id=b72ae900d4348118829fe04abdc11b620930c30f

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:47 +01:00
Vladimir Serbinenko ee27f07a65 kern/partition: Unbreak support for nested partitions
When using syntax "hd0,gtp3,dfly1" then ptr points to trailing part, ",dfly1".
So, it's improper to consider it as an invalid partition.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:47 +01:00
Andrew Hamilton cb639acea0 lib/tss2/tss2_structs.h: Fix clang build - remove duplicate typedef
grub-core/lib/tss2/tss2_structs.h contains a duplicate typedef as follows:
  typedef TPMS_SCHEME_HASH_t TPMS_SCHEME_KDF2_t;

This causes a build failure when compiling with clang. Remove the
duplicate typedef which allows successfully building GRUB with clang.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 21:24:47 +01:00
Yuri Zaporozhets 696e35b7ff include/grub/mm.h: Remove duplicate inclusion of grub/err.h
The header is included twice. Fix that.

Signed-off-by: Yuri Zaporozhets <yuriz@qrv-systems.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 12:16:56 +01:00
James Le Cuirot 187338f1ac script/execute: Don't let trailing blank lines determine the return code
The grub_script_execute_sourcecode() parses and executes code one line
at a time, updating the return code each time because only the last line
determines the final status. However, trailing new lines were also
executed, masking any failure on the previous line. Fix this by only
trying to execute the command when there is actually one present.

This has presumably never been noticed because this code is not used by
regular functions, only in special cases like eval and menu entries. The
latter generally don't return at all, having booted an OS. When failing
to boot, upstream GRUB triggers the fallback mechanism regardless of the
return code.

We noticed the problem while using Red Hat's patches, which change this
behaviour to take account of the return code. In that case, a failure
takes you back to the menu rather than triggering a fallback.

Signed-off-by: James Le Cuirot <jlecuirot@microsoft.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 12:11:09 +01:00
Glenn Washburn ff173a1c0c gitignore: Ignore generated files from libtasn
The commit 504058e8 (libtasn1: Compile into asn1 module) generates files
into the grub-core/lib/libtasn1-grub directory and commit 99cda678
(asn1_test: Test module for libtasn1) generates files into the
grub-core/tests/asn1/tests directory. Ignore these directories as they
are not under revision control.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 12:05:38 +01:00
Pascal Hambourg fbcc388917 util/grub.d/30_os-prober.in: Conditionally show or hide chain and efi menu entries
On systems which support multiple boot platforms such as BIOS and
EFI, it makes no sense to show menu entries which are not supported
by the current boot platform. Menu entries generated from os-prober
"chain" boot type use boot sector chainloading which is supported
on PC BIOS platform only.

Show "chain" menu entries only if boot platform is PC BIOS.
Show "efi" menu entries only if boot platform is EFI.

This is aimed to allow os-prober to report both EFI and PC BIOS
boot loaders regardless of the current boot mode on x86 systems
which support both EFI and legacy BIOS boot, in order to generate
a config file which can be used with either BIOS or EFI boot.

Signed-off-by: Pascal Hambourg <pascal@plouf.fr.eu.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-03-05 11:53:33 +01:00
Pascal Hambourg 56ccc5ed56 util/grub.d/30_os-prober.in: Fix GRUB_OS_PROBER_SKIP_LIST for non-EFI
GRUB documentation states:

  GRUB_OS_PROBER_SKIP_LIST
    List of space-separated FS UUIDs of filesystems to be ignored from
    os-prober output. For efi chainloaders it’s <UUID>@<EFI FILE>

But the actual behaviour does not match this description.

  GRUB_OS_PROBER_SKIP_LIST="<UUID>"

does nothing. In order to skip non-EFI bootloaders, you must set

  GRUB_OS_PROBER_SKIP_LIST="<UUID>@<DEVICE>"

which is both absurd, <UUID> and <DEVICE> are redundant, and wrong,
<DEVICE> such as /dev/sd* may not be persistent across boots.

Also, any non-word character is accepted as a separator, including "-"
and "@" which may be present in UUIDs. This can cause false positives
because of partial UUID match.

This patch fixes these flaws while retaining some backward compatibility
with previous behaviour which may be expected by existing setups:
  - also accept <UUID>@/dev/* (with warning) for non-EFI bootloaders,
  - also accept comma and semicolon as separator.

Fixes: 55e706c9 (Add GRUB_OS_PROBER_SKIP_LIST to selectively skipping systems)

Signed-off-by: Pascal Hambourg <pascal@plouf.fr.eu.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 20:44:36 +01:00
Glenn Washburn 01f064064c docs: Do not reference non-existent --dumb option
This appears to be a relic from GRUB legacy that used a --dumb option for
its terminal command. The proper way to do this in GRUB2 is to set the
terminal to "dumb" via the terminfo command.

Fixes: https://savannah.gnu.org/bugs/?66302

Reported-by: Jernej Jakob <jernej.jakob+savgnu@gmail.com>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 20:44:36 +01:00
Glenn Washburn 3f440b5a53 docs: Replace @lbracechar{} and @rbracechar{} with @{ and @}
Support for @lbracechar{} and @rbracechar{} was added in GNU Texinfo 5.0
but many older systems may have versions lower than this. Use @{ and @}
to support a wider range of GNU Texinfo versions.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 20:44:36 +01:00
Egor Ignatov f209887381 fs/xfs: Fix grub_xfs_iterate_dir() return value in case of failure
Commit ef7850c757 (fs/xfs: Fix issues found while fuzzing the XFS
filesystem) introduced multiple boundary checks in grub_xfs_iterate_dir()
but handled the error incorrectly returning error code instead of 0.
Fix it. Also change the error message so that it doesn't match the
message in grub_xfs_read_inode().

Fixes: ef7850c757 (fs/xfs: Fix issues found while fuzzing the XFS filesystem)

Signed-off-by: Egor Ignatov <egori@altlinux.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 20:44:36 +01:00
Darrick J. Wong 1ed2628b56 fs/xfs: Add new superblock features added in Linux 6.12/6.13
The Linux port of XFS added a few new features in 2024. The existing
GRUB driver doesn't attempt to read or write any of the new metadata,
so, all three can be added to the incompat allowlist.

On the occasion align XFS_SB_FEAT_INCOMPAT_NREXT64 value.

Signed-off-by: Darrick J. Wong <djwong@kernel.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 20:44:36 +01:00
Michael Chang 348cd416a3 fs/ext2: Rework out-of-bounds read for inline and external extents
Previously, the number of extent entries was not properly capped based
on the actual available space. This could lead to insufficient reads for
external extents since the computation was based solely on the inline
extent layout.

In this patch, when processing the extent header we determine whether
the header is stored inline, i.e. at inode->blocks.dir_blocks, or in an
external extent block. We then clamp the number of entries accordingly
(using max_inline_ext for inline extents and max_external_ext for
external extent blocks).

This change ensures that only the valid number of extent entries is
processed preventing out-of-bound reads and potential filesystem
corruption.

Fixes: 7e2f750f0a (fs/ext2: Fix out-of-bounds read for inline extents)

Signed-off-by: Michael Chang <mchang@suse.com>
Tested-by: Christian Hesse <mail@eworm.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 20:44:36 +01:00
Leo Sandoval c730eddd2a disk/ahci: Remove conditional operator for endtime
The conditional makes no sense when the two possible expressions have
the same value, so, remove it (perhaps the compiler does it for us but
better to remove it). This change makes spinup argument unused. So, drop
it as well.

Signed-off-by: Leo Sandoval <lsandova@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 20:39:24 +01:00
Benjamin Herrenschmidt f0a08324d0 term/ns8250-spcr: Return if redirection is disabled
The Microsoft spec for SPCR says "The base address of the Serial Port
register set described using the ACPI Generic Address Structure, or
0 if console redirection is disabled". So, return early if redirection
is disabled (base address = 0). If this check is not done we may get
invalid ports on machines with redirection disabled and boot may hang
when reading the grub.cfg file.

Signed-off-by: Benjamin Herrenschmidt <benh@kernel.crashing.org>
Reviewed-by: Leo Sandoval <lsandova@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 19:34:57 +01:00
Lukas Fink 7161e2437d commands/file: Fix NULL dereference in the knetbsd tests
The pointer returned by grub_elf_file() is not checked to verify it is
not NULL before use. A NULL pointer may be returned when the given file
does not have a valid ELF header.

Fixes: https://savannah.gnu.org/bugs/?61960

Signed-off-by: Glenn Washburn <development@efficientek.com>
Signed-off-by: Lukas Fink <lukas.fink1@gmail.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 19:34:57 +01:00
Heinrich Schuchardt 11b9c2dd0d gdb_helper: Typo hueristic
%s/hueristic/heuristic/

Signed-off-by: Heinrich Schuchardt <heinrich.schuchardt@canonical.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 19:34:57 +01:00
Ruihan Li 224aefd057 kern/efi/mm: Reset grub_mm_add_region_fn after ExitBootServices() call
The EFI Boot Services can be used after ExitBootServices() call because
the GRUB code still may allocate memory.

An example call stack is:

  grub_multiboot_boot
    grub_multiboot2_make_mbi
      grub_efi_finish_boot_services
        b->exit_boot_services
    normal_boot
      grub_relocator32_boot
        grub_relocator_alloc_chunk_align_safe
          grub_relocator_alloc_chunk_align
            grub_malloc
              grub_memalign
                grub_mm_add_region_fn
                [= grub_efi_mm_add_regions]
                  grub_efi_allocate_any_pages
                    grub_efi_allocate_pages_real
                      b->allocate_pages

This can lead to confusing errors. After ExitBootServices() call
b->allocate_pages may point to the NULL address resulting in something like:

  !!!! X64 Exception Type - 01(#DB - Debug)  CPU Apic ID - 00000000 !!!!
  RIP  - 000000000000201F, CS  - 0000000000000038, RFLAGS - 0000000000200002
  RAX  - 000000007F9EE010, RCX - 0000000000000001, RDX - 0000000000000002
  RBX  - 0000000000000006, RSP - 00000000001CFBEC, RBP - 0000000000000000
  RSI  - 0000000000000000, RDI - 00000000FFFFFFFF
  R8   - 0000000000000006, R9  - 000000007FEDFFB8, R10 - 0000000000000000
  R11  - 0000000000000475, R12 - 0000000000000001, R13 - 0000000000000002
  R14  - 00000000FFFFFFFF, R15 - 000000007E432C08
  DS   - 0000000000000030, ES  - 0000000000000030, FS  - 0000000000000030
  GS   - 0000000000000030, SS  - 0000000000000030
  CR0  - 0000000080010033, CR2 - 0000000000000000, CR3 - 000000007FC01000
  CR4  - 0000000000000668, CR8 - 0000000000000000
  DR0  - 0000000000000000, DR1 - 0000000000000000, DR2 - 0000000000000000
  DR3  - 0000000000000000, DR6 - 00000000FFFF0FF0, DR7 - 0000000000000400
  GDTR - 000000007F9DE000 0000000000000047, LDTR - 0000000000000000
  IDTR - 000000007F470018 0000000000000FFF,   TR - 0000000000000000
  FXSAVE_STATE - 00000000001CF840

Ideally we would like to avoid all memory allocations after exiting EFI
Boot Services altogether but that requires significant code changes. This
patch adds a simple workaround that resets grub_mm_add_region_fn to NULL
after ExitBootServices() call, so:

  - Memory allocations have a better chance of succeeding because grub_memalign()
    will try to reclaim the disk cache if it sees a NULL in grub_mm_add_region_fn.

  - At worst it will fail to allocate memory but it will explicitly tell users
    that it's out of memory, which is still much better than the current
    situation where it fails in a fairly random way and triggers a CPU fault.

Signed-off-by: Ruihan Li <lrh2000@pku.edu.cn>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 19:34:57 +01:00
Duan Yayong 531750f7bf i386/tsc: The GRUB menu gets stuck due to unserialized rdtsc
This patch is used to fix GRUB menu gets stuck in server AC
poweron/poweroff stress test of x86_64, which is reproduced with
1/200 ratio. The root cause analysis as below:

Q: What's the code logic?

A: The grub_tsc_init() function will init tsc by setting grub_tsc_rate,
   which call stack is:

     grub_tsc_init() -> grub_tsc_calibrate_from_pmtimer() -> grub_divmod64()

   Among, grub_divmod64() function needs tsc_diff as the second parameter.
   In grub_pmtimer_wait_count_tsc(), we will call grub_get_tsc() function
   to get time stamp counter value to assign to start_tsc variable, and
   get into while (1) loop space to get end_tsc variable value with same
   function, after 3580 ticks, return "end_tsc - start_tsc". Actually,
   rdtsc instruction will be called in grub_get_tsc, but rdtsc instruction
   is not reliable (for the reason see the next question), which will cause
   tsc_diff to be a very big number larger than (1UL << 32) or a negative
   number, so that grub_tsc_rate will be zero. When run_menu() function is
   startup, and calls grub_tsc_get_time_ms() function to get current time
   to check if timeout time reach, at this time, grub_tsc_get_time_ms()
   function will return zero due to zero grub_tsc_rate variable, then GRUB
   menu gets stuck...

Q: What's the difference between rdtsc and rdtscp instructions in x86_64
   architecture? Here is more explanations from Intel® 64 and IA-32
   Architectures Software Developer’s Manual Volume 2B (December 2024):
   https://cdrdv2.intel.com/v1/dl/getContent/671241

A: In page 4-558 -> RDTSC—Read Time-Stamp Counter:
   The RDTSC instruction is not a serializing instruction. It does not
   necessarily wait until all previous instructions have been executed
   before reading the counter. Similarly, subsequent instructions may
   begin execution before the read operation is performed. The following
   items may guide software seeking to order executions of RDTSC:
     - If software requires RDTSC to be executed only after all previous
       instructions have executed and all previous loads are globally
       visible, it can execute LFENCE immediately before RDTSC.
     - If software requires RDTSC to be executed only after all previous
       instructions have executed and all previous loads and stores are
       globally visible, it can execute the sequence MFENCE;LFENCE
       immediately before RDTSC.
     - If software requires RDTSC to be executed prior to execution of any
       subsequent instruction (including any memory accesses), it can execute
       the sequence LFENCE immediately after RDTSC.

A: In page 4-560 -> RDTSCP—Read Time-Stamp Counter and Processor ID:
   The RDTSCP instruction is not a serializing instruction, but it does wait
   until all previous instructions have executed and all previous loads are
   globally visible. But it does not wait for previous stores to be globally
   visible, and subsequent instructions may begin execution before the read
   operation is performed. The following items may guide software seeking to
   order executions of RDTSCP:
     - If software requires RDTSCP to be executed only after all previous
       stores are globally visible, it can execute MFENCE immediately before
       RDTSCP.
     - If software requires RDTSCP to be executed prior to execution of any
       subsequent instruction (including any memory accesses), it can execute
       LFENCE immediately after RDTSCP.

Q: Why there is a cpuid serializing instruction before rdtsc instruction,
   but "grub_get_tsc" still cannot work as expect?

A: From Intel® 64 and IA-32 Architectures Software Developer's Manual
   Volume 2A: Instruction Set Reference, A-L (December 2024):
   https://cdrdv2.intel.com/v1/dl/getContent/671199

   In page 3-222 -> CPUID—CPU Identification:
   CPUID can be executed at any privilege level to serialize instruction execution.
   Serializing instruction execution guarantees that any modifications to flags,
   registers, and memory for previous instructions are completed before
   the next instruction is fetched and executed.

   So we only kept the instruction rdtsc and its previous instruction in order
   currently. But it is still out-of-order possibility between rdtsc instruction
   and its subsequent instruction.

Q: Why do we do this fix?

A: In the one hand, add cpuid instruction after rdtsc instruction to make sure
   rdtsc instruction to be executed prior to execution of any subsequent instruction,
   about serializing execution that all previous instructions have been executed
   before rdtsc, there is a cpuid usage in original code. In the other hand, using
   cpuid instruction rather than lfence can make sure a forward compatibility for
   previous HW.

   Base this fix, we did 1500 cycles power on/off stress test, and did not reproduce
   this issue again.

Fixes: https://savannah.gnu.org/bugs/?66257

Signed-off-by: Duan Yayong <duanyayong@bytedance.com>
Signed-off-by: Li Yongqiang <liyongqiang@huaqin.com>
Signed-off-by: Sun Ming <simon.sun@huaqin.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 19:25:38 +01:00
Duan Yayong f2a1f66e72 kern/i386/tsc_pmtimer: The GRUB menu gets stuck due to failed calibration
The grub_divmod64() may return 0 but grub_tsc_calibrate_from_pmtimer()
still returns 1 saying calibration succeeded. Of course it is not true.
So, return 0 when grub_divmod64() returns 0. This way other calibration
functions can be called subsequently.

Signed-off-by: Duan Yayong <duanyayong@bytedance.com>
Signed-off-by: Li Yongqiang <liyongqiang@huaqin.com>
Signed-off-by: Sun Ming <simon.sun@huaqin.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 15:51:04 +01:00
Sergii Dmytruk 13f005ed83 loader/i386/linux: Fix cleanup if kernel doesn't support 64-bit addressing
Simply returning from grub_cmd_linux() doesn't free "file" resource nor
calls grub_dl_ref(my_mod). Jump to "fail" label for proper cleanup like
other error checks do.

Signed-off-by: Sergii Dmytruk <sergii.dmytruk@3mdeb.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-26 15:31:59 +01:00
Alec Brown 4dc6166571 loader/i386/bsd: Use safe math to avoid underflow
The operation kern_end - kern_start may underflow when we input it into
grub_relocator_alloc_chunk_addr() call. To avoid this we can use safe
math for this subtraction.

Fixes: CID 73845

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:58 +01:00
Alec Brown 490a6ab71c loader/i386/linux: Cast left shift to grub_uint32_t
The Coverity complains that we might overflow into a negative value when
setting linux_params.kernel_alignment to (1 << align). We can remedy
this by casting it to grub_uint32_t.

Fixes: CID 473876

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:58 +01:00
Lidong Chen a8d6b06331 kern/misc: Add sanity check after grub_strtoul() call
When the format string, fmt0, includes a positional argument
grub_strtoul() or grub_strtoull() is called to extract the argument
position. However, the returned argument position isn't fully validated.
If the format is something like "%0$x" then these functions return
0 which leads to an underflow in the calculation of the args index, curn.
The fix is to add a check to ensure the extracted argument position is
greater than 0 before computing curn. Additionally, replace one
grub_strtoull() with grub_strtoul() and change curn type to make code
more correct.

Fixes: CID 473841

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:58 +01:00
Lidong Chen 8e6e87e792 kern/partition: Add sanity check after grub_strtoul() call
The current code incorrectly assumes that both the input and the values
returned by grub_strtoul() are always valid which can lead to potential
errors. This fix ensures proper validation to prevent any unintended issues.

Fixes: CID 473843

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:58 +01:00
Alec Brown 5b36a5210e normal/menu: Use safe math to avoid an integer overflow
The Coverity indicates that the variable current_entry might overflow.
To prevent this use safe math when adding GRUB_MENU_PAGE_SIZE to current_entry.

On the occasion fix limiting condition which was broken.

Fixes: CID 473853

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:58 +01:00
Alec Brown 9907d9c272 bus/usb/ehci: Define GRUB_EHCI_TOGGLE as grub_uint32_t
The Coverity indicates that GRUB_EHCI_TOGGLE is an int that contains
a negative value and we are using it for the variable token which is
grub_uint32_t. To remedy this we can cast the definition to grub_uint32_t.

Fixes: CID 473851

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:58 +01:00
Lidong Chen f8795cde21 misc: Ensure consistent overflow error messages
Update the overflow error messages to make them consistent
across the GRUB code.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:58 +01:00
Lidong Chen 66733f7c7d osdep/unix/getroot: Fix potential underflow
The entry_len is initialized in grub_find_root_devices_from_mountinfo()
to 0 before the while loop iterates through /proc/self/mountinfo. If the
file is empty or contains only invalid entries entry_len remains
0 causing entry_len - 1 in the subsequent for loop initialization
to underflow. To prevent this add a check to ensure entry_len > 0 before
entering the for loop.

Fixes: CID 473877

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
2025-02-13 15:45:58 +01:00
Lidong Chen d13b6e8ebd script/execute: Fix potential underflow and NULL dereference
The result is initialized to 0 in grub_script_arglist_to_argv().
If the for loop condition is not met both result.args and result.argc
remain 0 causing result.argc - 1 to underflow and/or result.args NULL
dereference. Fix the issues by adding relevant checks.

Fixes: CID 473880

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Alec Brown e3c578a56f fs/sfs: Check if allocated memory is NULL
When using grub_zalloc(), if we are out of memory, this function can fail.
After allocating memory, we should check if grub_zalloc() returns NULL.
If so, we should handle this error.

Fixes: CID 473856

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Alec Brown 1c06ec9005 net: Check if returned pointer for allocated memory is NULL
When using grub_malloc(), the function can fail if we are out of memory.
After allocating memory we should check if this function returned NULL
and handle this error if it did.

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Lidong Chen dee2c14fd6 net: Prevent overflows when allocating memory for arrays
Use grub_calloc() when allocating memory for arrays to ensure proper
overflow checks are in place.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Lidong Chen 4beeff8a31 net: Use safe math macros to prevent overflows
Replace direct arithmetic operations with macros from include/grub/safemath.h
to prevent potential overflow issues when calculating the memory sizes.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Lidong Chen dd6a4c8d10 fs/zfs: Add missing NULL check after grub_strdup() call
Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Lidong Chen 13065f69da fs/zfs: Check if returned pointer for allocated memory is NULL
When using grub_malloc() or grub_zalloc(), these functions can fail if
we are out of memory. After allocating memory we should check if these
functions returned NULL and handle this error if they did.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Lidong Chen 7f38e32c7e fs/zfs: Prevent overflows when allocating memory for arrays
Use grub_calloc() when allocating memory for arrays to ensure proper
overflow checks are in place.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Lidong Chen 88e491a0f7 fs/zfs: Use safe math macros to prevent overflows
Replace direct arithmetic operations with macros from include/grub/safemath.h
to prevent potential overflow issues when calculating the memory sizes.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Lidong Chen cde9f7f338 fs: Prevent overflows when assigning returned values from read_number()
The direct assignment of the unsigned long long value returned by
read_number() can potentially lead to an overflow on a 32-bit systems.
The fix replaces the direct assignments with calls to grub_cast()
which detects the overflows and safely assigns the values if no
overflow is detected.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Lidong Chen 84bc0a9a68 fs: Prevent overflows when allocating memory for arrays
Use grub_calloc() when allocating memory for arrays to ensure proper
overflow checks are in place.

The HFS+ and squash4 security vulnerabilities were reported by
Jonathan Bar Or <jonathanbaror@gmail.com>.

Fixes: CVE-2025-0678
Fixes: CVE-2025-1125

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Lidong Chen 6608163b08 fs: Use safe math macros to prevent overflows
Replace direct arithmetic operations with macros from include/grub/safemath.h
to prevent potential overflow issues when calculating the memory sizes.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:57 +01:00
Alec Brown fbaddcca54 disk/ieee1275/ofdisk: Call grub_ieee1275_close() when grub_malloc() fails
In the dev_iterate() function a handle is opened but isn't closed when
grub_malloc() returns NULL. We should fix this by closing it on error.

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
Alec Brown 33bd6b5ac5 disk: Check if returned pointer for allocated memory is NULL
When using grub_malloc(), grub_zalloc() or grub_calloc(), these functions can
fail if we are out of memory. After allocating memory we should check if these
functions returned NULL and handle this error if they did.

On the occasion make a NULL check in ATA code more obvious.

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
Alec Brown d8151f9833 disk: Prevent overflows when allocating memory for arrays
Use grub_calloc() when allocating memory for arrays to ensure proper
overflow checks are in place.

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
Alec Brown c407724dad disk: Use safe math macros to prevent overflows
Replace direct arithmetic operations with macros from include/grub/safemath.h
to prevent potential overflow issues when calculating the memory sizes.

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
Daniel Axtens c4bc55da28 fs: Disable many filesystems under lockdown
The idea is to permit the following: btrfs, cpio, exfat, ext, f2fs, fat,
hfsplus, iso9660, squash4, tar, xfs and zfs.

The JFS, ReiserFS, romfs, UDF and UFS security vulnerabilities were
reported by Jonathan Bar Or <jonathanbaror@gmail.com>.

Fixes: CVE-2025-0677
Fixes: CVE-2025-0684
Fixes: CVE-2025-0685
Fixes: CVE-2025-0686
Fixes: CVE-2025-0689

Suggested-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
Daniel Axtens 26db660503 fs/bfs: Disable under lockdown
The BFS is not fuzz-clean. Don't allow it to be loaded under lockdown.
This will also disable the AFS.

Fixes: CVE-2024-45778
Fixes: CVE-2024-45779

Reported-by: Nils Langius <nils@langius.de>
Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
B Horn 5f31164aed commands/hexdump: Disable memory reading in lockdown mode
Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
B Horn 340e4d058f commands/memrw: Disable memory reading in lockdown mode
With the rest of module being blocked in lockdown mode it does not make
a lot of sense to leave memory reading enabled. This also goes in par
with disabling the dump command.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
B Horn 34824806ac commands/minicmd: Block the dump command in lockdown mode
The dump enables a user to read memory which should not be possible
in lockdown mode.

Fixes: CVE-2025-1118

Reported-by: B Horn <b@horn.uk>
Reported-by: Jonathan Bar Or <jonathanbaror@gmail.com>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
Lidong Chen c68b7d2362 commands/test: Stack overflow due to unlimited recursion depth
The test_parse() evaluates test expression recursively. Due to lack of
recursion depth check a specially crafted expression may cause a stack
overflow. The recursion is only triggered by the parentheses usage and
it can be unlimited. However, sensible expressions are unlikely to
contain more than a few parentheses. So, this patch limits the recursion
depth to 100, which should be sufficient.

Reported-by: Nils Langius <nils@langius.de>
Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
Jonathan Bar Or dad8f50297 commands/read: Fix an integer overflow when supplying more than 2^31 characters
The grub_getline() function currently has a signed integer variable "i"
that can be overflown when user supplies more than 2^31 characters.
It results in a memory corruption of the allocated line buffer as well
as supplying large negative values to grub_realloc().

Fixes: CVE-2025-0690

Reported-by: Jonathan Bar Or <jonathanbaror@gmail.com>
Signed-off-by: Jonathan Bar Or <jonathanbaror@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:56 +01:00
Lidong Chen b970a5ed96 gettext: Integer overflow leads to heap OOB write
The size calculation of the translation buffer in
grub_gettext_getstr_from_position() may overflow
to 0 leading to heap OOB write. This patch fixes
the issue by using grub_add() and checking for
an overflow.

Fixes: CVE-2024-45777

Reported-by: Nils Langius <nils@langius.de>
Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-02-13 15:45:56 +01:00
Lidong Chen 09bd6eb58b gettext: Integer overflow leads to heap OOB write or read
Calculation of ctx->grub_gettext_msg_list size in grub_mofile_open() may
overflow leading to subsequent OOB write or read. This patch fixes the
issue by replacing grub_zalloc() and explicit multiplication with
grub_calloc() which does the same thing in safe manner.

Fixes: CVE-2024-45776

Reported-by: Nils Langius <nils@langius.de>
Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-02-13 15:45:55 +01:00
B Horn 7580addfc8 gettext: Remove variables hooks on module unload
The gettext module does not entirely cleanup after itself in
its GRUB_MOD_FINI() leaving a few variables hooks in place.
It is not possible to unload gettext module because normal
module depends on it. Though fix the issues for completeness.

Fixes: CVE-2025-0622

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:55 +01:00
B Horn 9c16197734 normal: Remove variables hooks on module unload
The normal module does not entirely cleanup after itself in
its GRUB_MOD_FINI() leaving a few variables hooks in place.
It is not possible to unload normal module now but fix the
issues for completeness.

On the occasion replace 0s with NULLs for "pager" variable
hooks unregister.

Fixes: CVE-2025-0622

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:55 +01:00
B Horn 2123c5bca7 commands/pgp: Unregister the "check_signatures" hooks on module unload
If the hooks are not removed they can be called after the module has
been unloaded leading to an use-after-free.

Fixes: CVE-2025-0622

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:55 +01:00
B Horn 0bf56bce47 commands/ls: Fix NULL dereference
The grub_strrchr() may return NULL when the dirname do not contain "/".
This can happen on broken filesystems.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:55 +01:00
Lidong Chen 05be856a8c commands/extcmd: Missing check for failed allocation
The grub_extcmd_dispatcher() calls grub_arg_list_alloc() to allocate
a grub_arg_list struct but it does not verify the allocation was successful.
In case of failed allocation the NULL state pointer can be accessed in
parse_option() through grub_arg_parse() which may lead to a security issue.

Fixes: CVE-2024-45775

Reported-by: Nils Langius <nils@langius.de>
Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-02-13 15:45:55 +01:00
B Horn 98ad84328d kern/dl: Check for the SHF_INFO_LINK flag in grub_dl_relocate_symbols()
The grub_dl_relocate_symbols() iterates through the sections in
an ELF looking for relocation sections. According to the spec [1]
the SHF_INFO_LINK flag should be set if the sh_info field is meant
to be a section index.

[1] https://refspecs.linuxbase.org/elf/gabi4+/ch4.sheader.html

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:55 +01:00
B Horn d72208423d kern/dl: Use correct segment in grub_dl_set_mem_attrs()
The previous code would never actually call grub_update_mem_attrs()
as sh_info will always be zero for the sections that exist in memory.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:55 +01:00
B Horn 500e5fdd82 kern/dl: Fix for an integer overflow in grub_dl_ref()
It was possible to overflow the value of mod->ref_count, a signed
integer, by repeatedly invoking insmod on an already loaded module.
This led to a use-after-free. As once ref_count was overflowed it became
possible to unload the module while there was still references to it.

This resolves the issue by using grub_add() to check if the ref_count
will overflow and then stops further increments. Further changes were
also made to grub_dl_unref() to check for the underflow condition and
the reference count was changed to an unsigned 64-bit integer.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:55 +01:00
Daniel Axtens 2c34af908e video/readers/jpeg: Do not permit duplicate SOF0 markers in JPEG
Otherwise a subsequent header could change the height and width
allowing future OOB writes.

Fixes: CVE-2024-45774

Reported-by: Nils Langius <nils@langius.de>
Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:55 +01:00
B Horn 0707accab1 net/tftp: Fix stack buffer overflow in tftp_open()
An overly long filename can be passed to tftp_open() which would cause
grub_normalize_filename() to write out of bounds.

Fixed by adding an extra argument to grub_normalize_filename() for the
space available, making it act closer to a strlcpy(). As several fixed
strings are strcpy()'d after into the same buffer, their total length is
checked to see if they exceed the remaining space in the buffer. If so,
return an error.

On the occasion simplify code a bit by removing unneeded rrqlen zeroing.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:45:55 +01:00
B Horn 5eef881528 net: Fix OOB write in grub_net_search_config_file()
The function included a call to grub_strcpy() which copied data from an
environment variable to a buffer allocated in grub_cmd_normal(). The
grub_cmd_normal() didn't consider the length of the environment variable.
So, the copy operation could exceed the allocation and lead to an OOB
write. Fix the issue by replacing grub_strcpy() with grub_strlcpy() and
pass the underlying buffers size to the grub_net_search_config_file().

Fixes: CVE-2025-0624

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-02-13 15:44:58 +01:00
B Horn aa8b4d7fac net: Remove variables hooks when interface is unregisted
The grub_net_network_level_interface_unregister(), previously
implemented in a header, did not remove the variables hooks that
were registered in grub_net_network_level_interface_register().
Fix this by implementing the same logic used to register the
variables and move the function into the grub-core/net/net.c.

Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:48 +01:00
B Horn a1dd8e59da net: Unregister net_default_ip and net_default_mac variables hooks on unload
The net module is a dependency of normal. So, it shouldn't be possible
to unload the net. Though unregister variables hooks as a precaution.
It also gets in line with unregistering the other net module hooks.

Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:48 +01:00
B Horn d8a937ccae script/execute: Limit the recursion depth
If unbounded recursion is allowed it becomes possible to collide the
stack with the heap. As UEFI firmware often lacks guard pages this
becomes an exploitable issue as it is possible in some cases to do
a controlled overwrite of a section of this heap region with
arbitrary data.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:47 +01:00
B Horn 8a7103fddf kern/partition: Limit recursion in part_iterate()
The part_iterate() is used by grub_partition_iterate() as a callback in
the partition iterate functions. However, part_iterate() may also call
the partition iterate functions which may lead to recursion. Fix potential
issue by limiting the recursion depth.

Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:47 +01:00
B Horn 18212f0648 kern/disk: Limit recursion depth
The grub_disk_read() may trigger other disk reads, e.g. via loopbacks.
This may lead to very deep recursion which can corrupt the heap. So, fix
the issue by limiting reads depth.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:47 +01:00
B Horn 67f70f70a3 disk/loopback: Reference tracking for the loopback
It was possible to delete a loopback while there were still references
to it. This led to an exploitable use-after-free.

Fixed by implementing a reference counting in the grub_loopback struct.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:47 +01:00
Michael Chang 13febd78db disk/cryptodisk: Require authentication after TPM unlock for CLI access
The GRUB may use TPM to verify the integrity of boot components and the
result can determine whether a previously sealed key can be released. If
everything checks out, showing nothing has been tampered with, the key
is released and GRUB unlocks the encrypted root partition for the next
stage of booting.

However, the liberal Command Line Interface (CLI) can be misused by
anyone in this case to access files in the encrypted partition one way
or another. Despite efforts to keep the CLI secure by preventing utility
command output from leaking file content, many techniques in the wild
could still be used to exploit the CLI, enabling attacks or learning
methods to attack. It's nearly impossible to account for all scenarios
where a hack could be applied.

Therefore, to mitigate potential misuse of the CLI after the root device
has been successfully unlocked via TPM, the user should be required to
authenticate using the LUKS password. This added layer of security
ensures that only authorized users can access the CLI reducing the risk
of exploitation or unauthorized access to the encrypted partition.

Fixes: CVE-2024-49504

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:47 +01:00
B Horn 16f196874f kern/file: Implement filesystem reference counting
The grub_file_open() and grub_file_close() should be the only places
that allow a reference to a filesystem to stay open. So, add grub_dl_t
to grub_fs_t and set this in the GRUB_MOD_INIT() for each filesystem to
avoid issues when filesystems forget to do it themselves or do not track
their own references, e.g. squash4.

The fs_label(), fs_uuid(), fs_mtime() and fs_read() should all ref and
unref in the same function but it is essentially redundant in GRUB
single threaded model.

Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:47 +01:00
B Horn a791068729 kern/file: Ensure file->data is set
This is to avoid a generic issue were some filesystems would not set
data and also not set a grub_errno. This meant it was possible for many
filesystems to grub_dl_unref() themselves multiple times resulting in
it being possible to unload the filesystems while there were still
references to them, e.g., via a loopback.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:47 +01:00
B Horn d1d6b7ea58 fs/xfs: Ensuring failing to mount sets a grub_errno
It was previously possible for grub_xfs_mount() to return NULL without
setting grub_errno if the XFS version was invalid. This resulted in it
being possible for grub_dl_unref() to be called twice allowing the XFS
module to be unloaded while there were still references to it.

Fixing this problem in general by ensuring a grub_errno is set if the
fail label is reached.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:47 +01:00
Michael Chang 6ccc77b59d fs/xfs: Fix out-of-bounds read
The number of records in the root key array read from disk was not being
validated against the size of the root node. This could lead to an
out-of-bounds read.

This patch adds a check to ensure that the number of records in the root
key array does not exceed the expected size of a root node read from
disk. If this check detects an out-of-bounds condition the operation is
aborted to prevent random errors due to metadata corruption.

Reported-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:47 +01:00
B Horn 067b6d225d fs/ntfs: Implement attribute verification
It was possible to read OOB when an attribute had a size that exceeded
the allocated buffer. This resolves that by making sure all attributes
that get read are fully in the allocated space by implementing
a function to validate them.

Defining the offsets in include/grub/ntfs.h but they are only used in
the validation function and not across the rest of the NTFS code.

Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:47 +01:00
B Horn 048777bc29 fs/ntfs: Use a helper function to access attributes
Right now to access the next attribute the code reads the length of the
current attribute and adds that to the current pointer. This is error
prone as bounds checking needs to be performed all over the place. So,
implement a helper and ensure its used across find_attr() and read_attr().

This commit does *not* implement full bounds checking. It is just the
preparation work for this to be added into the helper.

Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:46 +01:00
B Horn 237a71184a fs/ntfs: Track the end of the MFT attribute buffer
The end of the attribute buffer should be stored alongside the rest of
the attribute struct as right now it is not possible to implement bounds
checking when accessing attributes sequentially.

This is done via:
  - updating init_attr() to set at->end and check is is not initially out of bounds,
  - implementing checks as init_attr() had its type change in its callers,
  - updating the value of at->end when needed.

Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:46 +01:00
Michael Chang aff2631878 fs/ntfs: Fix out-of-bounds read
When parsing NTFS file records the presence of the 0xFF marker indicates
the end of the attribute list. This value signifies that there are no
more attributes to process.

However, when the end marker is missing due to corrupted metadata the
loop continues to read beyond the attribute list resulting in out-of-bounds
reads and potentially entering an infinite loop.

This patch adds a check to provide a stop condition for the loop ensuring
it stops at the end of the attribute list or at the end of the Master File
Table. This guards against out-of-bounds reads and prevents infinite loops.

Reported-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:46 +01:00
Michael Chang 7e2f750f0a fs/ext2: Fix out-of-bounds read for inline extents
When inline extents are used, i.e. the extent tree depth equals zero,
a maximum of four entries can fit into the inode's data block. If the
extent header states a number of entries greater than four the current
ext2 implementation causes an out-of-bounds read. Fix this issue by
capping the number of extents to four when reading inline extents.

Reported-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:46 +01:00
Lidong Chen edd995a26e fs/jfs: Inconsistent signed/unsigned types usage in return values
The getblk() returns a value of type grub_int64_t which is assigned to
iagblk and inoblk, both of type grub_uint64_t, in grub_jfs_read_inode()
via grub_jfs_blkno(). This patch fixes the type mismatch in the
functions. Additionally, the getblk() will return 0 instead of -1 on
failure cases. This change is safe because grub_errno is always set in
getblk() to indicate errors and it is later checked in the callers.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:46 +01:00
Lidong Chen bd999310fe fs/jfs: Use full 40 bits offset and address for a data extent
An extent's logical offset and address are represented as a 40-bit value
split into two parts: the most significant 8 bits and the least
significant 32 bits. Currently the JFS code uses only the least
significant 32 bits value for offsets and addresses assuming the data
size will never exceed the 32-bit range. This approach ignores the most
significant 8 bits potentially leading to incorrect offsets and
addresses for larger values. The patch fixes it by incorporating the
most significant 8 bits into the calculation to get the full 40-bits
value for offsets and addresses.

https://jfs.sourceforge.net/project/pub/jfslayout.pdf

  "off1,off2 is a 40-bit field, containing the logical offset of the first
   block in the extent.
   ...
   addr1,addr2 is a 40-bit field, containing the address of the extent."

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:46 +01:00
Lidong Chen ab09fd0531 fs/jfs: Fix OOB read caused by invalid dir slot index
While fuzz testing JFS with ASAN enabled an OOB read was detected in
grub_jfs_opendir(). The issue occurred due to an invalid directory slot
index in the first entry of the sorted directory slot array in the inode
directory header. The fix ensures the slot index is validated before
accessing it. Given that an internal or a leaf node in a directory B+
tree is a 4 KiB in size and each directory slot is always 32 bytes, the
max number of slots in a node is 128. The validation ensures that the
slot index doesn't exceed this limit.

[1] https://jfs.sourceforge.net/project/pub/jfslayout.pdf

  JFS will allocate 4K of disk space for an internal node of the B+ tree.
  An internal node looks the same as a leaf node.
          - page 10

  Fixed number of Directory Slots depending on the size of the node. These are
  the slots to be used for storing the directory slot array and the directory
  entries or router entries. A directory slot is always 32 bytes.
  ...
  A Directory Slot Array which is a sorted array of indices to the directory
  slots that are currently in use.
  ...
  An internal or a leaf node in the directory B+ tree is a 4K page.
          - page 25

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-01-23 16:22:46 +01:00
Lidong Chen 66175696f3 fs/jfs: Fix OOB read in jfs_getent()
The JFS fuzzing revealed an OOB read in grub_jfs_getent(). The crash
was caused by an invalid leaf nodes count, diro->dirpage->header.count,
which was larger than the maximum number of leaf nodes allowed in an
inode. This fix is to ensure that the leaf nodes count is validated in
grub_jfs_opendir() before calling grub_jfs_getent().

On the occasion replace existing raw numbers with newly defined constant.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-01-23 16:22:46 +01:00
Michael Chang 1443833a95 fs/iso9660: Fix invalid free
The ctx->filename can point to either a string literal or a dynamically
allocated string. The ctx->filename_alloc field is used to indicate the
type of allocation.

An issue has been identified where ctx->filename is reassigned to
a string literal in susp_iterate_dir() but ctx->filename_alloc is not
correctly handled. This oversight causes a memory leak and an invalid
free operation later.

The fix involves checking ctx->filename_alloc, freeing the allocated
string if necessary and clearing ctx->filename_alloc for string literals.

Reported-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:46 +01:00
B Horn 965db59708 fs/iso9660: Set a grub_errno if mount fails
It was possible for a grub_errno to not be set if mount of an ISO 9660
filesystem failed when set_rockridge() returned 0.

This isn't known to be exploitable as the other filesystems due to
filesystem helper checking the requested file type. Though fixing
as a precaution.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:46 +01:00
B Horn f7c070a2e2 fs/hfsplus: Set a grub_errno if mount fails
It was possible for mount to fail but not set grub_errno. This led to
a possible double decrement of the module reference count if the NULL
page was mapped.

Fixing in general as a similar bug was fixed in commit 61b13c187
(fs/hfsplus: Set grub_errno to prevent NULL pointer access) and there
are likely more variants around.

Fixes: CVE-2024-45783

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:46 +01:00
B Horn 563436258c fs/f2fs: Set a grub_errno if mount fails
It was previously possible for grub_errno to not be set when
grub_f2fs_mount() failed if nat_bitmap_ptr() returned NULL.

This issue is solved by ensuring a grub_errno is set in the fail case.

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-23 16:22:46 +01:00
Lidong Chen 0087bc6902 fs/tar: Integer overflow leads to heap OOB write
Both namesize and linksize are derived from hd.size, a 12-digit octal
number parsed by read_number(). Later direct arithmetic calculation like
"namesize + 1" and "linksize + 1" may exceed the maximum value of
grub_size_t leading to heap OOB write. This patch fixes the issue by
using grub_add() and checking for an overflow.

Fixes: CVE-2024-45780

Reported-by: Nils Langius <nils@langius.de>
Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alec Brown <alec.r.brown@oracle.com>
2025-01-23 16:15:31 +01:00
B Horn 2c8ac08c99 fs/tar: Initialize name in grub_cpio_find_file()
It was possible to iterate through grub_cpio_find_file() without
allocating name and not setting mode to GRUB_ARCHELP_ATTR_END, which
would cause the uninitialized value for name to be used as an argument
for canonicalize() in grub_archelp_dir().

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-16 15:07:22 +01:00
B Horn 417547c104 fs/hfs: Fix stack OOB write with grub_strcpy()
Replaced with grub_strlcpy().

Fixes: CVE-2024-45782
Fixes: CVE-2024-56737
Fixes: https://savannah.gnu.org/bugs/?66599

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2025-01-16 15:05:23 +01:00
B Horn c1a291b01f fs/ufs: Fix a heap OOB write
grub_strcpy() was used to copy a symlink name from the filesystem
image to a heap allocated buffer. This led to a OOB write to adjacent
heap allocations. Fix by using grub_strlcpy().

Fixes: CVE-2024-45781

Reported-by: B Horn <b@horn.uk>
Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-12-02 17:32:51 +01:00
B Horn ea703528a8 misc: Implement grub_strlcpy()
grub_strlcpy() acts the same way as strlcpy() does on most *NIX,
returning the length of src and ensuring dest is always NUL
terminated except when size is 0.

Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-12-02 17:32:51 +01:00
Stefan Berger 6811f6f09d tpm2_key_protector: Enable build for powerpc_ieee1275
Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-11-28 23:02:24 +01:00
Stefan Berger ff14b89bda ieee1275/tcg2: Add TCG2 driver for ieee1275 PowerPC firmware
Follow recent extensions of EFI support providing a TCG2 driver with
a public API for getting the maximum TPM command size and passing a TPM
command through to the TPM 2. Implement this functionality using ieee1275
PowerPC firmware API calls. Move tcg2.c into the TCG2 driver.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-11-28 22:57:09 +01:00
Stefan Berger 72092a8641 ieee1275/tcg2: Refactor grub_ieee1275_tpm_init()
Move tpm_get_tpm_version() into grub_ieee1275_tpm_init() and invalidate
grub_ieee1275_tpm_ihandle in case no TPM 2 could be detected. Try the
initialization only once so that grub_tpm_present() will always return
the same result. Use the grub_ieee1275_tpm_ihandle as indicator for an
available TPM instead of grub_ieee1275_tpm_version, which can now be
removed.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-11-28 22:37:50 +01:00
Stefan Berger 8c0b5f2003 ieee1275/ibmvpm: Move TPM initialization functions to own file
Move common initialization functions from the ibmvtpm driver module into
tcg2.c that will be moved into the new TCG2 driver in a subsequent patch.
Make the functions available to the ibmvtpm driver as public functions
and variables.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-11-28 22:21:41 +01:00
Stefan Berger 7344b3c7ce ieee1275: Consolidate repeated definitions of IEEE1275_IHANDLE_INVALID
Consolidate repeated definitions of IEEE1275_IHANDLE_INVALID that are cast
to the type grub_ieee1275_ihandle_t. On the occasion add "GRUB_" prefix to
the constant name.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-11-28 22:15:29 +01:00
Stefan Berger 29d1bd2a96 term/ieee1275/serial: Cast 0 to proper type
Cast 0 to proper type grub_ieee1275_ihandle_t. This type is
used for struct grub_serial_port's handle that assigns or
compares with IEEE1275_IHANDLE_INVALID.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-11-28 22:11:30 +01:00
Stefan Berger 99ee68a014 tss2: Adjust bit fields for big endian targets
The TPM bit fields need to be in reverse order for big endian targets,
such as ieee1275 PowerPC platforms that run GRUB in big endian mode.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-11-28 22:09:51 +01:00
Gary Lin 3770a69050 docs: Document TPM2 key protector
Update the user manual to address TPM2 key protector including the two
related commands, tpm2_key_protector_init and tpm2_key_protector_clear,
and the user-space utility: grub-protect.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:56 +01:00
Gary Lin f898440cc1 tests: Add tpm2_key_protector_test
For the tpm2_key_protector module, the TCG2 command submission function
is the only difference between a QEMU instance and grub-emu. To test
TPM2 key unsealing with a QEMU instance, it requires an extra OS image
to invoke grub-protect to seal the LUKS key, rather than a simple
grub-shell rescue CD image. On the other hand, grub-emu can share the
emulated TPM2 device with the host, so that we can seal the LUKS key on
host and test key unsealing with grub-emu.

This test script firstly creates a simple LUKS image to be loaded as a
loopback device in grub-emu. Then an emulated TPM2 device is created by
"swtpm chardev" and PCR 0 and 1 are extended.

There are several test cases in the script to test various settings. Each
test case uses grub-protect or tpm2-tools to seal the LUKS password
with PCR 0 and PCR 1. Then grub-emu is launched to load the LUKS image,
try to mount the image with tpm2_key_protector_init and cryptomount, and
verify the result.

Based on the idea from Michael Chang.

Cc: Michael Chang <mchang@suse.com>
Cc: Stefan Berger <stefanb@linux.ibm.com>
Cc: Glenn Washburn <development@efficientek.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:56 +01:00
Gary Lin 76a2bcb997 tpm2_key_protector: Add grub-emu support
As a preparation to test tpm2_key_protector with grub-emu, the new
option, --tpm-device, is introduced to specify the TPM device for
grub-emu so that grub-emu can access an emulated TPM device from
the host.

Since grub-emu can directly access the device on host, it's easy to
implement the essential TCG2 command submission function with the
read/write functions and enable tpm2_key_protector module for grub-emu,
so that we can further test TPM2 key unsealing with grub-emu.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:56 +01:00
Gary Lin 135e0bc886 diskfilter: Look up cryptodisk devices first
When using disk auto-unlocking with TPM 2.0, the typical grub.cfg may
look like this:

  tpm2_key_protector_init --tpm2key=(hd0,gpt1)/boot/grub/sealed.tpm
  cryptomount -u <PART-UUID> -P tpm2
  search --fs-uuid --set=root <FS-UUID>

Since the disk search order is based on the order of module loading, the
attacker could insert a malicious disk with the same FS-UUID root to
trick GRUB to boot into the malicious root and further dump memory to
steal the unsealed key.

Do defend against such an attack, we can specify the hint provided by
"grub-probe" to search the encrypted partition first:

  search --fs-uuid --set=root --hint='cryptouuid/<PART-UUID>' <FS-UUID>

However, for LVM on an encrypted partition, the search hint provided by
"grub-probe" is:

  --hint='lvmid/<VG-UUID>/<LV-UUID>'

It doesn't guarantee to look up the logical volume from the encrypted
partition, so the attacker may have the chance to fool GRUB to boot
into the malicious disk.

To minimize the attack surface, this commit tweaks the disk device search
in diskfilter to look up cryptodisk devices first and then others, so
that the auto-unlocked disk will be found first, not the attacker's disk.

Cc: Fabian Vogt <fvogt@suse.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:56 +01:00
Gary Lin b35480b48e cryptodisk: Wipe out the cached keys from protectors
An attacker may insert a malicious disk with the same crypto UUID and
trick GRUB to mount the fake root. Even though the key from the key
protector fails to unlock the fake root, it's not wiped out cleanly so
the attacker could dump the memory to retrieve the secret key. To defend
such attack, wipe out the cached key when we don't need it.

Cc: Fabian Vogt <fvogt@suse.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:56 +01:00
Patrick Colp 6abf8af3c5 cryptodisk: Fallback to passphrase
If a protector is specified, but it fails to unlock the disk, fall back
to asking for the passphrase.

Before requesting the passphrase, the error from the key protector(s)
has to be cleared, or the later code, e.g., LUKS code, may stop as
grub_errno is set. This commit prints error from the key protector(s)
and sets grub_errno to GRUB_ERR_NONE to have a fresh start.

Signed-off-by: Patrick Colp <patrick.colp@oracle.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:55 +01:00
Patrick Colp fba3a474e0 tpm2_key_protector: Implement NV index
Currently with the TPM2 protector, only SRK mode is supported and
NV index support is just a stub. Implement the NV index option.

Note: This only extends support on the unseal path. grub-protect
has not been updated. tpm2-tools can be used to insert a key into
the NV index.

An example of inserting a key using tpm2-tools:

  # Get random key.
  tpm2_getrandom 32 > key.dat

  # Create primary object.
  tpm2_createprimary -C o -g sha256 -G ecc -c primary.ctx

  # Create policy object. `pcrs.dat` contains the PCR values to seal against.
  tpm2_startauthsession -S session.dat
  tpm2_policypcr -S session.dat -l sha256:7,11 -f pcrs.dat -L policy.dat
  tpm2_flushcontext session.dat

  # Seal key into TPM.
  cat key.dat | tpm2_create -C primary.ctx -u key.pub -r key.priv -L policy.dat -i-
  tpm2_load -C primary.ctx -u key.pub -r key.priv -n sealing.name -c sealing.ctx
  tpm2_evictcontrol -C o -c sealing.ctx 0x81000000

Then to unseal the key in GRUB, add this to grub.cfg:

  tpm2_key_protector_init --mode=nv --nvindex=0x81000000 --pcrs=7,11
  cryptomount -u <UUID> --protector tpm2

Signed-off-by: Patrick Colp <patrick.colp@oracle.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:55 +01:00
Gary Lin 550ada7d67 tpm2_key_protector: Support authorized policy
This commit handles the TPM2_PolicyAuthorize command from the key file
in TPM 2.0 Key File format.

TPM2_PolicyAuthorize is the essential command to support authorized
policy which allows the users to sign TPM policies with their own keys.
Per TPM 2.0 Key File [1], CommandPolicy for TPM2_PolicyAuthorize
comprises "TPM2B_PUBLIC pubkey", "TPM2B_DIGEST policy_ref", and
"TPMT_SIGNATURE signature". To verify the signature, the current policy
digest is hashed with the hash algorithm written in "signature", and then
"signature" is verified with the hashed policy digest and "pubkey". Once
TPM accepts "signature", TPM2_PolicyAuthorize is invoked to authorize the
signed policy.

To create the key file with authorized policy, here are the pcr-oracle [2]
commands:

  # Generate the RSA key and create the authorized policy file
  $ pcr-oracle \
	--rsa-generate-key \
	--private-key policy-key.pem \
	--auth authorized.policy \
	create-authorized-policy 0,2,4,7,9

  # Seal the secret with the authorized policy
  $ pcr-oracle \
	--key-format tpm2.0 \
	--auth authorized.policy \
	--input disk-secret.txt \
	--output sealed.key \
	seal-secret

  # Sign the predicted PCR policy
  $ pcr-oracle \
	--key-format tpm2.0 \
	--private-key policy-key.pem \
	--from eventlog \
	--stop-event "grub-file=grub.cfg" \
	--after \
	--input sealed.key \
	--output /boot/efi/efi/grub/sealed.tpm \
	sign 0,2,4,7,9

Then specify the key file and the key protector to grub.cfg in the EFI
system partition:

  tpm2_key_protector_init -a RSA --tpm2key=(hd0,gpt1)/efi/grub/sealed.tpm
  cryptomount -u <PART_UUID> -P tpm2

For any change in the boot components, just run the "sign" command again
to update the signature in sealed.tpm, and TPM can unseal the key file
with the updated PCR policy.

[1] https://www.hansenpartnership.com/draft-bottomley-tpm2-keys.html
[2] https://github.com/okirch/pcr-oracle

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:55 +01:00
Hernan Gatta 5f6a2fd513 util/grub-protect: Add new tool
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
has to ensure 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 \
                      --tpm2-pcrs=0,2,4,7,9 \
                      --tpm2key \
                      --tpm2-keyfile=luks-key \
                      --tpm2-outfile=/boot/efi/efi/grub/sealed.tpm

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

  $ sudo grub-protect --action=add \
                      --protector=tpm2 \
                      --tpm2-pcrs=0,2,4,7,9 \
                      --tpm2-keyfile=luks-key \
                      --tpm2-outfile=/boot/efi/efi/grub/sealed.key

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

  tpm2_key_protector_init --tpm2key=(hd0,gpt1)/efi/grub/sealed.tpm
  cryptomount -u <SDB1_UUID> -P tpm2

Or, for the raw sealed key:

  tpm2_key_protector_init --keyfile=(hd0,gpt1)/efi/grub/sealed.key --pcrs=0,2,4,7,9
  cryptomount -u <SDB1_UUID> -P tpm2

The benefit of using TPM 2.0 Key File is that the PCR set is already
written in the key file, so there is no need to specify PCRs when
invoking tpm2_key_protector_init.

Signed-off-by: Hernan Gatta <hegatta@linux.microsoft.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:55 +01:00
Hernan Gatta ad0c52784a cryptodisk: Support key protectors
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.

Signed-off-by: Hernan Gatta <hegatta@linux.microsoft.com>
Signed-off-by: Michael Chang <mchang@suse.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:55 +01:00
Hernan Gatta 48e230c317 key_protector: Add TPM2 Key Protector
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
     description [4] EXPLICIT UTF8String OPTIONAL,
     rsaParent   [5] EXPLICIT BOOLEAN 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 construct 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/grub/sealed-1.key
  cryptomount -u <PART1_UUID> -P tpm2

  tpm2_key_protector_init --keyfile=(hd0,gpt1)/efi/grub/sealed-2.key --pcrs=7,11
  cryptomount -u <PART2_UUID> -P tpm2

Or, to unseal the TPM 2.0 Key file:

  tpm2_key_protector_init --tpm2key=(hd0,gpt1)/efi/grub/sealed-1.tpm
  cryptomount -u <PART1_UUID> -P tpm2

  tpm2_key_protector_init --tpm2key=(hd0,gpt1)/efi/grub/sealed-2.tpm --pcrs=7,11
  cryptomount -u <PART2_UUID> -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.

This commit only supports one policy command: TPM2_PolicyPCR. The
command set will be extended to support advanced features, such as
authorized policy, in the later commits.

Cc: James Bottomley <jejb@linux.ibm.com>
Signed-off-by: Hernan Gatta <hegatta@linux.microsoft.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:55 +01:00
Gary Lin 35c9904df4 tss2: Add TPM2 Software Stack (TSS2) support
A Trusted Platform Module (TPM) Software Stack (TSS) provides logic to
compose and submit TPM commands and parse 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 implementations of various grub_tpm2_* functions
(inventoried below), and logic to write and read command and response
buffers, respectively, using the TPM wire protocol.

Functions:
  - grub_tpm2_create(),
  - grub_tpm2_createprimary(),
  - grub_tpm2_evictcontrol(),
  - grub_tpm2_flushcontext(),
  - grub_tpm2_load(),
  - grub_tpm2_pcr_read(),
  - grub_tpm2_policygetdigest(),
  - grub_tpm2_policypcr(),
  - grub_tpm2_readpublic(),
  - grub_tpm2_startauthsession(),
  - grub_tpm2_unseal(),
  - grub_tpm2_loadexternal(),
  - grub_tpm2_hash(),
  - grub_tpm2_verifysignature(),
  - grub_tpm2_policyauthorize(),
  - grub_tpm2_testparms().

Signed-off-by: Hernan Gatta <hegatta@linux.microsoft.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:55 +01:00
Gary Lin 63a78f4b4d tss2: Add TPM2 types and Marshal/Unmarshal functions
This commit adds the necessary TPM2 types and structs as the preparation
for the TPM2 Software Stack (TSS2) support. The Marshal/Unmarshal
functions are also added to handle the data structure to be submitted to
TPM2 commands and to be received from the response.

Signed-off-by: Hernan Gatta <hegatta@linux.microsoft.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:55 +01:00
Gary Lin 2ad159d9b3 tss2: Add TPM2 buffer handling functions
As the preparation to support TPM2 Software Stack (TSS2), this commit
implements the TPM2 buffer handling functions to pack data for the TPM2
commands and unpack the data from the response.

Cc: Stefan Berger <stefanb@linux.ibm.com>
Signed-off-by: Hernan Gatta <hegatta@linux.microsoft.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:55 +01:00
Hernan Gatta 5d260302da key_protector: Add key protectors framework
A key protector encapsulates functionality to retrieve an unlocking key
for a fully-encrypted disk from a specific source. A key protector
module registers itself with the key protectors framework when it is
loaded and unregisters when unloaded. Additionally, a key protector may
accept parameters that describe how it should operate.

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

Cc: Vladimir Serbinenko <phcoder@gmail.com>
Signed-off-by: Hernan Gatta <hegatta@linux.microsoft.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:55 +01:00
Gary Lin 3d60732f9f libtasn1: Add the documentation
Document libtasn1 in docs/grub-dev.texi and add the upgrade steps.
Also add the patches to make libtasn1 compatible with GRUB code.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Daniel Axtens 99cda67889 asn1_test: Test module for libtasn1
Import tests from libtasn1 that use functionality we import.
This test module is integrated into functional_test so that the
user can run the test in GRUB shell.

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 commit 5e10be48e5 (tests: Add
check-native and check-nonnative make targets).

Cc: Vladimir Serbinenko <phcoder@gmail.com>
Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Daniel Axtens 504058e82a libtasn1: Compile into asn1 module
Create a wrapper file that specifies the module license.
Set up the makefile so it is built.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Gary Lin 8a0fedef21 asn1_test: Enable the testcase only when GRUB_LONG_MAX is larger than GRUB_INT_MAX
There is a testcase to test the values larger than "int" but smaller
than "long". However, for some architectures, "long" and "int" are the
same and the compiler may issue a warning like this:

grub-core/tests/asn1/tests/Test_overflow.c:48:50: error: left shift of negative value [-Werror=shift-negative-value]
       unsigned long num = ((long) GRUB_UINT_MAX) << 2;
                                                  ^~

To avoid unnecessary error the testcase is enabled only when
GRUB_LONG_MAX is larger than GRUB_INT_MAX.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Gary Lin 66cf4cb144 asn1_test: Use the grub-specific functions and types
This commit converts functions and types to the grub-specific ones:
  - LONG_MAX -> GRUB_LONG_MAX,
  - INT_MAX -> GRUB_INT_MAX,
  - UINT_MAX -> GRUB_UINT_MAX,
  - size_t -> grub_size_t,
  - memcmp() -> grub_memcmp(),
  - memcpy() -> grub_memcpy(),
  - free() -> grub_free(),
  - strcmp() -> grub_strcmp().

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Gary Lin 0d0913fc61 asn1_test: Print the error messages with grub_printf()
This commit replaces printf() and fprintf() with grub_printf() to print
the error messages for the testcases. Besides, asn1_strerror() is used
to convert the result code to strings instead of asn1_perror().

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Gary Lin 2e93a8e4bd asn1_test: Remove "verbose" and the unnecessary printf()
This commit removes the "verbose" variables and the unnecessary printf()
to simplify the output.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Gary Lin b7568e3358 asn1_test: Return either 0 or 1 to reflect the results
Some testcases use exit() to end the test. Since all the asn1 testcases
are invoked as functions, this commit replaces exit() with return to
reflect the test results, so that the main test function can check the
results.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Gary Lin d60a04baef asn1_test: Rename the main functions to the test names
This commit changes the main functions in the testcases to the test
names so that the real "main" test function can invokes them.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Gary Lin 54e0e19a29 asn1_test: Include asn1_test.h only
This commit removes all the headers and only uses asn1_test.h.
To avoid including int.h from grub-core/lib/libtasn1-grub/lib,
CONST_DOWN is defined in reproducers.c.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Gary Lin 0ad1d4ba86 libtasn1: Fix the potential buffer overrun
In _asn1_tag_der(), the first while loop for the long form may end up
with a "k" value with "ASN1_MAX_TAG_SIZE" and cause the buffer overrun
in the second while loop. This commit tweaks the conditional check to
avoid producing a too large "k".

This is a quick fix and may differ from the official upstream fix.

libtasn1 issue: https://gitlab.com/gnutls/libtasn1/-/issues/49

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Gary Lin 4160ca9839 libtasn1: Use grub_divmod64() for division
Replace a 64-bit division with a call to grub_divmod64(), preventing
creation of __udivdi3() calls on 32-bit platforms.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:54 +01:00
Gary Lin 8f56e5e5cf libtasn1: Adjust the header paths in libtasn1.h
Since libtasn1.h is the header to be included by users, including the
standard POSIX headers in libtasn1.h would force the user to add the
CFLAGS/CPPFLAGS for the POSIX headers.

This commit adjusts the header paths to use the grub headers instead of
the standard POSIX headers, so that users only need to include
libtasn1.h to use libtasn1 functions.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:53 +01:00
Gary Lin d86df91cbe libtasn1: Replace strcat() with _asn1_str_cat()
strcat() is not available in GRUB. This commit replaces strcat() and
_asn1_strcat() with the bounds-checking _asn1_str_cat().

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:53 +01:00
Gary Lin 32fdfe6008 libtasn1: Replace strcat() with strcpy() in _asn1_str_cat()
strcat() is not available in GRUB. This commit replaces strcat() with
strcpy() in _asn1_str_cat() as the preparation to replace other strcat()
with the bounds-checking _asn1_str_cat().

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:53 +01:00
Gary Lin fa498af7b9 libtasn1: Disable code not needed in GRUB
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.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:53 +01:00
Daniel Axtens 9a26abbc36 libtasn1: Import libtasn1-4.19.0
Import a very trimmed-down set of libtasn1 files:

  curl -L -O https://ftp.gnu.org/gnu/libtasn1/libtasn1-4.19.0.tar.gz
  tar xvzf libtasn1-4.19.0.tar.gz
  rm -rf grub-core/lib/libtasn1
  mkdir -p grub-core/lib/libtasn1/lib
  mkdir -p grub-core/lib/libtasn1/tests
  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/libtasn1/lib
  cp libtasn1-4.19.0/lib/includes/libtasn1.h grub-core/lib/libtasn1
  cp libtasn1-4.19.0/tests/{CVE-2018-1000654-1_asn1_tab.h,CVE-2018-1000654-2_asn1_tab.h,CVE-2018-1000654.c,object-id-decoding.c,object-id-encoding.c,octet-string.c,reproducers.c,Test_overflow.c,Test_simple.c,Test_strings.c} grub-core/lib/libtasn1/tests
  rm -rf libtasn1-4.19.0*

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:53 +01:00
Daniel Axtens c85c2b9f5f posix_wrap: Tweaks in preparation for libtasn1
Cc: Vladimir Serbinenko <phcoder@gmail.com>
Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Stefan Berger <stefanb@linux.ibm.com>
2024-11-28 21:50:17 +01:00
Rasmus Villemoes 4f6c460917 kern/fs: Honour file->read_hook() in grub_fs_blocklist_read()
Unlike files accessed via a normal file system, the file->read_hook() is
not honoured when using blocklist notation.

This means that when trying to use a dedicated, 1 KiB, raw partition
for the environment block and hence does something like

  save_env --file=(hd0,gpt9)0+2 X Y Z

this fails with "sparse file not allowed", which is rather unexpected,
as I've explicitly said exactly which blocks should be used. Adding
a little debugging reveals that grub_file_size(file) is 1024 as expected,
but total_length is 0, simply because the callback was never invoked, so
blocklists is an empty list.

Fix that by honouring the ->read_hook() set by the caller, also when
a "file" is specified with blocklist notation.

Signed-off-by: Rasmus Villemoes <rasmus.villemoes@prevas.dk>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-11-28 20:23:15 +01:00
Glenn Washburn 792132c72a docs: Fix incorrect and potentially confusing language and minor formatting
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-11-28 19:55:34 +01:00
Andrew Hamilton 1763d83f54 docs: Correct GRUB config file name for network boot
Correct the documentation for the grub.cfg searching via network that
will be done based on ethernet type, -01, which was missing, and a given
MAC address.

Fixes: https://savannah.gnu.org/bugs/?65152

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-31 16:50:01 +01:00
Andrew Hamilton 097fd9d9a1 docs: Correct chainloader UEFI secure boot info
Correct documentation for UEFI secure boot to remove statement that
chainloader does not work with secure boot. This was fixed by the commit
6d05264 (kern/efi/sb: Add chainloaded image as shim's verifiable object).

Fixes: https://savannah.gnu.org/bugs/?62004

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-31 16:40:41 +01:00
Andrew Hamilton f48e6af117 docs: Correct PXE environment variables descriptions
Correct documentation for pxe_default_server, pxe_default_gatway and
pxe_blksize. Only pxe_default_server is actually used (alias for
net_default_server). So, capture this and remove the other two.

Fixes: https://savannah.gnu.org/bugs/?54480

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-31 16:36:25 +01:00
Valentin Gehrke dd743ba42d loader/multiboot: Do not add modules before successful download
Multiboot modules that could not be read successfully, e.g. via network,
should not be added to the list of modules to forward to the operating
system that is to be booted subsequently.

This patch is necessary because even if a grub.cfg checks whether or not
a module was successfully downloaded, it is futile to retry a failed
download as the corrupted module will be forwarded either way.

Signed-off-by: Valentin Gehrke <valentin.gehrke@kernkonzept.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-31 16:29:01 +01:00
Sudhakar Kuppusamy 9a9082b501 grub-mkimage: Add SBAT metadata into ELF note for PowerPC targets
The SBAT metadata is read from CSV file and transformed into an ELF note
with the -s option.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-31 16:18:36 +01:00
Sudhakar Kuppusamy f97d4618a5 grub-mkimage: Create new ELF note for SBAT
In order to store the SBAT data we create a new ELF note. The string
".sbat", zero-padded to 4 byte alignment, shall be entered in the name
field. The string "SBAT"'s ASCII values, 0x53424154, should be entered
in the type field.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Sudhakar Kuppusamy <sudhakar@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-31 16:13:06 +01:00
Leo Sandoval f26b39860d commands/legacycfg: Avoid closing file twice
An internal (at Red Hat) static soure code scan detected an
use-after-free scenario:

  Error: USE_AFTER_FREE (CWE-416):
  grub-2.06/grub-core/commands/legacycfg.c:194: freed_arg: "grub_file_close" frees "file".
  grub-2.06/grub-core/commands/legacycfg.c:201: deref_arg: Calling "grub_file_close" dereferences freed pointer "file".
  #  199|         if (!args)
  #  200|   	{
  #  201|-> 	  grub_file_close (file);
  #  202|   	  grub_free (suffix);
  #  203|   	  grub_free (entrysrc);

So, remove the extra file close call.

Signed-off-by: Leo Sandoval <lsandova@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-31 16:08:36 +01:00
Daniel Kiper 337cb24862 nx: Rename GRUB_DL_ALIGN to DL_ALIGN
Rename has been skipped by mistake in the original commit.

Fixes: 94649c026 (nx: Set page permissions for loaded modules)

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Sudeep Holla <sudeep.holla@arm.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
2024-10-31 16:07:03 +01:00
Benjamin Herrenschmidt 31de991dee kern/acpi: Fix out of bounds access in grub_acpi_xsdt_find_table()
The calculation of the size of the table was incorrect (copy/pasta from
grub_acpi_rsdt_find_table() I assume...). The entries are 64-bit long.

This causes us to access beyond the end of the table which is causing
crashes during boot on some systems. Typically this is causing a crash
on VMWare when using UEFI and enabling serial autodetection, as

  grub_acpi_find_table (GRUB_ACPI_SPCR_SIGNATURE);

will goes past the end of the table (the SPCR table doesn't exits).

Signed-off-by: Benjamin Herrenschmidt <benh@kernel.crashing.org>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Tested-by: Renata Ravanelli <rravanel@redhat.com>
2024-10-31 16:04:00 +01:00
Mate Kukri f5bb766e68 nx: Set the NX compatible flag for the GRUB EFI images
For NX the GRUB binary has to announce that it is compatible with the
NX feature. This implies that when loading the executable GRUB image
several attributes are true:
  - the binary doesn't need an executable stack,
  - the binary doesn't need sections to be both executable and writable,
  - the binary knows how to use the EFI Memory Attributes Protocol on code
    it is loading.

This patch:
  - adds a definition for the PE DLL Characteristics flag GRUB_PE32_NX_COMPAT,
  - changes grub-mkimage to set that flag.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Jan Setje-Eilers <jan.setjeeilers@oracle.com>
Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-11 14:45:00 +02:00
Mate Kukri 94649c0267 nx: Set page permissions for loaded modules
For NX we need to set write and executable permissions on the sections
of GRUB modules when we load them. All allocatable sections are marked
readable. In addition:
  - SHF_WRITE sections are marked as writable,
  - and SHF_EXECINSTR sections are marked as executable.

Where relevant for the platform the tramp and GOT areas are marked non-writable.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Robbie Harwood <rharwood@redhat.com>
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Signed-off-by: Jan Setje-Eilers <jan.setjeeilers@oracle.com>
Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-11 14:43:03 +02:00
Mate Kukri 09ca66673a nx: Add memory attribute get/set API
For NX we need to set the page access permission attributes for write
and execute permissions. This patch adds two new primitives, grub_set_mem_attrs()
and grub_clear_mem_attrs(), and associated constants definitions used
for that purpose. For most platforms it adds a dummy implementation.
On EFI platforms it implements the primitives using the EFI Memory
Attribute Protocol, defined in UEFI 2.10 specification.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Jan Setje-Eilers <jan.setjeeilers@oracle.com>
Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-11 14:35:54 +02:00
Mate Kukri 9fb80dd57e modules: Load module sections at page-aligned addresses
Currently we load module sections at whatever alignment gcc+ld happened
to dump into the ELF section header which is often less then the page
size. Since NX protections are page based this alignment must be rounded
up to page size on platforms supporting NX protections. This patch
switches EFI platforms to load module sections at 4 KiB page-aligned
addresses. It then changes the allocation size computation and the
loader code in grub_dl_load_segments() to align the locations and sizes
up to these boundaries and fills any added padding with zeros. All of
this happens before relocations are applied, so the relocations factor
that in with no change.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Signed-off-by: Jan Setje-Eilers <jan.setjeeilers@oracle.com>
Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-11 14:34:28 +02:00
Peter Jones 6e2fe134ef modules: Don't allocate space for non-allocable sections
Currently when loading GRUB modules we allocate space for all sections
including those without SHF_ALLOC set. We then copy the sections that
/do/ have SHF_ALLOC set into the allocated memory leaving some of our
allocation untouched forever. Additionally, on platforms with GOT fixups
and trampolines we currently compute alignment round-ups for the
sections and sections with sh_size = 0. This patch removes the extra
space from the allocation computation and makes the allocation
computation loop skip empty sections as the loading loop does.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Jan Setje-Eilers <jan.setjeeilers@oracle.com>
Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-By: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 13:23:19 +02:00
Peter Jones 2b79d550f3 modules: Strip .llvm_addrsig sections and similar
Currently GRUB modules built with Clang or GCC have several sections
which we don't actually need or support. We already have a list of
sections to skip in genmod.sh and this patch adds the following
sections to that list (as well as a few newlines):
  - .note.gnu.property
  - .llvm*

Note that the glob there won't work without a new enough linker but the
failure is just reversion to the status quo. So, that's not a big problem.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Jan Setje-Eilers <jan.setjeeilers@oracle.com>
Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-By: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 13:18:00 +02:00
Peter Jones 246c82cdae modules: Make .module_license read-only
Currently .module_license is set writable, that is, the section has the
SHF_WRITE flag set, in the module's ELF headers. This probably never
actually matters but it can't possibly be correct. The patch sets that
data as "const" which causes that flag not to be set.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Jan Setje-Eilers <jan.setjeeilers@oracle.com>
Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-By: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 13:15:17 +02:00
Daniel Kiper 616adeb80b i386/memory: Rename PAGE_SIZE to GRUB_PAGE_SIZE and make it global
This is an x86-specific thing and should be available globally.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Sergii Dmytruk <sergii.dmytruk@3mdeb.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 13:11:23 +02:00
Daniel Kiper 95a7bfef5d i386/memory: Rename PAGE_SHIFT to GRUB_PAGE_SHIFT
This fixes naming inconsistency that goes against coding style as well
as helps to avoid potential conflicts and confusion as this constant is
used in multiple places.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Sergii Dmytruk <sergii.dmytruk@3mdeb.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 13:10:10 +02:00
Daniel Kiper 1b1061409d i386/msr: Extract and improve MSR support detection code
Currently rdmsr and wrmsr commands have own MSR support detection code.
This code is the same. So, it is duplicated. Additionally, this code
cannot be reused by others. Hence, extract this code to a function and
make it public. By the way, improve a code a bit.

Additionally, use GRUB_ERR_BAD_DEVICE instead of GRUB_ERR_BUG to signal
an error because errors encountered by this new routine are not bugs.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Sergii Dmytruk <sergii.dmytruk@3mdeb.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 13:09:06 +02:00
Daniel Kiper 929fafdf5e i386/msr: Rename grub_msr_read() and grub_msr_write()
Use more obvious names which match corresponding instructions:
  * grub_msr_read()  => grub_rdmsr(),
  * grub_msr_write() => grub_wrmsr().

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Sergii Dmytruk <sergii.dmytruk@3mdeb.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 13:08:31 +02:00
Daniel Kiper d96cfd7bf8 i386/msr: Merge rdmsr.h and wrmsr.h into msr.h
It does not make sense to have separate headers for individual static
functions. So, make one common place to store them.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Sergii Dmytruk <sergii.dmytruk@3mdeb.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 13:06:34 +02:00
Michael Chang 86ec48882b commands/tpm: Skip loopback image measurement
The loopback image is configured to function as a disk by being mapped
as a block device. Instead of measuring the entire block device we
should focus on tracking the individual files accessed from it. For
example, we do not directly measure block devices like hd0 disk but the
files opened from it.

This method is important to avoid running out of memory since loopback
images can be very large. Trying to read and measure the whole image at
once could cause out of memory errors and disrupt the boot process.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 13:04:37 +02:00
Michael Chang 3808b1a9bd net/drivers/efi/efinet: Skip virtual VLAN devices during card enumeration
Similarly to the issue described in commit c52ae4057 (efinet: skip
virtual IPv4 and IPv6 devices during card enumeration) the UEFI PXE
driver creates additional VLAN child devices when a VLAN ID is
configured on a network interface associated with a physical NIC. These
virtual VLAN devices must be skipped during card enumeration to ensure
that the subsequent SNP exclusive open operation targets the correct
physical card instances. Otherwise packet transfer would fail.

A device path example with VLAN nodes:

  /MAC(123456789ABC,0x1)/Vlan(20)/IPv4(0.0.0.0,0x0,DHCP,0.0.0.0,0.0.0.0,0.0.0.0)

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 12:38:47 +02:00
Michael Chang e5f047be05 efi/console: Properly clear leftover artifacts from the screen
A regression in GRUB 2.12 causes the GRUB screen to become cluttered
with artifacts from the previous screen whether it's the UEFI post UI,
UEFI shell or any graphical UI running before GRUB. This issue occurs
in situations like booting GRUB from the UEFI shell and going straight
to the rescue or command shell causing visual discomfort.

The regression was introduced by commit 2d7c3abd8 (efi/console: Do not
set text-mode until it is actually needed). To address the screen
flickering issue this commit suppresses the text-mode setting until the
first output is requested. Before text-mode is set any attempt to clear
the screen has no effect. This inactive period renders the clear screen
ineffective in early boot stages, potentially leaving leftover artifacts
that will clutter the GRUB console display, as there is no guarantee
there will always be a clear screen after the first output.

The issue is fixed by ensuring grub_console_cls() to work through lazy
mode-setting, while also avoiding screen clearing for the hidden menu
which the flicker-free patch aims to improve.

Fixes: 2d7c3abd8 (efi/console: Do not set text-mode until we actually need it)

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 12:36:56 +02:00
Heinrich Schuchardt c5ae124e11 kern/riscv/efi/init: Use time register in grub_efi_get_time_ms()
The cycle register is not guaranteed to count at constant frequency.
If it is counting at all depends on the state the performance monitoring
unit. Use the time register to measure time.

Signed-off-by: Heinrich Schuchardt <heinrich.schuchardt@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-10-10 12:13:37 +02:00
Frediano Ziglio 9c34d56c2d loader/efi/linux: Reset freed pointer
Avoid dangling pointer. Code should not be reached but better safe than sorry.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 19:12:08 +02:00
Frediano Ziglio 92bed41bf8 loader/efi/linux: Reuse len variable
Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 19:05:32 +02:00
Frediano Ziglio 33cb8aecdd lib/x86_64/relocator_asm: Use .quad instead of .long
They are single 64-bit values. Used in other assembly files too.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 17:58:56 +02:00
Frediano Ziglio 77cd623dee lib/x86_64/relocator_asm: Fix comment in code
The instruction uses a 64-bit immediate.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 17:49:19 +02:00
Frediano Ziglio 95145eea5e loader/efi/linux: Update comment
The function called is grub_utf8_to_utf16().

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 17:46:54 +02:00
Vladimir Serbinenko d333e8bb37 util/grub-mkimagexx: Explicitly move modules to __bss_start for MIPS targets
Assembly code looks for modules at __bss_start. Make this position explicit
rather than matching BSS alignment and module alignment.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 17:36:17 +02:00
Vladimir Serbinenko 34b7f37212 include/grub/offsets.h: Set mod_align to 4 on MIPS
Module structure has natural alignment of 4. Respect it explicitly
rather than relying on the fact that _end is usually aligned.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 17:29:35 +02:00
Vladimir Serbinenko ed06516738 gentpl: Put boot/mips/startup_raw.S into beginning of the image
Otherwise it breaks the decompressors for MIPS targets.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 17:25:27 +02:00
Vladimir Serbinenko 648f2d16c0 configure: Add -mno-gpopt option for mips and mipsel targets
Without it compiler generates GPREL16 references which do not work
with our memory layout.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 17:22:47 +02:00
Vladimir Serbinenko f0710d2d8f lib/xzembed/xz_dec_bcj: Silence warning when no BCJ is available
BCJ is not available for all platforms hence arguments may end up unused.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 17:12:06 +02:00
Vladimir Serbinenko e61157bbd2 fs/erofs: Replace 64-bit modulo with bitwise operations
Otherwise depending on compiler we end up with umoddi3 reference and
failed module dependency resolution.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 17:08:38 +02:00
Vladimir Serbinenko 5313fa8394 configure: Look for .otf fonts
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 17:05:24 +02:00
Mate Kukri 33b94f2a9b loader/efi/chainloader: Do not print device path of chainloaded file
Users have no reason to see this and it can break graphical boot.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 16:18:02 +02:00
Andrew Hamilton ab1e6fc044 docs: Document all GRUB modules
Add documentation for all GRUB modules contained in the source code tree.
When possible, cross-references to additional detail on commands was added
from their corresponding module documentation. In addition, documentation
for the file command was added.

Signed-off-by: Andrew Hamilton <adhamilt@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 16:13:27 +02:00
Michael Chang 9537f4403d commands/bli: Fix crash in get_part_uuid()
The get_part_uuid() function made an assumption that the target GRUB
device is a partition device and accessed device->disk->partition
without checking for NULL. There are four situations where this
assumption is problematic:

1. The device is a net device instead of a disk.
2. The device is an abstraction device, like LVM, RAID, or CRYPTO, which
   is mostly logical "disk" ((lvmid/<UUID>) and so on).
3. Firmware RAID may present the ESP to GRUB as an EFI disk (hd0) device
   if it is contained within a Linux software RAID.
4. When booting from a CD-ROM, the ESP is a VFAT image indexed by the El
   Torito boot catalog. The boot device is set to (cd0), corresponding
   to the CD-ROM image mounted as an ISO 9660 filesystem.

As a result, get_part_uuid() could lead to a NULL pointer dereference
and trigger a synchronous exception during boot if the ESP falls into
one of these categories. This patch fixes the problem by adding the
necessary checks to handle cases where the ESP is not a partition device.

Additionally, to avoid disrupting the boot process, this patch relaxes
the severity of the errors in this context to non-critical. Errors will
be logged, but they will not prevent the boot process from continuing.

Fixes: e0fa7dc84 (bli: Add a module for the Boot Loader Interface)

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-By: Oliver Steffen <osteffen@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-09-05 16:08:17 +02:00
Thomas Schmitt b53ec06a1d util/grub-mkrescue: Check existence of option arguments
As reported by Victoriia Egorova in bug 65880, grub-mkrescue does not
verify that the expected argument of an option like -d or -k does really
exist in argv. So, check the loop counter before incrementing it inside
the loop which copies argv to argp_argv. Issue an error message similar
to what older versions of grub-mkrescue did with a missing argument,
e.g. 2.02.

Fixes: https://savannah.gnu.org/bugs/index.php?65880

Signed-off-by: Thomas Schmitt <scdbackup@gmx.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 19:31:35 +02:00
Tobias Heider ab9fe80300 loader/efi/fdt: Add fdtdump command to access device tree
The fdtdump command allows dumping arbitrary device tree properties
and saving them to a variable similar to the smbios command.

This is useful in scripts where further actions such as selecting
a kernel or loading another device tree depend on the compatible
or model values of the device tree provided by the firmware.

For now only the root level properties of the dtb are exposed.

Signed-off-by: Tobias Heider <tobias.heider@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 19:21:02 +02:00
Vladimir Serbinenko 0cfec355d0 osdep/devmapper/getroot: Unmark 2 strings for translation
First they're use macros so they can't be translated as-is.
Second there is no point in translating them as they're too technical.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 19:14:41 +02:00
Vladimir Serbinenko f171122f03 loader/emu/linux: Fix determination of program name
Current code works only if package matches binary name transformation rules.
It's often true but is not guaranteed.

Fixes: https://savannah.gnu.org/bugs/?64410

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 19:11:48 +02:00
Vladimir Serbinenko 828717833f disk/cryptodisk: Fix translatable message
Fixes: https://savannah.gnu.org/bugs/?64408

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:51:52 +02:00
Vladimir Serbinenko 9a2134a70f tests: Add test for ZFS zstd
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:47:54 +02:00
Vladimir Serbinenko f96df6fe9f fs/zfs/zfs: Add support for zstd compression
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:43:23 +02:00
Mate Kukri 55d35d6283 kern/efi/mm: Detect calls to grub_efi_drop_alloc() with wrong page counts
Silently keeping entries in the list if the address matches, but the
page count doesn't is a bad idea, and can lead to double frees.

grub_efi_free_pages() have already freed parts of this block by this
point, and thus keeping the whole block in the list and freeing it again
at exit can lead to double frees.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:34:38 +02:00
Mate Kukri 61f1d0a612 kern/efi/mm: Change grub_efi_allocate_pages_real() to call semantically correct free function
If the firmware happens to return 0 as an address of allocated pages,
grub_efi_allocate_pages_real() tries to allocate a new set of pages,
and then free the ones at address 0.

However at that point grub_efi_store_alloc() wasn't yet called, so
freeing the pages at 0 using grub_efi_free_pages() which calls
grub_efi_drop_alloc() isn't necessary, so let's call b->free_pages()
instead.

The call to grub_efi_drop_alloc() doesn't seem particularly harmful,
because it seems to do nothing if the allocation it is asked to drop
isn't on the list, but the call to it is obviously unnecessary here.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:33:16 +02:00
Mate Kukri dc0a3a27d6 kern/efi/mm: Change grub_efi_mm_add_regions() to keep track of map allocation size
If the map was too big for the initial allocation, it was freed and replaced
with a bigger one, but the free call still used the hard-coded size.

Seems like this wasn't hit for a long time, because most firmware maps
fit into 12K.

This bug was triggered on Project Mu firmware with a big memory map, and
results in the heap getting trashed and the firmware ASSERTING on
corrupted heap guard values when GRUB exits.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:30:32 +02:00
Yifan Zhao b990df0bef tests/util/grub-fs-tester: Fix EROFS label tests in grub-fs-tester
mkfs.erofs with version < 1.6 does not support the -L option.
Let's detect the version of mkfs.erofs and skip the label tests
if it is not supported.

Suggested-by: Glenn Washburn <development@efficientek.com>
Signed-off-by: Yifan Zhao <zhaoyifan@sjtu.edu.cn>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:23:08 +02:00
Glenn Washburn d41c64811d tests: Switch to requiring exfatprogs from exfat-utils
The current Debian stable, now 12, has dropped the exfat-utils package
that the exfat filesystem test requires to run. There is an exfatprogs
package that replaces exfat-utils, though it is not a drop-in replacement
because mkfs.exfat has differing command line option names. Note, that
we're not yet switching to using the exfat kernel module because this
allows the testings on kernels that do not have the module.

Update mkfs.exfat usage to adhere to the different exfatprogs usage. Also,
the exfatprogs mkfs.exfat, following the exfat specification more closely,
only allows a maximum of 22 bytes of UTF-16 characters in the volume label
compared to 30 bytes from exfat-utils. So the exfat label test is updated
accordingly.

Update documentation to note that exfatprogs is now needed and also
exfat-fuse, which is needed do the fuse mount.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:19:12 +02:00
Glenn Washburn c1ee4da6a9 tests/util/grub-shell-luks-tester: Fix detached header test getting wrong header path
When $detached_header was set 1, $luksdiskfile was set to the LUKS header
file path with "${detached_header:-$luksfile}" appended, which evaluates
to "1". Fix this by using two statements to set $luksdiskfile. The first
sets it to the header file if $detached_header is set, otherwise leave it
unset. The second statement sets it to itself if it is already set,
otherwise it is set to $luksfile.

Fixes: a7b540e6e (tests: Add cryptomount functional test)

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:14:20 +02:00
Glenn Washburn c22e052fe2 tests/util/grub-shell: Add flexibility in QEMU firmware handling
First look for firmware files in the source directory and then, if not
found, look for them in locations where Debian installs them. Prefer to
use the unified firmware file and, if not found, use the pflash firmware
files split in to code and variables. By looking for files in the source
directory first, system firmware files can be overridden and it can be
ensured that the tests can be run regardless of the distro or where the
system firmware files are stored. If no firmware files are found, print
an error message and exit with error.

If a firmware VARS file is found, use it with snapshot mode enabled, which
makes the VARS writable to the virtual machine, but does not write back
the changes to the file. This allows using the readonly system VARS file
without copying it or using it in readonly mode, which causes the ARM
machine to fail. This also gives tests effectively their own ephemeral VARS
file that can be written to without causing side-effects for other tests.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:11:32 +02:00
Glenn Washburn d2fc9dfcd1 tests/util/grub-shell: Use pflash instead of -bios to load UEFI firmware
According to the OVMF whitepaper [1]:

  IMPORTANT: Never pass OVMF.fd to qemu with the -bios option. That option
  maps the firmware image as ROM into the guest's address space, and forces
  OVMF to emulate non-volatile variables with a fallback driver that is
  bound to have insufficient and confusing semantics.

Use the pflash interface instead. Currently the unified firmware file is
used, which contains both firmware code and variable sections. By enabling
snapshot on the pflash device, the firmware can be loaded in such a way
that variables can be written to without writing to the backing file.

Since pflash does no searching for firmware paths that are not absolute,
unlike the -bios option, also make firmware paths absolute. Additionally,
update the previous firmware paths or file names that did not correspond to
ones installed by Debian.

Use the q35 machine, instead of the default i440fx, for i386-efi because
the default machine type does not emulate a flash device, which is now
needed to load the firmware.

[1] http://www.linux-kvm.org/downloads/lersek/ovmf-whitepaper-c770f8c.txt

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:10:28 +02:00
Glenn Washburn 88a7e64c2c tests/util/grub-shell: Print gdbinfo if on EFI platform
Allow using GDB to debug a failing QEMU test. This output does not cause
issues for tests because it happens before the trim line, and so will be
ignored.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:05:35 +02:00
Glenn Washburn b8d29f1146 configure: Add Debian/Ubuntu DejaVu font path
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 15:00:51 +02:00
Udo Steinberg 13b315c0a5 term/ns8250-spcr: Add one more 16550 debug type
Type 0x01 was introduced with the ACPI DBGP table and type 0x12 was introduced
with the ACPI DBG2 table. Type 0x12 is used by the ACPI SPCR table on recent
AWS bare-metal instances (c6i/c7i). Also give each debug type a proper name.

Signed-off-by: Udo Steinberg <udo@hypervisor.org>
Reviewed-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 14:58:29 +02:00
Vladimir Serbinenko 8abec8e153 loader/i386/multiboot_mbi: Fix handling of errors in broken aout-kludge
Current code in some codepaths neither discards nor reports errors.
Properly surface the error.

While on it split 2 cases of unrelated variables both named err.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 14:46:23 +02:00
Michael Chang d35ff22516 net/drivers/ieee1275/ofnet: Remove 200 ms timeout in get_card_packet() to reduce input latency
When GRUB image is netbooted on ppc64le, the keyboard input exhibits
significant latency, reports even say that characters are processed
about once per second. This issue makes interactively trying to debug
a ppc64le config very difficult.

It seems that the latency is largely caused by a 200 ms timeout in the
idle event loop, during which the network card interface is consistently
polled for incoming packets. Often, no packets arrive during this
period, so the timeout nearly always expires, which blocks the response
to key inputs.

Furthermore, this 200 ms timeout might not need to be enforced at this
basic layer, considering that GRUB performs synchronous reads and its
timeout management is actually handled by higher layers, not directly in
the card instance. Additionally, the idle polling, which reacts to
unsolicited packets like ICMP and SLAAC, would be fine at a less frequent
polling interval, rather than needing a timeout for receiving a response.

For these reasons, we believe the timeout in get_card_packet() should be
effectively removed. According to test results, the delay has disappeared,
and it is now much easier to use interactively.

Signed-Off-by: Michael Chang <mchang@suse.com>
Tested-by: Tony Jones <tonyj@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-20 14:44:10 +02:00
Hector Cao 86df79275d commands/efi/tpm: Re-enable measurements on confidential computing platforms
The measurements for confidential computing has been introduced in the
commit 4c76565b6 (efi/tpm: Add EFI_CC_MEASUREMENT_PROTOCOL support).
Recently the patch 30708dfe3 (tpm: Disable the tpm verifier if the TPM
device is not present) has been introduced to optimize the memory usage
when a TPM device is not available on platforms. This fix prevents the
tpm module to be loaded on confidential computing platforms, e.g. Intel
machines with TDX enabled, where the TPM device is not available.

In this patch, we propose to load the tpm module for this use case by
generalizing the tpm feature detection in order to cover CC platforms.
Basically, we do it by detecting the availability of the
EFI_CC_MEASUREMENT_PROTOCOL EFI protocol.

Fixes: https://savannah.gnu.org/bugs/?65821
Fixes: 30708dfe3 (tpm: Disable the tpm verifier if the TPM device is not present)

Signed-off-by: Hector Cao <hector.cao@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Kuppuswamy Sathyanarayanan <sathyanarayanan.kuppuswamy@linux.intel.com>
2024-06-06 16:55:16 +02:00
Tianjia Zhang 0b4d01794a util/grub-mkpasswd-pbkdf2: Simplify the main function implementation
Allocate memory if needed, while saving the corresponding release
operation, reducing the amount of code and code complexity.

Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-06 16:55:16 +02:00
Avnish Chouhan fa36f63760 kern/ieee1275/init: Add IEEE 1275 Radix support for KVM on Power
This patch adds support for Radix, Xive and Radix_gtse in Options
vector5 which is required for KVM LPARs. KVM LPARs ONLY support
Radix and not the Hash. Not enabling Radix on any PowerVM KVM LPARs
will result in boot failure.

Signed-off-by: Avnish Chouhan <avnish@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-06 16:55:16 +02:00
Vladimir Serbinenko c464f1ec34 fs/zfs/zfs: Mark vdev_zaps_v2 and head_errlog as supported
We don't need any actual adjustments as we don't use the affected structures.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-06 16:55:16 +02:00
Vladimir Serbinenko 2ffc14ba95 types: Add missing casts in compile-time byteswaps
Without them, e.g., 0x80LL on 64-bit target is 32-bit byte-swapped to
0xffffffff80000000 instead of correct 0x80000000.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-06 16:55:16 +02:00
Vladimir Serbinenko c6ac491204 font: Add Fedora-specific font paths
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-06 16:55:16 +02:00
Vladimir Serbinenko 5e8989e4ed fs/bfs: Fix improper grub_free() on non-existing files
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-06 16:55:15 +02:00
Daniel Axtens c806e4dc88 io/gzio: Properly init a table
ARRAY_SIZE() is the count of elements, but the element size is 4 bytes, so
this was only initing the first 1/4th of the table. Detected with valgrind.

This should only matter in error paths, and I've not been able to identify
any actual misbehaviour that results from reading in-bounds but uninited data.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-06 16:55:15 +02:00
Daniel Axtens 243682baaa io/gzio: Abort early when get_byte() reads nothing
This isn't intended to be a functional change, but it makes a lot of failures a lot
faster, which is extremely helpful for fuzzing.

Without this change, we keep trying and trying to read more bytes into our buffer,
never being able to (read always returns 0) and so we just return old buffer contents
over and over until the decompression process fails some other way.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-06 16:55:15 +02:00
Alec Brown bb65d81fe3 cli_lock: Add build option to block command line interface
Add functionality to disable command line interface access and editing of GRUB
menu entries if GRUB image is built with --disable-cli.

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-06-06 16:54:10 +02:00
Yifan Zhao 56e58828cf fs/erofs: Add tests for EROFS in grub-fs-tester
This patch introduces three EROFS tests which cover compact, extended
and chunk-based inodes respectively.

Signed-off-by: Yifan Zhao <zhaoyifan@sjtu.edu.cn>
Reviewed-by: Glenn Washburn <development@efficientek.com>
Signed-off-by: Gao Xiang <hsiangkao@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-05-23 15:31:12 +02:00
Yifan Zhao 9d603061aa fs/erofs: Add support for the EROFS
The EROFS [1] is a lightweight read-only filesystem designed for performance
which has already been shipped in most Linux distributions as well as widely
used in several scenarios, such as Android system partitions, container
images and rootfs for embedded devices.

This patch brings in the EROFS uncompressed support. Now, it's possible to
boot directly through GRUB with an EROFS rootfs.

Support for the EROFS compressed files will be added later.

[1] https://erofs.docs.kernel.org

Signed-off-by: Yifan Zhao <zhaoyifan@sjtu.edu.cn>
Tested-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Gao Xiang <hsiangkao@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-05-23 15:30:29 +02:00
Gao Xiang 1ba39de62f safemath: Add ALIGN_UP_OVF() which checks for an overflow
The following EROFS patch will use this helper to handle
ALIGN_UP() overflow.

Signed-off-by: Gao Xiang <hsiangkao@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-05-23 15:19:06 +02:00
Jonathan Davies d291449ba3 docs: Fix spelling mistakes
Signed-off-by: Jonathan Davies <jonathan.davies@nutanix.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-05-23 15:03:26 +02:00
Pascal Hambourg 6cc2e4481b util/grub.d/00_header.in: Quote background image pathname in output
This is required if the pathname contains spaces or GRUB shell
metacharacters else the generated config file check will fail.

Signed-off-by: Pascal Hambourg <pascal@plouf.fr.eu.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-05-23 14:57:37 +02:00
Rogier f456add5f4 disk/lvm: GRUB fails to detect LVM volumes due to an incorrect computation of mda_end
When handling a regular LVM volume, GRUB can fail with the message:

  error: disk `lvmid/******-****-****-****-****-****-****/******-****-****-****-****-****-******' not found.

If the condition which triggers this exists, grub-probe will report the
error mentioned above. Similarly, the GRUB boot code will fail to detect
LVM volumes, resulting in a failure to boot off of LVM disks/partitions.
The condition can be created on any LVM VG by an LVM configuration change,
so any system with /boot on LVM can become unbootable at "any" time (after
any LVM configuration change).

The problem is caused by an incorrect computation of mda_end in disk/lvm.c,
when the metadata area wraps around. Apparently, this can start happening at
around 220 metadata changes to the VG.

Fixes: 879c4a834 (lvm: Fix two more potential data-dependent alloc overflows)
Fixes: https://savannah.gnu.org/bugs/?61620

Signed-off-by: Rogier <rogier777@gmail.com>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-By: Michael Chang <mchang@suse.com>
2024-05-23 14:42:39 +02:00
Forest 386b59ddb4 disk/cryptodisk: Allow user to retry failed passphrase
Give the user a chance to re-enter their cryptodisk passphrase after a typo,
rather than immediately failing (and likely dumping them into a GRUB shell).

By default, we allow 3 tries before giving up. A value in the
cryptodisk_passphrase_tries environment variable will override this default.

The user can give up early by entering an empty passphrase, just as they
could before this patch.

Signed-off-by: Forest <forestix@nom.one>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-05-09 15:30:31 +02:00
Lidong Chen 99b4c0c384 disk/mdraid1x_linux: Prevent infinite recursion
The test corpus for version-1 RAID generated an infinite recursion
in grub_partition_iterate() while attempting to read the superblock.
The reason for the issue was that the data region overlapped with
the superblock.

The infinite call loop looks like this:
  grub_partition_iterate() -> partmap->iterate() ->
    -> grub_disk_read() -> grub_disk_read_small() ->
    -> grub_disk_read_small_real() -> grub_diskfilter_read() ->
    -> read_lv() -> read_segment() -> grub_diskfilter_read_node() ->
    -> grub_disk_read() -> grub_disk_read_small() -> ...

The fix adds checks for both the superblock region and the data
region when parsing the superblock metadata in grub_mdraid_detect().

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-05-09 15:25:46 +02:00
Ard Biesheuvel b272ed230e efi: Fix stack protector issues
The "ground truth" stack protector cookie value is kept in a global
variable, and loaded in every function prologue and epilogue to store
it into resp. compare it with the stack slot holding the cookie.

If the comparison fails, the program aborts, and this might occur
spuriously when the global variable changes values between the entry and
exit of a function. This implies that assigning the global variable at
boot should not involve any instrumented function calls, unless special
care is taken to ensure that the live call stack is synchronized, which
is non-trivial.

So avoid any function calls, including grub_memcpy(), which is
unnecessary given that the stack cookie is always a suitably aligned
variable of the native word size.

While at it, leave the last byte 0x0 to avoid inadvertent unbounded
strings on the stack.

Note that the use of __attribute__((optimize)) is described as
unsuitable for production use in the GCC documentation, so let's drop
this as well now that it is no longer needed.

Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-05-09 15:20:05 +02:00
Oliver Steffen 6744840b17 build: Track explicit module dependencies in Makefile.core.def
Add a new keyword, "depends", to the module definition syntax
used in Makefile.core.def. This allows specifying explicit module
dependencies together with the module definition.

Do not track the "extra_deps.lst" file in the repository anymore,
it is now auto-generated.

Make use of this new keyword in the bli module definition.

Signed-off-by: Oliver Steffen <osteffen@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-05-09 15:04:54 +02:00
Daniel Kiper 8719cc2040 windows: Add _stack_chk_guard/_stack_chk_fail symbols for Windows 64-bit target
Otherwise the GRUB cannot start due to missing symbols when stack
protector is enabled on EFI platforms.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
2024-04-11 15:48:26 +02:00
Gary Lin 0876fdf215 util/bash-completion: Fix for bash-completion 2.12
_split_longopt() was the bash-completion private API and removed since
bash-completion 2.12. This commit initializes the bash-completion
general variables with _init_completion() to avoid the potential
"command not found" error.

Although bash-completion 2.12 introduces _comp_initialize() to deprecate
_init_completion(), _init_completion() is still chosen for the better
backward compatibility.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-04-11 15:48:25 +02:00
Vladimir 'phcoder' Serbinenko 28c4405208 util/grub-fstest: Add a new command zfs-bootfs
It is useful to check zfs-bootfs command.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-04-11 15:48:25 +02:00
Vladimir 'phcoder' Serbinenko 52e039e00b efi: Enable CMOS on x86 EFI platforms
The CMOS actually exists on most EFI platforms and in some cases is used to
store useful data that makes it justifiable for GRUB to read/write it.

As for date and time keep using EFI API and not CMOS one.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-04-11 15:48:25 +02:00
Vladimir 'phcoder' Serbinenko aa80270154 acpi: Mark MADT entries as packed
No alignment is guaranteed and in fact on my IA-64 SAPIC is aligned
to 4 bytes instead of 8 and causes a trap. It affects only rarely used
lsacpi command and so went unnoticed.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-04-11 15:48:25 +02:00
Michael Chang 39c927df66 gfxmenu/view: Resolve false grub_errno disrupting boot process
When enabling gfxmenu and choosing to boot the Xen hypervisor from its
menu, an error occurred:

  error: ../../grub-core/video/bitmap_scale.c:42:null src bitmap in grub_video_create_scaled.

The error is returned by grub_video_bitmap_create_scaled() when the
source pixmap is not there. The init_background() uses it to scale up
the background image so it can fully fit into the screen resolution.

However not all backgrounds are set by a image, i.e. the "desktop-image"
property of the theme file. Instead a color code may be used, for
example OpenSUSE's green background uses "desktop-color" property:

  desktop-color: "#0D202F"

So it is absolutely fine to call init_background() without a raw pixmap
if color code is used. A missing check has to be added to ensure the
grub_errno will not be erroneously set and gets in the way of ensuing
boot process.

The reason it happens sporadically is due to grub_errno is reset to
GRUB_ERR_NONE in other places if a function's error return can be
ignored. In particular this hunk in grub_gfxmenu_create_box() does the
majority of the reset of grub_errno returned by init_background(), but
the path may not be always chosen.

  grub_video_bitmap_load (&box->raw_pixmaps[i], path);
  grub_free (path);

  /* Ignore missing pixmaps.  */
  grub_errno = GRUB_ERR_NONE;

In any case, we cannot account on such random behavior and should only
return grub_errno if it is justified.

On the occasion move the grub_video_bitmap struct definition to the
beginning of the function.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-04-11 15:48:25 +02:00
Jon DeVree 68dd65cfda fs/xfs: Handle non-continuous data blocks in directory extents
The directory extent list does not have to be a continuous list of data
blocks. When GRUB tries to read a non-existant member of the list,
grub_xfs_read_file() will return a block of zero'ed memory. Checking for
a zero'ed magic number is sufficient to skip this non-existant data block.

Prior to commit 07318ee7e (fs/xfs: Fix XFS directory extent parsing)
this was handled as a subtle side effect of reading the (non-existant)
tail data structure. Since the block was zero'ed the computation of the
number of directory entries in the block would return 0 as well.

Fixes: 07318ee7e (fs/xfs: Fix XFS directory extent parsing)
Fixes: https://bugzilla.redhat.com/show_bug.cgi?id=2254370

Signed-off-by: Jon DeVree <nuxi@vault24.org>
Reviewed-By: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-04-11 15:46:44 +02:00
Julian Andres Klode 04d2a50f31 Revert "templates: Reinstate unused version comparison functions with warning"
We reinstated these functions before the 2.12 release with a warning
such that users upgrading to 2.12 who had custom scripts using them
would not get broken in the upgrade and agreed to remove them after
the 2.12 release. This removes them accordingly.

This reverts commit e7a831963 (templates: Reinstate unused version
comparison functions with warning).

Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Julian Andres Klode <julian.klode@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-02-15 16:54:59 +01:00
Gary Lin 4380c2d8ad util/bash-completion: Load scripts on demand
There are two system directories for bash-completion scripts. One is
/usr/share/bash-completion/completions/ and the other is
/etc/bash_completion.d/. The "etc" scripts are loaded in advance and
for backward compatibility while the "usr" scripts are loaded on demand.
To load scripts on demand it requires a corresponding script for every
command. So, the main bash-completion script is split into several
subscripts for different "grub-*" commands. To share the code the real
completion functions are still implemented in "grub" and each
subscript sources "grub" and invokes the corresponding function.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-02-15 16:51:36 +01:00
Samuel Thibault 9e1b18fc17 util/grub.d/10_hurd.in: Find proper ld.so on 64-bit systems
The 64-bit ABI defines ld.so to be /lib/ld-x86-64.so.1.

Signed-off-by: Samuel Thibault <samuel.thibault@ens-lyon.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-01-25 18:24:35 +01:00
Samuel Thibault a8c0504515 osdep/hurd/getroot: Fix 64-bit build
The file_get_fs_options() takes a mach_msg_type_number_t, 32-bit,
not a size_t, 64-bit on 64-bit platforms.

Signed-off-by: Samuel Thibault <samuel.thibault@ens-lyon.org>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-01-25 18:17:09 +01:00
Alec Brown d89a2a6e57 loader/i386/multiboot_mbi: Clean up redundant code
In grub-core/loader/i386/multiboot_mbi.c, Coverity spotted redundant code where
the variable err was being set to GRUB_ERR_NONE and then being overwritten
later without being used. Since this is unnecessary, we can remove the code
that sets err to GRUB_ERR_NONE.

Fixes: CID 428877

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-01-25 18:13:33 +01:00
Alec Brown db0d19dc5f osdep/unix/getroot: Clean up redundant code
In grub-core/osdep/unix/getroot.c, Coverity spotted redundant code where the
double pointer os_dev was being set to 0 and then being overwritten later
without being used. Since this is unnecessary, we can remove the code that
sets os_dev to 0.

Fixes: CID 428875

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-01-25 18:11:03 +01:00
Alec Brown c8bf758757 fs/jfs: Clean up redundant code
In grub-core/fs/jfs.c, Coverity spotted redundant code where the pointer diro
was being set to 0 and then being overwritten later without being used. Since
this is unnecessary, we can remove the code that sets diro to 0.

Fixes: CID 428876

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-01-25 18:08:48 +01:00
Gary Lin 5a311d029f tests: Switch password quality check off for luks2 test
When adding/changing the password for the luks2 partition, cryptsetup
may reject the command due to the weak password. Since this is only for
testing, add "--force-password" to switch password quality check off to
avoid the unexpected failure.

Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2024-01-25 18:07:49 +01:00
Oskari Pirhonen b835601c76 build: Include grub-core/extra_deps.lst in dist
Fixes build failure due to the extra_deps.lst file not existing in the
tarball. Found while trying to package GRUB 2.12 for Gentoo.

  make[3]: *** No rule to make target '/var/tmp/portage/sys-boot/grub-2.12/work/grub-2.12/grub-core/extra_deps.lst', needed by 'syminfo.lst'.  Stop.

Fixes: 89fbe0cac (grub-core/Makefile.am: Make path to extra_deps.lst relative to $(top_srcdir)/grub-core)
Fixes: 154dcb1ae (build: Allow explicit module dependencies)

Signed-off-by: Oskari Pirhonen <xxc3ncoredxx@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-22 16:07:36 +01:00
Daniel Kiper 8961305b4e Bump version to 2.13
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-20 17:25:46 +01:00
Daniel Kiper 5ca9db22e8 Release 2.12
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-20 16:54:46 +01:00
Glenn Washburn 477a0dbd5e efi: Add support for reproducible builds
Having randomly generated bytes in the binary output breaks reproducible
builds. Since build timestamps are usually the source of irreproducibility
there is a standard which defines an environment variable SOURCE_DATE_EPOCH
to be used when set for build timestamps. According to the standard [1], the
value of SOURCE_DATE_EPOCH is a base-10 integer of the number of seconds
since the UNIX epoch. Currently, this is a 10 digit number that fits into
32-bits, but will not shortly after the year 2100. So to be future-proof
only use the least significant 32-bits. On 64-bit architectures, where the
canary is also 64-bits, there is an extra 32-bits that can be filled to
provide more entropy. The first byte is NUL to filter out string buffer
overflow attacks and the remaining 24-bits are set to static random bytes.

[1] https://reproducible-builds.org/specs/source-date-epoch

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-20 14:36:18 +01:00
Glenn Washburn dcc1af5d68 efi: Generate stack protector canary at build time if urandom is available
Generating the canary at build time allows the canary to be different for
every build which could limit the effectiveness of certain exploits.
Fallback to the statically generated random bytes if /dev/urandom is not
readable, e.g. Windows.

On 32-bit architectures, which use a 32-bit canary, reduce the canary to
4 bytes with one byte being NUL to filter out string buffer overflow attacks.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-20 14:31:50 +01:00
Glenn Washburn e424e945c9 efi: Initialize canary to non-zero value
The canary, __stack_chk_guard, is in the BSS and so will get initialized to
zero if it is not explicitly initialized. If the UEFI firmware does not
support the RNG protocol, then the canary will not be randomized and will
be zero. This seems like a possibly easier value to write by an attacker.
Initialize canary to static random bytes, so that it is still random when
there is no RNG protocol. Set at least one byte to NUL to protect against
string buffer overflow attacks [1]. Code that writes NUL terminated strings
will terminate when a NUL is encountered in the input byte stream. So the
attacker will not be able to forge the canary by including it in the input
stream without terminating the string operation and thus limiting the
stack corruption.

[1] https://www.sans.org/blog/stack-canaries-gingerly-sidestepping-the-cage/

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-20 14:17:23 +01:00
Alec Brown 7c8ae7dcbd gfxmenu/gui_image: Fix double free of bitmap
In grub-core/gfxmenu/gui_image.c, Coverity detected a double free in the
function load_image(). The function checks if self->bitmap and self->raw_bitmap
aren't NULL and then frees them. In the case self->bitmap and self->raw_bitmap
are the same, only self->raw_bitmap is freed which would also free the memory
used by self->bitmap. However, in this case self->bitmap isn't being set to NULL
which could lead to a double free later in the code. After self->raw_bitmap is
freed, it gets set to the variable bitmap. If this variable is NULL, the code
could have a path that would free self->bitmap a second time in the function
rescale_image().

Fixes: CID 292472

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-14 19:29:34 +01:00
Qiumiao Zhang 63fc253fc9 commands/acpi: Fix calculation of ACPI tables addresses when processing RSDT and XSDT
According to the ACPI specification the XSDT Entry field contains an array
of 64-bit physical addresses which points to other DESCRIPTION_HEADERs. However,
the entry_ptr iterator is defined as a 32-bit pointer. It means each 64-bit
entry in the XSDT table is treated as two separate 32-bit entries then. Fix the
issue by using correct addresses sizes when processing RSDT and XSDT tables.

Signed-off-by: Qiumiao Zhang <zhangqiumiao1@huawei.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-13 14:21:21 +01:00
Vladimir Serbinenko f20123072a libnvpair: Support prefixed nvlist symbol names as found on NetBSD
NetBSD uses slightly different function names for the same functions.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-13 13:30:33 +01:00
Vladimir Serbinenko a13df3d15a bootstrap: Don't check gettext version
NetBSD gettext is older than the check but we don't actually need 0.18.3,
older one works fine. This is needed to make bootstrap work on NetBSD.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-13 13:25:34 +01:00
Vladimir Serbinenko 6d2aa7ee01 kern/mm: Use %x and cast for displaying sizeof()
There is some variance in how compiler treats sizeof() especially
on 32-bit platforms where it can be naturally either int or long.
Explicit cast solves the issue.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-13 13:18:42 +01:00
Vladimir Serbinenko b3d49a697b configure: Add RPATH for freetype on NetBSD
Without this build-time mkfont fails dynamic linking. This is not ideal
but improves the situation until a better solution is available.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-13 13:07:03 +01:00
Vladimir Serbinenko 52dbf66ea4 configure: Add *BSD font paths
*BSD puts fonts in other places. Add them to the list.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-13 13:03:32 +01:00
Vladimir Serbinenko 2d6a899806 autogen: Accept python3.10 as a python alternative
NetBSD doesn't provide python or python3.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-13 13:00:00 +01:00
Vladimir Serbinenko 3d4cb5a432 build: Rename HAVE_LIBZFS to USE_LIBZFS
The HAVE_LIBZFS is defined by libzfs test and hence conflicts with
manual definition. On NetBSD it ends up detecting zfs but not detecting
nvpair and creates confusion. Split them.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 18:01:55 +01:00
Vladimir Serbinenko e4dbe5cfa4 gnulib: Tolerate always_inline attribute being ignored
It's not critical, -Werror on it is inappropriate. We don't want to
modify gnulib too much. This warning is pretty much irrelevant.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 17:58:10 +01:00
Vladimir Serbinenko 31e47cfe2c util/editenv: Don't use %m formatter
It's not available on NetBSD outside of syslog. Using strerror() is more
reliable as we retrieve errno immediately rather than down the stack.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 17:55:14 +01:00
Vladimir Serbinenko f5905f6566 osdep/bsd/hostdisk: Fix NetBSD compilation
Wrong function and variable name cause a stupid compilation error on
NetBSD and OpenBSD. Only NetBSD and OpenBSD use this file. No other
platform is affected.

Additionally, define RAW_FLOPPY_MAJOR constant if it is missing.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 17:55:14 +01:00
Vladimir Serbinenko cb1824a871 osdep/generic/blocklist: Fix compilation
After recent change in blocklist types we have a type mismatch. Fixing it
requires a wrapper or large changes. I feel like wrapper makes more sense.

Without this patch we end up with a compilation problem and without wrapping
callback data is not passed properly anymore.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 17:53:56 +01:00
Vladimir Serbinenko 2f3faf02c4 disk/diskfilter: Remove unused variable
Variable e is set but never used. We can just remove it now.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 17:22:20 +01:00
Vladimir Serbinenko 3815acc57b build: Tolerate unused-but-set in generated lexer/bison files
We don't really control the small aspects of generated files and NetBSD
version has an unused variable that is then detected by gcc as warning
that is then promoted to error.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 17:18:18 +01:00
Vladimir Serbinenko c129e44e7f loader/i386/bsdXX: Fix loading after unaligned module
Current code implicitly assumes that aligning chunk_size + *kern_end is
the same as aligning on curload which is not the case because
chunk_size starts at zero even if *kern_end is unaligned and ALIGN_PAGE
moved curload to an aligned position but not *kern_end + chunk_size.

This fixes booting of FreeBSD with zfs module.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 17:14:27 +01:00
Mate Kukri 89fbe0cac9 grub-core/Makefile.am: Make path to extra_deps.lst relative to $(top_srcdir)/grub-core
The commit 154dcb1ae (build: Allow explicit module dependencies) broke
out of tree builds by introducing the extra_deps.lst file into the
source tree but referencing it just by name in grub-core/Makefile.am.
Fix it by adding $(top_srcdir)/grub-core to the path.

Fixes: 154dcb1ae (build: Allow explicit module dependencies)

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 17:06:13 +01:00
Mate Kukri 353beb80c0 util/grub-install: Move platdir path canonicalization after files were copied to grubdir
The commit 3f9eace2d (util/grub-install: Delay copying files to
{grubdir,platdir} after install_device was validated) delaying
copying of files caused a regression when installing without an
existing directory structure.

This patch ensures that the platform directory actually exists by the
time the code tries to canonicalize its filename.

Fixes: 3f9eace2d (util/grub-install: Delay copying files to {grubdir,platdir} after install_device was validated)

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 16:48:44 +01:00
Michael Chang f18a899ab1 util/grub-mkstandalone: Ensure deterministic tar file creation by sorting contents
The add_tar_files() function currently iterates through a directory's
content using readdir(), which doesn't guarantee a specific order. This
lack of deterministic behavior impacts reproducibility in the build process.

This commit resolves the issue by introducing sorting functionality.
The list retrieved by readdir() is now sorted alphabetically before
incorporation into the tar archive, ensuring consistent and predictable
file ordering within the archive.

On the occasion fix tfp memory leak.

Signed-off-by: Michael Chang <mchang@suse.com>
Signed-off-by: Bernhard Wiedemann <bwiedemann@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 15:47:08 +01:00
Michael Chang ed74bc3764 util/grub-mkstandalone: Ensure stable timestamps for generated images
This change mirrors a previous fix [1] but is specific to images
generated by grub-mkstandalone.

The former fix, commit 85a7be241 (util/mkimage: Use stable timestamp
when generating binaries.), focused on utilizing a stable timestamp
during binary generation in the util/mkimage context. This commit
extends that approach to the images produced by grub-mkstandalone,
ensuring consistency and stability in timestamps across all generated
binaries.

[1] 85a7be241 util/mkimage: Use stable timestamp when generating binaries.

Signed-off-by: Michael Chang <mchang@suse.com>
Signed-off-by: Bernhard Wiedemann <bwiedemann@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-12 15:12:41 +01:00
Mate Kukri 069cc46c96 net/http: Fix gcc-13 errors relating to type signedness
Replace definition of HTTP_PORT with a pre-processor macro that converts
the constant to the correct grub_uint16_t type.

Change "port" local variable definition in http_establish() to have the
same type.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com
2023-12-05 15:55:10 +01:00
Julian Andres Klode e7a831963e templates: Reinstate unused version comparison functions with warning
Revert the commit a79c567f6 (templates: Remove unused version comparison
functions) and add a warning to the functions that they are deprecated.

Removing the functions directly caused a lot of upgrade issues
with custom user scripts that called the functions. In Debian and
Ubuntu, grub-mkconfig is invoked as a post-installation script
and would fail, causing upgrades to fail halfway through and
putting the package manager into an inconsistent state.

FWIW, we get one bug per 2 weeks basically, for an interim Ubuntu
release which generally does not receive much usage, that is a high
number.

The proposal is to pick this for 2.12 and directly after the release
remove it again. Then users will have time to fix their scripts without
systems breaking immediately.

This reverts commit a79c567f6 (templates: Remove unused version
comparison functions).

Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Julian Andres Klode <julian.klode@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-05 15:47:40 +01:00
Mate Kukri 3f9eace2d3 util/grub-install: Delay copying files to {grubdir,platdir} after install_device was validated
Previously grub-install copied modules to grubdir before doing any
validation on the install_device.

When grub-install was called with an invalid install_device, modules
were already copied to /boot before it found out and was forced to rely
on atexit() rollback.

This patch delays copying the modules after at least some install_device
validation was done, and thus reduces reliance on successful rollback.

Signed-off-by: Mate Kukri <mate.kukri@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-05 15:32:30 +01:00
Julian Andres Klode e60015f574 efi: Set shim_lock_enabled even if validation is disabled
If validation has been disabled via MokSbState, secure boot on the
firmware is still enabled, and the kernel fails to boot.

This is a bit hacky, because shim_lock is not *fully* enabled, but
it triggers the right code paths.

Ultimately, all this will be resolved by shim gaining it's own image
loading and starting protocol, so this is more a temporary workaround.

Fixes: 6425c12cd (efi: Fallback to legacy mode if shim is loaded on x86 archs)

Cc: Peter Jones <pjones@redhat.com>
Cc: Michael Chang <mchang@suse.com>
Signed-off-by: Julian Andres Klode <julian.klode@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-05 15:28:39 +01:00
Oliver Steffen e35683317e docs: Improve bli module documentation
Improve the documentation of the bli module and explain in more detail what
it does. Make clear that GPT formatted drives are expected and other
partition formats are ignored. Also reorder and reword this section a bit.

Signed-off-by: Oliver Steffen <osteffen@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-05 15:26:36 +01:00
Oliver Steffen 57059ccb62 bli: Add explicit dependency on the part_gpt module
The bli module has a "hidden" dependency on the part_gpt module, which
is not picked up automatically by the build system. One purpose of the
bli module is to communicate the GPT UUID of the partition GRUB was
launched from to Linux user-space (systemd-gpt-auto-generator).
Without the part_gpt module, bli is not able to obtain the UUID. Since
bli does its work in the module initialization function, the order in
which the modules are loaded is also important: part_gpt needs to be
loaded before the bli module.

To solve this, track this dependency explicitly.

Note that the Boot Loader Interface specification, which bli aims to
implement, requires GPT formatted drives. The bli module ignores all
other partition formats.

Signed-off-by: Oliver Steffen <osteffen@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-05 15:06:58 +01:00
Oliver Steffen 154dcb1aea build: Allow explicit module dependencies
The build system deduces inter-module dependencies from the symbols
required and exported by the modules. This works well, except for some
rare cases where the dependency is indirect or hidden. A module might
not make use of any function of some other module, but still expect its
functionality to be available to GRUB.

To solve this, introduce a new file, currently empty, called extra_deps.lst
to track these cases manually. This file gets processed in the same way
as the automatically generated syminfo.lst, making it possible to inject
data into the dependency resolver.

Since *.lst files are set to be ignored by git, add an exception for
extra_deps.lst.

Additionally, introduce a new keyword for the syminfo.lst syntax:
"depends" allows specifying a module dependency directly:

  depends <module> <depdendency>...

Signed-off-by: Oliver Steffen <osteffen@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-05 14:58:36 +01:00
Stefan Berger 17c68472d1 kern/ieee1275/init/ppc64: Display upper_mem_limit when debugging
Display upper_mem_limit and its rounded-down value in MiB.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-05 14:55:30 +01:00
Stefan Berger 5f8e091b6a kern/ieee1275/init/ppc64: Fix a comment
Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-12-05 14:52:49 +01:00
Stefan Berger dc569b0777 kern/ieee1275/ieee1275: Display successful memory claims when debugging
Display successful memory claims with exact address and rounded-down
MiB location and rounded-up size in MiB.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Cc: Eric Snowberg <eric.snowberg@oracle.com>
Cc: Hari Bathini <hbathini@linux.ibm.com>
Cc: Pavithra Prakash <pavrampu@in.ibm.com>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Carolyn Scherrer <cpscherr@us.ibm.com>
Cc: Mahesh Salgaonkar <mahesh@linux.ibm.com>
Cc: Sourabh Jain <sourabhjain@linux.ibm.com>
2023-12-05 14:43:15 +01:00
Stefan Berger 0ac3d938a3 loader/powerpc/ieee1275: Use new allocation function for kernel and initrd
On PowerVM and KVM on Power use the new memory allocation function that
honors restrictions on which memory GRUB can actually use. In the request
structure indicate the request for a single memory block along with
address alignment restrictions. Request direct usage of the memory block
by setting init_region to false (prevent it from being added to GRUB's
heap). Initialize the found addr to -1, so that -1 will be returned
to the loader in case no memory could be allocated.

Report an out-of-memory error in case the initrd could not be loaded.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Cc: Hari Bathini <hbathini@linux.ibm.com>
Cc: Pavithra Prakash <pavrampu@in.ibm.com>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Carolyn Scherrer <cpscherr@us.ibm.com>
Cc: Mahesh Salgaonkar <mahesh@linux.ibm.com>
Cc: Sourabh Jain <sourabhjain@linux.ibm.com>
2023-12-05 14:39:33 +01:00
Stefan Berger 2a9a8518e9 kern/ieee1275/cmain/ppc64: Introduce flags to identify KVM and PowerVM
Introduce flags to identify PowerVM and KVM on Power and set them where
each type of host has been detected.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Cc: Hari Bathini <hbathini@linux.ibm.com>
Cc: Pavithra Prakash <pavrampu@in.ibm.com>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Carolyn Scherrer <cpscherr@us.ibm.com>
Cc: Mahesh Salgaonkar <mahesh@linux.ibm.com>
Cc: Sourabh Jain <sourabhjain@linux.ibm.com>
2023-12-05 14:37:09 +01:00
Stefan Berger 679691a13e kern/ieee1275/init/ppc64: Rename regions_claim() to grub_regions_claim()
Rename regions_claim() to grub_regions_claim() to make it available for
memory allocation. The ieee1275 loader will use this function on PowerVM
and KVM on Power and thus avoid usage of memory that it is not allowed
to use.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Cc: Hari Bathini <hbathini@linux.ibm.com>
Cc: Pavithra Prakash <pavrampu@in.ibm.com>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Carolyn Scherrer <cpscherr@us.ibm.com>
Cc: Mahesh Salgaonkar <mahesh@linux.ibm.com>
Cc: Sourabh Jain <sourabhjain@linux.ibm.com>
2023-12-05 14:31:38 +01:00
Stefan Berger d49e86db2c kern/ieee1275/init/ppc64: Add support for alignment requirements
Add support for memory alignment requirements and adjust a candidate
address to it before checking whether the block is large enough. This
must be done in this order since the alignment adjustment can make
a block smaller than what was requested.

None of the current callers has memory alignment requirements but the
ieee1275 loader for kernel and initrd will use it to convey them.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Cc: Hari Bathini <hbathini@linux.ibm.com>
Cc: Pavithra Prakash <pavrampu@in.ibm.com>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Carolyn Scherrer <cpscherr@us.ibm.com>
Cc: Mahesh Salgaonkar <mahesh@linux.ibm.com>
Cc: Sourabh Jain <sourabhjain@linux.ibm.com>
2023-12-05 14:29:55 +01:00
Stefan Berger fe5d5e8571 kern/ieee1275/init/ppc64: Return allocated address using context
Return the allocated address of the memory block in the request structure
if a memory allocation was actually done. Leave the address untouched
otherwise. This enables a caller who wants to use the allocated memory
directly, rather than adding the memory to the heap, to see where memory
was allocated. None of the current callers need this but the converted
ieee1275 loader will make use of it.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Cc: Hari Bathini <hbathini@linux.ibm.com>
Cc: Pavithra Prakash <pavrampu@in.ibm.com>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Carolyn Scherrer <cpscherr@us.ibm.com>
Cc: Mahesh Salgaonkar <mahesh@linux.ibm.com>
Cc: Sourabh Jain <sourabhjain@linux.ibm.com>
2023-12-05 14:22:54 +01:00
Stefan Berger ea2c934849 kern/ieee1275/init/ppc64: Decide by request whether to initialize region
Let the regions_claim() request structure's init_region determine whether
to call grub_mm_init_region() on it. This allows for adding memory to
GRUB's memory heap if init_region is set to true, or direct usage of the
memory otherwise. Set all current callers' init_region to true since they
want to add memory regions to GRUB's heap.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Cc: Hari Bathini <hbathini@linux.ibm.com>
Cc: Pavithra Prakash <pavrampu@in.ibm.com>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Carolyn Scherrer <cpscherr@us.ibm.com>
Cc: Mahesh Salgaonkar <mahesh@linux.ibm.com>
Cc: Sourabh Jain <sourabhjain@linux.ibm.com>
2023-12-05 14:18:44 +01:00
Stefan Berger 0bb59fa9a3 kern/ieee1275/init/ppc64: Introduce a request for regions_claim()
The regions_claim() function limits the allocation of memory regions
by excluding certain memory areas from being used by GRUB. This for
example includes a gap between 640MB and 768MB as well as an upper
limit beyond which no memory may be used when an fadump is present.
However, the ieee1275 loader for kernel and initrd currently does not
use regions_claim() for memory allocation on PowerVM and KVM on Power
and therefore may allocate memory in those areas that it should not use.

To make the regions_claim() function more flexible and ultimately usable
for the ieee1275 loader, introduce a request structure to pass various
parameters to the regions_claim() function that describe the properties
of requested memory chunks. In a first step, move the total and flags
variables into this structure.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Cc: Hari Bathini <hbathini@linux.ibm.com>
Cc: Pavithra Prakash <pavrampu@in.ibm.com>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Carolyn Scherrer <cpscherr@us.ibm.com>
Cc: Mahesh Salgaonkar <mahesh@linux.ibm.com>
Cc: Sourabh Jain <sourabhjain@linux.ibm.com>
2023-12-05 14:12:26 +01:00
Anthony Iliopoulos aa7c132267 fs/xfs: Add large extent counters incompat feature support
XFS introduced 64-bit extent counters for inodes via a series of
upstream commits and the feature was marked as stable in v6.5 via
commit 61d7e8274cd8 (xfs: drop EXPERIMENTAL tag for large extent
counts).

Further, xfsprogs release v6.5.0 switched this feature on by default
in mkfs.xfs via commit e5b18d7d1d96 (mkfs: enable large extent counts
by default).

Filesystems formatted with large extent count support, nrext64=1, are
thus currently not recognizable by GRUB, since this is an incompat
feature. Add the required support so that those filesystems and inodes
with large extent counters can be read by GRUB.

Signed-off-by: Anthony Iliopoulos <ailiop@suse.com>
Reviewed-by: Andrey Albershteyn <aalbersh@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Marta Lewandowska <mlewando@redhat.com>
Tested-by: Sebastian Andrzej Siewior <sebastian@breakpoint.cc>
2023-11-22 19:13:46 +01:00
Vladimir Serbinenko 64e3cee72a gpt: Add compile time asserts for guid and gpt_partentry sizes
With new alignment specification it's easy to screw up. Fortunately if it
happens the size will be bigger than intended. Compile time assert will catch
this.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-11-08 05:05:06 +01:00
Vladimir Serbinenko 7de6fe9635 types: Split aligned and packed guids
On ia64 alignment requirements are strict. When we pass a pointer to
UUID it needs to be at least 4-byte aligned or EFI will crash.
On the other hand in device path there is no padding for UUID, so we
need 2 types in one formor another. Make 4-byte aligned and unaligned types

The code is structured in a way to accept unaligned inputs
in most cases and supply 4-byte aligned outputs.

Efiemu case is a bit ugly because there inputs and outputs are
reversed and so we need careful casts to account for this
inversion.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-11-08 05:04:24 +01:00
Vladimir Serbinenko 5fc985bfdd gpt_partition: Mark grub_gpt_partentry as having natural alignment
gpt_partition contains grub_guid. We need to decide whether the whole
structure is unaligned and then we need to use packed_guid. But we never
have unaligned part entries as we read them in an aligned buffer from disk.
Hence just make it all aligned.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
2023-11-06 22:48:24 +01:00
Vladimir Serbinenko 7ad30299da efi: Deduplicate configuration table search function
We do table search in many places doing exactly the same algorithm.
The only minor variance in users is which table is used if several entries
are present. As specification mandates uniqueness and even if it ever isn't,
first entry is good enough, unify this code and always use the first entry.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-11-06 22:47:16 +01:00
Vladimir Serbinenko c6cf807fc0 lsefi: Add missing static qualifier
known_protocols isn't used anywhere else and even misses grub_ prefix, so
let's make it local (static).

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-11-06 22:38:12 +01:00
Vladimir Serbinenko a964e359bc types: Fix typo
Just a small grammar mistake.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-11-06 22:37:31 +01:00
Qiumiao Zhang 3f79e3b158 util/grub-mount: Check file path sanity
The function argp_parser() in util/grub-mount.c lacks a check on the
sanity of the file path when parsing parameters. This results in
a segmentation fault if a partition is mounted to a non-existent path.

Signed-off-by: Qiumiao Zhang <zhangqiumiao1@huawei.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-30 18:33:06 +01:00
Richard Marko 85e40b36ed configure: Make the DJVU_FONT_SOURCE configurable with --with-dejavufont=FILE
Font might be located in different location, the default font might
not be available on all systems or other font might be preferred.

Signed-off-by: Richard Marko <srk@48.io>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-30 18:19:07 +01:00
Mads Kiilerich 2d6631d2af configure: Make the Unifont FONT_SOURCE configurable with --with-unifont=FILE
Font might be located in different location, the default font might
not be available on all systems or other font might be preferred.

Signed-off-by: Mads Kiilerich <mads@kiilerich.com>
Signed-off-by: Richard Marko <srk@48.io>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-30 18:08:59 +01:00
Jon DeVree 07318ee7e1 fs/xfs: Fix XFS directory extent parsing
The XFS directory entry parsing code has never been completely correct
for extent based directories. The parser correctly handles the case
where the directory is contained in a single extent, but then mistakenly
assumes the data blocks for the multiple extent case are each identical
to the single extent case. The difference in the format of the data
blocks between the two cases is tiny enough that its gone unnoticed for
a very long time.

A recent change introduced some additional bounds checking into the XFS
parser. Like GRUB's existing parser, it is correct for the single extent
case but incorrect for the multiple extent case. When parsing a directory
with multiple extents, this new bounds checking is sometimes (but not
always) tripped and triggers an "invalid XFS directory entry" error. This
probably would have continued to go unnoticed but the /boot/grub/<arch>
directory is large enough that it often has multiple extents.

The difference between the two cases is that when there are multiple
extents, the data blocks do not contain a trailer nor do they contain
any leaf information. That information is stored in a separate set of
extents dedicated to just the leaf information. These extents come after
the directory entry extents and are not included in the inode size. So
the existing parser already ignores the leaf extents.

The only reason to read the trailer/leaf information at all is so that
the parser can avoid misinterpreting that data as directory entries. So
this updates the parser as follows:

For the single extent case the parser doesn't change much:
1. Read the size of the leaf information from the trailer
2. Set the end pointer for the parser to the start of the leaf
   information. (The previous bounds checking set the end pointer to the
   start of the trailer, so this is actually a small improvement.)
3. Set the entries variable to the expected number of directory entries.

For the multiple extent case:
1. Set the end pointer to the end of the block.
2. Do not set up the entries variable. Figuring out how many entries are
   in each individual block is complex and does not seem worth it when
   it appears to be safe to just iterate over the entire block.

The bounds check itself was also dependent upon the faulty XFS parser
because it accidentally used "filename + length - 1". Presumably this
was able to pass the fuzzer because in the old parser there was always
8 bytes of slack space between the tail pointer and the actual end of
the block. Since this is no longer the case the bounds check needs to be
updated to "filename + length + 1" in order to prevent a regression in
the handling of corrupt fliesystems.

Notes:
* When there is only one extent there will only ever be one block. If
  more than one block is required then XFS will always switch to holding
  leaf information in a separate extent.
* B-tree based directories seems to be parsed properly by the same code
  that handles multiple extents. This is unlikely to ever occur within
  /boot though because its only used when there are an extremely large
  number of directory entries.

Fixes: ef7850c75 (fs/xfs: Fix issues found while fuzzing the XFS filesystem)
Fixes: b2499b29c (Adds support for the XFS filesystem.)
Fixes: https://savannah.gnu.org/bugs/?64376

Signed-off-by: Jon DeVree <nuxi@vault24.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Sebastian Andrzej Siewior <sebastian@breakpoint.cc>
Tested-by: Marta Lewandowska <mlewando@redhat.com>
2023-10-30 18:01:22 +01:00
Lidong Chen ad7fb8e2e0 fs/xfs: Incorrect short form directory data boundary check
After parsing of the current entry, the entry pointer is advanced
to the next entry at the end of the "for" loop. In case where the
last entry is at the end of the data boundary, the advanced entry
pointer can point off the data boundary. The subsequent boundary
check for the advanced entry pointer can cause a failure.

The fix is to include the boundary check into the "for" loop
condition.

Signed-off-by: Lidong Chen <lidong.chen@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Sebastian Andrzej Siewior <sebastian@breakpoint.cc>
Tested-by: Marta Lewandowska <mlewando@redhat.com>
2023-10-30 17:16:18 +01:00
Vladimir 'phcoder' Serbinenko 4e10213de6 Revert "zfsinfo: Correct a check for error allocating memory"
Original commit is wrong because grub_file_get_device_name() may return NULL
if we use implicit $root. Additionally, the grub_errno is guaranteed to be
GRUB_ERR_NONE at the beginning of a command. So, everything should work as
expected and Coverity report, CID 73668, WRT to this code should be treated
as false positive.

This reverts commit 7aab03418 (zfsinfo: Correct a check for error allocating memory).

Fixes: 7aab03418 (zfsinfo: Correct a check for error allocating memory)

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-12 19:28:33 +02:00
ValdikSS 4266fd2bb2 disk/i386/pc/biosdisk: Read up to 63 sectors in LBA mode
Current code imposes limitations on the amount of sectors read in
a single call according to CHS layout of the disk even in LBA
read mode. There's no need to obey CHS layout restrictions for
LBA reads on LBA disks. It only slows down booting process.

See: https://lore.kernel.org/grub-devel/d42a11fa-2a59-b5e7-08b1-d2c60444bb99@valdikss.org.ru/

Signed-off-by: ValdikSS <iam@valdikss.org.ru>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-12 19:23:17 +02:00
ValdikSS cab04dcda3 kern/i386/pc/init: Flush cache only on VIA C3 and earlier
The code flushes the cache on VIA processors unconditionally which
is excessive. Check for cpuid family and execute wbinvd only on C3
and earlier.

Fixes: https://savannah.gnu.org/bugs/?45149
Fixes: 25492a0f0 (Add wbinvd around bios call.)

Signed-off-by: ValdikSS <iam@valdikss.org.ru>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-12 19:18:58 +02:00
Fabian Vogt 3c7e842571 fs/btrfs: Zero file data not backed by extents
Implicit holes in file data need to be zeroed explicitly, instead of
just leaving the data in the buffer uninitialized.

This led to kernels randomly failing to boot in "fun" ways when loaded
from btrfs with the no_holes feature enabled, because large blocks of
zeros in the kernel file contained random data instead.

Signed-off-by: Fabian Vogt <fvogt@suse.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Qu Wenruo <wqu@suse.com>
2023-10-12 19:01:45 +02:00
Stefan Berger 4bcf6f747c kern/ieee1275/init: Restrict high memory in presence of fadump on ppc64
When a kernel dump is present then restrict the high memory regions to
avoid allocating memory where the kernel dump resides. Use the
ibm,kernel-dump node under /rtas to determine whether a kernel dump
exists and up to which limit GRUB can use available memory. Set the
upper_mem_limit to the size of the kernel dump section of type
REAL_MODE_REGION and therefore only allow GRUB's memory usage for high
addresses from RMO_ADDR_MAX to upper_mem_limit. This means that GRUB can
use high memory in the range of RMO_ADDR_MAX (768MB) to upper_mem_limit
and the kernel-dump memory regions above upper_mem_limit remain
untouched. This change has no effect on memory allocations below
linux_rmo_save (typically at 640MB).

Also, fall back to allocating below rmo_linux_save in case the chunk of
memory there would be larger than the chunk of memory above RMO_ADDR_MAX.
This can for example occur if a free memory area is found starting at 300MB
extending up to 1GB but a kernel dump is located at 768MB and therefore
does not allow the allocation of the high memory area but requiring to use
the chunk starting at 300MB to avoid an unnecessary out-of-memory condition.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Hari Bathini <hbathini@linux.ibm.com>
Cc: Pavithra Prakash <pavrampu@in.ibm.com>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Carolyn Scherrer <cpscherr@us.ibm.com>
Cc: Mahesh Salgaonkar <mahesh@linux.ibm.com>
Cc: Sourabh Jain <sourabhjain@linux.ibm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-12 18:54:58 +02:00
Glenn Washburn cf58eca2a2 tests/util/grub-shell: Enable RNG device to better test stack smashing
In certain firmwares, e.g. OVMF, the RNG protocol is not enabled unless
there is an RNG device. When not enabled, GRUB fails to initialize the
stack guard with random bytes. For testing, this is not a big issue, but
there have been bugs found in the initialization. So turn this on for EFI
platforms to catch any regressions.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-12 18:48:28 +02:00
Glenn Washburn c3bdf263f6 kern/efi/init: Disable stack smashing protection on grub_efi_init()
GCC is electing to instrument grub_efi_init() to give it stack smashing
protection when configuring with --enable-stack-protector on the x86_64-efi
target. In the function prologue, the canary at the top of the stack frame
is set to the value of the stack guard. And in the epilogue, the canary is
checked to verify if it is equal to the guard and if not to call the stack
check fail function. The issue is that grub_efi_init() sets up the guard
by initializing it with random bytes, if the firmware supports the RNG
protocol. So in its prologue the canary will be set with the value of the
uninitialized guard, likely NUL bytes. Then the guard is initialized, and
finally the epilogue checks the canary against the guard, which will almost
certainly be different. This causes the code path for a smashed stack to be
taken, causing the machine to print out a message that stack smashing was
detected, wait 5 seconds, and then reboot. Disable grub_efi_init()
instrumentation so there is no stack smashing false positive generated.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-12 17:47:28 +02:00
Glenn Washburn 95963d97f8 disk/cryptodisk: Add support for LUKS2 in (proc)/luks_script
The sector size in bytes is added to each line and it is allowed to be
6 decimal digits long, which covers the most common cases of 512 and 4096
byte sectors with space for two additional digits as future-proofing. The
size allocation is updated to reflect this additional field. Also make
clearer the size allocation calculation.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-12 17:42:20 +02:00
Glenn Washburn 016f142577 disk/cryptodisk: Optimize luks_script_get()
Use the return value of grub_snprintf() to move the string pointer forward,
instead of incrementing the string pointer iteratively until a NULL byte is
reached. Move the space out of the format string argument, a small
optimization, but also makes the spacing clearer. Also, use the new
PRIxGRUB_OFFSET instead of PRIuGRUB_UINT64_T to accurately reflect the
format string for this type.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-12 17:37:16 +02:00
Glenn Washburn f7a663c007 term/serial: Ensure proper NULL termination after grub_strncpy()
A large enough argument to the --port option could cause a string buffer
to be not NULL terminated because grub_strncpy() does not guarantee NULL
termination if copied string is longer than max characters to copy.

Fixes: 712309eaae (term/serial: Use grub_strncpy() instead of grub_snprintf() when only copying string)

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-12 17:27:34 +02:00
Heinrich Schuchardt a19e47ca41 commands/efi/lsefisystab: Print the UEFI specification revision in human readable form
E.g. 2.10 instead of 00020064 and 2.3.1 instead of 0002001f.

See UEFI 2.10 specification, chapter 4.2.1 EFI_TABLE_HEADER.

Signed-off-by: Heinrich Schuchardt <heinrich.schuchardt@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-12 17:22:45 +02:00
Maxim Suhanov e58b870ff9 fs/ntfs: Make code more readable
Move some calls used to access NTFS attribute header fields into
functions with human-readable names.

Suggested-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-03 15:38:48 +02:00
Maxim Suhanov 1fe82c41e0 fs/ntfs: Fix an OOB read when parsing a volume label
This fix introduces checks to ensure that an NTFS volume label is always
read from the corresponding file record segment.

The current NTFS code allows the volume label string to be read from an
arbitrary, attacker-chosen memory location. However, the bytes read are
always treated as UTF-16LE. So, the final string displayed is mostly
unreadable and it can't be easily converted back to raw bytes.

The lack of this check is a minor issue, likely not causing a significant
data leak.

Reported-by: Maxim Suhanov <dfirblog@gmail.com>
Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-03 15:38:48 +02:00
Maxim Suhanov 7a5a116739 fs/ntfs: Fix an OOB read when parsing bitmaps for index attributes
This fix introduces checks to ensure that bitmaps for directory indices
are never read beyond their actual sizes.

The lack of this check is a minor issue, likely not exploitable in any way.

Reported-by: Maxim Suhanov <dfirblog@gmail.com>
Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-03 15:38:48 +02:00
Maxim Suhanov 7e5f031a6a fs/ntfs: Fix an OOB read when parsing directory entries from resident and non-resident index attributes
This fix introduces checks to ensure that index entries are never read
beyond the corresponding directory index.

The lack of this check is a minor issue, likely not exploitable in any way.

Reported-by: Maxim Suhanov <dfirblog@gmail.com>
Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-03 15:38:48 +02:00
Maxim Suhanov 0ed2458cc4 fs/ntfs: Fix an OOB read when reading data from the resident $DATA attribute
When reading a file containing resident data, i.e., the file data is stored in
the $DATA attribute within the NTFS file record, not in external clusters,
there are no checks that this resident data actually fits the corresponding
file record segment.

When parsing a specially-crafted file system image, the current NTFS code will
read the file data from an arbitrary, attacker-chosen memory offset and of
arbitrary, attacker-chosen length.

This allows an attacker to display arbitrary chunks of memory, which could
contain sensitive information like password hashes or even plain-text,
obfuscated passwords from BS EFI variables.

This fix implements a check to ensure that resident data is read from the
corresponding file record segment only.

Fixes: CVE-2023-4693

Reported-by: Maxim Suhanov <dfirblog@gmail.com>
Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-03 15:38:48 +02:00
Maxim Suhanov 43651027d2 fs/ntfs: Fix an OOB write when parsing the $ATTRIBUTE_LIST attribute for the $MFT file
When parsing an extremely fragmented $MFT file, i.e., the file described
using the $ATTRIBUTE_LIST attribute, current NTFS code will reuse a buffer
containing bytes read from the underlying drive to store sector numbers,
which are consumed later to read data from these sectors into another buffer.

These sectors numbers, two 32-bit integers, are always stored at predefined
offsets, 0x10 and 0x14, relative to first byte of the selected entry within
the $ATTRIBUTE_LIST attribute. Usually, this won't cause any problem.

However, when parsing a specially-crafted file system image, this may cause
the NTFS code to write these integers beyond the buffer boundary, likely
causing the GRUB memory allocator to misbehave or fail. These integers contain
values which are controlled by on-disk structures of the NTFS file system.

Such modification and resulting misbehavior may touch a memory range not
assigned to the GRUB and owned by firmware or another EFI application/driver.

This fix introduces checks to ensure that these sector numbers are never
written beyond the boundary.

Fixes: CVE-2023-4692

Reported-by: Maxim Suhanov <dfirblog@gmail.com>
Signed-off-by: Maxim Suhanov <dfirblog@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-03 15:38:48 +02:00
Michael Chang 48f569c78a kern/acpi: Skip NULL entries in RSDT and XSDT
During attempts to configure a serial console, a Page Fault Exception
and system reset were encountered, specifically on release 2.12~rc1.
This issue was not present in prior versions and seemed to affect only
a specific machine, potentially pointing to hardware or firmware flaw.

After investigation, it was discovered that the invalid page access
occurred during the discovery of serial MMIO ports as specified by
ACPI's SPCR table [1]. The recent change uncovered an issue in GRUB's
ACPI driver.

In certain cases, the XSDT/RSDT root table might contain a NULL entry as
a terminator, depending on how the tables are assembled. GRUB cannot
blindly trust the address in the root table to be valid and should
perform a sanity check for NULL entries. This patch introduces this
simple check.

This fix is also inspired by a related Linux kernel fix [2].

[1] 7b192ec4c term/ns8250: Use ACPI SPCR table when available to configure serial
[2] 0f929fbf0 ACPICA: Tables: Add new mechanism to skip NULL entries in RSDT and XSDT.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-03 15:38:48 +02:00
Glenn Washburn 28a509dd58 util/grub-install-common: Print usable grub-mkimage command
When grub-install is run with the verbose option, it will print a log
message indicating the grub-mkimage command and arguments used.
GRUB no longer calls the grub-mkimage binary internally, however the
command logged is a command that if run should effectively be what
grub-install used. However, as this has changed some of the newer
options have been incorrectly added so that the printed command fails
when run separately. This change makes the displayed command run as
intended.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-03 15:37:13 +02:00
Glenn Washburn 1c2e162306 util/grub-install-common: Minor improvements to printing of grub-mkimage command
This is a preparatory patch to make the following patch less cluttered. The
only visible change made here is to not print extra spaces when either or
both --note or --disable-shim-lock are not given and to not print an extra
space at the end of the command. The latter is done by constructing the
trailing argument string with spaces in front of each argument rather than
trailing. The allocation of the argument string is made precise, which has
the benefit of saving a few bytes, but more importantly self-documenting
what the needed allocated bytes are. Also, unneeded braces are removed from
an if block.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-03 15:35:24 +02:00
Vladimir 'phcoder' Serbinenko 968928240a lib/i386/relocator64: Fix 64-bit FreeBSD boot on BIOS
The commit 80948f532d (lib/i386/relocator64: Build fixes for i386) has
broken 64-bit FreeBSD boot on BIOS. This patch fixes the issue.

Fixes: 80948f532d (lib/i386/relocator64: Build fixes for i386)

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-10-03 12:46:37 +02:00
Anthony PERARD db1faedccd templates/linux_xen: Fix XSM entries generation
It turns out that setting $xen_version in linux_entry_xsm() override
$xen_version in the loop over $reverse_sorted_xen_list. This means
that only one entry per Xen version is going to enable XSM, but all
further entries are going to have "(XSM enabled)" in their titles
without enabling XSM.

When a "xenpolicy-$xen_version" file was found for the current
$xen_version, it would overwrite $xen_version to add "(XSM enabled)" to
the menu entry title. Once updated, the next call to linux_entry_xsm()
would also have this modified $xen_version and would look for the file
"xenpolicy-*(XSM enabled)" and fail.

Signed-off-by: Anthony PERARD <anthony.perard@citrix.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-09-22 18:38:36 +02:00
Xiaotian Wu 3335591c64 loongarch: Eliminate cmodel compilation warnings
In the configure phase, the "-mcmodel=large" CFLAGS passed the test, but
because it has not been implemented in gcc, the following warning will
appear when compiling:

  gcc: warning: 'large' is not supported, now cmodel is set to 'normal'

Signed-off-by: Xiaotian Wu <wuxiaotian@loongson.cn>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-09-22 18:38:36 +02:00
Glenn Washburn 084a66e307 configure: Enable -fno-omit-frame-pointer for backtrace module
The backtrace module is written assuming that the frame pointer is in %ebp.
By default, -Os optimization level is used, which enables the gcc option
-fomit-frame-pointer. This breaks the backtrace functionality. Enabling
this may cause an unnoticeable performance cost and virtually no size increase.

The backtrace command on x86_64 and probably i386 is broken due to the
above rationale. I've not verified, but presumably the backtrace that used
to be printed for an unhandled CPU exception is also broken. Do any distros
handle this?

Considering that, to my knowledge, no one has complained about this in the
over 13 years that -Os has been used, has this code actually been useful?
Is it worth disabling -fomit-frame-pointer? Though, I don't see much downside
right now in disabling it. Alternatively, we could disable/remove the
backtrace code. I think it would be nice to keep it and have it working.

Nowadays, presumably QEMU makes the GDB stub rarely used as I imagine most
are developing in a virtual machines. Also, the GDB stub does not work in UEFI.
So, if anyone is using it on real hardware, they are doing so on pretty old
machines. The lack of a GDB stub does not seem to be a pain point because
no one has got it working on UEFI.

This patch gets the backtrace command working on x86_64-efi in QEMU for me.
However, it hangs when run on my laptop. Not sure what's going on there.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-09-22 18:38:36 +02:00
Ard Biesheuvel 1f5b180742 loader/efi/linux: Implement x86 mixed mode using legacy boot
Recent mixed-mode Linux kernels, i.e., v4.0 or newer, can access EFI
runtime services at OS runtime even when the OS was not entered via the
EFI stub. This is because, instead of reverting back to the firmware's
segment selectors, GDTs and IDTs, the 64-bit kernel simply calls 32-bit
runtime services using compatibility mode, i.e., the same mode used for
32-bit user space, without taking down all interrupt handling, exception
handling, etc.

This means that GRUB's legacy x86 boot mode is sufficient to make use of
this: 32-bit i686 builds of GRUB can already boot 64-bit kernels in EFI
enlightened mode, but without going via the EFI stub, and provide all
the metadata that the OS needs to map the EFI runtime regions and call
EFI runtime services successfully.

It does mean that GRUB should not attempt to invoke the firmware's
LoadImage()/StartImage() methods on kernel builds that it knows cannot
be started natively. So, add a check for this in the native EFI boot
path and fall back to legacy x86 mode in such cases.

Note that in the general case, booting non-native images of the same
native word size, e.g., x64 EFI apps on arm64 firmware, might be
supported by means of emulation. So, let's only disallow images that use
a non-native word size. This will also permit booting i686 kernels on
x86_64 builds, although without access to runtime services, as this is
not supported by Linux.

This change on top of 2.12-rc1 is sufficient to boot ordinary Linux
mixed mode builds and get full access to the EFI runtime services.

Cc: Daniel Kiper <daniel.kiper@oracle.com>
Cc: Steve McIntyre <steve@einval.com>
Cc: Julian Andres Klode <julian.klode@canonical.com>
Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
Acked-by: Dimitri John Ledkov <dimitri.ledkov@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-09-22 18:38:36 +02:00
Ard Biesheuvel 67ae3981dc loader/i386/linux: Prefer entry in long mode when booting via EFI
The x86_64 Linux kernel can be booted in 32-bit mode, in which case the
startup code creates a set of preliminary page tables that map the first
4 GiB of physical memory 1:1 and enables paging. This is a prerequisite
for 64-bit execution and can therefore only be implemented in 32-bit code.

The x86_64 Linux kernel can also be booted in 64-bit mode directly: this
implies that paging is already enabled and it is the responsibility of
the bootloader to ensure that the active page tables cover the entire
loaded image, including its BSS space, the size of which is described in
the image's setup header.

Given that the EFI spec mandates execution in long mode for x86_64 and
stipulates that all system memory is mapped 1:1, the Linux/x86
requirements for 64-bit entry can be met trivially when booting on
x86_64 via EFI. So, enter via the 64-bit entry point in this case.

This involves inspecting the xloadflags field in the setup header to
check whether the 64-bit entry point is supported. This field was
introduced in Linux version v3.8 (early 2013).

This change ensures that all EFI firmware tables and other assets passed
by the firmware or bootloader in memory remain mapped and accessible
throughout the early startup code.

Avoiding the drop out of long mode will also be needed to support
upcoming CPU designs that no longer implement 32-bit mode at all
(as recently announced by Intel [0]).

[0] https://www.intel.com/content/www/us/en/developer/articles/technical/envisioning-future-simplified-architecture.html

Cc: Daniel Kiper <daniel.kiper@oracle.com>
Cc: Julian Andres Klode <julian.klode@canonical.com>
Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-09-22 18:38:36 +02:00
Vladimir Serbinenko 7ce5b49110 ZFS: Check bonustype in addition to dnode type
Some dnodes are shared with properties zap. This is used
e.g. for quotas. Then dnode type is 0xc4 and GRUB stumbles on
this. Check bonus type and if it's ok then ignore dnode type mismatch

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-09-18 02:44:35 +02:00
Vladimir Serbinenko 444089eec6 ZFS: Don't iterate over null objsets
Reading them is harmless but useless as they are empty by definition

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-09-18 02:44:02 +02:00
Vladimir Serbinenko 96446ce14e ZFS: Fix invalid memcmp
We ended up comparing over unset values as we had dnode_phys on one side
and dnode on another

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-09-18 02:43:32 +02:00
Vladimir Serbinenko 42a831d746 ZFS: support inode type embed into its ID
This is a speedup used in some ZFS version. This trips GRUB and makes it
unable to access directories. Just skip it for now and revisit
if we ever need this speedup.

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-09-18 02:42:21 +02:00
Heinrich Schuchardt 34a3adff82 video/efi_gop: Require shadow if PixelBltOnly
If the EFI graphics pixel format is PixelBltOnly, we cannot write directly
to the frame buffer. We need the shadow frame buffer which we copy via
the BitBlt operation to the hardware.

If the pixel format is PixelBltOnly and allocation of the shadow frame
buffer fails, we must raise an error to signal that the EFI GOP protocol
is not usable.

Signed-off-by: Heinrich Schuchardt <heinrich.schuchardt@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-31 17:21:40 +02:00
Glenn Washburn ac8ae924ca docs: Add menu to prevent older makeinfo versions from failing
It has been reported that makeinfo version 4.13a complains and returns
error when menus for chapter structuring commands are not present. It
is also known that newer makeinfos, such as version 6.7, will create
default menus when needed. Since the menu will be created regardless,
explicitly create it to support older makeinfo versions. This also
enables building to be successful when an older makeinfo is installed
because in that case info files are attempted to be generated with the
"all" target.

Reported-by: Olaf Hering <olaf@aepfle.de>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Olaf Hering <olaf@aepfle.de>
2023-08-31 17:16:32 +02:00
Glenn Washburn 3c42272105 docs: Use @ref instead of @xref
The @xref command is meant to be used at the beginning of a sentence
because its expansion creates a "See " prefix on all output formats, and
on older makeinfo versions is strict about enforcing a "." or "," after
the command. The @ref command has no such restriction and is just the
link, which allows more control over output. This also fixes an issue
where there was a repeated "see" in the output.

Reported-by: Olaf Hering <olaf@aepfle.de>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Olaf Hering <olaf@aepfle.de>
2023-08-31 17:11:20 +02:00
Glenn Washburn fff2e9ee83 tests/util/grub-shell-luks-tester: Allow setting timeout
Allow using the envvar GRUB_SHELL_LUKS_TIMEOUT to change the default
timeout. If not specified, use value of GRUB_SHELL_DEFAULT_TIMEOUT. And
if that is not specified, fallback to original 600s timeout.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-31 17:09:04 +02:00
Glenn Washburn 296d3ec835 disk/cryptodisk: Fix missing change when updating to use grub_uuidcasecmp()
This was causing the cryptomount command to return failure even though
the crypto device was successfully added. Of course, this meant that any
script using the return code would behave unexpectedly.

Fixes: 3cf2e848bc (disk/cryptodisk: Allows UUIDs to be compared in a dash-insensitive manner)

Suggested-by: Olaf Hering <olaf@aepfle.de>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrich Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-31 17:03:29 +02:00
Glenn Washburn 14c95e57fd kern/misc: Make grub_vsnprintf() C99/POSIX conformant
To comply with C99 and POSIX standards, snprintf() should return the
number of bytes that would be written to the string (excluding the
terminating NUL byte) if the buffer size was big enough. Before this
change, the return value was the minimum of the standard return and the
length of the buffer. Rarely is the return value of grub_snprintf() or
grub_vsnprintf() used with current code, and the few places where it is
used do not need to be changed.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-31 16:57:22 +02:00
Glenn Washburn 6d6b95720c tests: Add serial_test
This test is meant to test output via various serial devices. Currently,
only the PCI serial device is tested.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-31 16:55:41 +02:00
Glenn Washburn 846829aca8 tests/util/grub-shell: Allow explicitly using other serial ports for output
While here, move "-qemu=*" case to be next to the "--qemu-opts=*" case.
This causes no change in logic, but is more logically located.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-31 16:35:57 +02:00
Glenn Washburn ee2349ef65 tests/util/grub-shell-luks-tester: Do not remove generated files when test fails to allow debugging
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-31 16:34:35 +02:00
Glenn Washburn a63ef8c78c tests/util/grub-shell: Convert spaces to TABs
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-31 16:32:59 +02:00
Glenn Washburn 4fdcb339bb commands/ls: Print "????????????" if unable to get file size
In long list mode, if the file can not be opened, the file is not printed.
Instead, print the file but print the size as "????????????".

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 18:12:49 +02:00
Glenn Washburn 6889c67fe7 commands/ls: Send correct dirname to print functions
For each non-directory path argument to the ls command, the full path was
being sent to the print functions, instead of the dirname. The long output
print function expected dirname to be the directory containing the file
and so could not open the file to get the file size because the generated
path was incorrect. This caused the output to be a blank line.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 18:10:36 +02:00
Glenn Washburn fcbea18c58 fs/archelp: If path given to grub_archelp_dir() is not a directory return error
Specifically, return GRUB_ERR_BAD_FILE_TYPE because this is what is
expected by the ls command when it is given a path to a non-directory.
This fixes a bug where calling ls with a list of non-directory paths
outputs a blank line for each such argument.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 18:07:24 +02:00
Glenn Washburn 1de5832699 commands/videoinfo: Prevent crash when run while video driver already active
The videoinfo command will initialize all non-active video adapters. Video
drivers tend to zero out the global framebuffer object on initialization.
This is not a problem when there is no active video adapter. However, when
there is, then outputting to the video adapter will cause a crash because
methods in the framebuffer object are reinitialized. For example, this
command sequence will cause a crash.

  terminal_output --append gfxterm; videoinfo

When running in a QEMU headless with GRUB built for the x86_64-efi target,
the first command initializes the Bochs video adapter, which, among
other things, sets the set_page() member function. Then when videoinfo is
run, all non-Bochs video adapters will be initialized, each one wiping
the framebuffer and thus setting set_page to NULL. Soon after the videoinfo
command finishes there will be a call to grub_refresh(), which will
ultimately call the framebuffer's set_page which will be NULL and cause
a crash when called.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 18:04:04 +02:00
Glenn Washburn 43bf0b2a10 docs: Improve initrd documentation
A list of improvements:
  * Remove reference to "initial ramdisk" and replace with "initrd". This
    then covers the case of ramdisk and ramfs, which is the usual method
    with kernels 2.6 and newer.
  * Add sentence with URL to initrd documentation Linux kernel.
  * Add a section documenting how to have the initrd command generate
    a new-style initrd via a specially crafted argument and include an example.
  * Update initrd16 to refer to the initrd section and make note that
    initrd16 is only on the pc platform.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Oskari Pirhonen <xxc3ncoredxx@gmail.com>
Reviewed-by: Paul Menzel <pmenzel@molgen.mpg.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 18:00:41 +02:00
Glenn Washburn b0890d371c term/ns8250-spcr: Continue processing SPCR table even if revision is < 2
According to commit 0231d00082 (ACPI: SPCR: Make SPCR available to x86)
to the Linux kernel, "On x86, many systems have a valid SPCR table but the
table version is not 2 so the table version check must be a warning."

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Benjamin Herrenschmidt <benh@kernel.crashing.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 17:56:47 +02:00
Glenn Washburn 711e034235 docs: A note to cat that hexdump should be used for binary data
The cat command should not be used to print binary data because it can
show bytes not in the binary data and not show bytes that are in the data,
which can lead to confusion. This happens because cat does some processing
of the data stream, namely trying to decode substrings as UTF-8.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Oskari Pirhonen <xxc3ncoredxx@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 17:55:01 +02:00
Glenn Washburn 7ff4f3c963 docs: Document hexdump command
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Oskari Pirhonen <xxc3ncoredxx@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 17:52:41 +02:00
Glenn Washburn 2e1279af2b docs: Group usage of user-space utilities into single chapter
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Oskari Pirhonen <xxc3ncoredxx@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 17:49:11 +02:00
Qiumiao Zhang 3077b39bae util/grub-mount: Fix memory leak in fuse_getattr()
Signed-off-by: Qiumiao Zhang <zhangqiumiao1@huawei.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 17:48:22 +02:00
Michał Grzelak eba6bdcd3a configure: Fix SDL2 typo by referencing value
During configuration of SDL2, variable enable_grub_emu_sdl2 is checked
whether to throw an error message. However, error could not happen
because two unequal strings were compared. Fix this by referencing
value of enable_grub_emu_sdl2, not name.

Fixes: 17d6ac1a7 (emu: Add SDL2 support)

Signed-off-by: Michał Grzelak <mchl.grzlk@gmail.com>
Reviewed-by: Julian Andres Klode <julian.klode@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Paul Menzel <pmenzel@molgen.mpg.de>
2023-08-14 17:19:51 +02:00
Glenn Washburn 459f028cd3 docs: Add missing assumption
Also reword a prior sentence to be more clear.

Fixes: 5a3d2b4742 (docs: Add debugging chapter to development documentation)

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Oskari Pirhonen <xxc3ncoredxx@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 17:16:53 +02:00
Oskari Pirhonen e641b4ab32 util/grub.d/25_bli.in: Fix shebang on unmerged-usr
On an unmerged-usr system, grub-mkconfig errors out with the following
error due to /usr/bin/sh not existing:

  /usr/sbin/grub-mkconfig: /etc/grub.d/25_bli: /usr/bin/sh: bad interpreter: No such file or directory

Use a /bin/sh shebang to fix the error as well as match the other
existing files.

Fixes: 158a6583e (util/grub.d/25_bli.in: Activate bli module on EFI)

Signed-off-by: Oskari Pirhonen <xxc3ncoredxx@gmail.com>
Reviewed-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Oliver Steffen <osteffen@redhat.com>
2023-08-14 17:11:55 +02:00
Glenn Washburn 7f6149449c tests/util/grub-shell-luks-tester: Allow GRUB_SHELL_LUKS_DEFAULT_DEBUG and GRUB_TEST_DEFAULT_DEBUG to specify the debug level to grub-shell
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 17:08:09 +02:00
Glenn Washburn e1b97d7c37 tests/util/grub-shell: Allow setting the value of debug regardless of its previous state
This allows an invocation of grub-shell to set the value of debug regardless
of the global default environment variable GRUB_SHELL_DEFAULT_DEBUG.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 17:06:28 +02:00
Glenn Washburn 76e8962e85 tests/util/grub-shell: Allow setting default timeout via GRUB_SHELL_DEFAULT_TIMEOUT envvar
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 17:01:13 +02:00
Glenn Washburn 79ccfa90a1 tests/util/grub-shell: Add --verbose to grub-mkrescue when $debug is greater than 2
Since this is fairly verbose output, do not enable first level of debug
is turned on.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2023-08-14 16:58:15 +02:00
986 changed files with 260430 additions and 37236 deletions

No files matched your search

+8 -3
View File
@@ -104,6 +104,7 @@ widthspec.bin
/docs/version-dev.texi /docs/version-dev.texi
/docs/version.texi /docs/version.texi
/ehci_test /ehci_test
/erofs_test
/example_grub_script_test /example_grub_script_test
/example_scripted_test /example_scripted_test
/example_unit_test /example_unit_test
@@ -140,10 +141,12 @@ widthspec.bin
/grub-core/kernel.img.bin /grub-core/kernel.img.bin
/grub-core/lib/gnulib /grub-core/lib/gnulib
/grub-core/lib/libgcrypt-grub /grub-core/lib/libgcrypt-grub
/grub-core/lib/libtasn1-grub
/grub-core/modinfo.sh /grub-core/modinfo.sh
/grub-core/rs_decoder.h /grub-core/rs_decoder.h
/grub-core/symlist.c /grub-core/symlist.c
/grub-core/symlist.h /grub-core/symlist.h
/grub-core/tests/asn1/tests
/grub-core/trigtables.c /grub-core/trigtables.c
/grub-core/unidata.c /grub-core/unidata.c
/grub-editenv /grub-editenv
@@ -168,6 +171,8 @@ widthspec.bin
/grub-ofpathname.exe /grub-ofpathname.exe
/grub-probe /grub-probe
/grub-probe.exe /grub-probe.exe
/grub-protect
/grub-protect.exe
/grub-reboot /grub-reboot
/grub-render-label /grub-render-label
/grub-render-label.exe /grub-render-label.exe
@@ -233,7 +238,8 @@ widthspec.bin
/lzocompress_test /lzocompress_test
/luks1_test /luks1_test
/luks2_test /luks2_test
/m4/ /m4/*
!/m4/ax_check_link_flag.m4
/minixfs_test /minixfs_test
/missing /missing
/netboot_test /netboot_test
@@ -244,8 +250,6 @@ widthspec.bin
/pata_test /pata_test
/po/*.gmo /po/*.gmo
/po/*.mo /po/*.mo
/po/*.po
/po/LINGUAS
/po/Makefile.in.in /po/Makefile.in.in
/po/Makevars /po/Makevars
/po/Makevars.template /po/Makevars.template
@@ -278,3 +282,4 @@ widthspec.bin
/xfs_test /xfs_test
/xzcompress_test /xzcompress_test
/zfs_test /zfs_test
/zfs_zstd_test
+2 -6
View File
@@ -1,7 +1,3 @@
GRUB team is aware of following problems: Open bugs and issues are captured in the GRUB bug tracking system:
- Currently search and assembling multidevice abstractions scans
all the devices which can be slow.
- Cache isn't used correctly for video which results in slowness.
While these are bugs their solution has a potential of breaking more and more https://savannah.gnu.org/bugs/?group=grub
seriously. So it was decided for 1.99 that they aren't fixed.
+27 -22
View File
@@ -20,11 +20,12 @@ configuring the GRUB.
for i386, x86_64, arm (including thumb), arm64, mips(el), powerpc, sparc64 for i386, x86_64, arm (including thumb), arm64, mips(el), powerpc, sparc64
* GNU Make * GNU Make
* GNU Bison 2.3 or later * GNU Bison 2.3 or later
* GNU gettext 0.17 or later * GNU gettext
* GNU binutils 2.9.1.0.23 or later * GNU binutils 2.9.1.0.23 or later
* Flex 2.5.35 or later * Flex 2.5.35 or later
* pkg-config * pkg-config
* GNU patch * GNU patch
* wget (for downloading updated translations)
* Other standard GNU/Unix tools * Other standard GNU/Unix tools
* a libc with large file support (e.g. glibc 2.1 or later) * a libc with large file support (e.g. glibc 2.1 or later)
@@ -45,6 +46,10 @@ To build GRUB's graphical terminal (gfxterm), you need:
To build grub-mkfont the unicode fonts are required (xfonts-unifont package To build grub-mkfont the unicode fonts are required (xfonts-unifont package
on Debian). on Debian).
To build the optional grub-protect utility the following is needed:
* libtasn1 (libtasn1-6-dev on Debian)
If you use a development snapshot or want to hack on GRUB you may If you use a development snapshot or want to hack on GRUB you may
need the following. need the following.
@@ -62,7 +67,7 @@ More cross compiling toolchains can be found at the following trusted sites:
* https://mirrors.kernel.org/pub/tools/crosstool/ * https://mirrors.kernel.org/pub/tools/crosstool/
* https://toolchains.bootlin.com/ * https://toolchains.bootlin.com/
Prerequisites for make-check: Prerequisites for running make-check successfully:
* qemu, specifically the binary "qemu-system-ARCH" where ARCH is the * qemu, specifically the binary "qemu-system-ARCH" where ARCH is the
architecture GRUB has been built for; the "qemu-system" package on Debian architecture GRUB has been built for; the "qemu-system" package on Debian
@@ -74,25 +79,28 @@ Prerequisites for make-check:
* wamerican, for grub-fs-tester * wamerican, for grub-fs-tester
* mtools, FAT tools for EFI platforms * mtools, FAT tools for EFI platforms
* xfonts-unifont, for the functional tests * xfonts-unifont, for the functional tests
* swtpm-tools and tpm2-tools, for TPM2 key protector tests
* If running a Linux kernel the following modules must be loaded: * If running a Linux kernel the following modules must be loaded:
- fuse, loop - fuse, loop
- btrfs, ext4, f2fs, fat, hfs, hfsplus, jfs, mac-roman, minix, nilfs2, - btrfs, erofs, ext4, f2fs, fat, hfs, hfsplus, jfs, mac-roman, minix, nilfs2,
reiserfs, udf, xfs reiserfs, udf, xfs
- On newer kernels, the exfat kernel modules may be used instead of the - On newer kernels, the exfat kernel modules may be used instead of the
exfat FUSE filesystem exfat FUSE filesystem
- Kernel version 6.12.x was the last series to include reiserfs support,
so later kernels will fail the reiser filesystem test.
* The following are Debian named packages required mostly for the full * The following are Debian named packages required mostly for the full
suite of filesystem testing (but some are needed by other tests as well): suite of filesystem testing (but some are needed by other tests as well):
- btrfs-progs, dosfstools, e2fsprogs, exfat-utils, f2fs-tools, genromfs, - btrfs-progs, dosfstools, e2fsprogs, erofs-utils, exfatprogs, exfat-fuse,
hfsprogs, jfsutils, nilfs-tools, ntfs-3g, reiserfsprogs, squashfs-tools, f2fs-tools, genromfs, hfsprogs, jfsutils, nilfs-tools, ntfs-3g,
reiserfsprogs, udftools, xfsprogs, zfs-fuse reiserfsprogs, squashfs-tools, reiserfsprogs, udftools, xfsprogs, zfs-fuse
- exfat-fuse, if not using the exfat kernel module - exfat-fuse, if not using the exfat kernel module
- gzip, lzop, xz-utils - gzip, lzop, xz-utils
- attr, cpio, g++, gawk, parted, recode, tar, util-linux - attr, cpio, g++, gawk, parted, recode, tar, util-linux
Note that `make check' will run and many tests may complete successfully Note that `make check' will run and many tests may complete successfully
with only a subset of these prerequisites. However, some tests may be with only a subset of these prerequisites. However, some tests may fail
skipped or fail due to missing prerequisites. due to missing prerequisites.
To build the documentation you'll need: To build the documentation you'll need:
* texinfo, for the info and html documentation * texinfo, for the info and html documentation
@@ -135,15 +143,12 @@ The simplest way to compile this package is:
1. `cd' to the directory containing the package's source code. 1. `cd' to the directory containing the package's source code.
2. Skip this and following step if you use release tarball and proceed to 2. Type `./bootstrap'.
step 4. If you want translations type `./linguas.sh'.
3. Type `./bootstrap'. The autogen.sh (called by bootstrap) uses python. By default it is
autodetected, but it can be overridden by setting the PYTHON variable.
The autogen.sh (called by bootstrap) uses python. By default autodetect 3. Type `./configure' to configure the package for your system.
it, but it can be overridden by setting the PYTHON variable.
4. Type `./configure' to configure the package for your system.
If you're using `csh' on an old version of System V, you might If you're using `csh' on an old version of System V, you might
need to type `sh ./configure' instead to prevent `csh' from trying need to type `sh ./configure' instead to prevent `csh' from trying
to execute `configure' itself. to execute `configure' itself.
@@ -151,19 +156,19 @@ The simplest way to compile this package is:
Running `configure' takes awhile. While running, it prints some Running `configure' takes awhile. While running, it prints some
messages telling which features it is checking for. messages telling which features it is checking for.
6. Type `make' to compile the package. 4. Type `make' to compile the package.
7. Optionally, type `make check' to run any self-tests that come with 5. Optionally, type `make check' to run any self-tests that come with
the package. Note that many of the tests require root privileges in the package. Note that many of the tests require root privileges and
order to run. a specially crafted environment in order to run.
8. Type `make install' to install the programs and any data files and 6. Type `make install' to install the programs and any data files and
documentation. documentation.
9. Type `make html' or `make pdf' to generate the html or pdf 7. Type `make html' or `make pdf' to generate the html or pdf
documentation. Note, these are not built by default. documentation. Note, these are not built by default.
10. You can remove the program binaries and object files from the 8. You can remove the program binaries and object files from the
source code directory by typing `make clean'. To also remove the source code directory by typing `make clean'. To also remove the
files that `configure' created (so you can compile the package for files that `configure' created (so you can compile the package for
a different kind of computer), type `make distclean'. There is a different kind of computer), type `make distclean'. There is
+88 -27
View File
@@ -36,12 +36,15 @@ library = {
common = grub-core/kern/misc.c; common = grub-core/kern/misc.c;
common = grub-core/kern/partition.c; common = grub-core/kern/partition.c;
common = grub-core/lib/crypto.c; common = grub-core/lib/crypto.c;
common = grub-core/lib/hwfeatures-gcry.c;
common = grub-core/lib/json/json.c; common = grub-core/lib/json/json.c;
common = grub-core/disk/luks.c; common = grub-core/disk/luks.c;
common = grub-core/disk/luks2.c; common = grub-core/disk/luks2.c;
common = grub-core/disk/geli.c; common = grub-core/disk/geli.c;
common = grub-core/disk/key_protector.c;
common = grub-core/disk/cryptodisk.c; common = grub-core/disk/cryptodisk.c;
common = grub-core/disk/AFSplitter.c; common = grub-core/disk/AFSplitter.c;
common = grub-core/lib/argon2.c;
common = grub-core/lib/pbkdf2.c; common = grub-core/lib/pbkdf2.c;
common = grub-core/commands/extcmd.c; common = grub-core/commands/extcmd.c;
common = grub-core/lib/arg.c; common = grub-core/lib/arg.c;
@@ -55,7 +58,7 @@ library = {
library = { library = {
name = libgrubmods.a; name = libgrubmods.a;
cflags = '-fno-builtin -Wno-undef'; cflags = '-fno-builtin -Wno-undef -Wno-unused-but-set-variable';
cppflags = '-I$(srcdir)/grub-core/lib/minilzo -I$(srcdir)/grub-core/lib/xzembed -I$(srcdir)/grub-core/lib/zstd -DMINILZO_HAVE_CONFIG_H'; cppflags = '-I$(srcdir)/grub-core/lib/minilzo -I$(srcdir)/grub-core/lib/xzembed -I$(srcdir)/grub-core/lib/zstd -DMINILZO_HAVE_CONFIG_H';
common_nodist = grub_script.tab.c; common_nodist = grub_script.tab.c;
@@ -98,6 +101,7 @@ library = {
common = grub-core/fs/cpio_be.c; common = grub-core/fs/cpio_be.c;
common = grub-core/fs/odc.c; common = grub-core/fs/odc.c;
common = grub-core/fs/newc.c; common = grub-core/fs/newc.c;
common = grub-core/fs/erofs.c;
common = grub-core/fs/ext2.c; common = grub-core/fs/ext2.c;
common = grub-core/fs/fat.c; common = grub-core/fs/fat.c;
common = grub-core/fs/exfat.c; common = grub-core/fs/exfat.c;
@@ -160,6 +164,7 @@ library = {
common = grub-core/io/gzio.c; common = grub-core/io/gzio.c;
common = grub-core/io/xzio.c; common = grub-core/io/xzio.c;
common = grub-core/io/lzopio.c; common = grub-core/io/lzopio.c;
common = grub-core/io/zstdio.c;
common = grub-core/kern/ia64/dl_helper.c; common = grub-core/kern/ia64/dl_helper.c;
common = grub-core/kern/arm/dl_helper.c; common = grub-core/kern/arm/dl_helper.c;
common = grub-core/kern/arm64/dl_helper.c; common = grub-core/kern/arm64/dl_helper.c;
@@ -199,13 +204,39 @@ program = {
extra_dist = util/grub-mkimagexx.c; extra_dist = util/grub-mkimagexx.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBLZMA)'; ldadd = '$(LIBLZMA)';
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
program = {
name = grub-protect;
mansection = 1;
common = grub-core/kern/emu/argp_common.c;
common = grub-core/osdep/init.c;
common = grub-core/lib/tss2/buffer.c;
common = grub-core/lib/tss2/tss2_mu.c;
common = grub-core/lib/tss2/tpm2_cmd.c;
common = grub-core/commands/tpm2_key_protector/args.c;
common = grub-core/commands/tpm2_key_protector/tpm2key_asn1_tab.c;
common = util/grub-protect.c;
common = util/probe.c;
cflags = '-I$(srcdir)/grub-core/lib/tss2 -I$(srcdir)/grub-core/commands/tpm2_key_protector';
ldadd = libgrubmods.a;
ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBTASN1)';
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
condition = COND_GRUB_PROTECT;
};
program = { program = {
name = grub-mkrelpath; name = grub-mkrelpath;
mansection = 1; mansection = 1;
@@ -215,8 +246,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -230,8 +261,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -256,8 +287,8 @@ program = {
ldadd = '$(LIBLZMA)'; ldadd = '$(LIBLZMA)';
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -272,8 +303,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -295,8 +326,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -313,8 +344,8 @@ program = {
cflags = '$(FUSE_CFLAGS)'; cflags = '$(FUSE_CFLAGS)';
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM) $(FUSE_LIBS)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM) $(FUSE_LIBS)';
condition = COND_GRUB_MOUNT; condition = COND_GRUB_MOUNT;
@@ -331,8 +362,8 @@ program = {
cppflags = '-DGRUB_MKFONT=1'; cppflags = '-DGRUB_MKFONT=1';
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(FREETYPE_LIBS)'; ldadd = '$(FREETYPE_LIBS)';
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
@@ -350,8 +381,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -408,8 +439,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -423,8 +454,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -438,8 +469,8 @@ program = {
common = grub-core/kern/emu/argp_common.c; common = grub-core/kern/emu/argp_common.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -577,8 +608,8 @@ program = {
ldadd = '$(LIBLZMA)'; ldadd = '$(LIBLZMA)';
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
@@ -624,8 +655,8 @@ program = {
ldadd = '$(LIBLZMA)'; ldadd = '$(LIBLZMA)';
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -663,8 +694,8 @@ program = {
ldadd = '$(LIBLZMA)'; ldadd = '$(LIBLZMA)';
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -699,8 +730,8 @@ program = {
ldadd = '$(LIBLZMA)'; ldadd = '$(LIBLZMA)';
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBUTIL) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -763,6 +794,12 @@ script = {
dependencies = 'garbage-gen$(BUILD_EXEEXT)'; dependencies = 'garbage-gen$(BUILD_EXEEXT)';
}; };
script = {
testcase = native;
name = erofs_test;
common = tests/erofs_test.in;
};
script = { script = {
testcase = native; testcase = native;
name = ext234_test; name = ext234_test;
@@ -877,6 +914,12 @@ script = {
common = tests/zfs_test.in; common = tests/zfs_test.in;
}; };
script = {
testcase = native;
name = zfs_zstd_test;
common = tests/zfs_zstd_test.in;
};
script = { script = {
testcase = native; testcase = native;
name = cpio_test; name = cpio_test;
@@ -1130,6 +1173,12 @@ script = {
common = tests/netboot_test.in; common = tests/netboot_test.in;
}; };
script = {
testcase = nonnative;
name = serial_test;
common = tests/serial_test.in;
};
script = { script = {
testcase = nonnative; testcase = nonnative;
name = pseries_test; name = pseries_test;
@@ -1244,6 +1293,18 @@ script = {
common = tests/luks2_test.in; common = tests/luks2_test.in;
}; };
script = {
testcase = nonnative;
name = asn1_test;
common = tests/asn1_test.in;
};
script = {
testcase = nonnative;
name = tpm2_key_protector_test;
common = tests/tpm2_key_protector_test.in;
};
program = { program = {
testcase = native; testcase = native;
name = example_unit_test; name = example_unit_test;
@@ -1253,8 +1314,8 @@ program = {
common = grub-core/kern/misc.c; common = grub-core/kern/misc.c;
common = grub-core/tests/lib/test.c; common = grub-core/tests/lib/test.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -1268,8 +1329,8 @@ program = {
common = grub-core/kern/misc.c; common = grub-core/kern/misc.c;
common = grub-core/tests/lib/test.c; common = grub-core/tests/lib/test.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -1283,8 +1344,8 @@ program = {
common = grub-core/kern/misc.c; common = grub-core/kern/misc.c;
common = grub-core/tests/lib/test.c; common = grub-core/tests/lib/test.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -1299,8 +1360,8 @@ program = {
common = grub-core/tests/lib/test.c; common = grub-core/tests/lib/test.c;
common = grub-core/lib/priority_queue.c; common = grub-core/lib/priority_queue.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
condition = COND_HAVE_CXX; condition = COND_HAVE_CXX;
@@ -1315,8 +1376,8 @@ program = {
common = grub-core/kern/misc.c; common = grub-core/kern/misc.c;
common = grub-core/tests/lib/test.c; common = grub-core/tests/lib/test.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -1330,8 +1391,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -1348,8 +1409,8 @@ program = {
common = grub-core/kern/emu/argp_common.c; common = grub-core/kern/emu/argp_common.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -1364,8 +1425,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -1382,8 +1443,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
@@ -1411,8 +1472,8 @@ program = {
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
ldadd = libgrubgcry.a;
ldadd = grub-core/lib/gnulib/libgnu.a; ldadd = grub-core/lib/gnulib/libgnu.a;
ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; ldadd = '$(LIBINTL) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)';
}; };
+43
View File
@@ -1,3 +1,46 @@
New in 2.14:
* libgcrypt 1.11.
* LVM LV integrity and cachevol support.
* EROFS support.
* GRUB environment block inside the Btrfs header support.
* NX support for EFI platforms.
* shim loader protocol support.
* BLS and UKI support.
* Argon2 KDF support.
* TPM2 key protector support.
* Appended Signature Secure Boot Support for PowerPC.
* New option to block command line interface.
* Support dates outside of 1901..2038 range.
* zstdio decompression support.
* EFI code improvements and fixes.
* TPM driver fixes.
* Filesystems fixes.
* CVE and Coverity fixes.
* Tests improvements.
* Documentation improvements.
* ... and tons of other fixes and cleanups...
New in 2.12:
* GCC 13 support.
* clang 14 support.
* binutils 2.38 support.
* Unification of EFI Linux kernel loader across architectures.
* Transition to EFI Linux kernel stub loader for x86 architecture.
* Initial support for Boot Loader Interface.
* Support for dynamic GRUB runtime memory addition using firmware calls.
* PCI and MMIO UARTs support.
* SDL2 support.
* LoongArch support.
* TPM driver fixes.
* Many filesystems fixes.
* Many CVE and Coverity fixes.
* Debugging support improvements.
* Tests improvements.
* Documentation improvements.
* ...and tons of other fixes and cleanups...
New in 2.06: New in 2.06:
* GCC 10 support. * GCC 10 support.
+12 -1
View File
@@ -93,7 +93,18 @@ else
fi fi
grub_cv_prog_objcopy_absolute=yes grub_cv_prog_objcopy_absolute=yes
for link_addr in 0x2000 0x8000 0x7C00; do for link_addr in 0x2000 0x8000 0x7C00; do
if AC_TRY_COMMAND([${CC-cc} ${TARGET_CFLAGS} ${TARGET_LDFLAGS} -nostdlib ${TARGET_IMG_LDFLAGS_AC} ${TARGET_IMG_BASE_LDOPT},$link_addr conftest.o -o conftest.exec]); then :
target_img_base_ld="${TARGET_IMG_BASE_LDOPT}"
case "$target_img_base_ld" in
*_grub_text_base)
target_img_base_ld="${target_img_base_ld}=$link_addr"
;;
*)
target_img_base_ld="${target_img_base_ld},$link_addr"
;;
esac
if AC_TRY_COMMAND([${CC-cc} ${TARGET_CFLAGS} ${TARGET_LDFLAGS} -nostdlib ${TARGET_IMG_LDFLAGS_AC} ${target_img_base_ld} conftest.o -o conftest.exec]); then :
else else
AC_MSG_ERROR([${CC-cc} cannot link at address $link_addr]) AC_MSG_ERROR([${CC-cc} cannot link at address $link_addr])
fi fi
+50 -1
View File
@@ -9,7 +9,7 @@ fi
# Detect python # Detect python
if [ -z "$PYTHON" ]; then if [ -z "$PYTHON" ]; then
for i in python3 python; do for i in python3 python3.10 python; do
if command -v "$i" > /dev/null 2>&1; then if command -v "$i" > /dev/null 2>&1; then
PYTHON="$i" PYTHON="$i"
echo "Using $PYTHON..." echo "Using $PYTHON..."
@@ -35,6 +35,7 @@ ${PYTHON} util/import_unicode.py unicode/UnicodeData.txt unicode/BidiMirroring.t
echo "Importing libgcrypt..." echo "Importing libgcrypt..."
${PYTHON} util/import_gcry.py grub-core/lib/libgcrypt/ grub-core ${PYTHON} util/import_gcry.py grub-core/lib/libgcrypt/ grub-core
sed -n -f util/import_gcrypth.sed < grub-core/lib/libgcrypt/src/gcrypt.h.in > include/grub/gcrypt/gcrypt.h sed -n -f util/import_gcrypth.sed < grub-core/lib/libgcrypt/src/gcrypt.h.in > include/grub/gcrypt/gcrypt.h
sed -n -f util/import_gcrypt_inth.sed < grub-core/lib/libgcrypt/src/gcrypt-int.h >> include/grub/gcrypt/gcrypt.h
if [ -f include/grub/gcrypt/g10lib.h ]; then if [ -f include/grub/gcrypt/g10lib.h ]; then
rm include/grub/gcrypt/g10lib.h rm include/grub/gcrypt/g10lib.h
fi fi
@@ -51,6 +52,54 @@ for x in mpi-asm-defs.h mpih-add1.c mpih-sub1.c mpih-mul1.c mpih-mul2.c mpih-mul
cp grub-core/lib/libgcrypt-grub/mpi/generic/"$x" grub-core/lib/libgcrypt-grub/mpi/"$x" cp grub-core/lib/libgcrypt-grub/mpi/generic/"$x" grub-core/lib/libgcrypt-grub/mpi/"$x"
done done
for x in sha256-ssse3-amd64.S sha256-avx-amd64.S sha256-avx2-bmi2-amd64.S sha256-intel-shaext.c sha512-ssse3-amd64.S sha512-avx-amd64.S sha512-avx2-bmi2-amd64.S sha512-avx512-amd64.S; do
if [ -h grub-core/lib/libgcrypt-grub/cipher/"$x" ] || [ -f grub-core/lib/libgcrypt-grub/cipher/"$x" ]; then
rm grub-core/lib/libgcrypt-grub/cipher/"$x"
fi
cp grub-core/lib/libgcrypt/cipher/"$x" grub-core/lib/libgcrypt-grub/cipher/"$x"
done
if [ -f grub-core/lib/libgcrypt-grub/src/hwfeatures.c ]; then
rm grub-core/lib/libgcrypt-grub/src/hwfeatures.c
fi
for x in grub-core/lib/libgcrypt-patches/*.patch; do
patch -i $x -p1
done
echo "Importing libtasn1..."
if [ -d grub-core/lib/libtasn1-grub ]; then
rm -rf grub-core/lib/libtasn1-grub
fi
mkdir -p grub-core/lib/libtasn1-grub/lib
cp grub-core/lib/libtasn1/lib/*.[ch] grub-core/lib/libtasn1-grub/lib
cp grub-core/lib/libtasn1/libtasn1.h grub-core/lib/libtasn1-grub/
if [ -d grub-core/tests/asn1/tests ]; then
rm -rf grub-core/tests/asn1/tests
fi
mkdir grub-core/tests/asn1/tests
cp grub-core/lib/libtasn1/tests/*.[ch] grub-core/tests/asn1/tests
for patch in \
0001-libtasn1-disable-code-not-needed-in-grub.patch \
0002-libtasn1-replace-strcat-with-strcpy-in-_asn1_str_cat.patch \
0003-libtasn1-replace-strcat-with-_asn1_str_cat.patch \
0004-libtasn1-adjust-the-header-paths-in-libtasn1.h.patch \
0005-libtasn1-Use-grub_divmod64-for-division.patch \
0006-libtasn1-fix-the-potential-buffer-overrun.patch \
0007-asn1_test-include-asn1_test.h-only.patch \
0008-asn1_test-rename-the-main-functions-to-the-test-name.patch \
0009-asn1_test-return-either-0-or-1-to-reflect-the-result.patch \
0010-asn1_test-remove-verbose-and-the-unnecessary-printf.patch \
0011-asn1_test-print-the-error-messages-with-grub_printf.patch \
0012-asn1_test-use-the-grub-specific-functions-and-types.patch \
0013-asn1_test-enable-the-testcase-only-when-GRUB_LONG_MA.patch ; do
patch -p1 -i grub-core/lib/libtasn1-patches/$patch
done
echo "Generating Automake input..." echo "Generating Automake input..."
# Automake doesn't like including files from a path outside the project. # Automake doesn't like including files from a path outside the project.
+1251 -739
View File
File diff suppressed because it is too large. Load diff
+29 -4
View File
@@ -24,6 +24,7 @@ gnulib_modules="
argp argp
base64 base64
error error
filevercmp
fnmatch fnmatch
getdelim getdelim
getline getline
@@ -62,13 +63,11 @@ checkout_only_file=
copy=true copy=true
vc_ignore= vc_ignore=
SKIP_PO=t
# Build prerequisites # Build prerequisites
buildreq="\ buildreq="\
autoconf 2.64 autoconf 2.64
automake 1.14 automake 1.14
gettext 0.18.3 gettext -
git 1.5.5 git 1.5.5
patch - patch -
tar - tar -
@@ -84,7 +83,14 @@ bootstrap_post_import_hook () {
# Instead of patching our gnulib and therefore maintaining a fork, submit # Instead of patching our gnulib and therefore maintaining a fork, submit
# changes to gnulib and update the hash above when they've merged. Do not # changes to gnulib and update the hash above when they've merged. Do not
# add new patches here. # add new patches here.
patch -d grub-core/lib/gnulib -p2 < grub-core/lib/gnulib-patches/fix-width.patch for patchname in fix-width \
fix-regcomp-resource-leak \
fix-regexec-resource-leak \
fix-gcc-15-compile \
fix-unused-value; do
patch -d grub-core/lib/gnulib -p2 \
< "grub-core/lib/gnulib-patches/$patchname.patch"
done
for patchname in \ for patchname in \
0001-Support-POTFILES-shell \ 0001-Support-POTFILES-shell \
@@ -100,4 +106,23 @@ bootstrap_post_import_hook () {
bootstrap_epilogue () { bootstrap_epilogue () {
mv INSTALL.grub INSTALL mv INSTALL.grub INSTALL
if [ "x$SKIP_PO" = "x" ]; then
# Generate LINGUAS with all supported languages. Bootstrap will
# generate a LINGUAS, but it will not contain the autogenerated
# languages.
autogenerated="en@quot en@hebrew de@hebrew en@cyrillic en@greek en@arabic en@piglatin de_CH"
{
# NOTE: xargs has no POSIX compliant way to avoid running the program
# given as an argument when there are no input lines. So ensure that
# basename is always run with at least one argument, the empty string,
# and ignore the first line of output.
ls po/*.po | xargs -L 100 basename -s .po -a "" | tail -n +2
for x in $autogenerated; do
rm -f "po/$x.po"
echo "$x"
done
} | sort | uniq | xargs >po/LINGUAS
fi
} }
+6 -3
View File
@@ -24,6 +24,8 @@ if COND_HAVE_PCI
CFLAGS_PLATFORM += -DGRUB_HAS_PCI CFLAGS_PLATFORM += -DGRUB_HAS_PCI
endif endif
CPPFLAGS_GCRY_ASM = @CPPFLAGS_GCRY_ASM@
# Other options # Other options
CPPFLAGS_DEFAULT = -DGRUB_FILE=\"$(subst $(srcdir)/,,$<)\" CPPFLAGS_DEFAULT = -DGRUB_FILE=\"$(subst $(srcdir)/,,$<)\"
@@ -75,14 +77,14 @@ grubconfdir = $(sysconfdir)/grub.d
platformdir = $(pkglibdir)/$(target_cpu)-$(platform) platformdir = $(pkglibdir)/$(target_cpu)-$(platform)
starfielddir = $(pkgdatadir)/themes/starfield starfielddir = $(pkgdatadir)/themes/starfield
CFLAGS_GNULIB = -Wno-undef -Wno-sign-compare -Wno-unused -Wno-unused-parameter -Wno-redundant-decls -Wno-unreachable-code -Wno-conversion CFLAGS_GNULIB = -Wno-undef -Wno-sign-compare -Wno-unused -Wno-unused-parameter -Wno-redundant-decls -Wno-unreachable-code -Wno-conversion -Wno-error=attributes
CPPFLAGS_GNULIB = -I$(top_builddir)/grub-core/lib/gnulib -I$(top_srcdir)/grub-core/lib/gnulib CPPFLAGS_GNULIB = -I$(top_builddir)/grub-core/lib/gnulib -I$(top_srcdir)/grub-core/lib/gnulib
CFLAGS_POSIX = -fno-builtin CFLAGS_POSIX = -fno-builtin
CPPFLAGS_POSIX = -I$(top_srcdir)/grub-core/lib/posix_wrap CPPFLAGS_POSIX = -I$(top_srcdir)/grub-core/lib/posix_wrap
CFLAGS_GCRY = -Wno-error -Wno-missing-field-initializers -Wno-redundant-decls -Wno-undef $(CFLAGS_POSIX) CFLAGS_GCRY = -Wno-sign-compare -Wno-missing-field-initializers -Wno-redundant-decls -Wno-undef $(CFLAGS_POSIX)
CPPFLAGS_GCRY = -I$(top_srcdir)/grub-core/lib/libgcrypt_wrap $(CPPFLAGS_POSIX) -D_GCRYPT_IN_LIBGCRYPT=1 -I$(top_srcdir)/include/grub/gcrypt CPPFLAGS_GCRY = -I$(top_srcdir)/grub-core/lib/libgcrypt_wrap $(CPPFLAGS_POSIX) -D_GCRYPT_IN_LIBGCRYPT=1 -D_GCRYPT_CONFIG_H_INCLUDED=1 -I$(top_srcdir)/include/grub/gcrypt
CPPFLAGS_EFIEMU = -I$(top_srcdir)/grub-core/efiemu/runtime CPPFLAGS_EFIEMU = -I$(top_srcdir)/grub-core/efiemu/runtime
@@ -111,6 +113,7 @@ MOD_FILES =
MODULE_FILES = MODULE_FILES =
MARKER_FILES = MARKER_FILES =
KERNEL_HEADER_FILES = KERNEL_HEADER_FILES =
EXTRA_DEPS =
bin_SCRIPTS = bin_SCRIPTS =
bin_PROGRAMS = bin_PROGRAMS =
+54 -1
View File
@@ -16,7 +16,8 @@ EXTRA_DIST += docs/autoiso.cfg
EXTRA_DIST += docs/grub.cfg EXTRA_DIST += docs/grub.cfg
EXTRA_DIST += docs/osdetect.cfg EXTRA_DIST += docs/osdetect.cfg
EXTRA_DIST += conf/i386-cygwin-img-ld.sc EXTRA_DIST += conf/i386-cygwin-img.lds
EXTRA_DIST += conf/i386-pc-kernel.lds
EXTRA_DIST += grub-core/Makefile.core.def EXTRA_DIST += grub-core/Makefile.core.def
EXTRA_DIST += grub-core/Makefile.gcry.def EXTRA_DIST += grub-core/Makefile.gcry.def
@@ -29,21 +30,68 @@ EXTRA_DIST += grub-core/genemuinit.sh
EXTRA_DIST += grub-core/genemuinitheader.sh EXTRA_DIST += grub-core/genemuinitheader.sh
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-width.patch EXTRA_DIST += grub-core/lib/gnulib-patches/fix-width.patch
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-regcomp-resource-leak.patch
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-regexec-resource-leak.patch
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-gcc-15-compile.patch
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-unused-value.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/01_md.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/02_keccak_sse.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/03_mpiutil_alloc.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/03_sexp_free.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/04_aria.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/05_disable_rsa_shake.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/06_blake.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/07_disable_64div.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/08_sexp_leak.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/09-blake2b-hash-buffers.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/10-kdf-use-GPG-errs.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/11-kdf-remove-unsupported-kdfs.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/12-kdf-use-grub_divmod64.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/13_add_hwfeatures.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/14_fix_build_shaext.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/15_build_sha256_x86_64_efi_opt_code.patch
EXTRA_DIST += grub-core/lib/libgcrypt-patches/16_build_sha512_x86_64_efi_opt_code.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0001-libtasn1-disable-code-not-needed-in-grub.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0002-libtasn1-replace-strcat-with-strcpy-in-_asn1_str_cat.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0003-libtasn1-replace-strcat-with-_asn1_str_cat.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0004-libtasn1-adjust-the-header-paths-in-libtasn1.h.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0005-libtasn1-Use-grub_divmod64-for-division.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0006-libtasn1-fix-the-potential-buffer-overrun.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0007-asn1_test-include-asn1_test.h-only.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0008-asn1_test-rename-the-main-functions-to-the-test-name.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0009-asn1_test-return-either-0-or-1-to-reflect-the-result.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0010-asn1_test-remove-verbose-and-the-unnecessary-printf.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0011-asn1_test-print-the-error-messages-with-grub_printf.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0012-asn1_test-use-the-grub-specific-functions-and-types.patch
EXTRA_DIST += grub-core/lib/libtasn1-patches/0013-asn1_test-enable-the-testcase-only-when-GRUB_LONG_MA.patch
EXTRA_DIST += grub-core/lib/libgcrypt EXTRA_DIST += grub-core/lib/libgcrypt
EXTRA_DIST += grub-core/lib/libgcrypt-grub/mpi/generic EXTRA_DIST += grub-core/lib/libgcrypt-grub/mpi/generic
EXTRA_DIST += grub-core/lib/libtasn1
EXTRA_DIST += $(shell find $(top_srcdir)/include -name '*.h') EXTRA_DIST += $(shell find $(top_srcdir)/include -name '*.h')
EXTRA_DIST += $(shell find $(top_srcdir)/grub-core/lib -name '*.h') EXTRA_DIST += $(shell find $(top_srcdir)/grub-core/lib -name '*.h')
EXTRA_DIST += grub-core/efiemu/runtime/config.h EXTRA_DIST += grub-core/efiemu/runtime/config.h
EXTRA_DIST += grub-core/tests/crypto_cipher_mode_vectors.h
EXTRA_DIST += grub-core/tests/asn1/asn1_test.h
EXTRA_DIST += $(shell find $(top_srcdir)/grub-core/tests/asn1/tests -name '*.h')
EXTRA_DIST += $(shell find $(top_srcdir)/grub-core/commands/tpm2_key_protector -name '*.h')
EXTRA_DIST += grub-core/commands/tpm2_key_protector/tpm2key.asn
EXTRA_DIST += grub-core/commands/appendedsig/appendedsig.h
EXTRA_DIST += grub-core/lib/LzmaDec.c EXTRA_DIST += grub-core/lib/LzmaDec.c
EXTRA_DIST += grub-core/fs/cpio_common.c EXTRA_DIST += grub-core/fs/cpio_common.c
EXTRA_DIST += BUGS EXTRA_DIST += BUGS
EXTRA_DIST += MAINTAINERS
EXTRA_DIST += SECURITY
EXTRA_DIST += util/i386/efi/grub-dumpdevtree EXTRA_DIST += util/i386/efi/grub-dumpdevtree
EXTRA_DIST += util/spkmodem-recv.c EXTRA_DIST += util/spkmodem-recv.c
EXTRA_DIST += util/import_gcrypth.sed EXTRA_DIST += util/import_gcrypth.sed
EXTRA_DIST += util/import_gcrypt_inth.sed
EXTRA_DIST += util/bin2h.c EXTRA_DIST += util/bin2h.c
EXTRA_DIST += util/grub-gen-asciih.c EXTRA_DIST += util/grub-gen-asciih.c
EXTRA_DIST += util/grub-gen-widthspec.c EXTRA_DIST += util/grub-gen-widthspec.c
@@ -125,6 +173,9 @@ EXTRA_DIST += po/hebrew.sed
EXTRA_DIST += tests/dfly-mbr-mbexample.mbr.img.gz EXTRA_DIST += tests/dfly-mbr-mbexample.mbr.img.gz
EXTRA_DIST += tests/dfly-mbr-mbexample.dfly.img.gz EXTRA_DIST += tests/dfly-mbr-mbexample.dfly.img.gz
EXTRA_DIST += tests/iso9660_ce_loop2.iso.gz
EXTRA_DIST += tests/iso9660_ce_loop.iso.gz
EXTRA_DIST += tests/iso9660_early_ce.iso.gz
EXTRA_DIST += coreboot.cfg EXTRA_DIST += coreboot.cfg
@@ -135,6 +186,8 @@ EXTRA_DIST += tests/file_filter/file.lzop
EXTRA_DIST += tests/file_filter/file.lzop.sig EXTRA_DIST += tests/file_filter/file.lzop.sig
EXTRA_DIST += tests/file_filter/file.xz EXTRA_DIST += tests/file_filter/file.xz
EXTRA_DIST += tests/file_filter/file.xz.sig EXTRA_DIST += tests/file_filter/file.xz.sig
EXTRA_DIST += tests/file_filter/file.zstd
EXTRA_DIST += tests/file_filter/file.zstd.sig
EXTRA_DIST += tests/file_filter/keys EXTRA_DIST += tests/file_filter/keys
EXTRA_DIST += tests/file_filter/keys.pub EXTRA_DIST += tests/file_filter/keys.pub
EXTRA_DIST += tests/file_filter/test.cfg EXTRA_DIST += tests/file_filter/test.cfg
@@ -2,6 +2,7 @@
SECTIONS SECTIONS
{ {
. = _grub_text_base;
.text : .text :
{ {
start = . ; start = . ;
+51
View File
@@ -0,0 +1,51 @@
ENTRY(_start)
/*
* Align sections to a 16-byte boundary. This guarantees ABI compatibility with
* C generated code.
*/
SECTION_ALIGN = 0x10;
PHDRS {
text PT_LOAD FLAGS(7) /* PF_R | PF_W | PF_X */;
}
SECTIONS
{
/*
* Set section alignment to 1. This allows sections to be aligned without
* creating holes in the VMA space or gaps in the file.
*/
. = _grub_text_base;
.text ALIGN(0x1) : {
_start = .;
*(.text .text.*)
. = ALIGN(SECTION_ALIGN);
} :text
.rodata ALIGN(0x1) : {
*(.rodata .rodata.*)
. = ALIGN(SECTION_ALIGN);
} :text
.module_license ALIGN(0x1) : {
*(.module_license)
. = ALIGN(SECTION_ALIGN);
} :text
.data ALIGN(0x1) : {
*(.data .data.*)
. = ALIGN(SECTION_ALIGN);
_edata = .;
} :text
.bss ALIGN(0x1) : {
__bss_start = .;
*(.bss .bss.*)
*(COMMON)
. = ALIGN(SECTION_ALIGN);
_end = .;
} :text
/DISCARD/ : {
*(.interp)
*(.note*)
*(.comment)
*(.build-id)
}
}
+2
View File
@@ -64,6 +64,8 @@
# define GRUB_TARGET_CPU "@GRUB_TARGET_CPU@" # define GRUB_TARGET_CPU "@GRUB_TARGET_CPU@"
# define GRUB_PLATFORM "@GRUB_PLATFORM@" # define GRUB_PLATFORM "@GRUB_PLATFORM@"
# define GRUB_STACK_PROTECTOR_INIT @GRUB_STACK_PROTECTOR_INIT@
# define RE_ENABLE_I18N 1 # define RE_ENABLE_I18N 1
# define _GNU_SOURCE 1 # define _GNU_SOURCE 1
+454 -56
View File
@@ -34,7 +34,7 @@ dnl "TARGET_" (such as TARGET_CC, TARGET_CFLAGS, etc.) are used for
dnl the target type. See INSTALL for full list of variables and dnl the target type. See INSTALL for full list of variables and
dnl description of the relationships between them. dnl description of the relationships between them.
AC_INIT([GRUB],[2.12~rc1],[bug-grub@gnu.org]) AC_INIT([GRUB],[2.15],[bug-grub@gnu.org])
AS_CASE(["$ERROR_PLATFORM_NOT_SUPPORT_SSP"], AS_CASE(["$ERROR_PLATFORM_NOT_SUPPORT_SSP"],
[n | no | nO | N | No | NO], [ERROR_PLATFORM_NOT_SUPPORT_SSP=no], [n | no | nO | N | No | NO], [ERROR_PLATFORM_NOT_SUPPORT_SSP=no],
@@ -53,7 +53,7 @@ save_program_prefix="${program_prefix}"
AC_CANONICAL_TARGET AC_CANONICAL_TARGET
program_prefix="${save_program_prefix}" program_prefix="${save_program_prefix}"
AM_INIT_AUTOMAKE([1.11]) AM_INIT_AUTOMAKE([1.11 tar-ustar])
AC_PREREQ(2.64) AC_PREREQ(2.64)
AC_CONFIG_SRCDIR([include/grub/dl.h]) AC_CONFIG_SRCDIR([include/grub/dl.h])
AC_CONFIG_HEADERS([config-util.h]) AC_CONFIG_HEADERS([config-util.h])
@@ -76,6 +76,7 @@ grub_TRANSFORM([grub-mkpasswd-pbkdf2])
grub_TRANSFORM([grub-mkrelpath]) grub_TRANSFORM([grub-mkrelpath])
grub_TRANSFORM([grub-mkrescue]) grub_TRANSFORM([grub-mkrescue])
grub_TRANSFORM([grub-probe]) grub_TRANSFORM([grub-probe])
grub_TRANSFORM([grub-protect])
grub_TRANSFORM([grub-reboot]) grub_TRANSFORM([grub-reboot])
grub_TRANSFORM([grub-script-check]) grub_TRANSFORM([grub-script-check])
grub_TRANSFORM([grub-set-default]) grub_TRANSFORM([grub-set-default])
@@ -802,6 +803,17 @@ if test "x$target_cpu" = xmips || test "x$target_cpu" = xmipsel ; then
if test "x$grub_cv_cc_mflush_func" = xyes; then if test "x$grub_cv_cc_mflush_func" = xyes; then
TARGET_CFLAGS="$TARGET_CFLAGS -mflush-func=grub_red_herring" TARGET_CFLAGS="$TARGET_CFLAGS -mflush-func=grub_red_herring"
fi fi
AC_CACHE_CHECK([whether -mno-gpopt works], [grub_cv_cc_mno_gpopt], [
CFLAGS="$TARGET_CFLAGS -mno-gpopt -Werror"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[]])],
[grub_cv_cc_mno_gpopt=yes],
[grub_cv_cc_mno_gpopt=no])
])
if test "x$grub_cv_cc_mno_gpopt" = xyes; then
TARGET_CFLAGS="$TARGET_CFLAGS -mno-gpopt"
fi
fi fi
@@ -901,6 +913,31 @@ if test "x$target_cpu" = xloongarch64; then
TARGET_CCASFLAGS="$TARGET_CCASFLAGS -Wa,-mla-global-with-abs" TARGET_CCASFLAGS="$TARGET_CCASFLAGS -Wa,-mla-global-with-abs"
fi fi
if test "x$target_cpu" = xriscv64 || test "x$target_cpu" = xriscv32; then
AC_CACHE_CHECK([for no-relax options], grub_cv_target_cc_mno_relax, [
grub_cv_target_cc_mno_relax=no
for cand in "-mno-relax" "-Wa,-mno-relax"; do
if test x"$grub_cv_target_cc_mno_relax" != xno ; then
break
fi
CFLAGS="$TARGET_CFLAGS $cand -Werror"
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
asm (".globl start; start:");
void __main (void);
void __main (void) {}
int main (void);
]], [[]])], [grub_cv_target_cc_mno_relax="$cand"], [])
done
])
CFLAGS="$TARGET_CFLAGS"
if test x"$grub_cv_target_cc_mno_relax" != xno ; then
TARGET_CFLAGS="$TARGET_CFLAGS $grub_cv_target_cc_mno_relax"
TARGET_CCASFLAGS="$TARGET_CCASFLAGS $grub_cv_target_cc_mno_relax"
fi
fi
# GRUB doesn't use float or doubles at all. Yet some toolchains may decide # GRUB doesn't use float or doubles at all. Yet some toolchains may decide
# that floats are a good fit to run instead of what's written in the code. # that floats are a good fit to run instead of what's written in the code.
# Given that floating point unit is disabled (if present to begin with) # Given that floating point unit is disabled (if present to begin with)
@@ -1020,6 +1057,19 @@ if test x"$target_cpu" = xsparc64 ; then
TARGET_LDFLAGS="$TARGET_LDFLAGS $grub_cv_target_cc_mno_relax" TARGET_LDFLAGS="$TARGET_LDFLAGS $grub_cv_target_cc_mno_relax"
fi fi
# The backtrace module relies on frame pointers and the default optimization
# level, -Os, omits them. Make sure they are enabled.
AC_CACHE_CHECK([whether -fno-omit-frame-pointer works], [grub_cv_cc_fno_omit_frame_pointer], [
CFLAGS="$TARGET_CFLAGS -fno-omit-frame-pointer"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[]])],
[grub_cv_cc_fno_omit_frame_pointer=yes],
[grub_cv_cc_fno_omit_frame_pointer=no])
])
if test "x$grub_cv_cc_fno_omit_frame_pointer" = xyes; then
TARGET_CFLAGS="$TARGET_CFLAGS -fno-omit-frame-pointer"
fi
# By default, GCC 4.4 generates .eh_frame sections containing unwind # By default, GCC 4.4 generates .eh_frame sections containing unwind
# information in some cases where it previously did not. GRUB doesn't need # information in some cases where it previously did not. GRUB doesn't need
# these and they just use up vital space. Restore the old compiler # these and they just use up vital space. Restore the old compiler
@@ -1098,6 +1148,239 @@ if test "x$grub_cv_cc_fno_ident" = xyes; then
TARGET_CFLAGS="$TARGET_CFLAGS -fno-ident" TARGET_CFLAGS="$TARGET_CFLAGS -fno-ident"
fi fi
# Implementation of the --disable-amd64-as-feature-detection switch.
AC_MSG_CHECKING([whether to enable AMD64 as(1) feature detection])
if test x$target_cpu = xx86_64 -a x$platform = xefi; then
CPPFLAGS_GCRY_ASM="-D__x86_64 -DHAVE_CPU_ARCH_X86"
AC_ARG_ENABLE(amd64-as-feature-detection,
AS_HELP_STRING([--disable-amd64-as-feature-detection],
[Disable the auto-detection of AMD64 as(1) features]),
[amd64_as_feature_detection=$enableval],
[amd64_as_feature_detection=yes])
else
CPPFLAGS_GCRY_ASM=
amd64_as_feature_detection=no
fi
AC_MSG_RESULT($amd64_as_feature_detection)
#
# Check whether GCC assembler supports features needed for libgcrypt amd64
# implementations
#
if test $amd64_as_feature_detection = yes; then
AC_CACHE_CHECK([whether GCC assembler is compatible for amd64 assembly implementations],
[grub_cv_gcc_x86_platform_as_ok],
[if test "$target_cpu" != "x86_64" ; then
grub_cv_gcc_x86_platform_as_ok="n/a"
else
grub_cv_gcc_x86_platform_as_ok=no
AC_LINK_IFELSE([AC_LANG_PROGRAM(
[[__asm__(
/* Test if '.type' and '.size' are supported. */
/* These work only on ELF targets. */
".text\n\t"
"asmfunc:\n\t"
".size asmfunc,.-asmfunc;\n\t"
".type asmfunc,@function;\n\t"
/* Test if assembler allows use of '/' for constant division
* (Solaris/x86 issue). If previous constant division check
* and "-Wa,--divide" workaround failed, this causes assembly
* to be disable on this machine. */
"xorl \$(123456789/12345678), %ebp;\n\t"
);
void asmfunc(void);]], [ asmfunc(); ])],
[grub_cv_gcc_x86_platform_as_ok=yes])
fi])
if test "$grub_cv_gcc_x86_platform_as_ok" = "yes"; then
# Define __PIC__ to ensure the assembly code use PIC instructions
CPPFLAGS_GCRY_ASM="$CPPFLAGS_GCRY_ASM -D__PIC__=1 -DHAVE_COMPATIBLE_GCC_AMD64_PLATFORM_AS"
fi
#
# Check whether GCC assembler supports Intel syntax
#
AC_CACHE_CHECK([whether GCC assembler is compatible for Intel syntax assembly implementations],
[grub_cv_gcc_platform_as_ok_for_intel_syntax],
[if test "$target_cpu" != "x86_64" ; then
grub_cv_gcc_platform_as_ok_for_intel_syntax="n/a"
else
grub_cv_gcc_platform_as_ok_for_intel_syntax=no
AC_LINK_IFELSE([AC_LANG_PROGRAM(
[[__asm__(
".intel_syntax noprefix\n\t"
".text\n\t"
"actest:\n\t"
"pxor xmm1, xmm7;\n\t"
"vperm2i128 ymm2, ymm3, ymm0, 1;\n\t"
"add eax, ebp;\n\t"
"rorx eax, ebp, 1;\n\t"
"sub eax, [esp + 4];\n\t"
"add dword ptr [esp + eax], 0b10101;\n\t"
".att_syntax prefix\n\t"
);
void actest(void);]], [ actest(); ])],
[grub_cv_gcc_platform_as_ok_for_intel_syntax=yes])
fi])
if test "$grub_cv_gcc_platform_as_ok_for_intel_syntax" = "yes" ; then
CPPFLAGS_GCRY_ASM="$CPPFLAGS_GCRY_ASM -DHAVE_INTEL_SYNTAX_PLATFORM_AS"
fi
#
# Check whether GCC inline assembler supports SSSE3 instructions
#
AC_CACHE_CHECK([whether GCC inline assembler supports SSSE3 instructions],
[grub_cv_gcc_inline_asm_ssse3],
[if test "$target_cpu" != "x86_64" ; then
grub_cv_gcc_inline_asm_ssse3="n/a"
else
grub_cv_gcc_inline_asm_ssse3=no
AC_LINK_IFELSE([AC_LANG_PROGRAM(
[[static unsigned char be_mask[16] __attribute__ ((aligned (16))) =
{ 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
void a(void) {
__asm__("pshufb %[mask], %%xmm2\n\t"::[mask]"m"(*be_mask):);
}]], [ a(); ] )],
[grub_cv_gcc_inline_asm_ssse3=yes])
fi])
if test "$grub_cv_gcc_inline_asm_ssse3" = "yes" ; then
CPPFLAGS_GCRY_ASM="$CPPFLAGS_GCRY_ASM -DHAVE_GCC_INLINE_ASM_SSSE3"
fi
#
# Check whether GCC inline assembler supports SHA Extensions instructions.
#
AC_CACHE_CHECK([whether GCC inline assembler supports SHA Extensions instructions],
[grub_cv_gcc_inline_asm_shaext],
[if test "$target_cpu" != "x86_64" ; then
grub_cv_gcc_inline_asm_shaext="n/a"
else
grub_cv_gcc_inline_asm_shaext=no
AC_LINK_IFELSE([AC_LANG_PROGRAM(
[[void a(void) {
__asm__("sha1rnds4 \$0, %%xmm1, %%xmm3\n\t":::"cc");
__asm__("sha1nexte %%xmm1, %%xmm3\n\t":::"cc");
__asm__("sha1msg1 %%xmm1, %%xmm3\n\t":::"cc");
__asm__("sha1msg2 %%xmm1, %%xmm3\n\t":::"cc");
__asm__("sha256rnds2 %%xmm0, %%xmm1, %%xmm3\n\t":::"cc");
__asm__("sha256msg1 %%xmm1, %%xmm3\n\t":::"cc");
__asm__("sha256msg2 %%xmm1, %%xmm3\n\t":::"cc");
}]], [ a(); ] )],
[grub_cv_gcc_inline_asm_shaext=yes])
fi])
if test "$grub_cv_gcc_inline_asm_shaext" = "yes" ; then
CPPFLAGS_GCRY_ASM="$CPPFLAGS_GCRY_ASM -DHAVE_GCC_INLINE_ASM_SHAEXT -DENABLE_SHAEXT_SUPPORT"
fi
#
# Check whether GCC inline assembler supports SSE4.1 instructions.
#
AC_CACHE_CHECK([whether GCC inline assembler supports SSE4.1 instructions],
[grub_cv_gcc_inline_asm_sse41],
[if test "$target_cpu" != "x86_64" ; then
grub_cv_gcc_inline_asm_sse41="n/a"
else
grub_cv_gcc_inline_asm_sse41=no
AC_LINK_IFELSE([AC_LANG_PROGRAM(
[[void a(void) {
int i;
__asm__("pextrd \$2, %%xmm0, %[out]\n\t" : [out] "=m" (i));
}]], [ a(); ] )],
[grub_cv_gcc_inline_asm_sse41=yes])
fi])
if test "$grub_cv_gcc_inline_asm_sse41" = "yes" ; then
CPPFLAGS_GCRY_ASM="$CPPFLAGS_GCRY_ASM -DHAVE_GCC_INLINE_ASM_SSE41"
fi
#
# Check whether GCC inline assembler supports AVX instructions
#
AC_CACHE_CHECK([whether GCC inline assembler supports AVX instructions],
[grub_cv_gcc_inline_asm_avx],
[if test "$target_cpu" != "x86_64" ; then
grub_cv_gcc_inline_asm_avx="n/a"
else
grub_cv_gcc_inline_asm_avx=no
AC_LINK_IFELSE([AC_LANG_PROGRAM(
[[void a(void) {
__asm__("xgetbv; vaesdeclast (%[mem]),%%xmm0,%%xmm7\n\t"::[mem]"r"(0):);
}]], [ a(); ] )],
[grub_cv_gcc_inline_asm_avx=yes])
fi])
if test "$grub_cv_gcc_inline_asm_avx" = "yes" ; then
CPPFLAGS_GCRY_ASM="$CPPFLAGS_GCRY_ASM -DHAVE_GCC_INLINE_ASM_AVX"
fi
#
# Check whether GCC inline assembler supports AVX2 instructions
#
AC_CACHE_CHECK([whether GCC inline assembler supports AVX2 instructions],
[grub_cv_gcc_inline_asm_avx2],
[if test "$target_cpu" != "x86_64" ; then
grub_cv_gcc_inline_asm_avx2="n/a"
else
grub_cv_gcc_inline_asm_avx2=no
AC_LINK_IFELSE([AC_LANG_PROGRAM(
[[void a(void) {
__asm__("xgetbv; vpbroadcastb %%xmm7,%%ymm1\n\t":::"cc");
}]], [ a(); ] )],
[grub_cv_gcc_inline_asm_avx2=yes])
fi])
if test "$grub_cv_gcc_inline_asm_avx2" = "yes" ; then
CPPFLAGS_GCRY_ASM="$CPPFLAGS_GCRY_ASM -DHAVE_GCC_INLINE_ASM_AVX2"
fi
#
# Check whether GCC inline assembler supports AVX512 instructions
#
AC_CACHE_CHECK([whether GCC inline assembler supports AVX512 instructions],
[grub_cv_gcc_inline_asm_avx512],
[if test "$target_cpu" != "x86_64" ; then
grub_cv_gcc_inline_asm_avx512="n/a"
else
grub_cv_gcc_inline_asm_avx512=no
AC_LINK_IFELSE([AC_LANG_PROGRAM(
[[void a(void) {
__asm__("xgetbv; vpopcntq %%zmm7, %%zmm1%{%%k1%}%{z%};\n\t":::"cc");
__asm__("vpexpandb %%zmm3, %%zmm1;\n\t":::"cc");
__asm__("vpxorq %%xmm7, %%xmm7, %%xmm7;\n\t":::"cc");
__asm__("vpxorq %%ymm7, %%ymm7, %%ymm7;\n\t":::"cc");
__asm__("vpxorq (%%eax)%{1to8%}, %%zmm7, %%zmm7;\n\t":::"cc");
}]], [ a(); ] )],
[grub_cv_gcc_inline_asm_avx512=yes])
fi])
if test "$grub_cv_gcc_inline_asm_avx512" = "yes" ; then
CPPFLAGS_GCRY_ASM="$CPPFLAGS_GCRY_ASM -DHAVE_GCC_INLINE_ASM_AVX512"
fi
#
# Check whether GCC inline assembler supports BMI2 instructions
#
AC_CACHE_CHECK([whether GCC inline assembler supports BMI2 instructions],
[grub_cv_gcc_inline_asm_bmi2],
[if test "$target_cpu" != "x86_64" ; then
grub_cv_gcc_inline_asm_bmi2="n/a"
else
grub_cv_gcc_inline_asm_bmi2=no
AC_LINK_IFELSE([AC_LANG_PROGRAM(
[[unsigned int a(unsigned int x, unsigned int y) {
unsigned int tmp1, tmp2;
asm ("rorxl %2, %1, %0"
: "=r" (tmp1)
: "rm0" (x), "J" (32 - ((23) & 31)));
asm ("andnl %2, %1, %0"
: "=r" (tmp2)
: "r0" (x), "rm" (y));
return tmp1 + tmp2;
}]], [ a(1, 2); ] )],
[grub_cv_gcc_inline_asm_bmi2=yes])
fi])
if test "$grub_cv_gcc_inline_asm_bmi2" = "yes" ; then
CPPFLAGS_GCRY_ASM="$CPPFLAGS_GCRY_ASM -DHAVE_GCC_INLINE_ASM_BMI2"
fi
fi
AC_SUBST(CPPFLAGS_GCRY_ASM)
CFLAGS="$TARGET_CFLAGS" CFLAGS="$TARGET_CFLAGS"
@@ -1171,14 +1454,16 @@ if test x$grub_cv_target_cc_link_format = x-arch,i386 || test x$grub_cv_target_c
TARGET_IMG_LDFLAGS='-nostdlib -static -Wl,-preload -Wl,-segalign,20' TARGET_IMG_LDFLAGS='-nostdlib -static -Wl,-preload -Wl,-segalign,20'
TARGET_IMG_LDFLAGS_AC='-nostdlib -static -Wl,-preload -Wl,-segalign,20' TARGET_IMG_LDFLAGS_AC='-nostdlib -static -Wl,-preload -Wl,-segalign,20'
TARGET_IMG_BASE_LDOPT="-Wl,-image_base" TARGET_IMG_BASE_LDOPT="-Wl,-image_base"
TARGET_IMG_BASE_LDOPT_ARG_SEP=","
TARGET_LDFLAGS_OLDMAGIC="" TARGET_LDFLAGS_OLDMAGIC=""
elif test x$grub_cv_target_cc_link_format = x-mi386pe || test x$grub_cv_target_cc_link_format = x-mi386pep ; then elif test x$grub_cv_target_cc_link_format = x-mi386pe || test x$grub_cv_target_cc_link_format = x-mi386pep ; then
TARGET_APPLE_LINKER=0 TARGET_APPLE_LINKER=0
TARGET_LDFLAGS_OLDMAGIC="-Wl,-N" TARGET_LDFLAGS_OLDMAGIC="-Wl,-N"
TARGET_IMG_LDSCRIPT='$(top_srcdir)'"/conf/i386-cygwin-img-ld.sc" TARGET_IMG_LDSCRIPT='$(top_srcdir)'"/conf/i386-cygwin-img.lds"
TARGET_IMG_LDFLAGS="-Wl,-T${TARGET_IMG_LDSCRIPT}" TARGET_IMG_LDFLAGS="-Wl,-T${TARGET_IMG_LDSCRIPT}"
TARGET_IMG_LDFLAGS_AC="-Wl,-T${srcdir}/conf/i386-cygwin-img-ld.sc" TARGET_IMG_LDFLAGS_AC="-Wl,-T${srcdir}/conf/i386-cygwin-img.lds"
TARGET_IMG_BASE_LDOPT="-Wl,-Ttext" TARGET_IMG_BASE_LDOPT="-Wl,--defsym=_grub_text_base"
TARGET_IMG_BASE_LDOPT_ARG_SEP="="
TARGET_IMG_CFLAGS= TARGET_IMG_CFLAGS=
else else
TARGET_APPLE_LINKER=0 TARGET_APPLE_LINKER=0
@@ -1186,7 +1471,27 @@ else
TARGET_IMG_LDSCRIPT= TARGET_IMG_LDSCRIPT=
TARGET_IMG_LDFLAGS='-Wl,-N' TARGET_IMG_LDFLAGS='-Wl,-N'
TARGET_IMG_LDFLAGS_AC='-Wl,-N' TARGET_IMG_LDFLAGS_AC='-Wl,-N'
TARGET_IMG_BASE_LDOPT="-Wl,-Ttext" if test "x$target_cpu-$platform" != "xi386-pc"; then
AX_CHECK_LINK_FLAG([-Wl,--image-base,0],
[TARGET_IMG_BASE_LDOPT="-Wl,--image-base,0 -Wl,-Ttext"],
[TARGET_IMG_BASE_LDOPT="-Wl,-Ttext"],
[],
[AC_LANG_SOURCE([
asm (".globl start; start:");
asm (".globl _start; _start:");
asm (".globl __start; __start:");
void __main (void);
void __main (void) {}
int main (void);
])])
TARGET_IMG_BASE_LDOPT_ARG_SEP=","
else
TARGET_IMG_BASE_LDOPT="-Wl,--defsym=_grub_text_base"
TARGET_IMG_BASE_LDOPT_ARG_SEP="="
TARGET_IMG_LDSCRIPT='$(top_srcdir)'"/conf/i386-pc-kernel.lds"
TARGET_IMG_LDFLAGS="${TARGET_IMG_LDFLAGS} -Wl,-T${TARGET_IMG_LDSCRIPT}"
TARGET_IMG_LDFLAGS_AC="-Wl,-T${srcdir}/conf/i386-pc-kernel.lds"
fi
TARGET_IMG_CFLAGS= TARGET_IMG_CFLAGS=
fi fi
@@ -1262,22 +1567,6 @@ AC_SUBST(TARGET_LDFLAGS_OLDMAGIC)
LDFLAGS="$TARGET_LDFLAGS" LDFLAGS="$TARGET_LDFLAGS"
if test "$target_cpu" = x86_64 || test "$target_cpu" = sparc64 || test "$target_cpu" = riscv64 \
|| test "$target_cpu" = loongarch64 ; then
# Use large model to support 4G memory
AC_CACHE_CHECK([whether option -mcmodel=large works], grub_cv_cc_mcmodel, [
CFLAGS="$TARGET_CFLAGS -mcmodel=large"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[]])],
[grub_cv_cc_mcmodel=yes],
[grub_cv_cc_mcmodel=no])
])
if test "x$grub_cv_cc_mcmodel" = xyes; then
TARGET_CFLAGS="$TARGET_CFLAGS -mcmodel=large"
elif test "$target_cpu" = sparc64 || test "$target_cpu" = riscv64; then
TARGET_CFLAGS="$TARGET_CFLAGS -mcmodel=medany"
fi
fi
if test "$target_cpu"-"$platform" = x86_64-efi; then if test "$target_cpu"-"$platform" = x86_64-efi; then
# EFI writes to stack below %rsp, we must not use the red zone # EFI writes to stack below %rsp, we must not use the red zone
AC_CACHE_CHECK([whether option -mno-red-zone works], grub_cv_cc_no_red_zone, [ AC_CACHE_CHECK([whether option -mno-red-zone works], grub_cv_cc_no_red_zone, [
@@ -1386,6 +1675,21 @@ fi]
CFLAGS="$TARGET_CFLAGS" CFLAGS="$TARGET_CFLAGS"
if test "$target_cpu" = x86_64 || test "$target_cpu" = sparc64 || test "$target_cpu" = riscv64 ; then
# Use large model to support 4G memory
AC_CACHE_CHECK([whether option -mcmodel=large works], grub_cv_cc_mcmodel, [
CFLAGS="$TARGET_CFLAGS -mcmodel=large"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[]])],
[grub_cv_cc_mcmodel=yes],
[grub_cv_cc_mcmodel=no])
])
if test "x$grub_cv_cc_mcmodel" = xyes; then
TARGET_CFLAGS="$TARGET_CFLAGS -mcmodel=large"
elif test "$target_cpu" = sparc64 || test "$target_cpu" = riscv64; then
TARGET_CFLAGS="$TARGET_CFLAGS -mcmodel=medany"
fi
fi
# Stack smashing protector. # Stack smashing protector.
grub_CHECK_STACK_PROTECTOR grub_CHECK_STACK_PROTECTOR
AC_ARG_ENABLE([stack-protector], AC_ARG_ENABLE([stack-protector],
@@ -1426,6 +1730,28 @@ else
AC_MSG_ERROR([invalid value $enable_stack_protector for --enable-stack-protector]) AC_MSG_ERROR([invalid value $enable_stack_protector for --enable-stack-protector])
fi fi
TARGET_CPPFLAGS="$TARGET_CPPFLAGS -DGRUB_STACK_PROTECTOR=1" TARGET_CPPFLAGS="$TARGET_CPPFLAGS -DGRUB_STACK_PROTECTOR=1"
if test -n "$SOURCE_DATE_EPOCH"; then
GRUB_STACK_PROTECTOR_INIT="0x00f2b7e2$(printf "%x" "$SOURCE_DATE_EPOCH" | sed 's/.*\(........\)$/\1/')"
elif test -r /dev/urandom; then
# Generate the 8 byte stack protector canary at build time if /dev/urandom
# is able to be read. The first byte should be NUL to filter out string
# buffer overflow attacks.
GRUB_STACK_PROTECTOR_INIT="$($PYTHON -c 'import codecs; rf=open("/dev/urandom", "rb"); print("0x00"+codecs.encode(rf.read(7), "hex").decode("ascii"))')"
else
# Some hosts may not have a urandom, e.g. Windows, so use statically
# generated random bytes
GRUB_STACK_PROTECTOR_INIT="0x00f2b7e2f193b25c"
fi
if test x"$target_m32" = x1 ; then
# Make sure that the canary default value is 24-bits by only using the
# lower 3 bytes on 32 bit systems. This allows the upper byte to be NUL
# to filter out string buffer overflow attacks.
GRUB_STACK_PROTECTOR_INIT="0x00$(echo "$GRUB_STACK_PROTECTOR_INIT" | sed 's/.*\(......\)$/\1/')"
fi
AC_SUBST([GRUB_STACK_PROTECTOR_INIT])
fi fi
CFLAGS="$TARGET_CFLAGS" CFLAGS="$TARGET_CFLAGS"
@@ -1498,7 +1824,18 @@ if test "x$target_cpu" = xi386; then
if test "$platform" != emu && test "x$TARGET_APPLE_LINKER" != x1 ; then if test "$platform" != emu && test "x$TARGET_APPLE_LINKER" != x1 ; then
if test ! -z "$TARGET_IMG_LDSCRIPT"; then if test ! -z "$TARGET_IMG_LDSCRIPT"; then
# Check symbols provided by linker script. # Check symbols provided by linker script.
CFLAGS="$TARGET_CFLAGS -nostdlib ${TARGET_IMG_LDFLAGS_AC} ${TARGET_IMG_BASE_LDOPT},0x8000" target_img_base_ld="${TARGET_IMG_BASE_LDOPT}"
case "$target_img_base_ld" in
*_grub_text_base)
target_img_base_ld="${target_img_base_ld}="
;;
*)
target_img_base_ld="${target_img_base_ld},"
;;
esac
target_img_base_ld="${target_img_base_ld}0x8000"
CFLAGS="$TARGET_CFLAGS -nostdlib ${TARGET_IMG_LDFLAGS_AC} ${target_img_base_ld}"
target_img_base_ld=""
fi fi
grub_CHECK_BSS_START_SYMBOL grub_CHECK_BSS_START_SYMBOL
grub_CHECK_END_SYMBOL grub_CHECK_END_SYMBOL
@@ -1609,7 +1946,7 @@ if test "$platform" = emu; then
AC_SUBST(HAVE_SDL2)], AC_SUBST(HAVE_SDL2)],
[grub_emu_sdl2_excuse="libSDL2 libraries are required to build \`grub-emu' with SDL2 support"]) [grub_emu_sdl2_excuse="libSDL2 libraries are required to build \`grub-emu' with SDL2 support"])
[fi] [fi]
if test x"enable_grub_emu_sdl2" = xyes && test x"$grub_emu_sdl2_excuse" != x ; then if test x"$enable_grub_emu_sdl2" = xyes && test x"$grub_emu_sdl2_excuse" != x ; then
AC_MSG_ERROR([SDL2 support for grub-emu was explicitly requested but can't be compiled ($grub_emu_sdl2_excuse)]) AC_MSG_ERROR([SDL2 support for grub-emu was explicitly requested but can't be compiled ($grub_emu_sdl2_excuse)])
fi fi
if test x"$grub_emu_sdl2_excuse" = x ; then if test x"$grub_emu_sdl2_excuse" = x ; then
@@ -1704,6 +2041,9 @@ if test x"$grub_mkfont_excuse" = x ; then
CPPFLAGS="$SAVED_CPPFLAGS" CPPFLAGS="$SAVED_CPPFLAGS"
LIBS="$SAVED_LIBS" LIBS="$SAVED_LIBS"
], [grub_mkfont_excuse=["need freetype2 library"]]) ], [grub_mkfont_excuse=["need freetype2 library"]])
if test x"$grub_mkfont_excuse" = x && test x"$host_kernel" = xnetbsd ; then
FREETYPE_LIBS="$FREETYPE_LIBS -Wl,-R,/usr/pkg/lib" ;
fi
fi fi
if test x"$enable_grub_mkfont" = xyes && test x"$grub_mkfont_excuse" != x ; then if test x"$enable_grub_mkfont" = xyes && test x"$grub_mkfont_excuse" != x ; then
@@ -1758,6 +2098,11 @@ if test x"$grub_build_mkfont_excuse" = x ; then
LIBS="$SAVED_LIBS" LIBS="$SAVED_LIBS"
CPPFLAGS="$SAVED_CPPFLAGS_2" CPPFLAGS="$SAVED_CPPFLAGS_2"
], [grub_build_mkfont_excuse=["need freetype2 library"]]) ], [grub_build_mkfont_excuse=["need freetype2 library"]])
if test x"$grub_build_mkfont_excuse" = x ; then
case x"$build_os" in
xnetbsd*) BUILD_FREETYPE_LIBS="$BUILD_FREETYPE_LIBS -Wl,-R,/usr/pkg/lib" ;;
esac
fi
PKG_CONFIG="$SAVED_PKG_CONFIG" PKG_CONFIG="$SAVED_PKG_CONFIG"
fi fi
@@ -1784,8 +2129,6 @@ CPPFLAGS="$SAVED_CPPFLAGS"
LDFLAGS="$SAVED_LDFLAGS" LDFLAGS="$SAVED_LDFLAGS"
DJVU_FONT_SOURCE=
starfield_excuse= starfield_excuse=
AC_ARG_ENABLE([grub-themes], AC_ARG_ENABLE([grub-themes],
@@ -1799,19 +2142,28 @@ if test x"$starfield_excuse" = x && test x"$enable_build_grub_mkfont" = xno ; th
starfield_excuse="No build-time grub-mkfont" starfield_excuse="No build-time grub-mkfont"
fi fi
if test x"$starfield_excuse" = x; then AC_ARG_WITH([dejavufont],
for ext in pcf pcf.gz bdf bdf.gz ttf ttf.gz; do AS_HELP_STRING([--with-dejavufont=FILE],
for dir in . /usr/src /usr/share/fonts/X11/misc /usr/share/fonts/truetype/ttf-dejavu /usr/share/fonts/dejavu /usr/share/fonts/truetype; do [set the DejeVu source [[guessed]]]))
if test -f "$dir/DejaVuSans.$ext"; then
DJVU_FONT_SOURCE="$dir/DejaVuSans.$ext"
break 2
fi
done
done
if test "x$DJVU_FONT_SOURCE" = x; then if test "x$with_dejavufont" = x; then
starfield_excuse="No DejaVu found" # search in well-known directories
fi if test x"$starfield_excuse" = x; then
for ext in pcf pcf.gz bdf bdf.gz ttf ttf.gz; do
for dir in . /usr/src /usr/share/fonts/X11/misc /usr/share/fonts/truetype/ttf-dejavu /usr/share/fonts/dejavu /usr/share/fonts/truetype /usr/pkg/share/fonts/X11/TTF /usr/local/share/fonts/dejavu /usr/X11R6/lib/X11/fonts/TTF /usr/share/fonts/dejavu-sans-fonts /usr/share/fonts/truetype/dejavu; do
if test -f "$dir/DejaVuSans.$ext"; then
DJVU_FONT_SOURCE="$dir/DejaVuSans.$ext"
break 2
fi
done
done
if test "x$DJVU_FONT_SOURCE" = x; then
starfield_excuse="No DejaVu found"
fi
fi
else
DJVU_FONT_SOURCE="$with_dejavufont"
fi fi
if test x"$enable_grub_themes" = xyes && test x"$starfield_excuse" != x; then if test x"$enable_grub_themes" = xyes && test x"$starfield_excuse" != x; then
@@ -1820,21 +2172,28 @@ fi
AC_SUBST([DJVU_FONT_SOURCE]) AC_SUBST([DJVU_FONT_SOURCE])
FONT_SOURCE= AC_ARG_WITH([unifont],
AS_HELP_STRING([--with-unifont=FILE],
[set the unifont source [[guessed]]]))
for ext in pcf pcf.gz bdf bdf.gz ttf ttf.gz; do if test "x$with_unifont" = x; then
for dir in . /usr/src /usr/share/fonts/X11/misc /usr/share/fonts/unifont /usr/share/fonts/uni /usr/share/fonts/truetype/unifont /usr/share/fonts/misc; do # search in well-known directories
if test -f "$dir/unifont.$ext"; then for ext in pcf pcf.gz bdf bdf.gz ttf ttf.gz otf otf.gz; do
md5="$(md5sum "$dir/unifont.$ext"|awk '{ print $1; }')" for dir in . /usr/src /usr/share/fonts/X11/misc /usr/share/fonts/unifont /usr/share/fonts/uni /usr/share/fonts/truetype/unifont /usr/share/fonts/misc /usr/pkg/share/fonts/X11/misc /usr/local/share/fonts/gnu-unifont /usr/local/share/fonts/unifont; do
# PCF and BDF from version 6.3 isn't hanled properly by libfreetype. if test -f "$dir/unifont.$ext"; then
if test "$md5" = 0a54834d2788c83886a3e1785a6a1e61 || test "$md5" = 28f2565c7a41d8d407e2551159385edb || test "$md5" = dae5e588461b3b92b87b6ffee734f936 || test "$md5" = 4a3d687aa5bb329ed05f4263a1016791 ; then md5="$(md5sum "$dir/unifont.$ext"|awk '{ print $1; }')"
continue # PCF and BDF from version 6.3 isn't hanled properly by libfreetype.
if test "$md5" = 0a54834d2788c83886a3e1785a6a1e61 || test "$md5" = 28f2565c7a41d8d407e2551159385edb || test "$md5" = dae5e588461b3b92b87b6ffee734f936 || test "$md5" = 4a3d687aa5bb329ed05f4263a1016791 ; then
continue
fi
FONT_SOURCE="$dir/unifont.$ext"
break 2
fi fi
FONT_SOURCE="$dir/unifont.$ext" done
break 2
fi
done done
done else
FONT_SOURCE="$with_unifont"
fi
if test x"$enable_build_grub_mkfont" = xno ; then if test x"$enable_build_grub_mkfont" = xno ; then
FONT_SOURCE= FONT_SOURCE=
@@ -1971,8 +2330,19 @@ fi
if test x"$libzfs_excuse" = x ; then if test x"$libzfs_excuse" = x ; then
AC_CHECK_LIB([nvpair], [nvlist_lookup_string], AC_CHECK_LIB([nvpair], [nvlist_lookup_string],
[], [have_normal_nvpair=yes],
[libzfs_excuse="need nvpair library"]) [have_normal_nvpair=no])
if test x"$have_normal_nvpair" = xno ; then
AC_CHECK_LIB([nvpair], [opensolaris_nvlist_lookup_string],
[have_prefixed_nvpair=yes],
[have_prefixed_nvpair=no])
if test x"$have_prefixed_nvpair" = xyes ; then
AC_DEFINE([GRUB_UTIL_NVPAIR_IS_PREFIXED], [1],
[Define to 1 if libnvpair symbols are prefixed with opensolaris_.])
else
libzfs_excuse="need nvpair library"
fi
fi
fi fi
if test x"$enable_libzfs" = xyes && test x"$libzfs_excuse" != x ; then if test x"$enable_libzfs" = xyes && test x"$libzfs_excuse" != x ; then
@@ -1982,16 +2352,37 @@ fi
if test x"$libzfs_excuse" = x ; then if test x"$libzfs_excuse" = x ; then
# We need both libzfs and libnvpair for a successful build. # We need both libzfs and libnvpair for a successful build.
LIBZFS="-lzfs" LIBZFS="-lzfs"
AC_DEFINE([HAVE_LIBZFS], [1],
[Define to 1 if you have the ZFS library.])
LIBNVPAIR="-lnvpair" LIBNVPAIR="-lnvpair"
AC_DEFINE([HAVE_LIBNVPAIR], [1], AC_DEFINE([USE_LIBZFS], [1],
[Define to 1 if you have the NVPAIR library.]) [Define to 1 if ZFS library should be used.])
fi fi
AC_SUBST([LIBZFS]) AC_SUBST([LIBZFS])
AC_SUBST([LIBNVPAIR]) AC_SUBST([LIBNVPAIR])
AC_ARG_ENABLE([grub-protect],
[AS_HELP_STRING([--enable-grub-protect],
[build and install the `grub-protect' utility (default=guessed)])])
if test x"$enable_grub_protect" = xno ; then
grub_protect_excuse="explicitly disabled"
fi
LIBTASN1=
if test x"$grub_protect_excuse" = x ; then
AC_CHECK_LIB([tasn1], [asn1_write_value], [LIBTASN1="-ltasn1"], [grub_protect_excuse="need libtasn1 library"])
fi
AC_SUBST([LIBTASN1])
if test x"$enable_grub_protect" = xyes && test x"$grub_protect_excuse" != x ; then
AC_MSG_ERROR([grub-protect was explicitly requested but can't be compiled ($grub_protect_excuse)])
fi
if test x"$grub_protect_excuse" = x ; then
enable_grub_protect=yes
else
enable_grub_protect=no
fi
AC_SUBST([enable_grub_protect])
LIBS="" LIBS=""
AC_SUBST([FONT_SOURCE]) AC_SUBST([FONT_SOURCE])
@@ -2046,6 +2437,7 @@ AC_SUBST(TARGET_CCASFLAGS)
AC_SUBST(TARGET_IMG_LDFLAGS) AC_SUBST(TARGET_IMG_LDFLAGS)
AC_SUBST(TARGET_IMG_CFLAGS) AC_SUBST(TARGET_IMG_CFLAGS)
AC_SUBST(TARGET_IMG_BASE_LDOPT) AC_SUBST(TARGET_IMG_BASE_LDOPT)
AC_SUBST(TARGET_IMG_BASE_LDOPT_ARG_SEP)
AC_SUBST(TARGET_APPLE_LINKER) AC_SUBST(TARGET_APPLE_LINKER)
AC_SUBST(HOST_CFLAGS) AC_SUBST(HOST_CFLAGS)
@@ -2108,6 +2500,7 @@ AM_CONDITIONAL([COND_GRUB_EMU_SDL], [test x$enable_grub_emu_sdl = xyes])
AM_CONDITIONAL([COND_GRUB_EMU_PCI], [test x$enable_grub_emu_pci = xyes]) AM_CONDITIONAL([COND_GRUB_EMU_PCI], [test x$enable_grub_emu_pci = xyes])
AM_CONDITIONAL([COND_GRUB_MKFONT], [test x$enable_grub_mkfont = xyes]) AM_CONDITIONAL([COND_GRUB_MKFONT], [test x$enable_grub_mkfont = xyes])
AM_CONDITIONAL([COND_GRUB_MOUNT], [test x$enable_grub_mount = xyes]) AM_CONDITIONAL([COND_GRUB_MOUNT], [test x$enable_grub_mount = xyes])
AM_CONDITIONAL([COND_GRUB_PROTECT], [test x$enable_grub_protect = xyes])
AM_CONDITIONAL([COND_HAVE_FONT_SOURCE], [test x$FONT_SOURCE != x]) AM_CONDITIONAL([COND_HAVE_FONT_SOURCE], [test x$FONT_SOURCE != x])
if test x$FONT_SOURCE != x ; then if test x$FONT_SOURCE != x ; then
HAVE_FONT_SOURCE=1 HAVE_FONT_SOURCE=1
@@ -2235,6 +2628,11 @@ echo grub-mount: Yes
else else
echo grub-mount: No "($grub_mount_excuse)" echo grub-mount: No "($grub_mount_excuse)"
fi fi
if [ x"$grub_protect_excuse" = x ]; then
echo grub-protect: Yes
else
echo grub-protect: No "($grub_protect_excuse)"
fi
if [ x"$starfield_excuse" = x ]; then if [ x"$starfield_excuse" = x ]; then
echo starfield theme: Yes echo starfield theme: Yes
echo With DejaVuSans font from $DJVU_FONT_SOURCE echo With DejaVuSans font from $DJVU_FONT_SOURCE
+189 -60
View File
@@ -77,7 +77,7 @@ This edition documents version @value{VERSION}.
* Coding style:: * Coding style::
* Finding your way around:: * Finding your way around::
* Contributing Changes:: * Contributing Changes::
* Setting up and running test suite:: * Tests::
* Updating External Code:: * Updating External Code::
* Debugging:: * Debugging::
* Porting:: * Porting::
@@ -485,8 +485,17 @@ If your intention is to just get started, please do not submit a inclusion
request. Instead, please subscribe to the mailing list, and communicate first request. Instead, please subscribe to the mailing list, and communicate first
(e.g. sending a patch, asking a question, commenting on another message...). (e.g. sending a patch, asking a question, commenting on another message...).
@node Tests
@chapter Tests
@menu
* Setting up and running test suite::
* Writing new tests::
@end menu
@node Setting up and running test suite @node Setting up and running test suite
@chapter Setting up and running test suite @section Setting up and running test suite
GRUB is basically a tiny operating system with read support for many file GRUB is basically a tiny operating system with read support for many file
systems and which has been ported to a variety of architectures. As such, its systems and which has been ported to a variety of architectures. As such, its
@@ -495,6 +504,47 @@ These dependencies are currently documented in the
@uref{https://git.savannah.gnu.org/cgit/grub.git/tree/INSTALL, INSTALL} @uref{https://git.savannah.gnu.org/cgit/grub.git/tree/INSTALL, INSTALL}
file in the source repository. Once installed, the test suite can be started file in the source repository. Once installed, the test suite can be started
by running the @command{make check} command from the GRUB build directory. by running the @command{make check} command from the GRUB build directory.
To properly run all the tests, the test suite must be run as the privileged
user, for instance to run the filesystem tests, which require mounting
filesystem images. Of course, virtualization or containers may be used, but
this requires extra configuration outside the scope of this document.
@node Writing new tests
@section Writing new tests
There are two kinds of tests in the GRUB test suite: native and non-native.
Native tests are those which run on the build architecture and non-native
run on the target architecture. The non-native tests are run in a QEMU
virtual machine using the grub-shell script in tests/util. When writing a
new test, first determine if it should run on the host or the target and
then look at the existing tests as examples of how to they should be written.
The GRUB test suite uses automake (@uref{https://www.gnu.org/software/automake/manual/automake.html#Tests, see documention here}). One thing of importance
to note is that tests have 4 classes of return codes: SKIP (77), HARD ERROR
(99), PASS (0), and FAIL (all other codes). A
@uref{https://www.gnu.org/software/automake/manual/automake.html#index-test-skip, SKIP return code}
should be returned when this test cannot be performed and thus should be
skipped. Typically this is because the target does not support the test,
such as the ohci USB test for the powerpc-ieee1275 target because there
are no native drivers for that target. A
@uref{https://www.gnu.org/software/automake/manual/automake.html#index-Distinction-between-errors-and-failures-in-testsuites, HARD ERROR return code}
should be returned when a failure in something other than what is intended
to be tested happens. This is commonly returned when the test cannot be
properly run because of deficiencies in the test environment, eg. when
testing the xfs filesystem, but the kernel has no support for mounting xfs
volumes. A SKIP should never be returned for a HARD ERROR condition
because at best the person running the test does not know if the test was
skipped because it doesn't apply to the target or because the tester failed
to setup the environment properly. At worst, the tester will believe that
everything is okay without realizing that the tests are not covering all
the code that it should.
Keep portability in mind while creating a new tests so that the tests can be
run on a variety of systems and shells. Do not use bashisms. Also try to avoid
using utilities that would unecessarily add software dependencies. Sometimes
this is unavoidable. Copy or adapt existing test implementations where feasible.
If the test is native and requires root, make sure to check that the test is
run with the root user and return HARD ERROR if it is not.
@node Updating External Code @node Updating External Code
@chapter Updating external code @chapter Updating external code
@@ -506,6 +556,8 @@ to update it.
* Gnulib:: * Gnulib::
* jsmn:: * jsmn::
* minilzo:: * minilzo::
* libtasn1::
* libgcrypt::
@end menu @end menu
@node Gnulib @node Gnulib
@@ -596,6 +648,77 @@ cp minilzo-2.10/*.[hc] grub-core/lib/minilzo
rm -r minilzo-2.10* rm -r minilzo-2.10*
@end example @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 xvzf libtasn1-4.19.0.tar.gz
rm -rf grub-core/lib/libtasn1
mkdir -p grub-core/lib/libtasn1/lib
mkdir -p grub-core/lib/libtasn1/tests
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 grub-core/lib/libtasn1
cp libtasn1-4.19.0/tests/@{CVE-2018-1000654-1_asn1_tab.h,CVE-2018-1000654-2_asn1_tab.h,CVE-2018-1000654.c,object-id-decoding.c,object-id-encoding.c,octet-string.c,reproducers.c,Test_overflow.c,Test_simple.c,Test_strings.c@} grub-core/lib/libtasn1/tests
rm -rf libtasn1-4.19.0*
@end example
After upgrading the library, it may be necessary to apply the patches in
@file{grub-core/lib/libtasn1-patches/} to adjust the code to be compatible with
GRUB. These patches were needed to use the current version of libtasn1. The
existing patches may not apply cleanly, apply at all, or even be needed for a
newer version of the library, and other patches may be needed due to changes in
the newer version. If existing patches need to be refreshed to apply cleanly,
please include updated patches as part of the a patch set sent to the list.
If new patches are needed or existing patches are not needed, also please send
additions or removals as part of any patch set upgrading libtasn1.
@node libgcrypt
@section libgcrypt
libgcrypt is a GNU implementation of crypto library. To import a new version
you need to unpack the release tarball into grub-core/lib/libgcrypt. Delete
following files/directories:
* acinclude.m4
* aclocal.m4
* autogen.rc
* autogen.sh
* build-aux
* ChangeLog
* ChangeLog-2011
* doc
* INSTALL
* m4
* Makefile.am
* Makefile.in
* NEWS
* random
* tests
* TODO
* */Makefile.in
* mpi/hppa1.1
Regenerate the file gost-sb.h:
grub-core/lib/libgcrypt/cipher$ gcc -o gost-s-box gost-s-box.c
grub-core/lib/libgcrypt/cipher$ ./gost-s-box gost-sb.h
Then rerun ./bootstrap and pay attention to the errors. Especially to warnings
that a file isn't a module as it means that some file is actually unused by
GRUB. If any, find where it declares its cipher or hash and add a pattern to
import_gcry.py. See commit ``libgcrypt: Import blake family of hashes'' for an
example. If file reallly is useless to GRUB in its current state, add it to
whitelist in import_gcry.py.
Compile and fix any new errors. Put patches into grub-core/lib/libgcrypt-patches
@node Debugging @node Debugging
@chapter Debugging @chapter Debugging
@@ -660,10 +783,11 @@ GDB is started from the @file{grub-core} directory in the GRUB2 build
directory. GRUB2 developers have made this more simple by including a GDB directory. GRUB2 developers have made this more simple by including a GDB
script which does much of the setup. This file is at @file{grub-core/gdb_grub} script which does much of the setup. This file is at @file{grub-core/gdb_grub}
in the build directory and is also installed via @command{make install}. in the build directory and is also installed via @command{make install}.
If not building GRUB, the distribution may have a package which installs When using a pre-built GRUB, the distribution may have a package which installs
this GDB script along with debug symbol binaries, such as Debian's this GDB script along with debug symbol binaries, such as Debian's
@samp{grub-pc-dbg} package. The GDB script is intended to be used @samp{grub-pc-dbg} package. The GDB script is intended to be used
like so, assuming: like so, assuming that @samp{/path/to/script} is the path to the directory
containing the gdb_grub script and debug symbol files:
@example @example
cd $(dirname /path/to/script/gdb_grub) cd $(dirname /path/to/script/gdb_grub)
@@ -787,6 +911,11 @@ out of its way to avoid using hardware breakpoints internally and uses them as
briefly as possible when needed, thus allowing the user to have a maximal briefly as possible when needed, thus allowing the user to have a maximal
number at their disposal. number at their disposal.
@menu
* OVMF debug log::
* Using the gdbinfo command::
@end menu
@node OVMF debug log @node OVMF debug log
@subsection OVMF debug log @subsection OVMF debug log
@@ -821,26 +950,26 @@ is to be run in a GDB session running with the @file{gdb_grub} GDB script.
@node Porting @node Porting
@chapter Porting @chapter Porting
GRUB2 is designed to be easily portable accross platforms. But because of the GRUB2 is designed to be easily portable across platforms. But because of the
nature of bootloader every new port must be done separately. Here is how I did nature of bootloader every new port must be done separately. Here is how I did
MIPS (loongson and ARC) and Xen ports. Note than this is more of suggestions, MIPS (loongson and ARC) and Xen ports. Note that this is more of a suggestion,
not absolute truth. and not absolute truth.
First of all grab any architecture specifications you can find in public First of all, grab any architecture specifications you can find in the public
(please avoid NDA). domain (please avoid NDA).
First stage is ``Hello world''. I've done it outside of GRUB for simplicity. First stage is ``Hello world''. I've done it outside of GRUB for simplicity.
Your task is to have a small program which is loadable as bootloader and Your task is to have a small program which is loadable as bootloader and
clearly shows its presence to you. If you have easily accessible console clearly shows its presence to you. If you have an easily accessible console
you can just print a message. If you have a mapped framebuffer you know address you can just print a message. If you have a mapped framebuffer you know the address
of, you can draw a square. If you have a debug facility, just hanging without of, you can draw a square. If you have a debug facility, just hanging without
crashing might be enough. For the first stage you can choose to load the crashing might be enough. For the first stage, you can choose to load the
bootloader across the network since format for network image is often easier bootloader across the network since the format for a network image is often easier
than for local boot and it skips the need of small intermediary stages and than for local boot and it skips the need of small intermediary stages and
nvram handling. Additionally you can often have a good idea of the needed nvram handling. Additionally, you can often have a good idea of the needed
format by running ``file'' on any netbootable executable for given platform. format by running ``file'' on any netbootable executable for the given platform.
This program should probably have 2 parts: an assembler and C one. Assembler one This program should probably have 2 parts: an assembler and C one. The assembler one
handles BSS cleaning and other needed setup (on some platforms you may need handles BSS cleaning and other needed setup (on some platforms you may need
to switch modes or copy the executable to its definitive position). So your code to switch modes or copy the executable to its definitive position). So your code
may look like (x86 assembly for illustration purposes) may look like (x86 assembly for illustration purposes)
@@ -882,12 +1011,12 @@ Sometimes you need a third file: assembly stubs for ABI-compatibility.
Once this file is functional it's time to move it into GRUB2. The startup Once this file is functional it's time to move it into GRUB2. The startup
assembly file goes to grub-core/kern/$cpu/$platform/startup.S. You should also assembly file goes to grub-core/kern/$cpu/$platform/startup.S. You should also
include grub/symbol.h and replace call to entry point with call to include grub/symbol.h and replace the call to entry point with call to
EXT_C(grub_main). The C file goes to grub-core/kern/$cpu/$platform/init.c EXT_C(grub_main). The C file goes to grub-core/kern/$cpu/$platform/init.c
and its entry point is renamed to void grub_machine_init (void). Keep final and its entry point is renamed to void grub_machine_init (void). Keep final
infinite loop for now. Stubs file if any goes to infinite loop for now. Stub files if any goes to
grub-core/kern/$cpu/$platform/callwrap.S. Sometimes either $cpu or $platform grub-core/kern/$cpu/$platform/callwrap.S. Sometimes either $cpu or $platform
is dropped if file is used on several cpus respectivelyplatforms. is dropped if file is used on several cpus respectively or platforms.
Check those locations if they already have what you're looking for. Check those locations if they already have what you're looking for.
Then modify in configure.ac the following parts: Then modify in configure.ac the following parts:
@@ -905,10 +1034,10 @@ esac
@end example @end example
Sometimes CPU have additional architecture names which don't influence booting. Sometimes CPU have additional architecture names which don't influence booting.
You might want to have some canonical name to avoid having bunch of identical You might want to have some canonical name to avoid having a bunch of identical
platforms with different names. platforms with different names.
NOTE: it doesn't influence compile optimisations which depend solely on NOTE: It doesn't influence compile optimisations which depend solely on
chosen compiler and compile options. chosen compiler and compile options.
@example @example
@@ -970,7 +1099,7 @@ AM_CONDITIONAL([COND_powerpc_ieee1275], [test x$target_cpu = xpowerpc -a x$platf
@end example @end example
Next stop is gentpl.py. You need to add your platform to the list of supported Next stop is gentpl.py. You need to add your platform to the list of supported
ones (sorry that this list is duplicated): ones (unfortunately, this list is duplicated):
@example @example
GRUB_PLATFORMS = [ "emu", "i386_pc", "i386_efi", "i386_qemu", "i386_coreboot", GRUB_PLATFORMS = [ "emu", "i386_pc", "i386_efi", "i386_qemu", "i386_coreboot",
@@ -980,21 +1109,21 @@ GRUB_PLATFORMS = [ "emu", "i386_pc", "i386_efi", "i386_qemu", "i386_coreboot",
"mips_qemu_mips", "s390_mainframe" ] "mips_qemu_mips", "s390_mainframe" ]
@end example @end example
You may also want already to add new platform to one or several of available Now you may also want to add a new platform to one or several of available
groups. In particular we always have a group for each CPU even when only groups. In particular we always have a group for each CPU even when only
one platform for given CPU is available. one platform for given CPU is available.
Then comes grub-core/Makefile.core.def. In the block ``kernel'' you'll need Then comes grub-core/Makefile.core.def. In the block ``kernel'' you'll need
to define ldflags for your platform ($cpu_$platform_ldflags). You also need to to define ldflags for your platform ($cpu_$platform_ldflags). You also need to
declare startup asm file ($cpu_$platform_startup) as well as any other files declare a startup asm file ($cpu_$platform_startup) as well as any other files,
(e.g. init.c and callwrap.S) (e.g. $cpu_$platform = kern/$cpu/$platform/init.c). like init.c or callwrap.S (e.g. $cpu_$platform = kern/$cpu/$platform/init.c).
At this stage you will also need to add dummy dl.c and cache.S with functions At this stage, you will also need to add a dummy dl.c and cache.S with functions
grub_err_t grub_arch_dl_check_header (void *ehdr), grub_err_t grub_err_t grub_arch_dl_check_header (void *ehdr), grub_err_t
grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr) (dl.c) and grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr) (dl.c) and
void grub_arch_sync_caches (void *address, grub_size_t len) (cache.S). They void grub_arch_sync_caches (void *address, grub_size_t len) (cache.S). They
won't be used for now. won't be used for now.
You will need to create directory include/$cpu/$platform and a file You will need to create a directory include/$cpu/$platform and a file
include/$cpu/types.h. The latter following this template: include/$cpu/types.h. The latter following this template:
@example @example
@@ -1018,7 +1147,7 @@ include/$cpu/types.h. The latter following this template:
You will also need to add a dummy file to datetime and setjmp modules to You will also need to add a dummy file to datetime and setjmp modules to
avoid any of it having no files. It can be just completely empty at this stage. avoid any of it having no files. It can be just completely empty at this stage.
You'll need to make grub-mkimage.c (util/grub_mkimage.c) aware of the needed You'll need to make grub-mkimage (in util/grub_mkimage.c) aware of the needed
format. For most commonly used formats like ELF, PE, aout or raw the support format. For most commonly used formats like ELF, PE, aout or raw the support
is already present and you'll need to make it follow the existant code paths is already present and you'll need to make it follow the existant code paths
for your platform adding adjustments if necessary. When done compile: for your platform adding adjustments if necessary. When done compile:
@@ -1029,47 +1158,47 @@ for your platform adding adjustments if necessary. When done compile:
make > /dev/null make > /dev/null
@end example @end example
And create image And create an image:
@example @example
./grub-mkimage -d grub-core -O $format_id -o test.img ./grub-mkimage -d grub-core -O $format_id -o test.img
@end example @end example
And it's time to test your test.img. And now it's time to test your test.img.
If it works next stage is to have heap, console and timer. If it works, the next stage is to have a heap, console and timer.
To have the heap working you need to determine which regions are suitable for To have the heap working you need to determine which regions are suitable for
heap usage, allocate them from firmware and map (if applicable). Then call heap usage, allocate them from the firmware and map them, if applicable.
grub_mm_init_region (void *start, grub_size_t s) for every of this region. Then call grub_mm_init_region (void *start, grub_size_t s) for each region.
As a shortcut for early port you can allocate right after _end or have As a shortcut for an early port, you can allocate right after _end or have
a big static array for heap. If you do you'll probably need to come back to a big static array for heap. If you do, you'll probably need to come back to
this later. As for output console you should distinguish between an array of this later. As for output console you should distinguish between an array of
text, terminfo or graphics-based console. Many of real-world examples don't text, terminfo or graphics-based console. Many real-world examples don't
fit perfectly into any of these categories but one of the models is easier fit perfectly into any of these categories but one of the models is easier
to be used as base. In second and third case you should add your platform to to be used as base. In the second and third case, you should add your platform to
terminfokernel respectively videoinkernel group. A good example of array of terminfokernel respectively videoinkernel group. A good example of array of
text is i386-pc (kern/i386/pc/init.c and term/i386/pc/console.c). text is i386-pc (kern/i386/pc/init.c and term/i386/pc/console.c),
Of terminfo is ieee1275 (kern/ieee1275/init.c and term/ieee1275/console.c). of terminfo is ieee1275 (kern/ieee1275/init.c and term/ieee1275/console.c),
Of video is loongson (kern/mips/loongson/init.c). Note that terminfo has and of video is loongson (kern/mips/loongson/init.c). Note that terminfo has
to be inited in 2 stages: one before (to get at least rudimentary console to be inited in 2 stages: one before (to get at least rudimentary console
as early as possible) and another after the heap (to get full-featured console). as early as possible) and another after the heap (to get full-featured console).
For the input there are string of keys, terminfo and direct hardware. For string For the input, there is a string of keys (eg. i386-pc, same files), terminfo
of keys look at i386-pc (same files), for terminfo ieee1275 (same files) and for (ieee1275, same files), and hardware (loongson, see kern/mips/loongson/init.c
hardware loongson (kern/mips/loongson/init.c and term/at_keyboard.c). and term/at_keyboard.c).
For the timer you'll need to call grub_install_get_time_ms (...) with as sole For the timer, you'll need to call grub_install_get_time_ms (...) with the
argument a function returning a grub_uint64_t of a number of milliseconds sole argument a function returning a grub_uint64_t number of milliseconds
elapsed since arbitrary point in the past. elapsed since arbitrary point in the past.
Once these steps accomplished you can remove the inifinite loop and you should Once these steps are accomplished, you can remove the inifinite loop and you should
be able to get to the minimal console. Next step is to have module loading be able to get to the minimal console. Next step is to have module loading
working. For this you'll need to fill kern/$cpu/dl.c and kern/$cpu/cache.S working. For this, you'll need to fill kern/$cpu/dl.c and kern/$cpu/cache.S
with real handling of relocations and respectively the real sync of I and D with real handling of relocations and respectively the real sync of I and D
caches. Also you'll need to decide where in the image to store the modules. caches. Also you'll need to decide where in the image to store the modules.
Usual way is to have it concatenated at the end. In this case you'll need to Usual way is to have it concatenated at the end. In this case you'll need to
modify startup.S to copy modules out of bss to let's say ALIGN_UP (_end, 8) modify startup.S to copy modules out of bss to let's say ALIGN_UP (_end, 8)
before cleaning out bss. You'll probably find useful to add total_module_size before cleaning out bss. You'll probably find it useful to add total_module_size
field to startup.S. In init.c you need to set grub_modbase to the address field to startup.S. In init.c you need to set grub_modbase to the address
where modules can be found. You may need grub_modules_get_end () to avoid where modules can be found. You may need grub_modules_get_end () to avoid
declaring the space occupied by modules as usable for heap. You can test modules declaring the space occupied by modules as usable for heap. You can test modules
@@ -1085,9 +1214,9 @@ Once this works, you should think of implementing disk access. Look around
disk/ for examples. disk/ for examples.
Then, very importantly, you probably need to implement the actual loader Then, very importantly, you probably need to implement the actual loader
(examples available in loader/) (examples available in loader/).
Last step to have minimally usable port is to add support to grub-install to The last step to have a minimally usable port is to add support to grub-install to
put GRUB in a place where firmware or platform will pick it up. put GRUB in a place where firmware or platform will pick it up.
Next steps are: filling datetime.c, setjmp.S, network (net/drivers), Next steps are: filling datetime.c, setjmp.S, network (net/drivers),
@@ -1096,15 +1225,15 @@ video (video/), halt (lib/), reboot (lib/).
Please add your platform to Platform limitations and Supported kernels chapter Please add your platform to Platform limitations and Supported kernels chapter
in user documentation and mention any steps you skipped which result in reduced in user documentation and mention any steps you skipped which result in reduced
features or performance. Here is the quick checklist of features. Some of them features or performance. Here is the quick checklist of features. Some of them
are less important than others and skipping them is completely ok, just needs are less important than others and skipping them is completely ok, it just needs
to be mentioned in user documentation. to be mentioned in user documentation.
Checklist: Checklist:
@itemize @itemize
@item Is heap big enough? @item Is the heap big enough?
@item Which charset is supported by console? @item Which charset is supported by the console?
@item Does platform have disk driver? @item Does the platform have disk driver?
@item Do you have network card support? @item Is there network card support?
@item Are you able to retrieve datetime (with date)? @item Are you able to retrieve datetime (with date)?
@item Are you able to set datetime (with date)? @item Are you able to set datetime (with date)?
@item Is serial supported? @item Is serial supported?
@@ -1130,16 +1259,16 @@ GRUB?
@node Error Handling @node Error Handling
@chapter Error Handling @chapter Error Handling
Error handling in GRUB 2 is based on exception handling model. As C language Error handling in GRUB 2 is based on exception handling model. As the C language
doesn't directly support exceptions, exception handling behavior is emulated doesn't directly support exceptions, exception handling behavior is emulated
in software. in software.
When exception is raised, function must return to calling function. If calling When an exception is raised, the function must return to the calling function. If the calling
function does not provide handling of the exception it must return back to its function does not provide handling of the exception it must return back to its
calling function and so on, until exception is handled. If exception is not calling function and so on, until the exception is handled. If the exception is not
handled before prompt is displayed, error message will be shown to user. handled before a prompt is displayed, error message will be shown to user.
Exception information is stored on @code{grub_errno} global variable. If Exception information is stored in the @code{grub_errno} global variable. If
@code{grub_errno} variable contains value @code{GRUB_ERR_NONE}, there is no active @code{grub_errno} variable contains value @code{GRUB_ERR_NONE}, there is no active
exception and application can continue normal processing. When @code{grub_errno} has exception and application can continue normal processing. When @code{grub_errno} has
other value, it is required that application code either handles this error or other value, it is required that application code either handles this error or
+4021 -117
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
[NAME]
grub-protect \- protect a disk key with a key protector
[DESCRIPTION]
grub-protect helps to protect a disk encryption key with a specified key protector.
+9 -2
View File
@@ -631,7 +631,10 @@ def platform_values(defn, platform, suffix):
def extra_dist(defn): def extra_dist(defn):
return foreach_value(defn, "extra_dist", lambda value: value + " ") return foreach_value(defn, "extra_dist", lambda value: value + " ")
def platform_sources(defn, p): return platform_values(defn, p, "") def extra_dep(defn):
return foreach_value(defn, "depends", lambda value: value + " ")
def platform_sources(defn, p): return platform_values(defn, p, "_head") + platform_values(defn, p, "")
def platform_nodist_sources(defn, p): return platform_values(defn, p, "_nodist") def platform_nodist_sources(defn, p): return platform_values(defn, p, "_nodist")
def platform_startup(defn, p): return platform_specific_values(defn, p, "_startup", "startup") def platform_startup(defn, p): return platform_specific_values(defn, p, "_startup", "startup")
@@ -657,7 +660,7 @@ def first_time(defn, snippet):
def is_platform_independent(defn): def is_platform_independent(defn):
if 'enable' in defn: if 'enable' in defn:
return False return False
for suffix in [ "", "_nodist" ]: for suffix in [ "", "_head", "_nodist" ]:
template = platform_values(defn, GRUB_PLATFORMS[0], suffix) template = platform_values(defn, GRUB_PLATFORMS[0], suffix)
for platform in GRUB_PLATFORMS[1:]: for platform in GRUB_PLATFORMS[1:]:
if template != platform_values(defn, platform, suffix): if template != platform_values(defn, platform, suffix):
@@ -699,6 +702,10 @@ def module(defn, platform):
gvar_add("MOD_FILES", name + ".mod") gvar_add("MOD_FILES", name + ".mod")
gvar_add("MARKER_FILES", name + ".marker") gvar_add("MARKER_FILES", name + ".marker")
gvar_add("CLEANFILES", name + ".marker") gvar_add("CLEANFILES", name + ".marker")
for dep in defn.find_all("depends"):
gvar_add("EXTRA_DEPS", "depends " + name + " " + dep + ":")
output(""" output("""
""" + name + """.marker: $(""" + cname(defn) + """_SOURCES) $(nodist_""" + cname(defn) + """_SOURCES) """ + name + """.marker: $(""" + cname(defn) + """_SOURCES) $(nodist_""" + cname(defn) + """_SOURCES)
$(TARGET_CPP) -DGRUB_LST_GENERATOR $(CPPFLAGS_MARKER) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(""" + cname(defn) + """_CPPFLAGS) $(CPPFLAGS) $^ > $@.new || (rm -f $@; exit 1) $(TARGET_CPP) -DGRUB_LST_GENERATOR $(CPPFLAGS_MARKER) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(""" + cname(defn) + """_CPPFLAGS) $(CPPFLAGS) $^ > $@.new || (rm -f $@; exit 1)
+11 -3
View File
@@ -90,6 +90,7 @@ endif
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/mm.h 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/parser.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/partition.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/partition.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/key_protector.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/stack_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/term.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/time.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/time.h
@@ -153,6 +154,7 @@ endif
if COND_i386_ieee1275 if COND_i386_ieee1275
KERNEL_HEADER_FILES += $(top_builddir)/include/grub/machine/kernel.h KERNEL_HEADER_FILES += $(top_builddir)/include/grub/machine/kernel.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/ieee1275/ieee1275.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/ieee1275/ieee1275.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/ieee1275/alloc.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/terminfo.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/terminfo.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/extcmd.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/extcmd.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/lib/arg.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/lib/arg.h
@@ -240,9 +242,12 @@ endif
if COND_powerpc_ieee1275 if COND_powerpc_ieee1275
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/ieee1275/ieee1275.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/ieee1275/ieee1275.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/ieee1275/alloc.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/terminfo.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/terminfo.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/extcmd.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/extcmd.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/lib/arg.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/lib/arg.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/powerpc/ieee1275/ieee1275.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/powerpc/ieee1275/platform_keystore.h
endif endif
if COND_sparc64_ieee1275 if COND_sparc64_ieee1275
@@ -452,8 +457,11 @@ crypto.lst: $(srcdir)/lib/libgcrypt-grub/cipher/crypto.lst
platform_DATA += crypto.lst platform_DATA += crypto.lst
CLEANFILES += crypto.lst CLEANFILES += crypto.lst
syminfo.lst: gensyminfo.sh kernel_syms.lst $(MODULE_FILES) extra_deps.lst:
cat kernel_syms.lst > $@.new @echo $(EXTRA_DEPS) | sed "s/\s*:\s*/\n/g" > $@
syminfo.lst: gensyminfo.sh kernel_syms.lst extra_deps.lst $(MODULE_FILES)
cat kernel_syms.lst extra_deps.lst > $@.new
for m in $(MODULE_FILES); do \ for m in $(MODULE_FILES); do \
sh $< $$m >> $@.new || exit 1; \ sh $< $$m >> $@.new || exit 1; \
done done
@@ -463,7 +471,7 @@ syminfo.lst: gensyminfo.sh kernel_syms.lst $(MODULE_FILES)
moddep.lst: syminfo.lst genmoddep.awk video.lst moddep.lst: syminfo.lst genmoddep.awk video.lst
cat $< | sort | $(AWK) -f $(srcdir)/genmoddep.awk > $@ || (rm -f $@; exit 1) cat $< | sort | $(AWK) -f $(srcdir)/genmoddep.awk > $@ || (rm -f $@; exit 1)
platform_DATA += moddep.lst platform_DATA += moddep.lst
CLEANFILES += config.log syminfo.lst moddep.lst CLEANFILES += config.log syminfo.lst moddep.lst extra_deps.lst
$(MOD_FILES): %.mod : genmod.sh moddep.lst %.module$(EXEEXT) build-grub-module-verifier$(BUILD_EXEEXT) $(MOD_FILES): %.mod : genmod.sh moddep.lst %.module$(EXEEXT) build-grub-module-verifier$(BUILD_EXEEXT)
TARGET_OBJ2ELF=@TARGET_OBJ2ELF@ sh $^ $@ TARGET_OBJ2ELF=@TARGET_OBJ2ELF@ sh $^ $@
+200 -21
View File
@@ -10,6 +10,7 @@ transform_data = {
installdir = noinst; installdir = noinst;
name = genmod.sh; name = genmod.sh;
common = genmod.sh.in; common = genmod.sh.in;
i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)';
}; };
transform_data = { transform_data = {
@@ -82,21 +83,21 @@ kernel = {
riscv64_efi_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version -R .eh_frame'; riscv64_efi_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version -R .eh_frame';
i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x9000'; i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x9000';
i386_qemu_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_qemu_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_qemu_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x9000'; i386_qemu_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x9000';
i386_coreboot_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_coreboot_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_coreboot_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x9000'; i386_coreboot_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x9000';
i386_multiboot_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_multiboot_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_multiboot_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x9000'; i386_multiboot_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x9000';
i386_ieee1275_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_ieee1275_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_ieee1275_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x10000'; i386_ieee1275_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x10000';
i386_xen_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_xen_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_xen_ldflags = '$(TARGET_IMG_BASE_LDOPT),0'; i386_xen_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0';
x86_64_xen_ldflags = '$(TARGET_IMG_LDFLAGS)'; x86_64_xen_ldflags = '$(TARGET_IMG_LDFLAGS)';
x86_64_xen_ldflags = '$(TARGET_IMG_BASE_LDOPT),0'; x86_64_xen_ldflags = '$(TARGET_IMG_BASE_LDOPT),0';
i386_xen_pvh_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_xen_pvh_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_xen_pvh_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x100000'; i386_xen_pvh_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x100000';
mips_loongson_ldflags = '-Wl,-Ttext,0x80200000'; mips_loongson_ldflags = '-Wl,-Ttext,0x80200000';
powerpc_ieee1275_ldflags = '-Wl,-Ttext,0x200000'; powerpc_ieee1275_ldflags = '-Wl,-Ttext,0x200000';
@@ -248,6 +249,7 @@ kernel = {
xen = term/xen/console.c; xen = term/xen/console.c;
xen = disk/xen/xendisk.c; xen = disk/xen/xendisk.c;
xen = commands/boot.c; xen = commands/boot.c;
xen = kern/xen/cmdline.c;
i386_xen_pvh = commands/boot.c; i386_xen_pvh = commands/boot.c;
i386_xen_pvh = disk/xen/xendisk.c; i386_xen_pvh = disk/xen/xendisk.c;
@@ -255,6 +257,7 @@ kernel = {
i386_xen_pvh = kern/i386/xen/tsc.c; i386_xen_pvh = kern/i386/xen/tsc.c;
i386_xen_pvh = kern/i386/xen/pvh.c; i386_xen_pvh = kern/i386/xen/pvh.c;
i386_xen_pvh = kern/xen/init.c; i386_xen_pvh = kern/xen/init.c;
i386_xen_pvh = kern/xen/cmdline.c;
i386_xen_pvh = term/xen/console.c; i386_xen_pvh = term/xen/console.c;
ia64_efi = kern/ia64/efi/startup.S; ia64_efi = kern/ia64/efi/startup.S;
@@ -331,6 +334,9 @@ kernel = {
powerpc_ieee1275 = kern/powerpc/cache.S; powerpc_ieee1275 = kern/powerpc/cache.S;
powerpc_ieee1275 = kern/powerpc/dl.c; powerpc_ieee1275 = kern/powerpc/dl.c;
powerpc_ieee1275 = kern/powerpc/compiler-rt.S; powerpc_ieee1275 = kern/powerpc/compiler-rt.S;
powerpc_ieee1275 = kern/lockdown.c;
powerpc_ieee1275 = kern/powerpc/ieee1275/ieee1275.c;
powerpc_ieee1275 = kern/powerpc/ieee1275/platform_keystore.c;
sparc64_ieee1275 = kern/sparc64/cache.S; sparc64_ieee1275 = kern/sparc64/cache.S;
sparc64_ieee1275 = kern/sparc64/dl.c; sparc64_ieee1275 = kern/sparc64/dl.c;
@@ -367,6 +373,9 @@ kernel = {
emu = kern/emu/cache_s.S; emu = kern/emu/cache_s.S;
emu = kern/emu/hostdisk.c; emu = kern/emu/hostdisk.c;
emu = osdep/unix/hostdisk.c; emu = osdep/unix/hostdisk.c;
emu = osdep/relpath.c;
emu = osdep/getroot.c;
emu = osdep/unix/getroot.c;
emu = osdep/exec.c; emu = osdep/exec.c;
extra_dist = osdep/unix/exec.c; extra_dist = osdep/unix/exec.c;
emu = osdep/devmapper/hostdisk.c; emu = osdep/devmapper/hostdisk.c;
@@ -442,10 +451,10 @@ image = {
sparc64_ieee1275 = boot/sparc64/ieee1275/boot.S; sparc64_ieee1275 = boot/sparc64/ieee1275/boot.S;
i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x7C00'; i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x7C00';
i386_qemu_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_qemu_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_qemu_ldflags = '$(TARGET_IMG_BASE_LDOPT),$(GRUB_BOOT_MACHINE_LINK_ADDR)'; i386_qemu_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)$(GRUB_BOOT_MACHINE_LINK_ADDR)';
i386_qemu_ccasflags = '-DGRUB_BOOT_MACHINE_LINK_ADDR=$(GRUB_BOOT_MACHINE_LINK_ADDR)'; i386_qemu_ccasflags = '-DGRUB_BOOT_MACHINE_LINK_ADDR=$(GRUB_BOOT_MACHINE_LINK_ADDR)';
/* The entry point for a.out binaries on sparc64 starts /* The entry point for a.out binaries on sparc64 starts
@@ -470,7 +479,7 @@ image = {
cppflags = '-DHYBRID_BOOT=1'; cppflags = '-DHYBRID_BOOT=1';
i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x7C00'; i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x7C00';
objcopyflags = '-O binary'; objcopyflags = '-O binary';
enable = i386_pc; enable = i386_pc;
@@ -481,7 +490,7 @@ image = {
i386_pc = boot/i386/pc/cdboot.S; i386_pc = boot/i386/pc/cdboot.S;
i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x7C00'; i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x7C00';
sparc64_ieee1275 = boot/sparc64/ieee1275/boot.S; sparc64_ieee1275 = boot/sparc64/ieee1275/boot.S;
@@ -501,7 +510,7 @@ image = {
i386_pc = boot/i386/pc/pxeboot.S; i386_pc = boot/i386/pc/pxeboot.S;
i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x7C00'; i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x7C00';
objcopyflags = '-O binary'; objcopyflags = '-O binary';
enable = i386_pc; enable = i386_pc;
@@ -512,7 +521,7 @@ image = {
i386_pc = boot/i386/pc/diskboot.S; i386_pc = boot/i386/pc/diskboot.S;
i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x8000'; i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x8000';
sparc64_ieee1275 = boot/sparc64/ieee1275/diskboot.S; sparc64_ieee1275 = boot/sparc64/ieee1275/diskboot.S;
sparc64_ieee1275_ldflags = '-Wl,-Ttext=0x4200'; sparc64_ieee1275_ldflags = '-Wl,-Ttext=0x4200';
@@ -528,7 +537,7 @@ image = {
i386_pc = boot/i386/pc/lnxboot.S; i386_pc = boot/i386/pc/lnxboot.S;
i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)';
i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x6000'; i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x6000';
objcopyflags = '-O binary'; objcopyflags = '-O binary';
enable = i386_pc; enable = i386_pc;
@@ -536,7 +545,7 @@ image = {
image = { image = {
name = xz_decompress; name = xz_decompress;
mips = boot/mips/startup_raw.S; mips_head = boot/mips/startup_raw.S;
common = boot/decompressor/minilib.c; common = boot/decompressor/minilib.c;
common = boot/decompressor/xz.c; common = boot/decompressor/xz.c;
common = lib/xzembed/xz_dec_bcj.c; common = lib/xzembed/xz_dec_bcj.c;
@@ -554,7 +563,7 @@ image = {
image = { image = {
name = none_decompress; name = none_decompress;
mips = boot/mips/startup_raw.S; mips_head = boot/mips/startup_raw.S;
common = boot/decompressor/none.c; common = boot/decompressor/none.c;
cppflags = '-DGRUB_EMBED_DECOMPRESSOR=1'; cppflags = '-DGRUB_EMBED_DECOMPRESSOR=1';
@@ -570,7 +579,7 @@ image = {
i386_pc_nodist = rs_decoder.h; i386_pc_nodist = rs_decoder.h;
objcopyflags = '-O binary'; objcopyflags = '-O binary';
ldflags = '$(TARGET_IMG_LDFLAGS) $(TARGET_IMG_BASE_LDOPT),0x8200'; ldflags = '$(TARGET_IMG_LDFLAGS) $(TARGET_IMG_BASE_LDOPT)$(TARGET_IMG_BASE_LDOPT_ARG_SEP)0x8200';
enable = i386_pc; enable = i386_pc;
}; };
@@ -714,12 +723,16 @@ module = {
name = cmostest; name = cmostest;
common = commands/i386/cmostest.c; common = commands/i386/cmostest.c;
enable = cmos; enable = cmos;
enable = i386_efi;
enable = x86_64_efi;
}; };
module = { module = {
name = cmosdump; name = cmosdump;
common = commands/i386/cmosdump.c; common = commands/i386/cmosdump.c;
enable = cmos; enable = cmos;
enable = i386_efi;
enable = x86_64_efi;
}; };
module = { module = {
@@ -841,6 +854,18 @@ module = {
common = commands/blocklist.c; common = commands/blocklist.c;
}; };
module = {
name = blsuki;
common = commands/blsuki.c;
common = lib/gnulib/filevercmp.c;
enable = powerpc_ieee1275;
enable = efi;
enable = i386_pc;
enable = emu;
cflags = '$(CFLAGS_POSIX) $(CFLAGS_GNULIB)';
cppflags = '$(CPPFLAGS_POSIX) $(CPPFLAGS_GNULIB)';
};
module = { module = {
name = boot; name = boot;
common = commands/boot.c; common = commands/boot.c;
@@ -971,8 +996,23 @@ module = {
module = { module = {
name = pgp; name = pgp;
common = commands/pgp.c; common = commands/pgp.c;
cflags = '$(CFLAGS_POSIX)'; cflags = '$(CFLAGS_GCRY) -Wno-redundant-decls';
cppflags = '-I$(srcdir)/lib/posix_wrap'; cppflags = '$(CPPFLAGS_GCRY)';
};
module = {
name = appendedsig;
common = commands/appendedsig/appendedsig.c;
common = commands/appendedsig/x509.c;
common = commands/appendedsig/pkcs7.c;
common = commands/appendedsig/asn1util.c;
common = commands/appendedsig/gnutls_asn1_tab.c;
common = commands/appendedsig/pkix_asn1_tab.c;
enable = emu;
enable = powerpc_ieee1275;
cflags = '$(CFLAGS_GCRY) -Wno-redundant-decls';
cppflags = '$(CPPFLAGS_GCRY) -I$(srcdir)/lib/libtasn1-grub';
depends = crypto, gcry_rsa, gcry_sha256, gcry_sha512, mpi, asn1;
}; };
module = { module = {
@@ -1278,6 +1318,11 @@ module = {
common = disk/raid6_recover.c; common = disk/raid6_recover.c;
}; };
module = {
name = key_protector;
common = disk/key_protector.c;
};
module = { module = {
name = scsi; name = scsi;
common = disk/scsi.c; common = disk/scsi.c;
@@ -1438,6 +1483,11 @@ module = {
common = fs/odc.c; common = fs/odc.c;
}; };
module = {
name = erofs;
common = fs/erofs.c;
};
module = { module = {
name = ext2; name = ext2;
common = fs/ext2.c; common = fs/ext2.c;
@@ -1592,6 +1642,7 @@ module = {
common = fs/zfs/zfs_lz4.c; common = fs/zfs/zfs_lz4.c;
common = fs/zfs/zfs_sha256.c; common = fs/zfs/zfs_sha256.c;
common = fs/zfs/zfs_fletcher.c; common = fs/zfs/zfs_fletcher.c;
cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/zstd';
}; };
module = { module = {
@@ -1670,6 +1721,8 @@ module = {
module = { module = {
name = crypto; name = crypto;
common = lib/crypto.c; common = lib/crypto.c;
common = lib/hwfeatures-gcry.c;
x86_64_efi = lib/x86_64/efi/hwfeatures-gcry.c;
extra_dist = lib/libgcrypt-grub/cipher/crypto.lst; extra_dist = lib/libgcrypt-grub/cipher/crypto.lst;
}; };
@@ -1679,6 +1732,11 @@ module = {
common = lib/pbkdf2.c; common = lib/pbkdf2.c;
}; };
module = {
name = argon2;
common = lib/argon2.c;
};
module = { module = {
name = relocator; name = relocator;
common = lib/relocator.c; common = lib/relocator.c;
@@ -1993,7 +2051,7 @@ module = {
extra_dist = script/yylex.l; extra_dist = script/yylex.l;
extra_dist = script/parser.y; extra_dist = script/parser.y;
cflags = '$(CFLAGS_POSIX) -Wno-redundant-decls'; cflags = '$(CFLAGS_POSIX) -Wno-redundant-decls -Wno-unused-but-set-variable';
cppflags = '$(CPPFLAGS_POSIX)'; cppflags = '$(CPPFLAGS_POSIX)';
}; };
@@ -2165,6 +2223,30 @@ module = {
common = tests/setjmp_test.c; common = tests/setjmp_test.c;
}; };
module = {
name = dsa_sexp_test;
common = tests/dsa_sexp_test.c;
cflags = '$(CFLAGS_GCRY) -Wno-redundant-decls';
cppflags = '$(CPPFLAGS_GCRY)';
};
module = {
name = rsa_sexp_test;
common = tests/rsa_sexp_test.c;
cflags = '$(CFLAGS_GCRY) -Wno-redundant-decls';
cppflags = '$(CPPFLAGS_GCRY)';
};
module = {
name = appended_signature_test;
common = tests/appended_signature_test.c;
common = tests/appended_signatures.h;
enable = emu;
enable = powerpc_ieee1275;
};
module = { module = {
name = signature_test; name = signature_test;
common = tests/signature_test.c; common = tests/signature_test.c;
@@ -2186,6 +2268,16 @@ module = {
common = tests/pbkdf2_test.c; common = tests/pbkdf2_test.c;
}; };
module = {
name = argon2_test;
common = tests/argon2_test.c;
};
module = {
name = crypto_cipher_mode_test;
common = tests/crypto_cipher_mode_test.c;
};
module = { module = {
name = legacy_password_test; name = legacy_password_test;
common = tests/legacy_password_test.c; common = tests/legacy_password_test.c;
@@ -2238,6 +2330,10 @@ module = {
common = tests/videotest_checksum.c; common = tests/videotest_checksum.c;
}; };
/*
* These tests fail depending on the version of unifont. As we don't distribute
* our own unifont it fails for most users. Disable them so that they don't mask
* real failures. They can be reinstated once we solve unifont problem.
module = { module = {
name = gfxterm_menu; name = gfxterm_menu;
common = tests/gfxterm_menu.c; common = tests/gfxterm_menu.c;
@@ -2247,6 +2343,7 @@ module = {
name = cmdline_cat_test; name = cmdline_cat_test;
common = tests/cmdline_cat_test.c; common = tests/cmdline_cat_test.c;
}; };
*/
module = { module = {
name = bitmap; name = bitmap;
@@ -2433,6 +2530,13 @@ module = {
cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/minilzo -DMINILZO_HAVE_CONFIG_H'; cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/minilzo -DMINILZO_HAVE_CONFIG_H';
}; };
module = {
name = zstdio;
common = io/zstdio.c;
cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/zstd';
cflags='-Wno-unreachable-code';
};
module = { module = {
name = testload; name = testload;
common = commands/testload.c; common = commands/testload.c;
@@ -2519,9 +2623,25 @@ module = {
common = lib/libgcrypt-grub/mpi/mpicoder.c; common = lib/libgcrypt-grub/mpi/mpicoder.c;
common = lib/libgcrypt-grub/mpi/mpih-rshift.c; common = lib/libgcrypt-grub/mpi/mpih-rshift.c;
common = lib/libgcrypt-grub/mpi/mpi-inline.c; common = lib/libgcrypt-grub/mpi/mpi-inline.c;
common = lib/libgcrypt-grub/mpi/mpih-const-time.c;
common = lib/libgcrypt-grub/mpi/mpi-scan.c;
common = lib/libgcrypt-grub/src/const-time.c;
common = lib/libgcrypt_wrap/mem.c; common = lib/libgcrypt_wrap/mem.c;
common = lib/libgcrypt-grub/cipher/md.c;
cflags = '$(CFLAGS_GCRY) -Wno-redundant-decls -Wno-sign-compare'; cflags = '$(CFLAGS_GCRY) -Wno-redundant-decls -Wno-unused-but-set-variable';
cppflags = '$(CPPFLAGS_GCRY)';
};
module = {
name = pubkey;
common = lib/libgcrypt-grub/cipher/pubkey-util.c;
common = lib/libgcrypt-grub/cipher/rsa-common.c;
common = lib/libgcrypt-grub/cipher/dsa-common.c;
common = lib/libgcrypt-grub/src/sexp.c;
common = lib/b64dec.c;
cflags = '$(CFLAGS_GCRY) -Wno-redundant-decls';
cppflags = '$(CPPFLAGS_GCRY)'; cppflags = '$(CPPFLAGS_GCRY)';
}; };
@@ -2552,6 +2672,34 @@ module = {
enable = efi; enable = efi;
}; };
module = {
name = tss2;
common = lib/tss2/buffer.c;
common = lib/tss2/tss2_mu.c;
common = lib/tss2/tpm2_cmd.c;
common = lib/tss2/tss2.c;
efi = lib/efi/tcg2.c;
emu = lib/tss2/tcg2_emu.c;
powerpc_ieee1275 = lib/ieee1275/tcg2.c;
enable = efi;
enable = emu;
enable = powerpc_ieee1275;
cppflags = '-I$(srcdir)/lib/tss2';
};
module = {
name = tpm2_key_protector;
common = commands/tpm2_key_protector/args.c;
common = commands/tpm2_key_protector/module.c;
common = commands/tpm2_key_protector/tpm2key.c;
common = commands/tpm2_key_protector/tpm2key_asn1_tab.c;
/* The plaform support of tpm2_key_protector depends on the tcg2 implementation in tss2. */
enable = efi;
enable = emu;
enable = powerpc_ieee1275;
cppflags = '-I$(srcdir)/lib/tss2 -I$(srcdir)/lib/libtasn1-grub';
};
module = { module = {
name = tr; name = tr;
common = commands/tr.c; common = commands/tr.c;
@@ -2594,4 +2742,35 @@ module = {
name = bli; name = bli;
efi = commands/bli.c; efi = commands/bli.c;
enable = efi; enable = efi;
depends = part_gpt;
};
module = {
name = asn1;
common = lib/libtasn1-grub/lib/decoding.c;
common = lib/libtasn1-grub/lib/coding.c;
common = lib/libtasn1-grub/lib/element.c;
common = lib/libtasn1-grub/lib/structure.c;
common = lib/libtasn1-grub/lib/parser_aux.c;
common = lib/libtasn1-grub/lib/gstr.c;
common = lib/libtasn1-grub/lib/errors.c;
common = lib/libtasn1_wrap/wrap.c;
cflags = '$(CFLAGS_POSIX) $(CFLAGS_GNULIB)';
/* -Wno-type-limits comes from configure.ac of libtasn1 */
cppflags = '$(CPPFLAGS_POSIX) $(CPPFLAGS_GNULIB) -I$(srcdir)/lib/libtasn1-grub -I$(srcdir)/lib/libtasn1-grub/lib -Wno-type-limits';
};
module = {
name = asn1_test;
common = tests/asn1/tests/CVE-2018-1000654.c;
common = tests/asn1/tests/object-id-decoding.c;
common = tests/asn1/tests/object-id-encoding.c;
common = tests/asn1/tests/octet-string.c;
common = tests/asn1/tests/reproducers.c;
common = tests/asn1/tests/Test_overflow.c;
common = tests/asn1/tests/Test_simple.c;
common = tests/asn1/tests/Test_strings.c;
common = tests/asn1/asn1_test.c;
cflags = '-Wno-uninitialized';
cppflags = '-I$(srcdir)/lib/libtasn1-grub -I$(srcdir)/tests/asn1/';
}; };
+6
View File
@@ -50,6 +50,12 @@ grub_memmove (void *dest, const void *src, grub_size_t n)
return dest; return dest;
} }
void *
grub_memcpy (void *dest, const void *src, grub_size_t n)
{
return grub_memmove (dest, src, n);
}
int int
grub_memcmp (const void *s1, const void *s2, grub_size_t n) grub_memcmp (const void *s1, const void *s2, grub_size_t n)
{ {
+1 -1
View File
@@ -218,7 +218,7 @@ enum
#define GRUB_EHCI_TERMINATE (1<<0) #define GRUB_EHCI_TERMINATE (1<<0)
#define GRUB_EHCI_TOGGLE (1<<31) #define GRUB_EHCI_TOGGLE ((grub_uint32_t) 1<<31)
enum enum
{ {
+52 -27
View File
@@ -38,6 +38,20 @@
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
enum
{
OPTION_EXCLUDE = 0,
OPTION_LOAD_ONLY,
OPTION_V1,
OPTION_V2,
OPTION_OEMID,
OPTION_OEMTABLE,
OPTION_OEMTABLEREV,
OPTION_OEMTABLECREATOR,
OPTION_OEMTABLECREATORREV,
OPTION_NO_EBDA
};
static const struct grub_arg_option options[] = { static const struct grub_arg_option options[] = {
{"exclude", 'x', 0, {"exclude", 'x', 0,
N_("Don't load host tables specified by comma-separated list."), N_("Don't load host tables specified by comma-separated list."),
@@ -490,21 +504,21 @@ grub_cmd_acpi (struct grub_extcmd_context *ctxt, int argc, char **args)
if (rsdp) if (rsdp)
{ {
grub_uint32_t *entry_ptr; grub_uint8_t *entry_ptr;
char *exclude = 0; char *exclude = 0;
char *load_only = 0; char *load_only = 0;
char *ptr; char *ptr;
/* RSDT consists of header and an array of 32-bit pointers. */ grub_size_t tbl_addr_size;
struct grub_acpi_table_header *rsdt; struct grub_acpi_table_header *table_head;
exclude = state[0].set ? grub_strdup (state[0].arg) : 0; exclude = state[OPTION_EXCLUDE].set ? grub_strdup (state[OPTION_EXCLUDE].arg) : 0;
if (exclude) if (exclude)
{ {
for (ptr = exclude; *ptr; ptr++) for (ptr = exclude; *ptr; ptr++)
*ptr = grub_tolower (*ptr); *ptr = grub_tolower (*ptr);
} }
load_only = state[1].set ? grub_strdup (state[1].arg) : 0; load_only = state[OPTION_LOAD_ONLY].set ? grub_strdup (state[OPTION_LOAD_ONLY].arg) : 0;
if (load_only) if (load_only)
{ {
for (ptr = load_only; *ptr; ptr++) for (ptr = load_only; *ptr; ptr++)
@@ -515,20 +529,31 @@ grub_cmd_acpi (struct grub_extcmd_context *ctxt, int argc, char **args)
rev1 = ! rsdp->revision; rev1 = ! rsdp->revision;
rev2 = rsdp->revision; rev2 = rsdp->revision;
if (rev2 && ((struct grub_acpi_table_header *) (grub_addr_t) ((struct grub_acpi_rsdp_v20 *) rsdp)->xsdt_addr) != NULL) if (rev2 && ((struct grub_acpi_table_header *) (grub_addr_t) ((struct grub_acpi_rsdp_v20 *) rsdp)->xsdt_addr) != NULL)
rsdt = (struct grub_acpi_table_header *) (grub_addr_t) ((struct grub_acpi_rsdp_v20 *) rsdp)->xsdt_addr; {
/* XSDT consists of header and an array of 64-bit pointers. */
table_head = (struct grub_acpi_table_header *) (grub_addr_t) ((struct grub_acpi_rsdp_v20 *) rsdp)->xsdt_addr;
tbl_addr_size = sizeof (((struct grub_acpi_rsdp_v20 *) rsdp)->xsdt_addr);
}
else else
rsdt = (struct grub_acpi_table_header *) (grub_addr_t) rsdp->rsdt_addr; {
/* RSDT consists of header and an array of 32-bit pointers. */
table_head = (struct grub_acpi_table_header *) (grub_addr_t) rsdp->rsdt_addr;
tbl_addr_size = sizeof (rsdp->rsdt_addr);
}
/* Load host tables. */ /* Load host tables. */
for (entry_ptr = (grub_uint32_t *) (rsdt + 1); for (entry_ptr = (grub_uint8_t *) (table_head + 1);
entry_ptr < (grub_uint32_t *) (((grub_uint8_t *) rsdt) entry_ptr < (grub_uint8_t *) (((grub_uint8_t *) table_head) + table_head->length);
+ rsdt->length); entry_ptr += tbl_addr_size)
entry_ptr++)
{ {
char signature[5]; char signature[5];
struct efiemu_acpi_table *table; struct efiemu_acpi_table *table;
struct grub_acpi_table_header *curtable struct grub_acpi_table_header *curtable;
= (struct grub_acpi_table_header *) (grub_addr_t) *entry_ptr; if (tbl_addr_size == sizeof (rsdp->rsdt_addr))
curtable = (struct grub_acpi_table_header *) (grub_addr_t) *((grub_uint32_t *) entry_ptr);
else
curtable = (struct grub_acpi_table_header *) (grub_addr_t) *((grub_uint64_t *) entry_ptr);
signature[4] = 0; signature[4] = 0;
for (i = 0; i < 4;i++) for (i = 0; i < 4;i++)
signature[i] = grub_tolower (curtable->signature[i]); signature[i] = grub_tolower (curtable->signature[i]);
@@ -612,26 +637,26 @@ grub_cmd_acpi (struct grub_extcmd_context *ctxt, int argc, char **args)
} }
/* Does user specify versions to generate? */ /* Does user specify versions to generate? */
if (state[2].set || state[3].set) if (state[OPTION_V1].set || state[OPTION_V2].set)
{ {
rev1 = state[2].set; rev1 = state[OPTION_V1].set;
if (state[3].set) if (state[OPTION_V2].set)
rev2 = rev2 ? : 2; rev2 = rev2 ? : 2;
else else
rev2 = 0; rev2 = 0;
} }
/* Does user override root header information? */ /* Does user override root header information? */
if (state[4].set) if (state[OPTION_OEMID].set)
grub_strncpy (root_oemid, state[4].arg, sizeof (root_oemid)); grub_strncpy (root_oemid, state[OPTION_OEMID].arg, sizeof (root_oemid));
if (state[5].set) if (state[OPTION_OEMTABLE].set)
grub_strncpy (root_oemtable, state[5].arg, sizeof (root_oemtable)); grub_strncpy (root_oemtable, state[OPTION_OEMTABLE].arg, sizeof (root_oemtable));
if (state[6].set) if (state[OPTION_OEMTABLEREV].set)
root_oemrev = grub_strtoul (state[6].arg, 0, 0); root_oemrev = grub_strtoul (state[OPTION_OEMTABLEREV].arg, 0, 0);
if (state[7].set) if (state[OPTION_OEMTABLECREATOR].set)
grub_strncpy (root_creator_id, state[7].arg, sizeof (root_creator_id)); grub_strncpy (root_creator_id, state[OPTION_OEMTABLECREATOR].arg, sizeof (root_creator_id));
if (state[8].set) if (state[OPTION_OEMTABLECREATORREV].set)
root_creator_rev = grub_strtoul (state[8].arg, 0, 0); root_creator_rev = grub_strtoul (state[OPTION_OEMTABLECREATORREV].arg, 0, 0);
/* Load user tables */ /* Load user tables */
for (i = 0; i < argc; i++) for (i = 0; i < argc; i++)
@@ -747,7 +772,7 @@ grub_cmd_acpi (struct grub_extcmd_context *ctxt, int argc, char **args)
acpi_tables = 0; acpi_tables = 0;
#if defined (__i386__) || defined (__x86_64__) #if defined (__i386__) || defined (__x86_64__)
if (! state[9].set) if (! state[OPTION_NO_EBDA].set)
{ {
grub_err_t err; grub_err_t err;
err = grub_acpi_create_ebda (); err = grub_acpi_create_ebda ();
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,133 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2020, 2022 Free Software Foundation, Inc.
* Copyright (C) 2020, 2022, 2025 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/crypto.h>
#include <libtasn1.h>
extern asn1_node grub_gnutls_gnutls_asn;
extern asn1_node grub_gnutls_pkix_asn;
#define GRUB_MAX_OID_LEN 32
/* RSA public key. */
#define GRUB_MAX_MPI 2
#define GRUB_RSA_PK_MODULUS 0
#define GRUB_RSA_PK_EXPONENT 1
/* Certificate fingerprint. */
#define GRUB_MAX_FINGERPRINT 3
#define GRUB_FINGERPRINT_SHA256 0
#define GRUB_FINGERPRINT_SHA384 1
#define GRUB_FINGERPRINT_SHA512 2
/* Max size of hash data. */
#define GRUB_MAX_HASH_LEN 64
/*
* One or more x509 certificates. We do limited parsing:
* extracting only the version, serial, issuer, subject, RSA public key
* and key size.
* Also, hold the sha256, sha384, and sha512 fingerprint of the certificate.
*/
struct x509_certificate
{
struct x509_certificate *next;
grub_uint8_t version;
grub_uint8_t *serial;
grub_size_t serial_len;
char *issuer;
grub_size_t issuer_len;
char *subject;
grub_size_t subject_len;
/* We only support RSA public keys. This encodes [modulus, publicExponent]. */
gcry_mpi_t mpis[GRUB_MAX_MPI];
grub_int32_t modulus_size;
grub_uint8_t fingerprint[GRUB_MAX_FINGERPRINT][GRUB_MAX_HASH_LEN];
};
typedef struct x509_certificate grub_x509_cert_t;
/* A PKCS#7 signed data signer info. */
struct pkcs7_signer
{
const gcry_md_spec_t *hash;
gcry_mpi_t sig_mpi;
};
typedef struct pkcs7_signer grub_pkcs7_signer_t;
/*
* A PKCS#7 signed data message. We make no attempt to match intelligently, so
* we don't save any info about the signer.
*/
struct pkcs7_data
{
grub_int32_t signer_count;
grub_pkcs7_signer_t *signers;
};
typedef struct pkcs7_data grub_pkcs7_data_t;
/*
* Import a DER-encoded certificate at 'data', of size 'size'. Place the results
* into 'results', which must be already allocated.
*/
extern grub_err_t
grub_x509_cert_parse (const void *data, grub_size_t size, grub_x509_cert_t *results);
/*
* Release all the storage associated with the x509 certificate. If the caller
* dynamically allocated the certificate, it must free it. The caller is also
* responsible for maintenance of the linked list.
*/
extern void
grub_x509_cert_release (grub_x509_cert_t *cert);
/*
* Parse a PKCS#7 message, which must be a signed data message. The message must
* be in 'sigbuf' and of size 'data_size'. The result is placed in 'msg', which
* must already be allocated.
*/
extern grub_err_t
grub_pkcs7_data_parse (const void *sigbuf, grub_size_t data_size, grub_pkcs7_data_t *msg);
/*
* Release all the storage associated with the PKCS#7 message. If the caller
* dynamically allocated the message, it must free it.
*/
extern void
grub_pkcs7_data_release (grub_pkcs7_data_t *msg);
/* Do libtasn1 init. */
extern int
grub_asn1_init (void);
/*
* Read a value from an ASN1 node, allocating memory to store it. It will work
* for anything where the size libtasn1 returns is right:
* - Integers
* - Octet strings
* - DER encoding of other structures
*
* It will _not_ work for things where libtasn1 size requires adjustment:
* - Strings that require an extra null byte at the end
* - Bit strings because libtasn1 returns the length in bits, not bytes.
*
* If the function returns a non-NULL value, the caller must free it.
*/
extern void *
grub_asn1_allocate_and_read (asn1_node node, const char *name, const char *friendly_name,
grub_int32_t *content_size);
+99
View File
@@ -0,0 +1,99 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2020, 2022 Free Software Foundation, Inc.
* Copyright (C) 2020, 2022, 2025 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 <libtasn1.h>
#include <grub/types.h>
#include <grub/err.h>
#include <grub/mm.h>
#include <grub/crypto.h>
#include <grub/misc.h>
#include <grub/gcrypt/gcrypt.h>
#include "appendedsig.h"
asn1_node grub_gnutls_gnutls_asn = NULL;
asn1_node grub_gnutls_pkix_asn = NULL;
extern const asn1_static_node grub_gnutls_asn1_tab[];
extern const asn1_static_node grub_pkix_asn1_tab[];
/*
* Read a value from an ASN1 node, allocating memory to store it. It will work
* for anything where the size libtasn1 returns is right:
* - Integers
* - Octet strings
* - DER encoding of other structures
*
* It will _not_ work for things where libtasn1 size requires adjustment:
* - Strings that require an extra NULL byte at the end
* - Bit strings because libtasn1 returns the length in bits, not bytes.
*
* If the function returns a non-NULL value, the caller must free it.
*/
void *
grub_asn1_allocate_and_read (asn1_node node, const char *name, const char *friendly_name,
grub_int32_t *content_size)
{
grub_int32_t result;
grub_uint8_t *tmpstr = NULL;
grub_int32_t tmpstr_size = 0;
result = asn1_read_value (node, name, NULL, &tmpstr_size);
if (result != ASN1_MEM_ERROR)
{
grub_error (GRUB_ERR_BAD_FILE_TYPE, "reading size of %s did not return expected status: %s",
friendly_name, asn1_strerror (result)) ;
return NULL;
}
tmpstr = grub_malloc (tmpstr_size);
if (tmpstr == NULL)
{
grub_error (GRUB_ERR_OUT_OF_MEMORY, "could not allocate memory to store %s",
friendly_name) ;
return NULL;
}
result = asn1_read_value (node, name, tmpstr, &tmpstr_size);
if (result != ASN1_SUCCESS)
{
grub_free (tmpstr);
grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading %s: %s", friendly_name,
asn1_strerror (result)) ;
return NULL;
}
*content_size = tmpstr_size;
return tmpstr;
}
int
grub_asn1_init (void)
{
int res;
res = asn1_array2tree (grub_gnutls_asn1_tab, &grub_gnutls_gnutls_asn, NULL);
if (res != ASN1_SUCCESS)
return res;
res = asn1_array2tree (grub_pkix_asn1_tab, &grub_gnutls_pkix_asn, NULL);
return res;
}
@@ -0,0 +1,148 @@
#include <grub/mm.h>
#include <libtasn1.h>
/*
* Imported from gnutls.asn.
* https://github.com/gnutls/gnutls/blob/master/lib/gnutls.asn
*/
const asn1_static_node grub_gnutls_asn1_tab[] = {
{ "GNUTLS", 536872976, NULL },
{ NULL, 1073741836, NULL },
{ "RSAPublicKey", 1610612741, NULL },
{ "modulus", 1073741827, NULL },
{ "publicExponent", 3, NULL },
{ "RSAPrivateKey", 1610612741, NULL },
{ "version", 1073741827, NULL },
{ "modulus", 1073741827, NULL },
{ "publicExponent", 1073741827, NULL },
{ "privateExponent", 1073741827, NULL },
{ "prime1", 1073741827, NULL },
{ "prime2", 1073741827, NULL },
{ "exponent1", 1073741827, NULL },
{ "exponent2", 1073741827, NULL },
{ "coefficient", 1073741827, NULL },
{ "otherPrimeInfos", 16386, "OtherPrimeInfos"},
{ "ProvableSeed", 1610612741, NULL },
{ "algorithm", 1073741836, NULL },
{ "seed", 7, NULL },
{ "OtherPrimeInfos", 1612709899, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "OtherPrimeInfo"},
{ "OtherPrimeInfo", 1610612741, NULL },
{ "prime", 1073741827, NULL },
{ "exponent", 1073741827, NULL },
{ "coefficient", 3, NULL },
{ "AlgorithmIdentifier", 1610612741, NULL },
{ "algorithm", 1073741836, NULL },
{ "parameters", 541081613, NULL },
{ "algorithm", 1, NULL },
{ "DigestInfo", 1610612741, NULL },
{ "digestAlgorithm", 1073741826, "DigestAlgorithmIdentifier"},
{ "digest", 7, NULL },
{ "DigestAlgorithmIdentifier", 1073741826, "AlgorithmIdentifier"},
{ "DSAPublicKey", 1073741827, NULL },
{ "DSAParameters", 1610612741, NULL },
{ "p", 1073741827, NULL },
{ "q", 1073741827, NULL },
{ "g", 3, NULL },
{ "DSASignatureValue", 1610612741, NULL },
{ "r", 1073741827, NULL },
{ "s", 3, NULL },
{ "DSAPrivateKey", 1610612741, NULL },
{ "version", 1073741827, NULL },
{ "p", 1073741827, NULL },
{ "q", 1073741827, NULL },
{ "g", 1073741827, NULL },
{ "Y", 1073741827, NULL },
{ "priv", 3, NULL },
{ "DHParameter", 1610612741, NULL },
{ "prime", 1073741827, NULL },
{ "base", 1073741827, NULL },
{ "privateValueLength", 16387, NULL },
{ "pkcs-11-ec-Parameters", 1610612754, NULL },
{ "oId", 1073741836, NULL },
{ "curveName", 31, NULL },
{ "ECParameters", 1610612754, NULL },
{ "namedCurve", 12, NULL },
{ "ECPrivateKey", 1610612741, NULL },
{ "Version", 1073741827, NULL },
{ "privateKey", 1073741831, NULL },
{ "parameters", 1610637314, "ECParameters"},
{ NULL, 2056, "0"},
{ "publicKey", 536895494, NULL },
{ NULL, 2056, "1"},
{ "PrincipalName", 1610612741, NULL },
{ "name-type", 1610620931, NULL },
{ NULL, 2056, "0"},
{ "name-string", 536879115, NULL },
{ NULL, 1073743880, "1"},
{ NULL, 27, NULL },
{ "KRB5PrincipalName", 1610612741, NULL },
{ "realm", 1610620955, NULL },
{ NULL, 2056, "0"},
{ "principalName", 536879106, "PrincipalName"},
{ NULL, 2056, "1"},
{ "RSAPSSParameters", 1610612741, NULL },
{ "hashAlgorithm", 1610637314, "AlgorithmIdentifier"},
{ NULL, 2056, "0"},
{ "maskGenAlgorithm", 1610637314, "AlgorithmIdentifier"},
{ NULL, 2056, "1"},
{ "saltLength", 1610653699, NULL },
{ NULL, 1073741833, "20"},
{ NULL, 2056, "2"},
{ "trailerField", 536911875, NULL },
{ NULL, 1073741833, "1"},
{ NULL, 2056, "3"},
{ "RSAOAEPParameters", 1610612741, NULL },
{ "hashAlgorithm", 1610637314, "AlgorithmIdentifier"},
{ NULL, 2056, "0"},
{ "maskGenAlgorithm", 1610637314, "AlgorithmIdentifier"},
{ NULL, 2056, "1"},
{ "pSourceFunc", 536895490, "AlgorithmIdentifier"},
{ NULL, 2056, "2"},
{ "GOSTParameters", 1610612741, NULL },
{ "publicKeyParamSet", 1073741836, NULL },
{ "digestParamSet", 16396, NULL },
{ "GOSTParametersOld", 1610612741, NULL },
{ "publicKeyParamSet", 1073741836, NULL },
{ "digestParamSet", 1073741836, NULL },
{ "encryptionParamSet", 16396, NULL },
{ "GOSTPrivateKey", 1073741831, NULL },
{ "GOSTPrivateKeyOld", 1073741827, NULL },
{ "IssuerSignTool", 1610612741, NULL },
{ "signTool", 1073741858, NULL },
{ "cATool", 1073741858, NULL },
{ "signToolCert", 1073741858, NULL },
{ "cAToolCert", 34, NULL },
{ "Gost28147-89-EncryptedKey", 1610612741, NULL },
{ "encryptedKey", 1073741831, NULL },
{ "maskKey", 1610637319, NULL },
{ NULL, 4104, "0"},
{ "macKey", 7, NULL },
{ "SubjectPublicKeyInfo", 1610612741, NULL },
{ "algorithm", 1073741826, "AlgorithmIdentifier"},
{ "subjectPublicKey", 6, NULL },
{ "GostR3410-TransportParameters", 1610612741, NULL },
{ "encryptionParamSet", 1073741836, NULL },
{ "ephemeralPublicKey", 1610637314, "SubjectPublicKeyInfo"},
{ NULL, 4104, "0"},
{ "ukm", 7, NULL },
{ "GostR3410-KeyTransport", 1610612741, NULL },
{ "sessionEncryptedKey", 1073741826, "Gost28147-89-EncryptedKey"},
{ "transportParameters", 536895490, "GostR3410-TransportParameters"},
{ NULL, 4104, "0"},
{ "TPMKey", 1610612741, NULL },
{ "type", 1073741836, NULL },
{ "emptyAuth", 1610637316, NULL },
{ NULL, 2056, "0"},
{ "parent", 1073741827, NULL },
{ "pubkey", 1073741831, NULL },
{ "privkey", 7, NULL },
{ "MLDSAPrivateKey", 536870917, NULL },
{ "version", 1073741827, NULL },
{ "privateKeyAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "privateKey", 1073741831, NULL },
{ "publicKey", 536895495, NULL },
{ NULL, 2056, "1"},
{ NULL, 0, NULL }
};
+452
View File
@@ -0,0 +1,452 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2020, 2022 Free Software Foundation, Inc.
* Copyright (C) 2020, 2022, 2025 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 "appendedsig.h"
#include <grub/misc.h>
#include <grub/crypto.h>
#include <grub/gcrypt/gcrypt.h>
#include <sys/types.h>
static char asn1_error[ASN1_MAX_ERROR_DESCRIPTION_SIZE];
/* RFC 5652 s 5.1. */
static const char *signedData_oid = "1.2.840.113549.1.7.2";
/* RFC 4055 s 2.1. */
static const char *sha256_oid = "2.16.840.1.101.3.4.2.1";
static const char *sha512_oid = "2.16.840.1.101.3.4.2.3";
static grub_err_t
process_content (grub_uint8_t *content, grub_int32_t size, grub_pkcs7_data_t *msg)
{
grub_int32_t res;
asn1_node signed_part;
grub_err_t err = GRUB_ERR_NONE;
char algo_oid[GRUB_MAX_OID_LEN];
grub_int32_t algo_oid_size;
grub_int32_t algo_count;
grub_int32_t signer_count;
grub_int32_t i;
char version;
grub_int32_t version_size = sizeof (version);
grub_uint8_t *result_buf;
grub_int32_t result_size = 0;
grub_int32_t crls_size = 0;
gcry_error_t gcry_err;
bool sha256_in_da, sha256_in_si, sha512_in_da, sha512_in_si;
char *da_path;
char *si_sig_path;
char *si_da_path;
res = asn1_create_element (grub_gnutls_pkix_asn, "PKIX1.pkcs-7-SignedData", &signed_part);
if (res != ASN1_SUCCESS)
return grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not create ASN.1 structure for PKCS#7 signed part");
res = asn1_der_decoding2 (&signed_part, content, &size,
ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
if (res != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"error reading PKCS#7 signed data: %s", asn1_error);
goto cleanup_signed_part;
}
/*
* SignedData ::= SEQUENCE {
* version CMSVersion,
* digestAlgorithms DigestAlgorithmIdentifiers,
* encapContentInfo EncapsulatedContentInfo,
* certificates [0] IMPLICIT CertificateSet OPTIONAL,
* crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
* signerInfos SignerInfos }
*/
res = asn1_read_value (signed_part, "version", &version, &version_size);
if (res != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE, "error reading signedData version: %s",
asn1_strerror (res));
goto cleanup_signed_part;
}
/* Signature version must be 1 because appended signature only support v1. */
if (version != 1)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"unexpected signature version v%d, only v1 supported", version);
goto cleanup_signed_part;
}
/*
* digestAlgorithms DigestAlgorithmIdentifiers
*
* DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
* DigestAlgorithmIdentifer is an X.509 AlgorithmIdentifier (10.1.1)
*
* RFC 4055 s 2.1:
* sha256Identifier AlgorithmIdentifier ::= { id-sha256, NULL }
* sha512Identifier AlgorithmIdentifier ::= { id-sha512, NULL }
*
* We only support 1 element in the set, and we do not check parameters atm.
*/
res = asn1_number_of_elements (signed_part, "digestAlgorithms", &algo_count);
if (res != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE, "error counting number of digest algorithms: %s",
asn1_strerror (res));
goto cleanup_signed_part;
}
if (algo_count <= 0)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE, "a minimum of 1 digest algorithm is required");
goto cleanup_signed_part;
}
if (algo_count > 2)
{
err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, "a maximum of 2 digest algorithms is supported");
goto cleanup_signed_part;
}
sha256_in_da = false;
sha512_in_da = false;
for (i = 0; i < algo_count; i++)
{
da_path = grub_xasprintf ("digestAlgorithms.?%d.algorithm", i + 1);
if (da_path == NULL)
{
err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not allocate path for digest algorithm parsing path");
goto cleanup_signed_part;
}
algo_oid_size = sizeof (algo_oid);
res = asn1_read_value (signed_part, da_path, algo_oid, &algo_oid_size);
if (res != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE, "error reading digest algorithm: %s",
asn1_strerror (res));
grub_free (da_path);
goto cleanup_signed_part;
}
if (grub_strncmp (sha512_oid, algo_oid, algo_oid_size) == 0)
{
if (sha512_in_da == false)
sha512_in_da = true;
else
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"SHA-512 specified twice in digest algorithm list");
grub_free (da_path);
goto cleanup_signed_part;
}
}
else if (grub_strncmp (sha256_oid, algo_oid, algo_oid_size) == 0)
{
if (sha256_in_da == false)
sha256_in_da = true;
else
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"SHA-256 specified twice in digest algorithm list");
grub_free (da_path);
goto cleanup_signed_part;
}
}
else
{
err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"only SHA-256 and SHA-512 hashes are supported, found OID %s",
algo_oid);
grub_free (da_path);
goto cleanup_signed_part;
}
grub_free (da_path);
}
/* At this point, at least one of sha{256,512}_in_da must be true. */
/*
* We ignore the certificates, but we don't permit CRLs. A CRL entry might be
* revoking the certificate we're using, and we have no way of dealing with
* that at the moment.
*/
res = asn1_read_value (signed_part, "crls", NULL, &crls_size);
if (res != ASN1_ELEMENT_NOT_FOUND)
{
err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"PKCS#7 messages with embedded CRLs are not supported");
goto cleanup_signed_part;
}
/* Read the signatures */
res = asn1_number_of_elements (signed_part, "signerInfos", &signer_count);
if (res != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE, "error counting number of signers: %s",
asn1_strerror (res));
goto cleanup_signed_part;
}
if (signer_count <= 0)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE, "a minimum of 1 signer is required");
goto cleanup_signed_part;
}
msg->signers = grub_calloc (signer_count, sizeof (grub_pkcs7_signer_t));
if (msg->signers == NULL)
{
err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not allocate space for %d signers", signer_count);
goto cleanup_signed_part;
}
msg->signer_count = 0;
for (i = 0; i < signer_count; i++)
{
si_da_path = grub_xasprintf ("signerInfos.?%d.digestAlgorithm.algorithm", i + 1);
if (si_da_path == NULL)
{
err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not allocate path for signer %d's digest algorithm parsing path",
i);
goto cleanup_signerInfos;
}
algo_oid_size = sizeof (algo_oid);
res = asn1_read_value (signed_part, si_da_path, algo_oid, &algo_oid_size);
if (res != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"error reading signer %d's digest algorithm: %s", i, asn1_strerror (res));
grub_free (si_da_path);
goto cleanup_signerInfos;
}
grub_free (si_da_path);
if (grub_strncmp (sha512_oid, algo_oid, algo_oid_size) == 0)
{
if (sha512_in_da == false)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"signer %d claims a SHA-512 signature which was not "
"specified in the outer DigestAlgorithms", i);
goto cleanup_signerInfos;
}
else
{
sha512_in_si = true;
msg->signers[i].hash = grub_crypto_lookup_md_by_name ("sha512");
}
}
else if (grub_strncmp (sha256_oid, algo_oid, algo_oid_size) == 0)
{
if (sha256_in_da == false)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"signer %d claims a SHA-256 signature which was not "
"specified in the outer DigestAlgorithms", i);
goto cleanup_signerInfos;
}
else
{
sha256_in_si = true;
msg->signers[i].hash = grub_crypto_lookup_md_by_name ("sha256");
}
}
else
{
err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"only SHA-256 and SHA-512 hashes are supported, found OID %s",
algo_oid);
goto cleanup_signerInfos;
}
if (msg->signers[i].hash == NULL)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"Hash algorithm for signer %d (OID %s) not loaded", i, algo_oid);
goto cleanup_signerInfos;
}
si_sig_path = grub_xasprintf ("signerInfos.?%d.signature", i + 1);
if (si_sig_path == NULL)
{
err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not allocate path for signer %d's signature parsing path", i);
goto cleanup_signerInfos;
}
result_buf = grub_asn1_allocate_and_read (signed_part, si_sig_path, "signature data", &result_size);
grub_free (si_sig_path);
if (result_buf == NULL)
{
err = grub_errno;
goto cleanup_signerInfos;
}
gcry_err = _gcry_mpi_scan (&(msg->signers[i].sig_mpi), GCRYMPI_FMT_USG,
result_buf, result_size, NULL);
grub_free (result_buf);
if (gcry_err != GPG_ERR_NO_ERROR)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"error loading signature %d into MPI structure: %d",
i, gcry_err);
goto cleanup_signerInfos;
}
/*
* Use msg->signer_count to track fully populated signerInfos so we know
* how many we need to clean up.
*/
msg->signer_count++;
}
/*
* Final consistency check of signerInfo.*.digestAlgorithm vs digestAlgorithms
* .*.algorithm. An algorithm must be present in both digestAlgorithms and
* signerInfo or in neither. We have already checked for an algorithm in
* signerInfo that is not in digestAlgorithms, here we check for algorithms in
* digestAlgorithms but not in signerInfos.
*/
if (sha512_in_da == true && sha512_in_si == false)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"SHA-512 specified in DigestAlgorithms but did not appear in SignerInfos");
goto cleanup_signerInfos;
}
if (sha256_in_da == true && sha256_in_si == false)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"SHA-256 specified in DigestAlgorithms but did not appear in SignerInfos");
goto cleanup_signerInfos;
}
asn1_delete_structure (&signed_part);
return GRUB_ERR_NONE;
cleanup_signerInfos:
for (i = 0; i < msg->signer_count; i++)
_gcry_mpi_release (msg->signers[i].sig_mpi);
grub_free (msg->signers);
cleanup_signed_part:
asn1_delete_structure (&signed_part);
return err;
}
grub_err_t
grub_pkcs7_data_parse (const void *sigbuf, grub_size_t data_size, grub_pkcs7_data_t *msg)
{
grub_int32_t res;
asn1_node content_info;
grub_err_t err = GRUB_ERR_NONE;
char content_oid[GRUB_MAX_OID_LEN];
grub_uint8_t *content;
grub_int32_t content_size;
grub_int32_t content_oid_size = sizeof (content_oid);
grub_int32_t size = (grub_int32_t) data_size;
if (data_size > GRUB_UINT_MAX)
return grub_error (GRUB_ERR_OUT_OF_RANGE,
"cannot parse a PKCS#7 message where data size > GRUB_UINT_MAX");
res = asn1_create_element (grub_gnutls_pkix_asn, "PKIX1.pkcs-7-ContentInfo", &content_info);
if (res != ASN1_SUCCESS)
return grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not create ASN.1 structure for PKCS#7 data: %s",
asn1_strerror (res));
res = asn1_der_decoding2 (&content_info, sigbuf, &size,
ASN1_DECODE_FLAG_STRICT_DER | ASN1_DECODE_FLAG_ALLOW_PADDING,
asn1_error);
if (res != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"error decoding PKCS#7 message DER: %s", asn1_error);
goto cleanup;
}
/*
* ContentInfo ::= SEQUENCE {
* contentType ContentType,
* content [0] EXPLICIT ANY DEFINED BY contentType }
*
* ContentType ::= OBJECT IDENTIFIER
*/
res = asn1_read_value (content_info, "contentType", content_oid, &content_oid_size);
if (res != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE, "error reading PKCS#7 content type: %s",
asn1_strerror (res));
goto cleanup;
}
/* OID for SignedData defined in 5.1. */
if (grub_strncmp (signedData_oid, content_oid, content_oid_size) != 0)
{
err = grub_error (GRUB_ERR_BAD_SIGNATURE,
"unexpected content type in PKCS#7 message: OID %s", content_oid);
goto cleanup;
}
content = grub_asn1_allocate_and_read (content_info, "content", "PKCS#7 message content", &content_size);
if (content == NULL)
{
err = grub_errno;
goto cleanup;
}
err = process_content (content, content_size, msg);
grub_free (content);
cleanup:
asn1_delete_structure (&content_info);
return err;
}
/*
* Release all the storage associated with the PKCS#7 message. If the caller
* dynamically allocated the message, it must free it.
*/
void
grub_pkcs7_data_release (grub_pkcs7_data_t *msg)
{
grub_int32_t i;
for (i = 0; i < msg->signer_count; i++)
_gcry_mpi_release (msg->signers[i].sig_mpi);
grub_free (msg->signers);
}
@@ -0,0 +1,485 @@
#include <grub/mm.h>
#include <libtasn1.h>
/*
* Imported from pkix.asn.
* https://github.com/gnutls/gnutls/blob/master/lib/pkix.asn
*/
const asn1_static_node grub_pkix_asn1_tab[] = {
{ "PKIX1", 536875024, NULL },
{ NULL, 1073741836, NULL },
{ "PrivateKeyUsagePeriod", 1610612741, NULL },
{ "notBefore", 1610637349, NULL },
{ NULL, 4104, "0"},
{ "notAfter", 536895525, NULL },
{ NULL, 4104, "1"},
{ "AuthorityKeyIdentifier", 1610612741, NULL },
{ "keyIdentifier", 1610637319, NULL },
{ NULL, 4104, "0"},
{ "authorityCertIssuer", 1610637314, "GeneralNames"},
{ NULL, 4104, "1"},
{ "authorityCertSerialNumber", 536895490, "CertificateSerialNumber"},
{ NULL, 4104, "2"},
{ "SubjectKeyIdentifier", 1073741831, NULL },
{ "KeyUsage", 1073741830, NULL },
{ "DirectoryString", 1610612754, NULL },
{ "teletexString", 1612709918, NULL },
{ "MAX", 524298, "1"},
{ "printableString", 1612709919, NULL },
{ "MAX", 524298, "1"},
{ "universalString", 1612709920, NULL },
{ "MAX", 524298, "1"},
{ "utf8String", 1612709922, NULL },
{ "MAX", 524298, "1"},
{ "bmpString", 538968097, NULL },
{ "MAX", 524298, "1"},
{ "SubjectAltName", 1073741826, "GeneralNames"},
{ "GeneralNames", 1612709899, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "GeneralName"},
{ "GeneralName", 1610612754, NULL },
{ "otherName", 1610620930, "AnotherName"},
{ NULL, 4104, "0"},
{ "rfc822Name", 1610620957, NULL },
{ NULL, 4104, "1"},
{ "dNSName", 1610620957, NULL },
{ NULL, 4104, "2"},
{ "x400Address", 1610620941, NULL },
{ NULL, 4104, "3"},
{ "directoryName", 1610620939, NULL },
{ NULL, 1073743880, "4"},
{ NULL, 2, "RelativeDistinguishedName"},
{ "ediPartyName", 1610620941, NULL },
{ NULL, 4104, "5"},
{ "uniformResourceIdentifier", 1610620957, NULL },
{ NULL, 4104, "6"},
{ "iPAddress", 1610620935, NULL },
{ NULL, 4104, "7"},
{ "registeredID", 536879116, NULL },
{ NULL, 4104, "8"},
{ "AnotherName", 1610612741, NULL },
{ "type-id", 1073741836, NULL },
{ "value", 541073421, NULL },
{ NULL, 1073743880, "0"},
{ "type-id", 1, NULL },
{ "IssuerAltName", 1073741826, "GeneralNames"},
{ "BasicConstraints", 1610612741, NULL },
{ "cA", 1610645508, NULL },
{ NULL, 131081, NULL },
{ "pathLenConstraint", 16387, NULL },
{ "CRLDistributionPoints", 1612709899, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "DistributionPoint"},
{ "DistributionPoint", 1610612741, NULL },
{ "distributionPoint", 1610637314, "DistributionPointName"},
{ NULL, 2056, "0"},
{ "reasons", 1610637314, "ReasonFlags"},
{ NULL, 4104, "1"},
{ "cRLIssuer", 536895490, "GeneralNames"},
{ NULL, 4104, "2"},
{ "DistributionPointName", 1610612754, NULL },
{ "fullName", 1610620930, "GeneralNames"},
{ NULL, 4104, "0"},
{ "nameRelativeToCRLIssuer", 536879106, "RelativeDistinguishedName"},
{ NULL, 4104, "1"},
{ "ReasonFlags", 1073741830, NULL },
{ "ExtKeyUsageSyntax", 1612709899, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 12, NULL },
{ "AuthorityInfoAccessSyntax", 1612709899, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "AccessDescription"},
{ "AccessDescription", 1610612741, NULL },
{ "accessMethod", 1073741836, NULL },
{ "accessLocation", 2, "GeneralName"},
{ "Attribute", 1610612741, NULL },
{ "type", 1073741836, NULL },
{ "values", 536870927, NULL },
{ NULL, 13, NULL },
{ "AttributeTypeAndValue", 1610612741, NULL },
{ "type", 1073741836, NULL },
{ "value", 13, NULL },
{ "Name", 1610612754, NULL },
{ "rdnSequence", 536870923, NULL },
{ NULL, 2, "RelativeDistinguishedName"},
{ "DistinguishedName", 1610612747, NULL },
{ NULL, 2, "RelativeDistinguishedName"},
{ "RelativeDistinguishedName", 1612709903, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "AttributeTypeAndValue"},
{ "Certificate", 1610612741, NULL },
{ "tbsCertificate", 1073741826, "TBSCertificate"},
{ "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "signature", 6, NULL },
{ "TBSCertificate", 1610612741, NULL },
{ "version", 1610653699, NULL },
{ NULL, 1073741833, "0"},
{ NULL, 2056, "0"},
{ "serialNumber", 1073741826, "CertificateSerialNumber"},
{ "signature", 1073741826, "AlgorithmIdentifier"},
{ "issuer", 1073741826, "Name"},
{ "validity", 1073741826, "Validity"},
{ "subject", 1073741826, "Name"},
{ "subjectPublicKeyInfo", 1073741826, "SubjectPublicKeyInfo"},
{ "issuerUniqueID", 1610637314, "UniqueIdentifier"},
{ NULL, 4104, "1"},
{ "subjectUniqueID", 1610637314, "UniqueIdentifier"},
{ NULL, 4104, "2"},
{ "extensions", 536895490, "Extensions"},
{ NULL, 2056, "3"},
{ "CertificateSerialNumber", 1073741827, NULL },
{ "Validity", 1610612741, NULL },
{ "notBefore", 1073741826, "Time"},
{ "notAfter", 2, "Time"},
{ "Time", 1610612754, NULL },
{ "utcTime", 1073741860, NULL },
{ "generalTime", 37, NULL },
{ "UniqueIdentifier", 1073741830, NULL },
{ "SubjectPublicKeyInfo", 1610612741, NULL },
{ "algorithm", 1073741826, "AlgorithmIdentifier"},
{ "subjectPublicKey", 6, NULL },
{ "Extensions", 1612709899, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "Extension"},
{ "Extension", 1610612741, NULL },
{ "extnID", 1073741836, NULL },
{ "critical", 1610645508, NULL },
{ NULL, 131081, NULL },
{ "extnValue", 7, NULL },
{ "CertificateList", 1610612741, NULL },
{ "tbsCertList", 1073741826, "TBSCertList"},
{ "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "signature", 6, NULL },
{ "TBSCertList", 1610612741, NULL },
{ "version", 1073758211, NULL },
{ "signature", 1073741826, "AlgorithmIdentifier"},
{ "issuer", 1073741826, "Name"},
{ "thisUpdate", 1073741826, "Time"},
{ "nextUpdate", 1073758210, "Time"},
{ "revokedCertificates", 1610629131, NULL },
{ NULL, 536870917, NULL },
{ "userCertificate", 1073741826, "CertificateSerialNumber"},
{ "revocationDate", 1073741826, "Time"},
{ "crlEntryExtensions", 16386, "Extensions"},
{ "crlExtensions", 536895490, "Extensions"},
{ NULL, 2056, "0"},
{ "AlgorithmIdentifier", 1610612741, NULL },
{ "algorithm", 1073741836, NULL },
{ "parameters", 541081613, NULL },
{ "algorithm", 1, NULL },
{ "Dss-Sig-Value", 1610612741, NULL },
{ "r", 1073741827, NULL },
{ "s", 3, NULL },
{ "Dss-Parms", 1610612741, NULL },
{ "p", 1073741827, NULL },
{ "q", 1073741827, NULL },
{ "g", 3, NULL },
{ "pkcs-7-ContentInfo", 1610612741, NULL },
{ "contentType", 1073741836, NULL },
{ "content", 541073421, NULL },
{ NULL, 1073743880, "0"},
{ "contentType", 1, NULL },
{ "pkcs-7-DigestInfo", 1610612741, NULL },
{ "digestAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "digest", 7, NULL },
{ "pkcs-7-SignedData", 1610612741, NULL },
{ "version", 1073741827, NULL },
{ "digestAlgorithms", 1073741826, "pkcs-7-DigestAlgorithmIdentifiers"},
{ "encapContentInfo", 1073741826, "pkcs-7-EncapsulatedContentInfo"},
{ "certificates", 1610637314, "pkcs-7-CertificateSet"},
{ NULL, 4104, "0"},
{ "crls", 1610637314, "pkcs-7-CertificateRevocationLists"},
{ NULL, 4104, "1"},
{ "signerInfos", 2, "pkcs-7-SignerInfos"},
{ "pkcs-7-DigestAlgorithmIdentifiers", 1610612751, NULL },
{ NULL, 2, "AlgorithmIdentifier"},
{ "pkcs-7-EncapsulatedContentInfo", 1610612741, NULL },
{ "eContentType", 1073741836, NULL },
{ "eContent", 536895501, NULL },
{ NULL, 2056, "0"},
{ "pkcs-7-CertificateRevocationLists", 1610612751, NULL },
{ NULL, 13, NULL },
{ "pkcs-7-CertificateChoices", 1610612754, NULL },
{ "certificate", 13, NULL },
{ "pkcs-7-CertificateSet", 1610612751, NULL },
{ NULL, 2, "pkcs-7-CertificateChoices"},
{ "IssuerAndSerialNumber", 1610612741, NULL },
{ "issuer", 1073741826, "Name"},
{ "serialNumber", 2, "CertificateSerialNumber"},
{ "pkcs-7-SignerInfo", 1610612741, NULL },
{ "version", 1073741827, NULL },
{ "sid", 1073741826, "SignerIdentifier"},
{ "digestAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "signedAttrs", 1610637314, "SignedAttributes"},
{ NULL, 4104, "0"},
{ "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "signature", 1073741831, NULL },
{ "unsignedAttrs", 536895490, "SignedAttributes"},
{ NULL, 4104, "1"},
{ "SignedAttributes", 1612709903, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "Attribute"},
{ "SignerIdentifier", 1610612754, NULL },
{ "issuerAndSerialNumber", 1073741826, "IssuerAndSerialNumber"},
{ "subjectKeyIdentifier", 536879111, NULL },
{ NULL, 4104, "0"},
{ "pkcs-7-SignerInfos", 1610612751, NULL },
{ NULL, 2, "pkcs-7-SignerInfo"},
{ "pkcs-10-CertificationRequestInfo", 1610612741, NULL },
{ "version", 1073741827, NULL },
{ "subject", 1073741826, "Name"},
{ "subjectPKInfo", 1073741826, "SubjectPublicKeyInfo"},
{ "attributes", 536879106, "Attributes"},
{ NULL, 4104, "0"},
{ "Attributes", 1610612751, NULL },
{ NULL, 2, "Attribute"},
{ "pkcs-10-CertificationRequest", 1610612741, NULL },
{ "certificationRequestInfo", 1073741826, "pkcs-10-CertificationRequestInfo"},
{ "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "signature", 6, NULL },
{ "pkcs-9-at-challengePassword", 1879048204, NULL },
{ "iso", 1073741825, "1"},
{ "member-body", 1073741825, "2"},
{ "us", 1073741825, "840"},
{ "rsadsi", 1073741825, "113549"},
{ "pkcs", 1073741825, "1"},
{ NULL, 1073741825, "9"},
{ NULL, 1, "7"},
{ "pkcs-9-challengePassword", 1610612754, NULL },
{ "printableString", 1073741855, NULL },
{ "utf8String", 34, NULL },
{ "pkcs-9-localKeyId", 1073741831, NULL },
{ "pkcs-8-PrivateKeyInfo", 1610612741, NULL },
{ "version", 1073741827, NULL },
{ "privateKeyAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "privateKey", 1073741831, NULL },
{ "attributes", 536895490, "Attributes"},
{ NULL, 4104, "0"},
{ "pkcs-8-EncryptedPrivateKeyInfo", 1610612741, NULL },
{ "encryptionAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "encryptedData", 2, "pkcs-8-EncryptedData"},
{ "pkcs-8-EncryptedData", 1073741831, NULL },
{ "pkcs-5-des-CBC-params", 1612709895, NULL },
{ NULL, 1048586, "8"},
{ "pkcs-5-des-EDE3-CBC-params", 1612709895, NULL },
{ NULL, 1048586, "8"},
{ "pkcs-5-aes128-CBC-params", 1612709895, NULL },
{ NULL, 1048586, "16"},
{ "pkcs-5-aes192-CBC-params", 1612709895, NULL },
{ NULL, 1048586, "16"},
{ "pkcs-5-aes256-CBC-params", 1612709895, NULL },
{ NULL, 1048586, "16"},
{ "Gost28147-89-Parameters", 1610612741, NULL },
{ "iv", 1073741831, NULL },
{ "encryptionParamSet", 12, NULL },
{ "pkcs-5-PBE-params", 1610612741, NULL },
{ "salt", 1073741831, NULL },
{ "iterationCount", 3, NULL },
{ "pkcs-5-PBES2-params", 1610612741, NULL },
{ "keyDerivationFunc", 1073741826, "AlgorithmIdentifier"},
{ "encryptionScheme", 2, "AlgorithmIdentifier"},
{ "pkcs-5-PBMAC1-params", 1610612741, NULL },
{ "keyDerivationFunc", 1073741826, "AlgorithmIdentifier"},
{ "messageAuthScheme", 2, "AlgorithmIdentifier"},
{ "pkcs-5-PBKDF2-params", 1610612741, NULL },
{ "salt", 1610612754, NULL },
{ "specified", 1073741831, NULL },
{ "otherSource", 2, "AlgorithmIdentifier"},
{ "iterationCount", 1073741827, NULL },
{ "keyLength", 1073758211, NULL },
{ "prf", 16386, "AlgorithmIdentifier"},
{ "pkcs-12-PFX", 1610612741, NULL },
{ "version", 1610874883, NULL },
{ "v3", 1, "3"},
{ "authSafe", 1073741826, "pkcs-7-ContentInfo"},
{ "macData", 16386, "pkcs-12-MacData"},
{ "pkcs-12-PbeParams", 1610612741, NULL },
{ "salt", 1073741831, NULL },
{ "iterations", 3, NULL },
{ "pkcs-12-MacData", 1610612741, NULL },
{ "mac", 1073741826, "pkcs-7-DigestInfo"},
{ "macSalt", 1073741831, NULL },
{ "iterations", 536903683, NULL },
{ NULL, 9, "1"},
{ "pkcs-12-AuthenticatedSafe", 1610612747, NULL },
{ NULL, 2, "pkcs-7-ContentInfo"},
{ "pkcs-12-SafeContents", 1610612747, NULL },
{ NULL, 2, "pkcs-12-SafeBag"},
{ "pkcs-12-SafeBag", 1610612741, NULL },
{ "bagId", 1073741836, NULL },
{ "bagValue", 1614815245, NULL },
{ NULL, 1073743880, "0"},
{ "badId", 1, NULL },
{ "bagAttributes", 536887311, NULL },
{ NULL, 2, "Attribute"},
{ "pkcs-12-CertBag", 1610612741, NULL },
{ "certId", 1073741836, NULL },
{ "certValue", 541073421, NULL },
{ NULL, 1073743880, "0"},
{ "certId", 1, NULL },
{ "pkcs-12-CRLBag", 1610612741, NULL },
{ "crlId", 1073741836, NULL },
{ "crlValue", 541073421, NULL },
{ NULL, 1073743880, "0"},
{ "crlId", 1, NULL },
{ "pkcs-12-SecretBag", 1610612741, NULL },
{ "secretTypeId", 1073741836, NULL },
{ "secretValue", 541073421, NULL },
{ NULL, 1073743880, "0"},
{ "secretTypeId", 1, NULL },
{ "pkcs-7-Data", 1073741831, NULL },
{ "pkcs-7-EncryptedData", 1610612741, NULL },
{ "version", 1073741827, NULL },
{ "encryptedContentInfo", 1073741826, "pkcs-7-EncryptedContentInfo"},
{ "unprotectedAttrs", 536895490, "pkcs-7-UnprotectedAttributes"},
{ NULL, 4104, "1"},
{ "pkcs-7-EncryptedContentInfo", 1610612741, NULL },
{ "contentType", 1073741836, NULL },
{ "contentEncryptionAlgorithm", 1073741826, "pkcs-7-ContentEncryptionAlgorithmIdentifier"},
{ "encryptedContent", 536895495, NULL },
{ NULL, 4104, "0"},
{ "pkcs-7-ContentEncryptionAlgorithmIdentifier", 1073741826, "AlgorithmIdentifier"},
{ "pkcs-7-UnprotectedAttributes", 1612709903, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "Attribute"},
{ "ProxyCertInfo", 1610612741, NULL },
{ "pCPathLenConstraint", 1073758211, NULL },
{ "proxyPolicy", 2, "ProxyPolicy"},
{ "ProxyPolicy", 1610612741, NULL },
{ "policyLanguage", 1073741836, NULL },
{ "policy", 16391, NULL },
{ "certificatePolicies", 1612709899, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "PolicyInformation"},
{ "PolicyInformation", 1610612741, NULL },
{ "policyIdentifier", 1073741836, NULL },
{ "policyQualifiers", 538984459, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "PolicyQualifierInfo"},
{ "PolicyQualifierInfo", 1610612741, NULL },
{ "policyQualifierId", 1073741836, NULL },
{ "qualifier", 541065229, NULL },
{ "policyQualifierId", 1, NULL },
{ "CPSuri", 1073741853, NULL },
{ "UserNotice", 1610612741, NULL },
{ "noticeRef", 1073758210, "NoticeReference"},
{ "explicitText", 16386, "DisplayText"},
{ "NoticeReference", 1610612741, NULL },
{ "organization", 1073741826, "DisplayText"},
{ "noticeNumbers", 536870923, NULL },
{ NULL, 3, NULL },
{ "DisplayText", 1610612754, NULL },
{ "ia5String", 1612709917, NULL },
{ "200", 524298, "1"},
{ "visibleString", 1612709923, NULL },
{ "200", 524298, "1"},
{ "bmpString", 1612709921, NULL },
{ "200", 524298, "1"},
{ "utf8String", 538968098, NULL },
{ "200", 524298, "1"},
{ "OCSPRequest", 1610612741, NULL },
{ "tbsRequest", 1073741826, "TBSRequest"},
{ "optionalSignature", 536895490, "Signature"},
{ NULL, 2056, "0"},
{ "TBSRequest", 1610612741, NULL },
{ "version", 1610653699, NULL },
{ NULL, 1073741833, "0"},
{ NULL, 2056, "0"},
{ "requestorName", 1610637314, "GeneralName"},
{ NULL, 2056, "1"},
{ "requestList", 1610612747, NULL },
{ NULL, 2, "Request"},
{ "requestExtensions", 536895490, "Extensions"},
{ NULL, 2056, "2"},
{ "Signature", 1610612741, NULL },
{ "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "signature", 1073741830, NULL },
{ "certs", 536895499, NULL },
{ NULL, 1073743880, "0"},
{ NULL, 2, "Certificate"},
{ "Request", 1610612741, NULL },
{ "reqCert", 1073741826, "CertID"},
{ "singleRequestExtensions", 536895490, "Extensions"},
{ NULL, 2056, "0"},
{ "CertID", 1610612741, NULL },
{ "hashAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "issuerNameHash", 1073741831, NULL },
{ "issuerKeyHash", 1073741831, NULL },
{ "serialNumber", 2, "CertificateSerialNumber"},
{ "OCSPResponse", 1610612741, NULL },
{ "responseStatus", 1073741826, "OCSPResponseStatus"},
{ "responseBytes", 536895490, "ResponseBytes"},
{ NULL, 2056, "0"},
{ "OCSPResponseStatus", 1610874901, NULL },
{ "successful", 1073741825, "0"},
{ "malformedRequest", 1073741825, "1"},
{ "internalError", 1073741825, "2"},
{ "tryLater", 1073741825, "3"},
{ "sigRequired", 1073741825, "5"},
{ "unauthorized", 1, "6"},
{ "ResponseBytes", 1610612741, NULL },
{ "responseType", 1073741836, NULL },
{ "response", 7, NULL },
{ "BasicOCSPResponse", 1610612741, NULL },
{ "tbsResponseData", 1073741826, "ResponseData"},
{ "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
{ "signature", 1073741830, NULL },
{ "certs", 536895499, NULL },
{ NULL, 1073743880, "0"},
{ NULL, 2, "Certificate"},
{ "ResponseData", 1610612741, NULL },
{ "version", 1610653699, NULL },
{ NULL, 1073741833, "0"},
{ NULL, 2056, "0"},
{ "responderID", 1073741826, "ResponderID"},
{ "producedAt", 1073741861, NULL },
{ "responses", 1610612747, NULL },
{ NULL, 2, "SingleResponse"},
{ "responseExtensions", 536895490, "Extensions"},
{ NULL, 2056, "1"},
{ "ResponderID", 1610612754, NULL },
{ "byName", 1610620939, NULL },
{ NULL, 1073743880, "1"},
{ NULL, 2, "RelativeDistinguishedName"},
{ "byKey", 536879111, NULL },
{ NULL, 2056, "2"},
{ "SingleResponse", 1610612741, NULL },
{ "certID", 1073741826, "CertID"},
{ "certStatus", 1073741826, "CertStatus"},
{ "thisUpdate", 1073741861, NULL },
{ "nextUpdate", 1610637349, NULL },
{ NULL, 2056, "0"},
{ "singleExtensions", 536895490, "Extensions"},
{ NULL, 2056, "1"},
{ "CertStatus", 1610612754, NULL },
{ "good", 1610620948, NULL },
{ NULL, 4104, "0"},
{ "revoked", 1610620930, "RevokedInfo"},
{ NULL, 4104, "1"},
{ "unknown", 536879106, "UnknownInfo"},
{ NULL, 4104, "2"},
{ "RevokedInfo", 1610612741, NULL },
{ "revocationTime", 1073741861, NULL },
{ "revocationReason", 537157653, NULL },
{ NULL, 1073743880, "0"},
{ "unspecified", 1, "0"},
{ "UnknownInfo", 1073741844, NULL },
{ "NameConstraints", 1610612741, NULL },
{ "permittedSubtrees", 1610637314, "GeneralSubtrees"},
{ NULL, 4104, "0"},
{ "excludedSubtrees", 536895490, "GeneralSubtrees"},
{ NULL, 4104, "1"},
{ "GeneralSubtrees", 1612709899, NULL },
{ "MAX", 1074266122, "1"},
{ NULL, 2, "GeneralSubtree"},
{ "GeneralSubtree", 1610612741, NULL },
{ "base", 1073741826, "GeneralName"},
{ "minimum", 1610653699, NULL },
{ NULL, 1073741833, "0"},
{ NULL, 4104, "0"},
{ "maximum", 536895491, NULL },
{ NULL, 4104, "1"},
{ "TlsFeatures", 536870923, NULL },
{ NULL, 3, NULL },
{ NULL, 0, NULL }
};
+970
View File
@@ -0,0 +1,970 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2020, 2022 Free Software Foundation, Inc.
* Copyright (C) 2020, 2022, 2025 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 <libtasn1.h>
#include <grub/types.h>
#include <grub/err.h>
#include <grub/mm.h>
#include <grub/crypto.h>
#include <grub/misc.h>
#include <grub/gcrypt/gcrypt.h>
#include "appendedsig.h"
static char asn1_error[ASN1_MAX_ERROR_DESCRIPTION_SIZE];
/* RFC 3279 2.3.1 RSA Keys. */
static const char *rsaEncryption_oid = "1.2.840.113549.1.1.1";
/* RFC 5280 Appendix A. */
static const char *commonName_oid = "2.5.4.3";
/* RFC 5280 4.2.1.3 Key Usage. */
static const char *keyUsage_oid = "2.5.29.15";
static const grub_uint8_t digitalSignatureUsage = 0x80;
/* RFC 5280 4.2.1.9 Basic Constraints. */
static const char *basicConstraints_oid = "2.5.29.19";
/* RFC 5280 4.2.1.12 Extended Key Usage. */
static const char *extendedKeyUsage_oid = "2.5.29.37";
static const char *codeSigningUsage_oid = "1.3.6.1.5.5.7.3.3";
/*
* RFC 3279 2.3.1
*
* The RSA public key MUST be encoded using the ASN.1 type RSAPublicKey:
*
* RSAPublicKey ::= SEQUENCE {
* modulus INTEGER, -- n
* publicExponent INTEGER } -- e
*
* where modulus is the modulus n, and publicExponent is the public exponent e.
*/
static grub_err_t
grub_parse_rsa_pubkey (grub_uint8_t *der, grub_int32_t dersize, grub_x509_cert_t *certificate)
{
grub_int32_t result;
asn1_node spk = NULL;
grub_uint8_t *m_data, *e_data;
grub_int32_t m_size, e_size;
grub_err_t err = GRUB_ERR_NONE;
gcry_error_t gcry_err;
result = asn1_create_element (grub_gnutls_gnutls_asn, "GNUTLS.RSAPublicKey", &spk);
if (result != ASN1_SUCCESS)
return grub_error (GRUB_ERR_OUT_OF_MEMORY,
"cannot create storage for public key ASN.1 data");
result = asn1_der_decoding2 (&spk, der, &dersize, ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"cannot decode certificate public key DER: %s", asn1_error);
goto cleanup;
}
m_data = grub_asn1_allocate_and_read (spk, "modulus", "RSA modulus", &m_size);
if (m_data == NULL)
{
err = grub_errno;
goto cleanup;
}
e_data = grub_asn1_allocate_and_read (spk, "publicExponent", "RSA public exponent", &e_size);
if (e_data == NULL)
{
err = grub_errno;
goto cleanup_m_data;
}
/*
* Convert m, e to mpi
*
* nscanned is not set for FMT_USG, it's only set for FMT_PGP, so we can't
* verify it.
*/
gcry_err = _gcry_mpi_scan (&certificate->mpis[0], GCRYMPI_FMT_USG, m_data, m_size, NULL);
if (gcry_err != GPG_ERR_NO_ERROR)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"error loading RSA modulus into MPI structure: %d", gcry_err);
goto cleanup_e_data;
}
gcry_err = _gcry_mpi_scan (&certificate->mpis[1], GCRYMPI_FMT_USG, e_data, e_size, NULL);
if (gcry_err != GPG_ERR_NO_ERROR)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"error loading RSA exponent into MPI structure: %d", gcry_err);
goto cleanup_m_mpi;
}
/* RSA key size in bits. */
certificate->modulus_size = (m_size * 8) - 8;
grub_free (e_data);
grub_free (m_data);
asn1_delete_structure (&spk);
return GRUB_ERR_NONE;
cleanup_m_mpi:
_gcry_mpi_release (certificate->mpis[0]);
cleanup_e_data:
grub_free (e_data);
cleanup_m_data:
grub_free (m_data);
cleanup:
asn1_delete_structure (&spk);
return err;
}
/*
* RFC 5280:
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING }
*
* AlgorithmIdentifiers come from RFC 3279, we are not strictly compilant as we
* only support RSA Encryption.
*/
static grub_err_t
grub_x509_read_subject_public_key (asn1_node asn, grub_x509_cert_t *results)
{
grub_int32_t result;
grub_err_t err;
const char *algo_name = "tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm";
const char *params_name = "tbsCertificate.subjectPublicKeyInfo.algorithm.parameters";
const char *pk_name = "tbsCertificate.subjectPublicKeyInfo.subjectPublicKey";
char algo_oid[GRUB_MAX_OID_LEN];
grub_int32_t algo_size = sizeof (algo_oid);
char params_value[2];
grub_int32_t params_size = sizeof (params_value);
grub_uint8_t *key_data = NULL;
grub_int32_t key_size = 0;
grub_uint32_t key_type;
/* Algorithm: see notes for rsaEncryption_oid. */
result = asn1_read_value (asn, algo_name, algo_oid, &algo_size);
if (result != ASN1_SUCCESS)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading x509 public key algorithm: %s",
asn1_strerror (result));
if (grub_strncmp (algo_oid, rsaEncryption_oid, sizeof (rsaEncryption_oid)) != 0)
return grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"unsupported x509 public key algorithm: %s", algo_oid);
/*
* RFC 3279 2.3.1 : The rsaEncryption OID is intended to be used in the
* algorithm field of a value of type AlgorithmIdentifier. The parameters
* field MUST have ASN.1 type NULL for this algorithm identifier.
*/
result = asn1_read_value (asn, params_name, params_value, &params_size);
if (result != ASN1_SUCCESS)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading x509 public key parameters: %s",
asn1_strerror (result));
if (params_value[0] != ASN1_TAG_NULL)
return grub_error (GRUB_ERR_BAD_FILE_TYPE,
"invalid x509 public key parameters: expected NULL");
/*
* RFC 3279 2.3.1: The DER encoded RSAPublicKey is the value of the BIT
* STRING subjectPublicKey.
*/
result = asn1_read_value_type (asn, pk_name, NULL, &key_size, &key_type);
if (result != ASN1_MEM_ERROR)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading size of x509 public key: %s",
asn1_strerror (result));
if (key_type != ASN1_ETYPE_BIT_STRING)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "unexpected ASN.1 type when reading x509 public key: %x",
key_type);
/* Length is in bits. */
key_size = (key_size + 7) / 8;
key_data = grub_malloc (key_size);
if (key_data == NULL)
return grub_error (GRUB_ERR_OUT_OF_MEMORY, "out of memory for x509 public key");
result = asn1_read_value (asn, pk_name, key_data, &key_size);
if (result != ASN1_SUCCESS)
{
grub_free (key_data);
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading public key data");
}
key_size = (key_size + 7) / 8;
err = grub_parse_rsa_pubkey (key_data, key_size, results);
grub_free (key_data);
return err;
}
/* Decode a string as defined in Appendix A. */
static grub_err_t
decode_string (char *der, grub_int32_t der_size, char **string, grub_size_t *string_size)
{
asn1_node strasn;
grub_int32_t result;
char *choice;
grub_int32_t choice_size = 0;
grub_int32_t tmp_size = 0;
grub_err_t err = GRUB_ERR_NONE;
result = asn1_create_element (grub_gnutls_pkix_asn, "PKIX1.DirectoryString", &strasn);
if (result != ASN1_SUCCESS)
return grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not create ASN.1 structure for certificate: %s",
asn1_strerror (result));
result = asn1_der_decoding2 (&strasn, der, &der_size, ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"could not parse DER for DirectoryString: %s", asn1_error);
goto cleanup;
}
choice = grub_asn1_allocate_and_read (strasn, "", "DirectoryString choice", &choice_size);
if (choice == NULL)
{
err = grub_errno;
goto cleanup;
}
if (grub_strncmp ("utf8String", choice, choice_size) == 0)
{
result = asn1_read_value (strasn, "utf8String", NULL, &tmp_size);
if (result != ASN1_MEM_ERROR)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading size of UTF-8 string: %s",
asn1_strerror (result));
goto cleanup_choice;
}
}
else if (grub_strncmp ("printableString", choice, choice_size) == 0)
{
result = asn1_read_value (strasn, "printableString", NULL, &tmp_size);
if (result != ASN1_MEM_ERROR)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading size of printableString: %s",
asn1_strerror (result));
goto cleanup_choice;
}
}
else
{
err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"only UTF-8 and printable DirectoryStrings are supported, got %s",
choice);
goto cleanup_choice;
}
/* Read size does not include trailing NUL. */
tmp_size++;
*string = grub_malloc (tmp_size);
if (*string == NULL)
{
err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
"cannot allocate memory for DirectoryString contents");
goto cleanup_choice;
}
result = asn1_read_value (strasn, choice, *string, &tmp_size);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading out %s in DirectoryString: %s",
choice, asn1_strerror (result));
grub_free (*string);
*string = NULL;
goto cleanup_choice;
}
*string_size = tmp_size + 1;
(*string)[tmp_size] = '\0';
cleanup_choice:
grub_free (choice);
cleanup:
asn1_delete_structure (&strasn);
return err;
}
/*
* TBSCertificate ::= SEQUENCE {
* version [0] EXPLICIT Version DEFAULT v1,
* ...
*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*/
static grub_err_t
check_version (asn1_node certificate, grub_x509_cert_t *results)
{
grub_int32_t rc;
const char *name = "tbsCertificate.version";
grub_uint8_t version;
grub_int32_t len = sizeof (version);
rc = asn1_read_value (certificate, name, &version, &len);
/* Require version 3. */
if (rc != ASN1_SUCCESS || len != 1)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading certificate version");
if (version != 0x02)
return grub_error (GRUB_ERR_BAD_FILE_TYPE,
"invalid x509 certificate version, expected v3 (0x02), got 0x%02x.",
version);
results->version = version;
return GRUB_ERR_NONE;
}
/* we extract only the CN and issuer. */
static grub_err_t
read_name (asn1_node asn, const char *name_path, char **name, grub_size_t *name_size)
{
grub_int32_t seq_components, set_components;
grub_int32_t result;
grub_int32_t i, j;
char *top_path, *set_path, *type_path, *val_path;
char type[GRUB_MAX_OID_LEN];
grub_int32_t type_len = sizeof (type);
grub_int32_t string_size = 0;
char *string_der;
grub_err_t err;
*name = NULL;
top_path = grub_xasprintf ("%s.rdnSequence", name_path);
if (top_path == NULL)
return grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not allocate memory for %s name parsing path", name_path);
result = asn1_number_of_elements (asn, top_path, &seq_components);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error counting name components: %s",
asn1_strerror (result));
goto cleanup;
}
for (i = 1; i <= seq_components; i++)
{
set_path = grub_xasprintf ("%s.?%d", top_path, i);
if (set_path == NULL)
{
err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not allocate memory for %s name set parsing path",
name_path);
goto cleanup_set;
}
/* This brings us, hopefully, to a set. */
result = asn1_number_of_elements (asn, set_path, &set_components);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"error counting name sub-components components (element %d): %s",
i, asn1_strerror (result));
goto cleanup_set;
}
for (j = 1; j <= set_components; j++)
{
type_path = grub_xasprintf ("%s.?%d.?%d.type", top_path, i, j);
if (type_path == NULL)
{
err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not allocate memory for %s name component type path",
name_path);
goto cleanup_set;
}
type_len = sizeof (type);
result = asn1_read_value (asn, type_path, type, &type_len);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading %s name component type: %s",
name_path, asn1_strerror (result));
goto cleanup_type;
}
if (grub_strncmp (type, commonName_oid, type_len) != 0)
{
grub_free (type_path);
continue;
}
val_path = grub_xasprintf ("%s.?%d.?%d.value", top_path, i, j);
if (val_path == NULL)
{
err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not allocate memory for %s name component value path",
name_path);
goto cleanup_type;
}
string_der = grub_asn1_allocate_and_read (asn, val_path, name_path, &string_size);
if (string_der == NULL)
{
err = grub_errno;
goto cleanup_val_path;
}
err = decode_string (string_der, string_size, name, name_size);
if (err)
goto cleanup_string;
grub_free (string_der);
grub_free (type_path);
grub_free (val_path);
break;
}
grub_free (set_path);
if (*name)
break;
}
grub_free (top_path);
return GRUB_ERR_NONE;
cleanup_string:
grub_free (string_der);
cleanup_val_path:
grub_free (val_path);
cleanup_type:
grub_free (type_path);
cleanup_set:
grub_free (set_path);
cleanup:
grub_free (top_path);
return err;
}
/* Verify the Key Usage extension. We require the Digital Signature usage. */
static grub_err_t
verify_key_usage (grub_uint8_t *value, grub_int32_t value_size)
{
asn1_node usageasn;
grub_int32_t result;
grub_err_t err = GRUB_ERR_NONE;
grub_uint8_t usage = 0xff;
grub_int32_t usage_size = sizeof (usage_size);
result = asn1_create_element (grub_gnutls_pkix_asn, "PKIX1.KeyUsage", &usageasn);
if (result != ASN1_SUCCESS)
return grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not create ASN.1 structure for key usage");
result = asn1_der_decoding2 (&usageasn, value, &value_size,
ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"error parsing DER for Key Usage: %s", asn1_error);
goto cleanup;
}
result = asn1_read_value (usageasn, "", &usage, &usage_size);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading Key Usage value: %s",
asn1_strerror (result));
goto cleanup;
}
if (!(usage & digitalSignatureUsage))
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"key usage (0x%x) missing Digital Signature usage", usage);
goto cleanup;
}
cleanup:
asn1_delete_structure (&usageasn);
return err;
}
/*
* BasicConstraints ::= SEQUENCE {
* cA BOOLEAN DEFAULT FALSE,
* pathLenConstraint INTEGER (0..MAX) OPTIONAL }
*/
static grub_err_t
verify_basic_constraints (grub_uint8_t *value, grub_int32_t value_size)
{
asn1_node basicasn;
grub_int32_t result;
grub_err_t err = GRUB_ERR_NONE;
char cA[6]; /* FALSE or TRUE. */
grub_int32_t cA_size = sizeof (cA);
result = asn1_create_element (grub_gnutls_pkix_asn, "PKIX1.BasicConstraints", &basicasn);
if (result != ASN1_SUCCESS)
return grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not create ASN.1 structure for Basic Constraints");
result = asn1_der_decoding2 (&basicasn, value, &value_size,
ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"error parsing DER for Basic Constraints: %s", asn1_error);
goto cleanup;
}
result = asn1_read_value (basicasn, "cA", cA, &cA_size);
if (result == ASN1_ELEMENT_NOT_FOUND)
{
/* Not present, default is False, so this is OK. */
err = GRUB_ERR_NONE;
goto cleanup;
}
else if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading Basic Constraints cA value: %s",
asn1_strerror (result));
goto cleanup;
}
/* The certificate must not be a CA certificate. */
if (grub_strncmp ("FALSE", cA, cA_size) != 0)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "unexpected CA value: %s", cA);
goto cleanup;
}
cleanup:
asn1_delete_structure (&basicasn);
return err;
}
/*
* Verify the Extended Key Usage extension. We require the Code Signing usage.
*
* ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
*
* KeyPurposeId ::= OBJECT IDENTIFIER
*/
static grub_err_t
verify_extended_key_usage (grub_uint8_t *value, grub_int32_t value_size)
{
asn1_node extendedasn;
grub_int32_t result, count, i = 0;
grub_err_t err = GRUB_ERR_NONE;
char usage[GRUB_MAX_OID_LEN], name[3];
grub_int32_t usage_size = sizeof (usage);
result = asn1_create_element (grub_gnutls_pkix_asn, "PKIX1.ExtKeyUsageSyntax", &extendedasn);
if (result != ASN1_SUCCESS)
return grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not create ASN.1 structure for Extended Key Usage");
result = asn1_der_decoding2 (&extendedasn, value, &value_size,
ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"error parsing DER for Extended Key Usage: %s", asn1_error);
goto cleanup;
}
/* If EKUs are present, it checks the presents of Code Signing usage. */
result = asn1_number_of_elements (extendedasn, "", &count);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error counting number of Extended Key Usages: %s",
asn1_strerror (result));
goto cleanup;
}
for (i = 1; i < count + 1; i++)
{
grub_memset (name, 0, sizeof (name));
grub_snprintf (name, sizeof (name), "?%d", i);
result = asn1_read_value (extendedasn, name, usage, &usage_size);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading Extended Key Usage: %s",
asn1_strerror (result));
goto cleanup;
}
if (grub_strncmp (codeSigningUsage_oid, usage, usage_size) == 0)
goto cleanup;
}
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "extended key usage missing Code Signing usage");
cleanup:
asn1_delete_structure (&extendedasn);
return err;
}
/*
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING
* -- contains the DER encoding of an ASN.1 value
* -- corresponding to the extension type identified
* -- by extnID
* }
*
* A certificate must:
* - contain the Digital Signature usage
* - not be a CA
* - contain no extended usages, or contain the Code Signing extended usage
* - not contain any other critical extensions (RFC 5280 s 4.2)
*/
static grub_err_t
verify_extensions (asn1_node cert)
{
grub_int32_t result;
grub_int32_t ext, num_extensions = 0;
grub_int32_t usage_present = 0, constraints_present = 0, extended_usage_present = 0;
char *oid_path, *critical_path, *value_path;
char extnID[GRUB_MAX_OID_LEN];
grub_int32_t extnID_size;
grub_err_t err;
char critical[6]; /* We get either "TRUE" or "FALSE". */
grub_int32_t critical_size;
grub_uint8_t *value;
grub_int32_t value_size;
result = asn1_number_of_elements (cert, "tbsCertificate.extensions", &num_extensions);
if (result != ASN1_SUCCESS)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "error counting number of extensions: %s",
asn1_strerror (result));
if (num_extensions < 2)
return grub_error (GRUB_ERR_BAD_FILE_TYPE,
"insufficient number of extensions for certificate, need at least 2, got %d",
num_extensions);
for (ext = 1; ext <= num_extensions; ext++)
{
oid_path = grub_xasprintf ("tbsCertificate.extensions.?%d.extnID", ext);
if (oid_path == NULL)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error extension OID path is empty");
return err;
}
extnID_size = sizeof (extnID);
result = asn1_read_value (cert, oid_path, extnID, &extnID_size);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading extension OID: %s",
asn1_strerror (result));
goto cleanup_oid_path;
}
critical_path = grub_xasprintf ("tbsCertificate.extensions.?%d.critical", ext);
if (critical_path == NULL)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error critical path is empty");
goto cleanup_oid_path;
}
critical_size = sizeof (critical);
result = asn1_read_value (cert, critical_path, critical, &critical_size);
if (result == ASN1_ELEMENT_NOT_FOUND)
critical[0] = '\0';
else if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error reading extension criticality: %s",
asn1_strerror (result));
goto cleanup_critical_path;
}
value_path = grub_xasprintf ("tbsCertificate.extensions.?%d.extnValue", ext);
if (value_path == NULL)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "error extnValue path is empty");
goto cleanup_critical_path;
}
value = grub_asn1_allocate_and_read (cert, value_path,
"certificate extension value", &value_size);
if (value == NULL)
{
err = grub_errno;
goto cleanup_value_path;
}
/*
* Now we must see if we recognise the OID. If we have an unrecognised
* critical extension we MUST bail.
*/
if (grub_strncmp (keyUsage_oid, extnID, extnID_size) == 0)
{
err = verify_key_usage (value, value_size);
if (err != GRUB_ERR_NONE)
goto cleanup_value;
usage_present++;
}
else if (grub_strncmp (basicConstraints_oid, extnID, extnID_size) == 0)
{
err = verify_basic_constraints (value, value_size);
if (err != GRUB_ERR_NONE)
goto cleanup_value;
constraints_present++;
}
else if (grub_strncmp (extendedKeyUsage_oid, extnID, extnID_size) == 0)
{
err = verify_extended_key_usage (value, value_size);
if (err != GRUB_ERR_NONE)
goto cleanup_value;
extended_usage_present++;
}
else if (grub_strncmp ("TRUE", critical, critical_size) == 0)
{
/*
* Per the RFC, we must not process a certificate with a critical
* extension we do not understand.
*/
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"unhandled critical x509 extension with OID %s", extnID);
goto cleanup_value;
}
grub_free (value);
grub_free (value_path);
grub_free (critical_path);
grub_free (oid_path);
}
if (usage_present != 1)
return grub_error (GRUB_ERR_BAD_FILE_TYPE,
"unexpected number of Key Usage extensions - expected 1, got %d",
usage_present);
if (constraints_present != 1)
return grub_error (GRUB_ERR_BAD_FILE_TYPE,
"unexpected number of basic constraints extensions - expected 1, got %d",
constraints_present);
if (extended_usage_present > 1)
return grub_error (GRUB_ERR_BAD_FILE_TYPE,
"unexpected number of Extended Key Usage extensions - expected 0 or 1, got %d",
extended_usage_present);
return GRUB_ERR_NONE;
cleanup_value:
grub_free (value);
cleanup_value_path:
grub_free (value_path);
cleanup_critical_path:
grub_free (critical_path);
cleanup_oid_path:
grub_free (oid_path);
return err;
}
static void
add_cert_fingerprint (const void *data, const grub_size_t data_size,
grub_x509_cert_t *const cert)
{
/* Add SHA256 hash of certificate. */
grub_crypto_hash ((gcry_md_spec_t *) &_gcry_digest_spec_sha256,
&cert->fingerprint[GRUB_FINGERPRINT_SHA256], data, data_size);
/* Add SHA384 hash of certificate. */
grub_crypto_hash ((gcry_md_spec_t *) &_gcry_digest_spec_sha384,
&cert->fingerprint[GRUB_FINGERPRINT_SHA384], data, data_size);
/* Add SHA512 hash of certificate. */
grub_crypto_hash ((gcry_md_spec_t *) &_gcry_digest_spec_sha512,
&cert->fingerprint[GRUB_FINGERPRINT_SHA512], data, data_size);
}
/*
* Parse a certificate whose DER-encoded form is in @data, of size @data_size.
* Return the results in @results, which must point to an allocated x509
* certificate.
*/
grub_err_t
grub_x509_cert_parse (const void *data, grub_size_t data_size, grub_x509_cert_t *results)
{
grub_int32_t result = 0;
asn1_node cert;
grub_err_t err;
grub_int32_t tmp_size;
grub_int32_t size = (grub_int32_t) data_size;
if (data_size > GRUB_UINT_MAX)
return grub_error (GRUB_ERR_OUT_OF_RANGE,
"cannot parse a certificate where data size > GRUB_UINT_MAX");
result = asn1_create_element (grub_gnutls_pkix_asn, "PKIX1.Certificate", &cert);
if (result != ASN1_SUCCESS)
return grub_error (GRUB_ERR_OUT_OF_MEMORY,
"could not create ASN.1 structure for certificate: %s",
asn1_strerror (result));
result = asn1_der_decoding2 (&cert, data, &size, ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
if (result != ASN1_SUCCESS)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
"could not parse DER for certificate: %s", asn1_error);
goto cleanup;
}
/*
* TBSCertificate ::= SEQUENCE {
* version [0] EXPLICIT Version DEFAULT v1
*/
err = check_version (cert, results);
if (err != GRUB_ERR_NONE)
goto cleanup;
/*
* serialNumber CertificateSerialNumber,
*
* CertificateSerialNumber ::= INTEGER
*/
results->serial = grub_asn1_allocate_and_read (cert, "tbsCertificate.serialNumber",
"certificate serial number", &tmp_size);
if (results->serial == NULL)
{
err = grub_errno;
goto cleanup;
}
/*
* It's safe to cast the signed int to an unsigned here, we know
* length is non-negative.
*/
results->serial_len = tmp_size;
/*
* signature AlgorithmIdentifier,
*
* We don't load the signature or issuer at the moment,
* as we don't attempt x509 verification.
*/
/*
* validity Validity,
*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*
* We can't validate this reasonably, we have no true time source on several
* platforms. For now we do not parse them.
*/
/*
* issuer Name,
*
* This is an X501 name, we parse out just the issuer.
*/
err = read_name (cert, "tbsCertificate.issuer", &results->issuer, &results->issuer_len);
if (err != GRUB_ERR_NONE)
goto cleanup_serial;
/*
* subject Name,
*
* This is an X501 name, we parse out just the CN.
*/
err = read_name (cert, "tbsCertificate.subject", &results->subject, &results->subject_len);
if (err != GRUB_ERR_NONE)
goto cleanup_issuer;
/*
* TBSCertificate ::= SEQUENCE {
* ...
* subjectPublicKeyInfo SubjectPublicKeyInfo,
* ...
*/
err = grub_x509_read_subject_public_key (cert, results);
if (err != GRUB_ERR_NONE)
goto cleanup_name;
/*
* TBSCertificate ::= SEQUENCE {
* ...
* extensions [3] EXPLICIT Extensions OPTIONAL
* -- If present, version MUST be v3
* }
*/
err = verify_extensions (cert);
if (err != GRUB_ERR_NONE)
goto cleanup_mpis;
/*
* We do not read or check the signature on the certificate:
* as discussed we do not try to validate the certificate but trust
* it implictly.
*/
asn1_delete_structure (&cert);
/* Add the fingerprint of the certificate. */
add_cert_fingerprint (data, data_size, results);
return GRUB_ERR_NONE;
cleanup_mpis:
_gcry_mpi_release (results->mpis[GRUB_RSA_PK_MODULUS]);
_gcry_mpi_release (results->mpis[GRUB_RSA_PK_EXPONENT]);
cleanup_name:
grub_free (results->subject);
cleanup_issuer:
grub_free (results->issuer);
cleanup_serial:
grub_free (results->serial);
cleanup:
asn1_delete_structure (&cert);
return err;
}
/*
* Release all the storage associated with the x509 certificate. If the caller
* dynamically allocated the certificate, it must free it. The caller is also
* responsible for maintenance of the linked list.
*/
void
grub_x509_cert_release (grub_x509_cert_t *cert)
{
grub_free (cert->issuer);
grub_free (cert->subject);
grub_free (cert->serial);
_gcry_mpi_release (cert->mpis[GRUB_RSA_PK_MODULUS]);
_gcry_mpi_release (cert->mpis[GRUB_RSA_PK_EXPONENT]);
}
+42 -1
View File
@@ -28,6 +28,7 @@
#include <grub/misc.h> #include <grub/misc.h>
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/partition.h> #include <grub/partition.h>
#include <grub/tpm.h>
#include <grub/types.h> #include <grub/types.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -48,6 +49,22 @@ get_part_uuid (const char *device_name, char **part_uuid)
if (device == NULL) if (device == NULL)
return grub_error (grub_errno, N_("cannot open device: %s"), device_name); return grub_error (grub_errno, N_("cannot open device: %s"), device_name);
if (device->disk == NULL)
{
grub_dprintf ("bli", "%s is not a disk device, partuuid skipped\n", device_name);
*part_uuid = NULL;
grub_device_close (device);
return GRUB_ERR_NONE;
}
if (device->disk->partition == NULL)
{
grub_dprintf ("bli", "%s has no partition, partuuid skipped\n", device_name);
*part_uuid = NULL;
grub_device_close (device);
return GRUB_ERR_NONE;
}
disk = grub_disk_open (device->disk->name); disk = grub_disk_open (device->disk->name);
if (disk == NULL) if (disk == NULL)
{ {
@@ -99,7 +116,7 @@ set_loader_device_part_uuid (void)
status = get_part_uuid (device_name, &part_uuid); status = get_part_uuid (device_name, &part_uuid);
if (status == GRUB_ERR_NONE) if (status == GRUB_ERR_NONE && part_uuid)
status = grub_efi_set_variable_to_string ("LoaderDevicePartUUID", &bli_vendor_guid, part_uuid, status = grub_efi_set_variable_to_string ("LoaderDevicePartUUID", &bli_vendor_guid, part_uuid,
GRUB_EFI_VARIABLE_BOOTSERVICE_ACCESS | GRUB_EFI_VARIABLE_BOOTSERVICE_ACCESS |
GRUB_EFI_VARIABLE_RUNTIME_ACCESS); GRUB_EFI_VARIABLE_RUNTIME_ACCESS);
@@ -111,10 +128,34 @@ set_loader_device_part_uuid (void)
return status; return status;
} }
static grub_err_t
set_loader_active_pcr_banks (void)
{
grub_efi_uint32_t active_pcr_banks;
char *active_pcr_banks_str;
grub_err_t status;
active_pcr_banks = grub_tpm2_active_pcr_banks();
active_pcr_banks_str = grub_xasprintf ("0x%08x", active_pcr_banks);
if (active_pcr_banks_str == NULL)
return grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("cannot allocate active PCR banks string"));
status = grub_efi_set_variable_to_string ("LoaderTpm2ActivePcrBanks",
&bli_vendor_guid,
active_pcr_banks_str,
GRUB_EFI_VARIABLE_BOOTSERVICE_ACCESS |
GRUB_EFI_VARIABLE_RUNTIME_ACCESS);
grub_free (active_pcr_banks_str);
return status;
}
GRUB_MOD_INIT (bli) GRUB_MOD_INIT (bli)
{ {
grub_efi_set_variable_to_string ("LoaderInfo", &bli_vendor_guid, PACKAGE_STRING, grub_efi_set_variable_to_string ("LoaderInfo", &bli_vendor_guid, PACKAGE_STRING,
GRUB_EFI_VARIABLE_BOOTSERVICE_ACCESS | GRUB_EFI_VARIABLE_BOOTSERVICE_ACCESS |
GRUB_EFI_VARIABLE_RUNTIME_ACCESS); GRUB_EFI_VARIABLE_RUNTIME_ACCESS);
set_loader_device_part_uuid (); set_loader_device_part_uuid ();
set_loader_active_pcr_banks ();
/* No error here is critical, other than being logged */
grub_print_error ();
} }
File diff suppressed because it is too large. Load diff
+8 -27
View File
@@ -92,7 +92,6 @@ lock_rom_area (void)
static void static void
fake_bios_data (int use_rom) fake_bios_data (int use_rom)
{ {
unsigned i;
void *acpi, *smbios; void *acpi, *smbios;
grub_uint16_t *ebda_seg_ptr, *low_mem_ptr; grub_uint16_t *ebda_seg_ptr, *low_mem_ptr;
@@ -101,33 +100,15 @@ fake_bios_data (int use_rom)
if ((*ebda_seg_ptr) || (*low_mem_ptr)) if ((*ebda_seg_ptr) || (*low_mem_ptr))
return; return;
acpi = 0; acpi = grub_efi_find_configuration_table (&acpi2_guid);
smbios = 0; grub_dprintf ("efi", "ACPI2: %p\n", acpi);
for (i = 0; i < grub_efi_system_table->num_table_entries; i++) if (!acpi) {
{ acpi = grub_efi_find_configuration_table (&acpi_guid);
grub_guid_t *guid = grub_dprintf ("efi", "ACPI: %p\n", acpi);
&grub_efi_system_table->configuration_table[i].vendor_guid; }
if (! grub_memcmp (guid, &acpi2_guid, sizeof (grub_guid_t))) smbios = grub_efi_find_configuration_table (&smbios_guid);
{ grub_dprintf ("efi", "SMBIOS: %p\n", smbios);
acpi = grub_efi_system_table->configuration_table[i].vendor_table;
grub_dprintf ("efi", "ACPI2: %p\n", acpi);
}
else if (! grub_memcmp (guid, &acpi_guid, sizeof (grub_guid_t)))
{
void *t;
t = grub_efi_system_table->configuration_table[i].vendor_table;
if (! acpi)
acpi = t;
grub_dprintf ("efi", "ACPI: %p\n", t);
}
else if (! grub_memcmp (guid, &smbios_guid, sizeof (grub_guid_t)))
{
smbios = grub_efi_system_table->configuration_table[i].vendor_table;
grub_dprintf ("efi", "SMBIOS: %p\n", smbios);
}
}
*ebda_seg_ptr = FAKE_EBDA_SEG; *ebda_seg_ptr = FAKE_EBDA_SEG;
*low_mem_ptr = (FAKE_EBDA_SEG >> 6); *low_mem_ptr = (FAKE_EBDA_SEG >> 6);
+3 -2
View File
@@ -29,7 +29,7 @@
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
struct known_protocol static struct known_protocol
{ {
grub_guid_t guid; grub_guid_t guid;
const char *name; const char *name;
@@ -96,7 +96,7 @@ grub_cmd_lsefi (grub_command_t cmd __attribute__ ((unused)),
grub_efi_handle_t handle = handles[i]; grub_efi_handle_t handle = handles[i];
grub_efi_status_t status; grub_efi_status_t status;
grub_efi_uintn_t num_protocols; grub_efi_uintn_t num_protocols;
grub_guid_t **protocols; grub_packed_guid_t **protocols;
grub_efi_device_path_t *dp; grub_efi_device_path_t *dp;
grub_printf ("Handle %p\n", handle); grub_printf ("Handle %p\n", handle);
@@ -129,6 +129,7 @@ grub_cmd_lsefi (grub_command_t cmd __attribute__ ((unused)),
} }
grub_free (handles);
return 0; return 0;
} }
+10 -2
View File
@@ -47,6 +47,7 @@ static const struct guid_mapping guid_mappings[] =
{ GRUB_EFI_HOB_LIST_GUID, "HOB LIST"}, { GRUB_EFI_HOB_LIST_GUID, "HOB LIST"},
{ GRUB_EFI_IMAGE_SECURITY_DATABASE_GUID, "IMAGE EXECUTION INFORMATION"}, { GRUB_EFI_IMAGE_SECURITY_DATABASE_GUID, "IMAGE EXECUTION INFORMATION"},
{ GRUB_EFI_LZMA_CUSTOM_DECOMPRESS_GUID, "LZMA CUSTOM DECOMPRESS"}, { GRUB_EFI_LZMA_CUSTOM_DECOMPRESS_GUID, "LZMA CUSTOM DECOMPRESS"},
{ GRUB_EFI_MEMORY_ATTRIBUTES_TABLE_GUID, "MEMORY ATTRIBUTES TABLE"},
{ GRUB_EFI_MEMORY_TYPE_INFORMATION_GUID, "MEMORY TYPE INFO"}, { GRUB_EFI_MEMORY_TYPE_INFORMATION_GUID, "MEMORY TYPE INFO"},
{ GRUB_EFI_MPS_TABLE_GUID, "MPS"}, { GRUB_EFI_MPS_TABLE_GUID, "MPS"},
{ GRUB_EFI_RT_PROPERTIES_TABLE_GUID, "RT PROPERTIES"}, { GRUB_EFI_RT_PROPERTIES_TABLE_GUID, "RT PROPERTIES"},
@@ -54,6 +55,7 @@ static const struct guid_mapping guid_mappings[] =
{ GRUB_EFI_SMBIOS_TABLE_GUID, "SMBIOS"}, { GRUB_EFI_SMBIOS_TABLE_GUID, "SMBIOS"},
{ GRUB_EFI_SMBIOS3_TABLE_GUID, "SMBIOS3"}, { GRUB_EFI_SMBIOS3_TABLE_GUID, "SMBIOS3"},
{ GRUB_EFI_SYSTEM_RESOURCE_TABLE_GUID, "SYSTEM RESOURCE TABLE"}, { GRUB_EFI_SYSTEM_RESOURCE_TABLE_GUID, "SYSTEM RESOURCE TABLE"},
{ GRUB_EFI_TCG2_FINAL_EVENTS_TABLE_GUID, "TCG2 FINAL EVENTS TABLE"},
{ GRUB_EFI_TIANO_CUSTOM_DECOMPRESS_GUID, "TIANO CUSTOM DECOMPRESS"}, { GRUB_EFI_TIANO_CUSTOM_DECOMPRESS_GUID, "TIANO CUSTOM DECOMPRESS"},
{ GRUB_EFI_TSC_FREQUENCY_GUID, "TSC FREQUENCY"}, { GRUB_EFI_TSC_FREQUENCY_GUID, "TSC FREQUENCY"},
}; };
@@ -64,12 +66,18 @@ grub_cmd_lsefisystab (struct grub_command *cmd __attribute__ ((unused)),
char **args __attribute__ ((unused))) char **args __attribute__ ((unused)))
{ {
const grub_efi_system_table_t *st = grub_efi_system_table; const grub_efi_system_table_t *st = grub_efi_system_table;
const grub_efi_uint32_t major_rev = st->hdr.revision >> 16;
const grub_efi_uint32_t minor_rev_upper = (st->hdr.revision & 0xffff) / 10;
const grub_efi_uint32_t minor_rev_lower = (st->hdr.revision & 0xffff) % 10;
grub_efi_configuration_table_t *t; grub_efi_configuration_table_t *t;
unsigned int i; unsigned int i;
grub_printf ("Address: %p\n", st); grub_printf ("Address: %p\n", st);
grub_printf ("Signature: %016" PRIxGRUB_UINT64_T " revision: %08x\n", grub_printf ("Signature: %016" PRIxGRUB_UINT64_T " revision: %u.%u",
st->hdr.signature, st->hdr.revision); st->hdr.signature, major_rev, minor_rev_upper);
if (minor_rev_lower)
grub_printf (".%u", minor_rev_lower);
grub_printf ("\n");
{ {
char *vendor; char *vendor;
grub_uint16_t *vendor_utf16; grub_uint16_t *vendor_utf16;
+6 -12
View File
@@ -136,22 +136,16 @@ grub_cmd_lssal (struct grub_command *cmd __attribute__ ((unused)),
int argc __attribute__ ((unused)), int argc __attribute__ ((unused)),
char **args __attribute__ ((unused))) char **args __attribute__ ((unused)))
{ {
const grub_efi_system_table_t *st = grub_efi_system_table;
grub_efi_configuration_table_t *t = st->configuration_table;
unsigned int i;
static grub_guid_t guid = GRUB_EFI_SAL_TABLE_GUID; static grub_guid_t guid = GRUB_EFI_SAL_TABLE_GUID;
void *table = grub_efi_find_configuration_table (&guid);
for (i = 0; i < st->num_table_entries; i++) if (table == NULL)
{ {
if (grub_memcmp (&guid, &t->vendor_guid, grub_printf ("SAL not found\n");
sizeof (grub_guid_t)) == 0) return GRUB_ERR_NONE;
{
disp_sal (t->vendor_table);
return GRUB_ERR_NONE;
}
t++;
} }
grub_printf ("SAL not found\n");
disp_sal (table);
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
} }
+2 -26
View File
@@ -18,44 +18,20 @@
*/ */
#include <grub/smbios.h> #include <grub/smbios.h>
#include <grub/misc.h>
#include <grub/efi/efi.h> #include <grub/efi/efi.h>
#include <grub/efi/api.h>
struct grub_smbios_eps * struct grub_smbios_eps *
grub_machine_smbios_get_eps (void) grub_machine_smbios_get_eps (void)
{ {
unsigned i;
static grub_guid_t smbios_guid = GRUB_EFI_SMBIOS_TABLE_GUID; static grub_guid_t smbios_guid = GRUB_EFI_SMBIOS_TABLE_GUID;
for (i = 0; i < grub_efi_system_table->num_table_entries; i++) return (struct grub_smbios_eps *) grub_efi_find_configuration_table (&smbios_guid);
{
grub_guid_t *guid =
&grub_efi_system_table->configuration_table[i].vendor_guid;
if (! grub_memcmp (guid, &smbios_guid, sizeof (grub_guid_t)))
return (struct grub_smbios_eps *)
grub_efi_system_table->configuration_table[i].vendor_table;
}
return 0;
} }
struct grub_smbios_eps3 * struct grub_smbios_eps3 *
grub_machine_smbios_get_eps3 (void) grub_machine_smbios_get_eps3 (void)
{ {
unsigned i;
static grub_guid_t smbios3_guid = GRUB_EFI_SMBIOS3_TABLE_GUID; static grub_guid_t smbios3_guid = GRUB_EFI_SMBIOS3_TABLE_GUID;
for (i = 0; i < grub_efi_system_table->num_table_entries; i++) return (struct grub_smbios_eps3 *) grub_efi_find_configuration_table (&smbios3_guid);
{
grub_guid_t *guid =
&grub_efi_system_table->configuration_table[i].vendor_guid;
if (! grub_memcmp (guid, &smbios3_guid, sizeof (grub_guid_t)))
return (struct grub_smbios_eps3 *)
grub_efi_system_table->configuration_table[i].vendor_table;
}
return 0;
} }
+58
View File
@@ -39,6 +39,7 @@ static grub_uint8_t grub_tpm_version;
static grub_int8_t tpm1_present = -1; static grub_int8_t tpm1_present = -1;
static grub_int8_t tpm2_present = -1; static grub_int8_t tpm2_present = -1;
static grub_efi_int64_t tpm2_active_pcr_banks = -1;
static grub_efi_boolean_t static grub_efi_boolean_t
grub_tpm1_present (grub_efi_tpm_protocol_t *tpm) grub_tpm1_present (grub_efi_tpm_protocol_t *tpm)
@@ -112,6 +113,7 @@ grub_tpm_handle_find (grub_efi_handle_t *tpm_handle,
grub_tpm_version = 1; grub_tpm_version = 1;
*protocol_version = 1; *protocol_version = 1;
grub_dprintf ("tpm", "TPM handle Found, version: 1\n"); grub_dprintf ("tpm", "TPM handle Found, version: 1\n");
grub_free (handles);
return 1; return 1;
} }
@@ -124,6 +126,7 @@ grub_tpm_handle_find (grub_efi_handle_t *tpm_handle,
grub_tpm_version = 2; grub_tpm_version = 2;
*protocol_version = 2; *protocol_version = 2;
grub_dprintf ("tpm", "TPM handle Found, version: 2\n"); grub_dprintf ("tpm", "TPM handle Found, version: 2\n");
grub_free (handles);
return 1; return 1;
} }
@@ -292,6 +295,15 @@ grub_tpm_present (void)
{ {
grub_efi_handle_t tpm_handle; grub_efi_handle_t tpm_handle;
grub_efi_uint8_t protocol_version; grub_efi_uint8_t protocol_version;
grub_efi_cc_protocol_t *cc;
/*
* When confidential computing measurement protocol is enabled
* we assume the TPM is present.
*/
cc = grub_efi_locate_protocol (&cc_measurement_guid, NULL);
if (cc != NULL)
return 1;
if (!grub_tpm_handle_find (&tpm_handle, &protocol_version)) if (!grub_tpm_handle_find (&tpm_handle, &protocol_version))
return 0; return 0;
@@ -323,3 +335,49 @@ grub_tpm_present (void)
return grub_tpm2_present (tpm); return grub_tpm2_present (tpm);
} }
} }
grub_uint32_t
grub_tpm2_active_pcr_banks (void)
{
EFI_TCG2_BOOT_SERVICE_CAPABILITY caps;
grub_efi_handle_t tpm_handle;
grub_efi_uint8_t protocol_version;
grub_efi_tpm2_protocol_t *tpm;
grub_efi_uint32_t active_pcr_banks;
grub_efi_status_t status;
if (tpm2_active_pcr_banks >= 0)
return (grub_uint32_t) tpm2_active_pcr_banks;
if (!grub_tpm_handle_find (&tpm_handle, &protocol_version))
return (grub_uint32_t) (tpm2_active_pcr_banks = 0);
if (protocol_version == 1)
return (grub_uint32_t) (tpm2_active_pcr_banks = 0); /* We report TPM2 status. */
tpm = grub_efi_open_protocol (tpm_handle, &tpm2_guid,
GRUB_EFI_OPEN_PROTOCOL_GET_PROTOCOL);
if (tpm == NULL)
{
grub_dprintf ("tpm", "Cannot open TPM2 protocol\n");
return (grub_uint32_t) (tpm2_active_pcr_banks = 0);
}
if (!grub_tpm2_present (tpm))
return (grub_uint32_t) (tpm2_active_pcr_banks = 0);
caps.Size = (grub_uint8_t) sizeof (caps);
status = tpm->get_capability (tpm, &caps);
if (status != GRUB_EFI_SUCCESS)
return (grub_uint32_t) (tpm2_active_pcr_banks = 0);
if (caps.StructureVersion.Major < 1 ||
(caps.StructureVersion.Major == 1 && caps.StructureVersion.Minor < 1))
/* There's a working TPM2 but without querying protocol, let userspace figure it out. */
return (grub_uint32_t) (tpm2_active_pcr_banks = GRUB_UINT_MAX);
status = tpm->get_active_pcr_banks (tpm, &active_pcr_banks);
if (status != GRUB_EFI_SUCCESS)
return (grub_uint32_t) (tpm2_active_pcr_banks = 0); /* Assume none available if the call fails. */
return (grub_uint32_t) (tpm2_active_pcr_banks = active_pcr_banks);
}
+6
View File
@@ -49,6 +49,9 @@ grub_extcmd_dispatcher (struct grub_command *cmd, int argc, char **args,
} }
state = grub_arg_list_alloc (ext, argc, args); state = grub_arg_list_alloc (ext, argc, args);
if (state == NULL)
return grub_errno;
if (grub_arg_parse (ext, argc, args, state, &new_args, &new_argc)) if (grub_arg_parse (ext, argc, args, state, &new_args, &new_argc))
{ {
context.state = state; context.state = state;
@@ -136,6 +139,9 @@ grub_register_extcmd_lockdown (const char *name, grub_extcmd_func_t func,
void void
grub_unregister_extcmd (grub_extcmd_t ext) grub_unregister_extcmd (grub_extcmd_t ext)
{ {
if (ext == NULL)
return;
grub_unregister_command (ext->cmd); grub_unregister_command (ext->cmd);
grub_free (ext); grub_free (ext);
} }
+2
View File
@@ -306,6 +306,8 @@ grub_cmd_file (grub_extcmd_context_t ctxt, int argc, char **args)
elf = grub_elf_file (file, file->name); elf = grub_elf_file (file, file->name);
if (elf == NULL)
break;
if (elf->ehdr.ehdr32.e_type != grub_cpu_to_le16_compile_time (ET_EXEC) if (elf->ehdr.ehdr32.e_type != grub_cpu_to_le16_compile_time (ET_EXEC)
|| elf->ehdr.ehdr32.e_ident[EI_DATA] != ELFDATA2LSB) || elf->ehdr.ehdr32.e_ident[EI_DATA] != ELFDATA2LSB)
break; break;
+1 -1
View File
@@ -73,7 +73,7 @@ hash_file (grub_file_t file, const gcry_md_spec_t *hash, void *result)
if (!readbuf || !context) if (!readbuf || !context)
goto fail; goto fail;
hash->init (context); hash->init (context, 0);
while (1) while (1)
{ {
grub_ssize_t r; grub_ssize_t r;
+6 -1
View File
@@ -24,6 +24,7 @@
#include <grub/lib/hexdump.h> #include <grub/lib/hexdump.h>
#include <grub/extcmd.h> #include <grub/extcmd.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/lockdown.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -51,7 +52,11 @@ grub_cmd_hexdump (grub_extcmd_context_t ctxt, int argc, char **args)
length = (state[1].set) ? grub_strtoul (state[1].arg, 0, 0) : 256; length = (state[1].set) ? grub_strtoul (state[1].arg, 0, 0) : 256;
if (!grub_strcmp (args[0], "(mem)")) if (!grub_strcmp (args[0], "(mem)"))
hexdump (skip, (char *) (grub_addr_t) skip, length); {
if (grub_is_lockdown() == GRUB_LOCKDOWN_ENABLED)
return grub_error (GRUB_ERR_ACCESS_DENIED, N_("memory reading is disabled in lockdown mode"));
hexdump (skip, (char *) (grub_addr_t) skip, length);
}
else if ((args[0][0] == '(') && (args[0][namelen - 1] == ')')) else if ((args[0][0] == '(') && (args[0][namelen - 1] == ')'))
{ {
grub_disk_t disk; grub_disk_t disk;
+3 -3
View File
@@ -104,13 +104,13 @@ static grub_command_t cmd, cmd_clean, cmd_set;
GRUB_MOD_INIT(cmostest) GRUB_MOD_INIT(cmostest)
{ {
cmd = grub_register_command ("cmostest", grub_cmd_cmostest, cmd = grub_register_command_lockdown ("cmostest", grub_cmd_cmostest,
N_("BYTE:BIT"), N_("BYTE:BIT"),
N_("Test bit at BYTE:BIT in CMOS.")); N_("Test bit at BYTE:BIT in CMOS."));
cmd_clean = grub_register_command ("cmosclean", grub_cmd_cmosclean, cmd_clean = grub_register_command_lockdown ("cmosclean", grub_cmd_cmosclean,
N_("BYTE:BIT"), N_("BYTE:BIT"),
N_("Clear bit at BYTE:BIT in CMOS.")); N_("Clear bit at BYTE:BIT in CMOS."));
cmd_set = grub_register_command ("cmosset", grub_cmd_cmosset, cmd_set = grub_register_command_lockdown ("cmosset", grub_cmd_cmosset,
N_("BYTE:BIT"), N_("BYTE:BIT"),
/* TRANSLATORS: A bit may be either set (1) or clear (0). */ /* TRANSLATORS: A bit may be either set (1) or clear (0). */
N_("Set bit at BYTE:BIT in CMOS.")); N_("Set bit at BYTE:BIT in CMOS."));
+7 -18
View File
@@ -26,7 +26,7 @@
#include <grub/extcmd.h> #include <grub/extcmd.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/i386/cpuid.h> #include <grub/i386/cpuid.h>
#include <grub/i386/rdmsr.h> #include <grub/i386/msr.h>
GRUB_MOD_LICENSE("GPLv3+"); GRUB_MOD_LICENSE("GPLv3+");
@@ -42,27 +42,16 @@ static const struct grub_arg_option options[] =
static grub_err_t static grub_err_t
grub_cmd_msr_read (grub_extcmd_context_t ctxt, int argc, char **argv) grub_cmd_msr_read (grub_extcmd_context_t ctxt, int argc, char **argv)
{ {
grub_uint32_t manufacturer[3], max_cpuid, a, b, c, features, addr; grub_err_t err;
grub_uint32_t addr;
grub_uint64_t value; grub_uint64_t value;
const char *ptr; const char *ptr;
char buf[sizeof("1122334455667788")]; char buf[sizeof("1122334455667788")];
/* err = grub_cpu_is_msr_supported ();
* The CPUID instruction should be used to determine whether MSRs
* are supported. (CPUID.01H:EDX[5] = 1)
*/
if (! grub_cpu_is_cpuid_supported ())
return grub_error (GRUB_ERR_BUG, N_("unsupported instruction"));
grub_cpuid (0, max_cpuid, manufacturer[0], manufacturer[2], manufacturer[1]); if (err != GRUB_ERR_NONE)
return grub_error (err, N_("RDMSR is unsupported"));
if (max_cpuid < 1)
return grub_error (GRUB_ERR_BUG, N_("unsupported instruction"));
grub_cpuid (1, a, b, c, features);
if (!(features & (1 << 5)))
return grub_error (GRUB_ERR_BUG, N_("unsupported instruction"));
if (argc != 1) if (argc != 1)
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument expected")); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument expected"));
@@ -76,7 +65,7 @@ grub_cmd_msr_read (grub_extcmd_context_t ctxt, int argc, char **argv)
if (*ptr != '\0') if (*ptr != '\0')
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("invalid argument")); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("invalid argument"));
value = grub_msr_read (addr); value = grub_rdmsr (addr);
if (ctxt->state[0].set) if (ctxt->state[0].set)
{ {
+7 -18
View File
@@ -27,7 +27,7 @@
#include <grub/lockdown.h> #include <grub/lockdown.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/i386/cpuid.h> #include <grub/i386/cpuid.h>
#include <grub/i386/wrmsr.h> #include <grub/i386/msr.h>
GRUB_MOD_LICENSE("GPLv3+"); GRUB_MOD_LICENSE("GPLv3+");
@@ -36,26 +36,15 @@ static grub_command_t cmd_write;
static grub_err_t static grub_err_t
grub_cmd_msr_write (grub_command_t cmd __attribute__ ((unused)), int argc, char **argv) grub_cmd_msr_write (grub_command_t cmd __attribute__ ((unused)), int argc, char **argv)
{ {
grub_uint32_t manufacturer[3], max_cpuid, a, b, c, features, addr; grub_err_t err;
grub_uint32_t addr;
grub_uint64_t value; grub_uint64_t value;
const char *ptr; const char *ptr;
/* err = grub_cpu_is_msr_supported ();
* The CPUID instruction should be used to determine whether MSRs
* are supported. (CPUID.01H:EDX[5] = 1)
*/
if (!grub_cpu_is_cpuid_supported ())
return grub_error (GRUB_ERR_BUG, N_("unsupported instruction"));
grub_cpuid (0, max_cpuid, manufacturer[0], manufacturer[2], manufacturer[1]); if (err != GRUB_ERR_NONE)
return grub_error (err, N_("WRMSR is unsupported"));
if (max_cpuid < 1)
return grub_error (GRUB_ERR_BUG, N_("unsupported instruction"));
grub_cpuid (1, a, b, c, features);
if (!(features & (1 << 5)))
return grub_error (GRUB_ERR_BUG, N_("unsupported instruction"));
if (argc != 2) if (argc != 2)
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("two arguments expected")); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("two arguments expected"));
@@ -77,7 +66,7 @@ grub_cmd_msr_write (grub_command_t cmd __attribute__ ((unused)), int argc, char
if (*ptr != '\0') if (*ptr != '\0')
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("invalid argument")); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("invalid argument"));
grub_msr_write (addr, value); grub_wrmsr (addr, value);
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
} }
+9 -94
View File
@@ -23,109 +23,24 @@
#include <grub/types.h> #include <grub/types.h>
#include <grub/tpm.h> #include <grub/tpm.h>
#include <grub/ieee1275/ieee1275.h> #include <grub/ieee1275/ieee1275.h>
#include <grub/ieee1275/tpm.h>
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/misc.h> #include <grub/misc.h>
static grub_ieee1275_ihandle_t tpm_ihandle;
static grub_uint8_t tpm_version;
#define IEEE1275_IHANDLE_INVALID ((grub_ieee1275_ihandle_t) 0)
static void
tpm_get_tpm_version (void)
{
grub_ieee1275_phandle_t vtpm;
char buffer[20];
if (!grub_ieee1275_finddevice ("/vdevice/vtpm", &vtpm) &&
!grub_ieee1275_get_property (vtpm, "compatible", buffer,
sizeof (buffer), NULL) &&
!grub_strcmp (buffer, "IBM,vtpm20"))
tpm_version = 2;
}
static grub_err_t
tpm_init (void)
{
static int init_success = 0;
if (!init_success)
{
if (grub_ieee1275_open ("/vdevice/vtpm", &tpm_ihandle) < 0)
{
tpm_ihandle = IEEE1275_IHANDLE_INVALID;
return GRUB_ERR_UNKNOWN_DEVICE;
}
init_success = 1;
tpm_get_tpm_version ();
}
return GRUB_ERR_NONE;
}
static int
ibmvtpm_2hash_ext_log (grub_uint8_t pcrindex,
grub_uint32_t eventtype,
const char *description,
grub_size_t description_size,
void *buf, grub_size_t size)
{
struct tpm_2hash_ext_log
{
struct grub_ieee1275_common_hdr common;
grub_ieee1275_cell_t method;
grub_ieee1275_cell_t ihandle;
grub_ieee1275_cell_t size;
grub_ieee1275_cell_t buf;
grub_ieee1275_cell_t description_size;
grub_ieee1275_cell_t description;
grub_ieee1275_cell_t eventtype;
grub_ieee1275_cell_t pcrindex;
grub_ieee1275_cell_t catch_result;
grub_ieee1275_cell_t rc;
};
struct tpm_2hash_ext_log args;
INIT_IEEE1275_COMMON (&args.common, "call-method", 8, 2);
args.method = (grub_ieee1275_cell_t) "2hash-ext-log";
args.ihandle = tpm_ihandle;
args.pcrindex = pcrindex;
args.eventtype = eventtype;
args.description = (grub_ieee1275_cell_t) description;
args.description_size = description_size;
args.buf = (grub_ieee1275_cell_t) buf;
args.size = (grub_ieee1275_cell_t) size;
if (IEEE1275_CALL_ENTRY_FN (&args) == -1)
return -1;
/*
* catch_result is set if firmware does not support 2hash-ext-log
* rc is GRUB_IEEE1275_CELL_FALSE (0) on failure
*/
if ((args.catch_result) || args.rc == GRUB_IEEE1275_CELL_FALSE)
return -1;
return 0;
}
static grub_err_t static grub_err_t
tpm2_log_event (unsigned char *buf, grub_size_t size, grub_uint8_t pcr, tpm2_log_event (unsigned char *buf, grub_size_t size, grub_uint8_t pcr,
const char *description) const char *description)
{ {
static int error_displayed = 0; static int error_displayed = 0;
int rc; grub_err_t err;
rc = ibmvtpm_2hash_ext_log (pcr, EV_IPL, err = grub_ieee1275_ibmvtpm_2hash_ext_log (pcr, EV_IPL,
description, grub_strlen(description) + 1, description, grub_strlen(description) + 1,
buf, size); buf, size);
if (rc && !error_displayed) if (err != GRUB_ERR_NONE && !error_displayed)
{ {
error_displayed++; error_displayed++;
return grub_error (GRUB_ERR_BAD_DEVICE, return err;
"2HASH-EXT-LOG failed: Firmware is likely too old.\n");
} }
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
@@ -138,7 +53,7 @@ grub_tpm_measure (unsigned char *buf, grub_size_t size, grub_uint8_t pcr,
grub_dprintf ("tpm", "log_event, pcr = %d, size = 0x%" PRIxGRUB_SIZE ", %s\n", grub_dprintf ("tpm", "log_event, pcr = %d, size = 0x%" PRIxGRUB_SIZE ", %s\n",
pcr, size, description); pcr, size, description);
if (tpm_version == 2) if (grub_ieee1275_tpm_ihandle != GRUB_IEEE1275_IHANDLE_INVALID)
return tpm2_log_event (buf, size, pcr, description); return tpm2_log_event (buf, size, pcr, description);
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
@@ -151,5 +66,5 @@ grub_tpm_present (void)
* Call tpm_init() "late" rather than from GRUB_MOD_INIT() so that device nodes * Call tpm_init() "late" rather than from GRUB_MOD_INIT() so that device nodes
* can be found. * can be found.
*/ */
return tpm_init() == GRUB_ERR_NONE; return grub_ieee1275_tpm_init() == GRUB_ERR_NONE;
} }
+5 -6
View File
@@ -143,7 +143,7 @@ legacy_file (const char *filename)
args[0] = oldname; args[0] = oldname;
grub_normal_add_menu_entry (1, args, NULL, NULL, "legacy", grub_normal_add_menu_entry (1, args, NULL, NULL, "legacy",
NULL, NULL, NULL, NULL,
entrysrc, 0); entrysrc, 0, NULL);
grub_free (args); grub_free (args);
entrysrc[0] = 0; entrysrc[0] = 0;
grub_free (oldname); grub_free (oldname);
@@ -198,14 +198,13 @@ legacy_file (const char *filename)
const char **args = grub_malloc (sizeof (args[0])); const char **args = grub_malloc (sizeof (args[0]));
if (!args) if (!args)
{ {
grub_file_close (file);
grub_free (suffix); grub_free (suffix);
grub_free (entrysrc); grub_free (entrysrc);
return grub_errno; return grub_errno;
} }
args[0] = entryname; args[0] = entryname;
grub_normal_add_menu_entry (1, args, NULL, NULL, NULL, grub_normal_add_menu_entry (1, args, NULL, NULL, NULL,
NULL, NULL, entrysrc, 0); NULL, NULL, entrysrc, 0, NULL);
grub_free (args); grub_free (args);
} }
@@ -625,7 +624,7 @@ check_password_md5_real (const char *entered,
if (!ctx) if (!ctx)
return 0; return 0;
GRUB_MD_MD5->init (ctx); GRUB_MD_MD5->init (ctx, 0);
GRUB_MD_MD5->write (ctx, entered, enteredlen); GRUB_MD_MD5->write (ctx, entered, enteredlen);
GRUB_MD_MD5->write (ctx, pw->salt + 3, pw->saltlen - 3); GRUB_MD_MD5->write (ctx, pw->salt + 3, pw->saltlen - 3);
GRUB_MD_MD5->write (ctx, entered, enteredlen); GRUB_MD_MD5->write (ctx, entered, enteredlen);
@@ -633,7 +632,7 @@ check_password_md5_real (const char *entered,
GRUB_MD_MD5->final (ctx); GRUB_MD_MD5->final (ctx);
grub_memcpy (alt_result, digest, MD5_HASHLEN); grub_memcpy (alt_result, digest, MD5_HASHLEN);
GRUB_MD_MD5->init (ctx); GRUB_MD_MD5->init (ctx, 0);
GRUB_MD_MD5->write (ctx, entered, enteredlen); GRUB_MD_MD5->write (ctx, entered, enteredlen);
GRUB_MD_MD5->write (ctx, pw->salt, pw->saltlen); /* include the $1$ header */ GRUB_MD_MD5->write (ctx, pw->salt, pw->saltlen); /* include the $1$ header */
for (i = enteredlen; i > 16; i -= 16) for (i = enteredlen; i > 16; i -= 16)
@@ -649,7 +648,7 @@ check_password_md5_real (const char *entered,
{ {
grub_memcpy (alt_result, digest, 16); grub_memcpy (alt_result, digest, 16);
GRUB_MD_MD5->init (ctx); GRUB_MD_MD5->init (ctx, 0);
if ((i & 1) != 0) if ((i & 1) != 0)
GRUB_MD_MD5->write (ctx, entered, enteredlen); GRUB_MD_MD5->write (ctx, entered, enteredlen);
else else
+68 -59
View File
@@ -87,37 +87,44 @@ grub_ls_list_devices (int longlist)
struct grub_ls_list_files_ctx struct grub_ls_list_files_ctx
{ {
char *dirname; char *dirname;
char *filename;
int all; int all;
int human; int human;
int longlist;
int print_dirhdr;
}; };
/* Helper for grub_ls_list_files. */ /* Helper for grub_ls_list_files. */
static int static int
print_files (const char *filename, const struct grub_dirhook_info *info, print_file (const char *filename, const struct grub_dirhook_info *info,
void *data)
{
struct grub_ls_list_files_ctx *ctx = data;
if (ctx->all || filename[0] != '.')
grub_printf ("%s%s ", filename, info->dir ? "/" : "");
return 0;
}
/* Helper for grub_ls_list_files. */
static int
print_files_long (const char *filename, const struct grub_dirhook_info *info,
void *data) void *data)
{ {
char *pathname = NULL;
struct grub_ls_list_files_ctx *ctx = data; struct grub_ls_list_files_ctx *ctx = data;
if ((! ctx->all) && (filename[0] == '.')) if ((! ctx->all) && (filename[0] == '.'))
return 0; return 0;
if ((ctx->filename != NULL) && (grub_strcmp (filename, ctx->filename) != 0))
return 0;
if (ctx->print_dirhdr)
{
grub_printf ("%s:\n", ctx->dirname);
ctx->print_dirhdr = 0;
}
if (! ctx->longlist)
{
if (ctx->filename != NULL)
grub_xputs (ctx->dirname);
grub_printf ("%s%s ", filename, info->dir ? "/" : "");
return 0;
}
if (! info->dir) if (! info->dir)
{ {
grub_file_t file; grub_file_t file;
char *pathname;
if (ctx->dirname[grub_strlen (ctx->dirname) - 1] == '/') if (ctx->dirname[grub_strlen (ctx->dirname) - 1] == '/')
pathname = grub_xasprintf ("%s%s", ctx->dirname, filename); pathname = grub_xasprintf ("%s%s", ctx->dirname, filename);
@@ -131,20 +138,19 @@ print_files_long (const char *filename, const struct grub_dirhook_info *info,
should be reported as directories. */ should be reported as directories. */
file = grub_file_open (pathname, GRUB_FILE_TYPE_GET_SIZE file = grub_file_open (pathname, GRUB_FILE_TYPE_GET_SIZE
| GRUB_FILE_TYPE_NO_DECOMPRESS); | GRUB_FILE_TYPE_NO_DECOMPRESS);
if (! file) if (file)
{ {
grub_errno = 0; if (! ctx->human)
grub_free (pathname); grub_printf ("%-12llu", (unsigned long long) file->size);
return 0; else
} grub_printf ("%-12s", grub_get_human_size (file->size,
if (! ctx->human)
grub_printf ("%-12llu", (unsigned long long) file->size);
else
grub_printf ("%-12s", grub_get_human_size (file->size,
GRUB_HUMAN_SIZE_SHORT)); GRUB_HUMAN_SIZE_SHORT));
grub_file_close (file); grub_file_close (file);
grub_free (pathname); }
else
grub_xputs ("????????????");
grub_errno = GRUB_ERR_NONE;
} }
else else
grub_printf ("%-12s", _("DIR")); grub_printf ("%-12s", _("DIR"));
@@ -165,13 +171,22 @@ print_files_long (const char *filename, const struct grub_dirhook_info *info,
datetime.day, datetime.hour, datetime.day, datetime.hour,
datetime.minute, datetime.second); datetime.minute, datetime.second);
} }
grub_printf ("%s%s\n", filename, info->dir ? "/" : ""); /*
* Only print the full path when listing a file path given as an argument
* to ls, i.e. when ctx->filename != NULL. File listings that are printed
* due to showing the contents of a directory do not need a full path because
* the full path to the directory will have already been printed.
*/
grub_printf ("%s%s\n", (ctx->filename != NULL) ? pathname : filename,
info->dir ? "/" : "");
grub_free (pathname);
return 0; return 0;
} }
static grub_err_t static grub_err_t
grub_ls_list_files (char *dirname, int longlist, int all, int human) grub_ls_list_files (char *dirname, int longlist, int all, int human, int dirhdr)
{ {
char *device_name; char *device_name;
grub_fs_t fs; grub_fs_t fs;
@@ -216,44 +231,38 @@ grub_ls_list_files (char *dirname, int longlist, int all, int human)
{ {
struct grub_ls_list_files_ctx ctx = { struct grub_ls_list_files_ctx ctx = {
.dirname = dirname, .dirname = dirname,
.filename = NULL,
.all = all, .all = all,
.human = human .human = human,
.longlist = longlist,
.print_dirhdr = dirhdr
}; };
if (longlist) (fs->fs_dir) (dev, path, print_file, &ctx);
(fs->fs_dir) (dev, path, print_files_long, &ctx);
else
(fs->fs_dir) (dev, path, print_files, &ctx);
if (grub_errno == GRUB_ERR_BAD_FILE_TYPE if (grub_errno == GRUB_ERR_BAD_FILE_TYPE
&& path[grub_strlen (path) - 1] != '/') && path[grub_strlen (path) - 1] != '/')
{ {
/*
* Reset errno as it is currently set, but will cause subsequent code
* to think there is an error.
*/
grub_errno = GRUB_ERR_NONE;
/* PATH might be a regular file. */ /* PATH might be a regular file. */
char *p; ctx.print_dirhdr = 0;
grub_file_t file; ctx.filename = grub_strrchr (dirname, '/');
struct grub_dirhook_info info; if (ctx.filename == NULL)
grub_errno = 0; goto fail;
++(ctx.filename);
file = grub_file_open (dirname, GRUB_FILE_TYPE_GET_SIZE ctx.dirname = grub_strndup (dirname, ctx.filename - dirname);
| GRUB_FILE_TYPE_NO_DECOMPRESS); if (ctx.dirname == NULL)
if (! file)
goto fail; goto fail;
grub_file_close (file); (fs->fs_dir) (dev, ctx.dirname + (path - dirname), print_file, &ctx);
p = grub_strrchr (dirname, '/') + 1; grub_free (ctx.dirname);
dirname = grub_strndup (dirname, p - dirname);
if (! dirname)
goto fail;
all = 1;
grub_memset (&info, 0, sizeof (info));
if (longlist)
print_files_long (p, &info, &ctx);
else
print_files (p, &info, &ctx);
grub_free (dirname);
} }
if (grub_errno == GRUB_ERR_NONE) if (grub_errno == GRUB_ERR_NONE)
@@ -268,7 +277,7 @@ grub_ls_list_files (char *dirname, int longlist, int all, int human)
grub_free (device_name); grub_free (device_name);
return 0; return GRUB_ERR_NONE;
} }
static grub_err_t static grub_err_t
@@ -281,10 +290,10 @@ grub_cmd_ls (grub_extcmd_context_t ctxt, int argc, char **args)
grub_ls_list_devices (state[0].set); grub_ls_list_devices (state[0].set);
else else
for (i = 0; i < argc; i++) for (i = 0; i < argc; i++)
grub_ls_list_files (args[i], state[0].set, state[2].set, grub_ls_list_files (args[i], state[0].set, state[2].set, state[1].set,
state[1].set); argc > 1);
return 0; return GRUB_ERR_NONE;
} }
static grub_extcmd_t cmd; static grub_extcmd_t cmd;
+12 -9
View File
@@ -122,17 +122,20 @@ grub_cmd_write (grub_command_t cmd, int argc, char **argv)
GRUB_MOD_INIT(memrw) GRUB_MOD_INIT(memrw)
{ {
cmd_read_byte = cmd_read_byte =
grub_register_extcmd ("read_byte", grub_cmd_read, 0, grub_register_extcmd_lockdown ("read_byte", grub_cmd_read, 0,
N_("ADDR"), N_("Read 8-bit value from ADDR."), N_("ADDR"),
options); N_("Read 8-bit value from ADDR."),
options);
cmd_read_word = cmd_read_word =
grub_register_extcmd ("read_word", grub_cmd_read, 0, grub_register_extcmd_lockdown ("read_word", grub_cmd_read, 0,
N_("ADDR"), N_("Read 16-bit value from ADDR."), N_("ADDR"),
options); N_("Read 16-bit value from ADDR."),
options);
cmd_read_dword = cmd_read_dword =
grub_register_extcmd ("read_dword", grub_cmd_read, 0, grub_register_extcmd_lockdown ("read_dword", grub_cmd_read, 0,
N_("ADDR"), N_("Read 32-bit value from ADDR."), N_("ADDR"),
options); N_("Read 32-bit value from ADDR."),
options);
cmd_write_byte = cmd_write_byte =
grub_register_command_lockdown ("write_byte", grub_cmd_write, grub_register_command_lockdown ("write_byte", grub_cmd_write,
N_("ADDR VALUE [MASK]"), N_("ADDR VALUE [MASK]"),
+16 -1
View File
@@ -53,6 +53,18 @@ grub_cmd_lsfreemem (grub_command_t cmd __attribute__ ((unused)),
return 0; return 0;
} }
static grub_err_t
grub_cmd_lsmemregions (grub_command_t cmd __attribute__ ((unused)),
int argc __attribute__ ((unused)),
char **args __attribute__ ((unused)))
{
#ifndef GRUB_MACHINE_EMU
grub_mm_dump_regions ();
#endif
return 0;
}
static grub_err_t static grub_err_t
grub_cmd_stress_big_allocs (grub_command_t cmd __attribute__ ((unused)), grub_cmd_stress_big_allocs (grub_command_t cmd __attribute__ ((unused)),
@@ -132,7 +144,7 @@ grub_cmd_stress_big_allocs (grub_command_t cmd __attribute__ ((unused)),
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
} }
static grub_command_t cmd_lsmem, cmd_lsfreemem, cmd_sba; static grub_command_t cmd_lsmem, cmd_lsfreemem, cmd_lsmemregions, cmd_sba;
GRUB_MOD_INIT (memtools) GRUB_MOD_INIT (memtools)
{ {
@@ -140,6 +152,8 @@ GRUB_MOD_INIT (memtools)
0, N_("List free and allocated memory blocks.")); 0, N_("List free and allocated memory blocks."));
cmd_lsfreemem = grub_register_command ("lsfreemem", grub_cmd_lsfreemem, cmd_lsfreemem = grub_register_command ("lsfreemem", grub_cmd_lsfreemem,
0, N_("List free memory blocks.")); 0, N_("List free memory blocks."));
cmd_lsmemregions = grub_register_command ("lsmemregions", grub_cmd_lsmemregions,
0, N_("List memory regions."));
cmd_sba = grub_register_command ("stress_big_allocs", grub_cmd_stress_big_allocs, cmd_sba = grub_register_command ("stress_big_allocs", grub_cmd_stress_big_allocs,
0, N_("Stress test large allocations.")); 0, N_("Stress test large allocations."));
} }
@@ -148,5 +162,6 @@ GRUB_MOD_FINI (memtools)
{ {
grub_unregister_command (cmd_lsmem); grub_unregister_command (cmd_lsmem);
grub_unregister_command (cmd_lsfreemem); grub_unregister_command (cmd_lsfreemem);
grub_unregister_command (cmd_lsmemregions);
grub_unregister_command (cmd_sba); grub_unregister_command (cmd_sba);
} }
+8 -3
View File
@@ -78,7 +78,7 @@ grub_normal_add_menu_entry (int argc, const char **args,
char **classes, const char *id, char **classes, const char *id,
const char *users, const char *hotkey, const char *users, const char *hotkey,
const char *prefix, const char *sourcecode, const char *prefix, const char *sourcecode,
int submenu) int submenu, grub_blsuki_entry_t *blsuki)
{ {
int menu_hotkey = 0; int menu_hotkey = 0;
char **menu_args = NULL; char **menu_args = NULL;
@@ -188,6 +188,7 @@ grub_normal_add_menu_entry (int argc, const char **args,
(*last)->args = menu_args; (*last)->args = menu_args;
(*last)->sourcecode = menu_sourcecode; (*last)->sourcecode = menu_sourcecode;
(*last)->submenu = submenu; (*last)->submenu = submenu;
(*last)->blsuki = blsuki;
menu->size++; menu->size++;
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
@@ -265,6 +266,9 @@ grub_cmd_menuentry (grub_extcmd_context_t ctxt, int argc, char **args)
if (! argc) if (! argc)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "missing arguments"); return grub_error (GRUB_ERR_BAD_ARGUMENT, "missing arguments");
if (! grub_strlen (args[argc - 1]))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "menuentry title is missing");
if (ctxt->state[3].set && ctxt->script) if (ctxt->state[3].set && ctxt->script)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "multiple menuentry definitions"); return grub_error (GRUB_ERR_BAD_ARGUMENT, "multiple menuentry definitions");
@@ -286,7 +290,8 @@ grub_cmd_menuentry (grub_extcmd_context_t ctxt, int argc, char **args)
users, users,
ctxt->state[2].arg, 0, ctxt->state[2].arg, 0,
ctxt->state[3].arg, ctxt->state[3].arg,
ctxt->extcmd->cmd->name[0] == 's'); ctxt->extcmd->cmd->name[0] == 's',
NULL);
src = args[argc - 1]; src = args[argc - 1];
args[argc - 1] = NULL; args[argc - 1] = NULL;
@@ -303,7 +308,7 @@ grub_cmd_menuentry (grub_extcmd_context_t ctxt, int argc, char **args)
ctxt->state[0].args, ctxt->state[4].arg, ctxt->state[0].args, ctxt->state[4].arg,
users, users,
ctxt->state[2].arg, prefix, src + 1, ctxt->state[2].arg, prefix, src + 1,
ctxt->extcmd->cmd->name[0] == 's'); ctxt->extcmd->cmd->name[0] == 's', NULL);
src[len - 1] = ch; src[len - 1] = ch;
args[argc - 1] = src; args[argc - 1] = src;
+14 -3
View File
@@ -29,6 +29,10 @@
#include <grub/command.h> #include <grub/command.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#ifdef GRUB_MACHINE_EFI
#include <grub/cryptodisk.h>
#endif
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
/* cat FILE */ /* cat FILE */
@@ -167,7 +171,7 @@ grub_mini_cmd_lsmod (struct grub_command *cmd __attribute__ ((unused)),
{ {
grub_dl_dep_t dep; grub_dl_dep_t dep;
grub_printf ("%s\t%d\t\t", mod->name, mod->ref_count); grub_printf ("%s\t%" PRIuGRUB_UINT64_T "\t\t", mod->name, mod->ref_count);
for (dep = mod->dep; dep; dep = dep->next) for (dep = mod->dep; dep; dep = dep->next)
{ {
if (dep != mod->dep) if (dep != mod->dep)
@@ -187,6 +191,13 @@ grub_mini_cmd_exit (struct grub_command *cmd __attribute__ ((unused)),
int argc __attribute__ ((unused)), int argc __attribute__ ((unused)),
char *argv[] __attribute__ ((unused))) char *argv[] __attribute__ ((unused)))
{ {
#ifdef GRUB_MACHINE_EFI
/*
* The "exit" command is often used to launch the next boot application.
* So, erase the secrets.
*/
grub_cryptodisk_erasesecrets ();
#endif
grub_exit (); grub_exit ();
/* Not reached. */ /* Not reached. */
} }
@@ -203,8 +214,8 @@ GRUB_MOD_INIT(minicmd)
grub_register_command ("help", grub_mini_cmd_help, grub_register_command ("help", grub_mini_cmd_help,
0, N_("Show this message.")); 0, N_("Show this message."));
cmd_dump = cmd_dump =
grub_register_command ("dump", grub_mini_cmd_dump, grub_register_command_lockdown ("dump", grub_mini_cmd_dump,
N_("ADDR [SIZE]"), N_("Show memory contents.")); N_("ADDR [SIZE]"), N_("Show memory contents."));
cmd_rmmod = cmd_rmmod =
grub_register_command ("rmmod", grub_mini_cmd_rmmod, grub_register_command ("rmmod", grub_mini_cmd_rmmod,
N_("MODULE"), N_("Remove a module.")); N_("MODULE"), N_("Remove a module."));
+36 -86
View File
@@ -136,41 +136,23 @@ struct signature_v4_header
grub_uint16_t hashed_sub; grub_uint16_t hashed_sub;
} GRUB_PACKED; } GRUB_PACKED;
const char *hashes[] = {
[0x01] = "md5",
[0x02] = "sha1",
[0x03] = "ripemd160",
[0x08] = "sha256",
[0x09] = "sha384",
[0x0a] = "sha512",
[0x0b] = "sha224"
};
struct gcry_pk_spec *grub_crypto_pk_dsa;
struct gcry_pk_spec *grub_crypto_pk_ecdsa;
struct gcry_pk_spec *grub_crypto_pk_rsa;
static int
dsa_pad (gcry_mpi_t *hmpi, grub_uint8_t *hval,
const gcry_md_spec_t *hash, struct grub_public_subkey *sk);
static int
rsa_pad (gcry_mpi_t *hmpi, grub_uint8_t *hval,
const gcry_md_spec_t *hash, struct grub_public_subkey *sk);
struct struct
{ {
const char *name; const char *name;
const char *sigsexp;
grub_size_t nmpisig; grub_size_t nmpisig;
const char *pubsexp;
grub_size_t nmpipub; grub_size_t nmpipub;
struct gcry_pk_spec **algo; struct gcry_pk_spec **algo;
int (*pad) (gcry_mpi_t *hmpi, grub_uint8_t *hval, const char *padding;
const gcry_md_spec_t *hash, struct grub_public_subkey *sk);
const char *module; const char *module;
} pkalgos[] = } pkalgos[] =
{ {
[1] = { "rsa", 1, 2, &grub_crypto_pk_rsa, rsa_pad, "gcry_rsa" }, [1] = { "rsa", "(sig-val (rsa (s %M)))", 1, "(public-key (dsa (n %M) (e %M)))", 2, &grub_crypto_pk_rsa, "pkcs1", "gcry_rsa" },
[3] = { "rsa", 1, 2, &grub_crypto_pk_rsa, rsa_pad, "gcry_rsa" }, [3] = { "rsa", "(sig-val (rsa (s %M)))", 1, "(public-key (dsa (n %M) (e %M)))", 2, &grub_crypto_pk_rsa, "pkcs1", "gcry_rsa" },
[17] = { "dsa", 2, 4, &grub_crypto_pk_dsa, dsa_pad, "gcry_dsa" }, [17] = { "dsa", "(sig-val (dsa (r %M) (s %M)))", 2,
"(public-key (dsa (p %M) (q %M) (g %M) (y %M)))",
4, &grub_crypto_pk_dsa, "raw", "gcry_dsa" },
}; };
struct grub_public_key struct grub_public_key
@@ -196,7 +178,7 @@ free_pk (struct grub_public_key *pk)
grub_size_t i; grub_size_t i;
for (i = 0; i < ARRAY_SIZE (sk->mpis); i++) for (i = 0; i < ARRAY_SIZE (sk->mpis); i++)
if (sk->mpis[i]) if (sk->mpis[i])
gcry_mpi_release (sk->mpis[i]); _gcry_mpi_release (sk->mpis[i]);
nsk = sk->next; nsk = sk->next;
grub_free (sk); grub_free (sk);
} }
@@ -303,7 +285,7 @@ grub_load_public_key (grub_file_t f)
goto fail; goto fail;
grub_memset (fingerprint_context, 0, GRUB_MD_SHA1->contextsize); grub_memset (fingerprint_context, 0, GRUB_MD_SHA1->contextsize);
GRUB_MD_SHA1->init (fingerprint_context); GRUB_MD_SHA1->init (fingerprint_context, 0);
GRUB_MD_SHA1->write (fingerprint_context, "\x99", 1); GRUB_MD_SHA1->write (fingerprint_context, "\x99", 1);
len_be = grub_cpu_to_be16 (len); len_be = grub_cpu_to_be16 (len);
GRUB_MD_SHA1->write (fingerprint_context, &len_be, sizeof (len_be)); GRUB_MD_SHA1->write (fingerprint_context, &len_be, sizeof (len_be));
@@ -336,7 +318,7 @@ grub_load_public_key (grub_file_t f)
GRUB_MD_SHA1->write (fingerprint_context, buffer, lb + sizeof (grub_uint16_t)); GRUB_MD_SHA1->write (fingerprint_context, buffer, lb + sizeof (grub_uint16_t));
if (gcry_mpi_scan (&sk->mpis[i], GCRYMPI_FMT_PGP, if (_gcry_mpi_scan (&sk->mpis[i], GCRYMPI_FMT_PGP,
buffer, lb + sizeof (grub_uint16_t), 0)) buffer, lb + sizeof (grub_uint16_t), 0))
{ {
grub_error (GRUB_ERR_BAD_SIGNATURE, N_("bad signature")); grub_error (GRUB_ERR_BAD_SIGNATURE, N_("bad signature"));
@@ -394,51 +376,6 @@ grub_crypto_pk_locate_subkey_in_trustdb (grub_uint64_t keyid)
return 0; return 0;
} }
static int
dsa_pad (gcry_mpi_t *hmpi, grub_uint8_t *hval,
const gcry_md_spec_t *hash, struct grub_public_subkey *sk)
{
unsigned nbits = gcry_mpi_get_nbits (sk->mpis[1]);
grub_dprintf ("crypt", "must be %u bits got %d bits\n", nbits,
(int)(8 * hash->mdlen));
return gcry_mpi_scan (hmpi, GCRYMPI_FMT_USG, hval,
nbits / 8 < (unsigned) hash->mdlen ? nbits / 8
: (unsigned) hash->mdlen, 0);
}
static int
rsa_pad (gcry_mpi_t *hmpi, grub_uint8_t *hval,
const gcry_md_spec_t *hash, struct grub_public_subkey *sk)
{
grub_size_t tlen, emlen, fflen;
grub_uint8_t *em, *emptr;
unsigned nbits = gcry_mpi_get_nbits (sk->mpis[0]);
int ret;
tlen = hash->mdlen + hash->asnlen;
emlen = (nbits + 7) / 8;
if (emlen < tlen + 11)
return 1;
em = grub_malloc (emlen);
if (!em)
return 1;
em[0] = 0x00;
em[1] = 0x01;
fflen = emlen - tlen - 3;
for (emptr = em + 2; emptr < em + 2 + fflen; emptr++)
*emptr = 0xff;
*emptr++ = 0x00;
grub_memcpy (emptr, hash->asnoid, hash->asnlen);
emptr += hash->asnlen;
grub_memcpy (emptr, hval, hash->mdlen);
ret = gcry_mpi_scan (hmpi, GCRYMPI_FMT_USG, em, emlen, 0);
grub_free (em);
return ret;
}
struct grub_pubkey_context struct grub_pubkey_context
{ {
grub_file_t sig; grub_file_t sig;
@@ -483,15 +420,12 @@ grub_verify_signature_init (struct grub_pubkey_context *ctxt, grub_file_t sig)
if (t != 0) if (t != 0)
return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("bad signature")); return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("bad signature"));
if (h >= ARRAY_SIZE (hashes) || hashes[h] == NULL)
return grub_error (GRUB_ERR_BAD_SIGNATURE, "unknown hash");
if (pk >= ARRAY_SIZE (pkalgos) || pkalgos[pk].name == NULL) if (pk >= ARRAY_SIZE (pkalgos) || pkalgos[pk].name == NULL)
return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("bad signature")); return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("bad signature"));
ctxt->hash = grub_crypto_lookup_md_by_name (hashes[h]); ctxt->hash = grub_crypto_lookup_md_by_algo (h);
if (!ctxt->hash) if (!ctxt->hash)
return grub_error (GRUB_ERR_BAD_SIGNATURE, "hash `%s' not loaded", hashes[h]); return grub_error (GRUB_ERR_BAD_SIGNATURE, "hash `%d' not loaded", h);
grub_dprintf ("crypt", "alive\n"); grub_dprintf ("crypt", "alive\n");
@@ -499,7 +433,7 @@ grub_verify_signature_init (struct grub_pubkey_context *ctxt, grub_file_t sig)
if (!ctxt->hash_context) if (!ctxt->hash_context)
return grub_errno; return grub_errno;
ctxt->hash->init (ctxt->hash_context); ctxt->hash->init (ctxt->hash_context, 0);
ctxt->sig = sig; ctxt->sig = sig;
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
@@ -528,7 +462,6 @@ grub_verify_signature_real (struct grub_pubkey_context *ctxt,
grub_uint16_t unhashed_sub; grub_uint16_t unhashed_sub;
grub_ssize_t r; grub_ssize_t r;
grub_uint8_t hash_start[2]; grub_uint8_t hash_start[2];
gcry_mpi_t hmpi;
grub_uint64_t keyid = 0; grub_uint64_t keyid = 0;
struct grub_public_subkey *sk; struct grub_public_subkey *sk;
@@ -620,7 +553,7 @@ grub_verify_signature_real (struct grub_pubkey_context *ctxt,
grub_memcpy (readbuf, &l, sizeof (l)); grub_memcpy (readbuf, &l, sizeof (l));
grub_dprintf ("crypt", "alive\n"); grub_dprintf ("crypt", "alive\n");
if (gcry_mpi_scan (&mpis[i], GCRYMPI_FMT_PGP, if (_gcry_mpi_scan (&mpis[i], GCRYMPI_FMT_PGP,
readbuf, lb + sizeof (grub_uint16_t), 0)) readbuf, lb + sizeof (grub_uint16_t), 0))
goto fail; goto fail;
grub_dprintf ("crypt", "alive\n"); grub_dprintf ("crypt", "alive\n");
@@ -638,8 +571,6 @@ grub_verify_signature_real (struct grub_pubkey_context *ctxt,
goto fail; goto fail;
} }
if (pkalgos[pk].pad (&hmpi, hval, ctxt->hash, sk))
goto fail;
if (!*pkalgos[pk].algo) if (!*pkalgos[pk].algo)
{ {
grub_dl_load (pkalgos[pk].module); grub_dl_load (pkalgos[pk].module);
@@ -652,7 +583,24 @@ grub_verify_signature_real (struct grub_pubkey_context *ctxt,
pkalgos[pk].module); pkalgos[pk].module);
goto fail; goto fail;
} }
if ((*pkalgos[pk].algo)->verify (0, hmpi, mpis, sk->mpis, 0, 0))
gcry_sexp_t hsexp, pubkey, sig;
grub_size_t errof;
if(_gcry_sexp_build(&hsexp, &errof, "(data (flags %s) (hash %s %b))", pkalgos[pk].padding, ctxt->hash->name, ctxt->hash->mdlen, hval))
goto fail;
if(_gcry_sexp_build(&pubkey, &errof, pkalgos[pk].pubsexp, sk->mpis[0], sk->mpis[1], sk->mpis[2], sk->mpis[3]))
goto fail;
if(_gcry_sexp_build(&sig, &errof, pkalgos[pk].sigsexp, mpis[0], mpis[1]))
goto fail;
_gcry_sexp_dump(sig);
_gcry_sexp_dump(hsexp);
_gcry_sexp_dump(pubkey);
if ((*pkalgos[pk].algo)->verify (sig, hsexp, pubkey))
goto fail; goto fail;
grub_free (readbuf); grub_free (readbuf);
@@ -972,7 +920,7 @@ GRUB_MOD_INIT(pgp)
grub_memset (&pseudo_file, 0, sizeof (pseudo_file)); grub_memset (&pseudo_file, 0, sizeof (pseudo_file));
/* Not an ELF module, skip. */ /* Not an ELF module, skip. */
if (header->type != OBJ_TYPE_PUBKEY) if (header->type != OBJ_TYPE_GPG_PUBKEY)
continue; continue;
pseudo_file.fs = &pseudo_fs; pseudo_file.fs = &pseudo_fs;
@@ -1010,6 +958,8 @@ GRUB_MOD_INIT(pgp)
GRUB_MOD_FINI(pgp) GRUB_MOD_FINI(pgp)
{ {
grub_register_variable_hook ("check_signatures", NULL, NULL);
grub_env_unset ("check_signatures");
grub_verifier_unregister (&grub_pubkey_verifier); grub_verifier_unregister (&grub_pubkey_verifier);
grub_unregister_extcmd (cmd); grub_unregister_extcmd (cmd);
grub_unregister_extcmd (cmd_trust); grub_unregister_extcmd (cmd_trust);
+15 -4
View File
@@ -25,6 +25,7 @@
#include <grub/types.h> #include <grub/types.h>
#include <grub/extcmd.h> #include <grub/extcmd.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -37,13 +38,14 @@ static const struct grub_arg_option options[] =
static char * static char *
grub_getline (int silent) grub_getline (int silent)
{ {
int i; grub_size_t i;
char *line; char *line;
char *tmp; char *tmp;
int c; int c;
grub_size_t alloc_size;
i = 0; i = 0;
line = grub_malloc (1 + i + sizeof('\0')); line = grub_malloc (1 + sizeof('\0'));
if (! line) if (! line)
return NULL; return NULL;
@@ -59,8 +61,17 @@ grub_getline (int silent)
line[i] = (char) c; line[i] = (char) c;
if (!silent) if (!silent)
grub_printf ("%c", c); grub_printf ("%c", c);
i++; if (grub_add (i, 1, &i))
tmp = grub_realloc (line, 1 + i + sizeof('\0')); {
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow is detected"));
return NULL;
}
if (grub_add (i, 1 + sizeof('\0'), &alloc_size))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow is detected"));
return NULL;
}
tmp = grub_realloc (line, alloc_size);
if (! tmp) if (! tmp)
{ {
grub_free (line); grub_free (line);
+55
View File
@@ -54,6 +54,41 @@ struct search_ctx
int is_cache; int is_cache;
}; };
static bool
is_unencrypted_disk (grub_disk_t disk)
{
grub_command_t cmd;
char *disk_str;
int disk_str_len;
int res;
if (disk->dev->id == GRUB_DISK_DEVICE_CRYPTODISK_ID)
return false; /* This is (crypto) disk. */
if (disk->dev->id == GRUB_DISK_DEVICE_DISKFILTER_ID)
{
char opt[] = "--quiet";
char *args[2];
cmd = grub_command_find ("cryptocheck");
if (cmd == NULL) /* No diskfilter module loaded for some reason. */
return true;
disk_str_len = grub_strlen (disk->name) + 2 + 1;
disk_str = grub_malloc (disk_str_len);
if (disk_str == NULL) /* Something is wrong, better report as unencrypted. */
return true;
grub_snprintf (disk_str, disk_str_len, "(%s)", disk->name);
args[0] = opt;
args[1] = disk_str;
res = cmd->func (cmd, 2, args);
grub_free (disk_str);
return (res != GRUB_ERR_NONE) ? true : false; /* GRUB_ERR_NONE for encrypted. */
}
return true;
}
/* Helper for FUNC_NAME. */ /* Helper for FUNC_NAME. */
static int static int
iterate_device (const char *name, void *data) iterate_device (const char *name, void *data)
@@ -86,6 +121,26 @@ iterate_device (const char *name, void *data)
grub_device_close (dev); grub_device_close (dev);
} }
/* Limit to encrypted disks when requested. */
if (ctx->flags & SEARCH_FLAGS_CRYPTODISK_ONLY)
{
grub_device_t dev;
dev = grub_device_open (name);
if (dev == NULL)
{
grub_errno = GRUB_ERR_NONE;
return 0;
}
if (dev->disk == NULL || is_unencrypted_disk (dev->disk) == true)
{
grub_device_close (dev);
grub_errno = GRUB_ERR_NONE;
return 0;
}
grub_device_close (dev);
}
#ifdef DO_SEARCH_FS_UUID #ifdef DO_SEARCH_FS_UUID
#define compare_fn grub_strcasecmp #define compare_fn grub_strcasecmp
#else #else
+6 -1
View File
@@ -41,6 +41,7 @@ static const struct grub_arg_option options[] =
ARG_TYPE_STRING}, ARG_TYPE_STRING},
{"no-floppy", 'n', 0, N_("Do not probe any floppy drive."), 0, 0}, {"no-floppy", 'n', 0, N_("Do not probe any floppy drive."), 0, 0},
{"efidisk-only", 0, 0, N_("Only probe EFI disks."), 0, 0}, {"efidisk-only", 0, 0, N_("Only probe EFI disks."), 0, 0},
{"cryptodisk-only", 0, 0, N_("Only probe encrypted disks."), 0, 0},
{"hint", 'h', GRUB_ARG_OPTION_REPEATABLE, {"hint", 'h', GRUB_ARG_OPTION_REPEATABLE,
N_("First try the device HINT. If HINT ends in comma, " N_("First try the device HINT. If HINT ends in comma, "
"also try subpartitions"), N_("HINT"), ARG_TYPE_STRING}, "also try subpartitions"), N_("HINT"), ARG_TYPE_STRING},
@@ -75,6 +76,7 @@ enum options
SEARCH_SET, SEARCH_SET,
SEARCH_NO_FLOPPY, SEARCH_NO_FLOPPY,
SEARCH_EFIDISK_ONLY, SEARCH_EFIDISK_ONLY,
SEARCH_CRYPTODISK_ONLY,
SEARCH_HINT, SEARCH_HINT,
SEARCH_HINT_IEEE1275, SEARCH_HINT_IEEE1275,
SEARCH_HINT_BIOS, SEARCH_HINT_BIOS,
@@ -189,6 +191,9 @@ grub_cmd_search (grub_extcmd_context_t ctxt, int argc, char **args)
if (state[SEARCH_EFIDISK_ONLY].set) if (state[SEARCH_EFIDISK_ONLY].set)
flags |= SEARCH_FLAGS_EFIDISK_ONLY; flags |= SEARCH_FLAGS_EFIDISK_ONLY;
if (state[SEARCH_CRYPTODISK_ONLY].set)
flags |= SEARCH_FLAGS_CRYPTODISK_ONLY;
if (state[SEARCH_LABEL].set) if (state[SEARCH_LABEL].set)
grub_search_label (id, var, flags, hints, nhints); grub_search_label (id, var, flags, hints, nhints);
else if (state[SEARCH_FS_UUID].set) else if (state[SEARCH_FS_UUID].set)
@@ -210,7 +215,7 @@ GRUB_MOD_INIT(search)
cmd = cmd =
grub_register_extcmd ("search", grub_cmd_search, grub_register_extcmd ("search", grub_cmd_search,
GRUB_COMMAND_FLAG_EXTRACTOR | GRUB_COMMAND_ACCEPT_DASH, GRUB_COMMAND_FLAG_EXTRACTOR | GRUB_COMMAND_ACCEPT_DASH,
N_("[-f|-l|-u|-s|-n] [--hint HINT [--hint HINT] ...]" N_("[-f|-l|-u|-s|-n] [--cryptodisk-only] [--hint HINT [--hint HINT] ...]"
" NAME"), " NAME"),
N_("Search devices by file, filesystem label" N_("Search devices by file, filesystem label"
" or filesystem UUID." " or filesystem UUID."
+18 -3
View File
@@ -29,6 +29,9 @@
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
/* Set a limit on recursion to avoid stack overflow. */
#define MAX_TEST_RECURSION_DEPTH 100
/* A simple implementation for signed numbers. */ /* A simple implementation for signed numbers. */
static int static int
grub_strtosl (char *arg, const char ** const end, int base) grub_strtosl (char *arg, const char ** const end, int base)
@@ -150,7 +153,7 @@ get_fileinfo (char *path, struct test_parse_ctx *ctx)
/* Parse a test expression starting from *argn. */ /* Parse a test expression starting from *argn. */
static int static int
test_parse (char **args, int *argn, int argc) test_parse (char **args, int *argn, int argc, int *depth)
{ {
struct test_parse_ctx ctx = { struct test_parse_ctx ctx = {
.and = 1, .and = 1,
@@ -387,13 +390,24 @@ test_parse (char **args, int *argn, int argc)
if (grub_strcmp (args[*argn], ")") == 0) if (grub_strcmp (args[*argn], ")") == 0)
{ {
(*argn)++; (*argn)++;
if (*depth > 0)
(*depth)--;
return ctx.or || ctx.and; return ctx.or || ctx.and;
} }
/* Recursively invoke if parenthesis. */ /* Recursively invoke if parenthesis. */
if (grub_strcmp (args[*argn], "(") == 0) if (grub_strcmp (args[*argn], "(") == 0)
{ {
(*argn)++; (*argn)++;
update_val (test_parse (args, argn, argc), &ctx);
if (++(*depth) > MAX_TEST_RECURSION_DEPTH)
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("max recursion depth exceeded"));
(*depth)--;
return ctx.or || ctx.and;
}
update_val (test_parse (args, argn, argc, depth), &ctx);
continue; continue;
} }
@@ -428,11 +442,12 @@ grub_cmd_test (grub_command_t cmd __attribute__ ((unused)),
int argc, char **args) int argc, char **args)
{ {
int argn = 0; int argn = 0;
int depth = 0;
if (argc >= 1 && grub_strcmp (args[argc - 1], "]") == 0) if (argc >= 1 && grub_strcmp (args[argc - 1], "]") == 0)
argc--; argc--;
return test_parse (args, &argn, argc) ? GRUB_ERR_NONE return test_parse (args, &argn, argc, &depth) ? GRUB_ERR_NONE
: grub_error (GRUB_ERR_TEST_FAILURE, N_("false")); : grub_error (GRUB_ERR_TEST_FAILURE, N_("false"));
} }
+10
View File
@@ -36,6 +36,16 @@ grub_tpm_verify_init (grub_file_t io,
{ {
*context = io->name; *context = io->name;
*flags |= GRUB_VERIFY_FLAGS_SINGLE_CHUNK; *flags |= GRUB_VERIFY_FLAGS_SINGLE_CHUNK;
/*
* The loopback image is mapped as a disk allowing it to function like
* a block device. However, we measure files read from the block device
* not the device itself. For example, we don't measure block devices like
* hd0 disk directly. This process is crucial to prevent out-of-memory
* errors as loopback images are inherently large.
*/
if ((type & GRUB_FILE_TYPE_MASK) == GRUB_FILE_TYPE_LOOPBACK)
*flags = GRUB_VERIFY_FLAGS_SKIP_VERIFICATION;
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
} }
@@ -0,0 +1,127 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2022 Microsoft Corporation
* Copyright (C) 2024 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <grub/err.h>
#include <grub/mm.h>
#include <grub/misc.h>
#include "tpm2_args.h"
grub_err_t
grub_tpm2_protector_parse_pcrs (char *value, grub_uint8_t *pcrs,
grub_uint8_t *pcr_count)
{
char *current_pcr = value;
char *next_pcr;
const char *pcr_end;
grub_uint64_t pcr;
grub_uint8_t i;
if (grub_strlen (value) == 0)
return GRUB_ERR_BAD_ARGUMENT;
*pcr_count = 0;
for (i = 0; i < TPM_MAX_PCRS; i++)
{
next_pcr = grub_strchr (current_pcr, ',');
if (next_pcr == current_pcr)
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("empty entry in PCR list"));
if (next_pcr != NULL)
*next_pcr = '\0';
pcr = grub_strtoul (current_pcr, &pcr_end, 10);
if (*current_pcr == '\0' || *pcr_end != '\0')
return grub_error (GRUB_ERR_BAD_NUMBER, N_("entry '%s' in PCR list is not a number"), current_pcr);
if (pcr > TPM_MAX_PCRS - 1)
return grub_error (GRUB_ERR_OUT_OF_RANGE, N_("entry %llu in PCR list is too large to be a PCR number, PCR numbers range from 0 to %u"), (unsigned long long)pcr, TPM_MAX_PCRS - 1);
pcrs[i] = (grub_uint8_t) pcr;
++(*pcr_count);
if (next_pcr == NULL)
break;
current_pcr = next_pcr + 1;
if (*current_pcr == '\0')
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("trailing comma at the end of PCR list"));
}
if (i == TPM_MAX_PCRS)
return grub_error (GRUB_ERR_OUT_OF_RANGE, N_("too many PCRs in PCR list, the maximum number of PCRs is %u"), TPM_MAX_PCRS);
return GRUB_ERR_NONE;
}
grub_err_t
grub_tpm2_protector_parse_asymmetric (const char *value,
grub_srk_type_t *srk_type)
{
if (grub_strcasecmp (value, "ECC") == 0 ||
grub_strcasecmp (value, "ECC_NIST_P256") == 0)
{
srk_type->type = TPM_ALG_ECC;
srk_type->detail.ecc_curve = TPM_ECC_NIST_P256;
}
else if (grub_strcasecmp (value, "RSA") == 0 ||
grub_strcasecmp (value, "RSA2048") == 0)
{
srk_type->type = TPM_ALG_RSA;
srk_type->detail.rsa_bits = 2048;
}
else
return grub_error (GRUB_ERR_OUT_OF_RANGE, N_("value '%s' is not a valid asymmetric key type"), value);
return GRUB_ERR_NONE;
}
grub_err_t
grub_tpm2_protector_parse_bank (const char *value, TPM_ALG_ID_t *bank)
{
if (grub_strcasecmp (value, "SHA1") == 0)
*bank = TPM_ALG_SHA1;
else if (grub_strcasecmp (value, "SHA256") == 0)
*bank = TPM_ALG_SHA256;
else if (grub_strcasecmp (value, "SHA384") == 0)
*bank = TPM_ALG_SHA384;
else 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);
return GRUB_ERR_NONE;
}
grub_err_t
grub_tpm2_protector_parse_tpm_handle (const char *value, TPM_HANDLE_t *handle)
{
grub_uint64_t num;
const char *str_end;
num = grub_strtoul (value, &str_end, 0);
if (*value == '\0' || *str_end != '\0')
return grub_error (GRUB_ERR_BAD_NUMBER, N_("TPM handle value '%s' is not a number"), value);
if (num > GRUB_UINT_MAX)
return grub_error (GRUB_ERR_OUT_OF_RANGE, N_("value %llu is too large to be a TPM handle, TPM handles are unsigned 32-bit integers"), (unsigned long long)num);
*handle = (TPM_HANDLE_t) num;
return GRUB_ERR_NONE;
}
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,7 @@
/* /*
* GRUB -- GRand Unified Bootloader * GRUB -- GRand Unified Bootloader
* Copyright (C) 2019 Free Software Foundation, Inc. * Copyright (C) 2022 Microsoft Corporation
* Copyright (C) 2024 Free Software Foundation, Inc.
* *
* GRUB is free software: you can redistribute it and/or modify * GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -16,22 +17,20 @@
* along with GRUB. If not, see <http://www.gnu.org/licenses/>. * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef GRUB_RDMSR_H #ifndef GRUB_TPM2_TPM2_HEADER
#define GRUB_RDMSR_H 1 #define GRUB_TPM2_TPM2_HEADER 1
/* #include <tss2_types.h>
* TODO: Add a general protection exception handler. #include <tss2_structs.h>
* Accessing a reserved or unimplemented MSR address results in a GP#. #include <tpm2_cmd.h>
*/
static inline grub_uint64_t /* Well-Known Windows SRK handle */
grub_msr_read (grub_uint32_t msr_id) #define TPM2_SRK_HANDLE 0x81000001
{
grub_uint32_t low, high;
asm volatile ("rdmsr" : "=a" (low), "=d" (high) : "c" (msr_id)); struct tpm2_sealed_key {
TPM2B_PUBLIC_t public;
TPM2B_PRIVATE_t private;
};
typedef struct tpm2_sealed_key tpm2_sealed_key_t;
return ((grub_uint64_t)high << 32) | low; #endif /* ! GRUB_TPM2_TPM2_HEADER */
}
#endif /* GRUB_RDMSR_H */
@@ -0,0 +1,49 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2022 Microsoft Corporation
* Copyright (C) 2024 Free Software Foundation, Inc.
*
* 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 "tpm2.h"
struct grub_srk_type
{
TPMI_ALG_PUBLIC_t type;
union {
TPM_KEY_BITS_t rsa_bits;
TPM_ECC_CURVE_t ecc_curve;
} detail;
};
typedef struct grub_srk_type grub_srk_type_t;
extern grub_err_t
grub_tpm2_protector_parse_pcrs (char *value, grub_uint8_t *pcrs, grub_uint8_t *pcr_count);
extern grub_err_t
grub_tpm2_protector_parse_asymmetric (const char *value, grub_srk_type_t *srk_type);
extern grub_err_t
grub_tpm2_protector_parse_bank (const char *value, TPM_ALG_ID_t *bank);
extern grub_err_t
grub_tpm2_protector_parse_tpm_handle (const char *value, TPM_HANDLE_t *handle);
#endif /* ! GRUB_TPM2_INTERNAL_ARGS_HEADER */
@@ -0,0 +1,49 @@
--
-- GRUB: GRand Unified Bootloader
-- Copyright (C) 2024 Free Software Foundation, Inc.
--
-- 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/>.
--
-- This file describes TPM 2.0 Key File format for libtasn1.
-- 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,
description [4] EXPLICIT UTF8String OPTIONAL,
rsaParent [5] EXPLICIT BOOLEAN OPTIONAL,
parent INTEGER,
pubkey OCTET STRING,
privkey OCTET STRING
}
END
@@ -0,0 +1,499 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2023 SUSE LLC
* Copyright (C) 2024 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <grub/list.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <tss2_buffer.h>
#include "tpm2key.h"
extern asn1_static_node tpm2key_asn1_tab[];
const char *sealed_key_oid = "2.23.133.10.1.5";
static int
asn1_allocate_and_read (asn1_node node, const char *name, void **content, grub_size_t *content_size)
{
grub_uint8_t *tmpstr = NULL;
int tmpstr_size = 0;
int ret;
if (content == NULL)
return ASN1_MEM_ERROR;
ret = asn1_read_value (node, name, NULL, &tmpstr_size);
if (ret != ASN1_MEM_ERROR)
return ret;
tmpstr = grub_malloc (tmpstr_size);
if (tmpstr == NULL)
return ASN1_MEM_ERROR;
ret = asn1_read_value (node, name, tmpstr, &tmpstr_size);
if (ret != ASN1_SUCCESS)
return ret;
*content = tmpstr;
*content_size = tmpstr_size;
return ASN1_SUCCESS;
}
static int
asn1_read_uint32 (asn1_node node, const char *name, grub_uint32_t *out)
{
grub_uint32_t tmp = 0;
grub_uint8_t *ptr;
void *data = NULL;
grub_size_t data_size;
int ret;
ret = asn1_allocate_and_read (node, name, &data, &data_size);
if (ret != ASN1_SUCCESS)
return ret;
/*
* ASN.1 INTEGER is encoded in the following format:
*
* TAG LENGTH OCTECTS
*
* The integer TAG is 02 and LENGTH is the number of followed OCTECTS in
* big endian. For example:
*
* 0x1: 02 01 01
* 0xabcd: 02 02 ab cd
*
* To decribe 0x1, it only takes 1 octect, so LENGTH is 0x01 and the
* octect is 0x01. On the other hand, 0xabcd requires 2 octects: 'ab" and
* 'cd', so LENGTH is 0x02.
*
* This function only expects a uint32 integer, so it rejects any integer
* containing more than 4 octects.
*/
if (data_size > 4)
{
ret = ASN1_MEM_ERROR;
goto error;
}
/* Copy the octects into 'tmp' to make it a big-endian uint32 */
ptr = (grub_uint8_t *) &tmp + (4 - data_size);
grub_memcpy (ptr, data, data_size);
/* Convert the big-endian integer to host uint32 */
tmp = grub_be_to_cpu32 (tmp);
*out = tmp;
error:
if (data)
grub_free (data);
return ret;
}
grub_err_t
grub_tpm2key_start_parsing (asn1_node *parsed_tpm2key, void *data, grub_size_t size)
{
asn1_node tpm2key;
asn1_node tpm2key_asn1 = NULL;
void *type_oid = NULL;
grub_size_t type_oid_size = 0;
void *empty_auth = NULL;
grub_size_t empty_auth_size = 0;
int tmp_size = 0;
int ret;
grub_err_t err;
/*
* 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,
* description [4] EXPLICIT UTF8String OPTIONAL,
* rsaParent [5] EXPLICIT BOOLEAN OPTIONAL,
* parent INTEGER,
* pubkey OCTET STRING,
* privkey OCTET STRING
* }
*/
ret = asn1_array2tree (tpm2key_asn1_tab, &tpm2key_asn1, NULL);
if (ret != ASN1_SUCCESS)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "failed to parse TPM2KEY ASN.1 array");
ret = asn1_create_element (tpm2key_asn1, "TPM2KEY.TPMKey", &tpm2key);
if (ret != ASN1_SUCCESS)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "failed to create TPM2KEY.TPMKey");
ret = asn1_der_decoding (&tpm2key, data, size, NULL);
if (ret != ASN1_SUCCESS)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "failed to decode TPM2KEY DER");
/* Check if 'type' is Sealed Key or not */
ret = asn1_allocate_and_read (tpm2key, "type", &type_oid, &type_oid_size);
if (ret != ASN1_SUCCESS)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a valid TPM2KEY file");
if (grub_memcmp (sealed_key_oid, type_oid, type_oid_size) != 0)
{
err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a valid TPM2KEY file");
goto error;
}
/* 'emptyAuth' must be 'TRUE' since we don't support password authorization */
ret = asn1_allocate_and_read (tpm2key, "emptyAuth", &empty_auth, &empty_auth_size);
if (ret != ASN1_SUCCESS || grub_strncmp ("TRUE", empty_auth, empty_auth_size) != 0)
{
err = grub_error (GRUB_ERR_BAD_ARGUMENT, "emptyAuth not TRUE");
goto error;
}
/* 'secret' should not be in a sealed key */
ret = asn1_read_value (tpm2key, "secret", NULL, &tmp_size);
if (ret != ASN1_ELEMENT_NOT_FOUND)
{
err = grub_error (GRUB_ERR_BAD_ARGUMENT, "\"secret\" not allowed for Sealed Key");
goto error;
}
*parsed_tpm2key = tpm2key;
err = GRUB_ERR_NONE;
error:
grub_free (type_oid);
grub_free (empty_auth);
return err;
}
void
grub_tpm2key_end_parsing (asn1_node tpm2key)
{
asn1_delete_structure (&tpm2key);
tpm2key = NULL;
}
grub_err_t
grub_tpm2key_get_rsaparent (asn1_node tpm2key, grub_uint8_t *rsaparent)
{
void *bool_str = NULL;
grub_size_t bool_str_size = 0;
int ret;
if (rsaparent == NULL)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "NULL pointer detected");
if (tpm2key == NULL)
return grub_error (GRUB_ERR_READ_ERROR, "invalid parent node");
ret = asn1_allocate_and_read (tpm2key, "rsaParent", &bool_str, &bool_str_size);
if (ret == ASN1_SUCCESS)
{
if (grub_strncmp ("TRUE", bool_str, bool_str_size) == 0)
*rsaparent = 1;
else
*rsaparent = 0;
}
else if (ret == ASN1_ELEMENT_NOT_FOUND)
*rsaparent = 0;
else
return grub_error (GRUB_ERR_READ_ERROR, "failed to retrieve rsaParent");
grub_free (bool_str);
return GRUB_ERR_NONE;
}
grub_err_t
grub_tpm2key_get_parent (asn1_node tpm2key, grub_uint32_t *parent)
{
int ret;
if (parent == NULL)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "NULL pointer detected");
if (tpm2key == NULL)
return grub_error (GRUB_ERR_READ_ERROR, "invalid parent node");
ret = asn1_read_uint32 (tpm2key, "parent", parent);
if (ret != ASN1_SUCCESS)
return grub_error (GRUB_ERR_READ_ERROR, "failed to retrieve parent");
return GRUB_ERR_NONE;
}
static grub_err_t
tpm2key_get_octstring (asn1_node tpm2key, const char *name, void **data, grub_size_t *size)
{
int ret;
if (name == NULL || data == NULL || size == NULL)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "invalid parameter(s)");
if (tpm2key == NULL)
return grub_error (GRUB_ERR_READ_ERROR, "invalid %s node", name);
ret = asn1_allocate_and_read (tpm2key, name, data, size);
if (ret != ASN1_SUCCESS)
return grub_error (GRUB_ERR_READ_ERROR, "failed to retrieve %s", name);
return GRUB_ERR_NONE;
}
grub_err_t
grub_tpm2key_get_pubkey (asn1_node tpm2key, void **data, grub_size_t *size)
{
return tpm2key_get_octstring (tpm2key, "pubkey", data, size);
}
grub_err_t
grub_tpm2key_get_privkey (asn1_node tpm2key, void **data, grub_size_t *size)
{
return tpm2key_get_octstring (tpm2key, "privkey", data, size);
}
/*
* The maximum and minimum number of elements for 'policy' and 'authPolicy' sequences
*
* Although there is no limit for the number of sequences elements, we set the upper
* bound to 99 to make it easier to implement the code.
*
* Any 'policy' or 'authPolicy' contains more than 99 commands/policies would become
* extremely complex to manage so it is impractical to support such use case.
*/
#define TPM2KEY_ELEMENTS_MAX 99
#define TPM2KEY_ELEMENTS_MIN 1
/*
* The string to fetch 'Policy' from 'authPolicy':
* authPolicy.?XX.Policy
*/
#define AUTHPOLICY_POL_MAX_STR "authPolicy.?XX.Policy"
#define AUTHPOLICY_POL_MAX (sizeof (AUTHPOLICY_POL_MAX_STR))
/*
* 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_STR AUTHPOLICY_POL_MAX_STR".?YY.CommandCode"
#define CMD_POL_MAX_STR AUTHPOLICY_POL_MAX_STR".?YY.CommandPolicy"
#define CMD_CODE_MAX (sizeof (CMD_CODE_MAX_STR))
#define CMD_POL_MAX (sizeof (CMD_POL_MAX_STR))
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 > TPM2KEY_ELEMENTS_MAX || policy_n < TPM2KEY_ELEMENTS_MIN)
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 != NULL)
{
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_error (GRUB_ERR_READ_ERROR, "failed to retrieve policy");
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);
}
}
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_error (GRUB_ERR_READ_ERROR, "failed to retrieve authPolicy");
/* Limit the number of authPolicy elements to two digits (99) */
if (authpol_n > TPM2KEY_ELEMENTS_MAX || authpol_n < TPM2KEY_ELEMENTS_MIN)
return grub_error (GRUB_ERR_OUT_OF_RANGE, "invalid number of authPolicy elements");
/*
* 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_error (GRUB_ERR_OUT_OF_MEMORY, "failed to allocate memory for authPolicy");
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_error (GRUB_ERR_READ_ERROR, "failed to retrieve policy from authPolicy");
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;
return GRUB_ERR_NONE;
error:
if (authpol != NULL)
{
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);
}
}
@@ -0,0 +1,87 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2023 SUSE LLC
* Copyright (C) 2024 Free Software Foundation, Inc.
*
* 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_TPM2KEY_HEADER
#define GRUB_TPM2_TPM2KEY_HEADER 1
#include <grub/types.h>
#include <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;
extern grub_err_t
grub_tpm2key_start_parsing (asn1_node *parsed_tpm2key, void *data, grub_size_t size);
extern void
grub_tpm2key_end_parsing (asn1_node tpm2key);
extern grub_err_t
grub_tpm2key_get_rsaparent (asn1_node tpm2key, grub_uint8_t *rsaparent);
extern grub_err_t
grub_tpm2key_get_parent (asn1_node tpm2key, grub_uint32_t *parent);
extern grub_err_t
grub_tpm2key_get_pubkey (asn1_node tpm2key, void **data, grub_size_t *size);
extern grub_err_t
grub_tpm2key_get_privkey (asn1_node tpm2key, void **data, grub_size_t *size);
extern grub_err_t
grub_tpm2key_get_policy_seq (asn1_node tpm2key, tpm2key_policy_t *policy_seq);
extern void
grub_tpm2key_free_policy_seq (tpm2key_policy_t policy_seq);
extern grub_err_t
grub_tpm2key_get_authpolicy_seq (asn1_node tpm2key, tpm2key_authpolicy_t *authpol_seq);
extern void
grub_tpm2key_free_authpolicy_seq (tpm2key_authpolicy_t authpol_seq);
#endif /* GRUB_TPM2_TPM2KEY_HEADER */
@@ -0,0 +1,63 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2024 Free Software Foundation, Inc.
*
* 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/>.
*/
/*
* 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'
* - 'libtasn1.h' for the definition of 'asn1_static_node'
*/
#include <grub/mm.h>
#include <libtasn1.h>
const asn1_static_node tpm2key_asn1_tab[] = {
{ "TPM2KEY", 536875024, NULL },
{ NULL, 1073741836, NULL },
{ "TPMPolicy", 1610612741, NULL },
{ "CommandCode", 1610620931, NULL },
{ NULL, 2056, "0"},
{ "CommandPolicy", 536879111, NULL },
{ NULL, 2056, "1"},
{ "TPMAuthPolicy", 1610612741, NULL },
{ "Name", 1610637346, NULL },
{ NULL, 2056, "0"},
{ "Policy", 536879115, NULL },
{ NULL, 1073743880, "1"},
{ NULL, 2, "TPMPolicy"},
{ "TPMKey", 536870917, NULL },
{ "type", 1073741836, NULL },
{ "emptyAuth", 1610637316, NULL },
{ NULL, 2056, "0"},
{ "policy", 1610637323, NULL },
{ NULL, 1073743880, "1"},
{ NULL, 2, "TPMPolicy"},
{ "secret", 1610637319, NULL },
{ NULL, 2056, "2"},
{ "authPolicy", 1610637323, NULL },
{ NULL, 1073743880, "3"},
{ NULL, 2, "TPMAuthPolicy"},
{ "description", 1610637346, NULL },
{ NULL, 2056, "4"},
{ "rsaParent", 1610637316, NULL },
{ NULL, 2056, "5"},
{ "parent", 1073741827, NULL },
{ "pubkey", 1073741831, NULL },
{ "privkey", 7, NULL },
{ NULL, 0, NULL }
};
+2 -2
View File
@@ -90,7 +90,7 @@ grub_usb_get_string (grub_usb_device_t dev, grub_uint8_t index, int langid,
0x06, (3 << 8) | index, 0x06, (3 << 8) | index,
langid, descstr.length, (char *) descstrp); langid, descstr.length, (char *) descstrp);
if (descstrp->length == 0) if (descstrp->length < 2)
{ {
grub_free (descstrp); grub_free (descstrp);
*string = grub_strdup (""); *string = grub_strdup ("");
@@ -99,7 +99,7 @@ grub_usb_get_string (grub_usb_device_t dev, grub_uint8_t index, int langid,
return GRUB_USB_ERR_NONE; return GRUB_USB_ERR_NONE;
} }
*string = grub_malloc (descstr.length * 2 + 1); *string = grub_malloc (descstrp->length * 2 + 1);
if (! *string) if (! *string)
{ {
grub_free (descstrp); grub_free (descstrp);
+5
View File
@@ -191,6 +191,11 @@ grub_cmd_videoinfo (grub_command_t cmd __attribute__ ((unused)),
/* Don't worry about errors. */ /* Don't worry about errors. */
grub_errno = GRUB_ERR_NONE; grub_errno = GRUB_ERR_NONE;
} }
else if (id != GRUB_VIDEO_DRIVER_NONE)
{
grub_puts_ (N_(" A video driver is active, cannot initialize this driver until it is deactivated\n"));
continue;
}
else else
{ {
if (adapter->init ()) if (adapter->init ())
+1 -1
View File
@@ -68,7 +68,7 @@ grub_cmd_xnu_uuid (grub_command_t cmd __attribute__ ((unused)),
ctx = grub_zalloc (GRUB_MD_MD5->contextsize); ctx = grub_zalloc (GRUB_MD_MD5->contextsize);
if (!ctx) if (!ctx)
return grub_errno; return grub_errno;
GRUB_MD_MD5->init (ctx); GRUB_MD_MD5->init (ctx, 0);
GRUB_MD_MD5->write (ctx, hash_prefix, sizeof (hash_prefix)); GRUB_MD_MD5->write (ctx, hash_prefix, sizeof (hash_prefix));
GRUB_MD_MD5->write (ctx, &serial, sizeof (serial)); GRUB_MD_MD5->write (ctx, &serial, sizeof (serial));
GRUB_MD_MD5->final (ctx); GRUB_MD_MD5->final (ctx);
+7 -9
View File
@@ -152,8 +152,7 @@ struct grub_ahci_device
static grub_err_t static grub_err_t
grub_ahci_readwrite_real (struct grub_ahci_device *dev, grub_ahci_readwrite_real (struct grub_ahci_device *dev,
struct grub_disk_ata_pass_through_parms *parms, struct grub_disk_ata_pass_through_parms *parms, int reset);
int spinup, int reset);
enum enum
@@ -573,7 +572,7 @@ grub_ahci_pciinit (grub_pci_device_t dev,
/* struct grub_disk_ata_pass_through_parms parms2; /* struct grub_disk_ata_pass_through_parms parms2;
grub_memset (&parms2, 0, sizeof (parms2)); grub_memset (&parms2, 0, sizeof (parms2));
parms2.taskfile.cmd = 8; parms2.taskfile.cmd = 8;
grub_ahci_readwrite_real (dev, &parms2, 1, 1);*/ grub_ahci_readwrite_real (dev, &parms2, 1);*/
} }
endtime = grub_get_time_ms () + 32000; endtime = grub_get_time_ms () + 32000;
@@ -908,15 +907,14 @@ grub_ahci_reset_port (struct grub_ahci_device *dev, int force)
dev->hba->ports[dev->port].sata_error = dev->hba->ports[dev->port].sata_error; dev->hba->ports[dev->port].sata_error = dev->hba->ports[dev->port].sata_error;
grub_memset (&parms2, 0, sizeof (parms2)); grub_memset (&parms2, 0, sizeof (parms2));
parms2.taskfile.cmd = 8; parms2.taskfile.cmd = 8;
return grub_ahci_readwrite_real (dev, &parms2, 1, 1); return grub_ahci_readwrite_real (dev, &parms2, 1);
} }
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
} }
static grub_err_t static grub_err_t
grub_ahci_readwrite_real (struct grub_ahci_device *dev, grub_ahci_readwrite_real (struct grub_ahci_device *dev,
struct grub_disk_ata_pass_through_parms *parms, struct grub_disk_ata_pass_through_parms *parms, int reset)
int spinup, int reset)
{ {
struct grub_pci_dma_chunk *bufc; struct grub_pci_dma_chunk *bufc;
grub_uint64_t endtime; grub_uint64_t endtime;
@@ -1038,7 +1036,7 @@ grub_ahci_readwrite_real (struct grub_ahci_device *dev,
grub_dprintf ("ahci", "AHCI tfd = %x\n", grub_dprintf ("ahci", "AHCI tfd = %x\n",
dev->hba->ports[dev->port].task_file_data); dev->hba->ports[dev->port].task_file_data);
endtime = grub_get_time_ms () + (spinup ? 20000 : 20000); endtime = grub_get_time_ms () + 20000;
while ((dev->hba->ports[dev->port].command_issue & 1)) while ((dev->hba->ports[dev->port].command_issue & 1))
if (grub_get_time_ms () > endtime || if (grub_get_time_ms () > endtime ||
(dev->hba->ports[dev->port].intstatus & GRUB_AHCI_HBA_PORT_IS_FATAL_MASK)) (dev->hba->ports[dev->port].intstatus & GRUB_AHCI_HBA_PORT_IS_FATAL_MASK))
@@ -1097,9 +1095,9 @@ grub_ahci_readwrite_real (struct grub_ahci_device *dev,
static grub_err_t static grub_err_t
grub_ahci_readwrite (grub_ata_t disk, grub_ahci_readwrite (grub_ata_t disk,
struct grub_disk_ata_pass_through_parms *parms, struct grub_disk_ata_pass_through_parms *parms,
int spinup) int spinup __attribute__((__unused__)))
{ {
return grub_ahci_readwrite_real (disk->data, parms, spinup, 0); return grub_ahci_readwrite_real (disk->data, parms, 0);
} }
static grub_err_t static grub_err_t
+2 -2
View File
@@ -112,10 +112,10 @@ grub_ata_identify (struct grub_ata *dev)
return grub_atapi_identify (dev); return grub_atapi_identify (dev);
info64 = grub_malloc (GRUB_DISK_SECTOR_SIZE); info64 = grub_malloc (GRUB_DISK_SECTOR_SIZE);
if (info64 == NULL)
return grub_errno;
info32 = (grub_uint32_t *) info64; info32 = (grub_uint32_t *) info64;
info16 = (grub_uint16_t *) info64; info16 = (grub_uint16_t *) info64;
if (! info16)
return grub_errno;
grub_memset (&parms, 0, sizeof (parms)); grub_memset (&parms, 0, sizeof (parms));
parms.buffer = info16; parms.buffer = info16;
+401 -55
View File
@@ -17,6 +17,7 @@
*/ */
#include <grub/cryptodisk.h> #include <grub/cryptodisk.h>
#include <grub/env.h>
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/misc.h> #include <grub/misc.h>
#include <grub/dl.h> #include <grub/dl.h>
@@ -26,6 +27,9 @@
#include <grub/file.h> #include <grub/file.h>
#include <grub/procfs.h> #include <grub/procfs.h>
#include <grub/partition.h> #include <grub/partition.h>
#include <grub/key_protector.h>
#include <grub/safemath.h>
#include <grub/hwfeatures-gcry.h>
#ifdef GRUB_UTIL #ifdef GRUB_UTIL
#include <grub/emu/hostdisk.h> #include <grub/emu/hostdisk.h>
@@ -44,7 +48,9 @@ enum
OPTION_KEYFILE, OPTION_KEYFILE,
OPTION_KEYFILE_OFFSET, OPTION_KEYFILE_OFFSET,
OPTION_KEYFILE_SIZE, OPTION_KEYFILE_SIZE,
OPTION_HEADER OPTION_HEADER,
OPTION_PROTECTOR,
OPTION_HWACCEL
}; };
static const struct grub_arg_option options[] = static const struct grub_arg_option options[] =
@@ -58,6 +64,9 @@ static const struct grub_arg_option options[] =
{"keyfile-offset", 'O', 0, N_("Key file offset (bytes)"), 0, ARG_TYPE_INT}, {"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}, {"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}, {"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},
{"hw-accel", 'A', 0, N_("Enable hardware acceleration."), 0, 0},
{0, 0, 0, 0, 0, 0} {0, 0, 0, 0, 0, 0}
}; };
@@ -296,7 +305,7 @@ grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
return GPG_ERR_OUT_OF_MEMORY; return GPG_ERR_OUT_OF_MEMORY;
tmp = grub_cpu_to_le64 (sector << log_sector_size); tmp = grub_cpu_to_le64 (sector << log_sector_size);
dev->iv_hash->init (ctx); dev->iv_hash->init (ctx, 0);
dev->iv_hash->write (ctx, dev->iv_prefix, dev->iv_prefix_len); dev->iv_hash->write (ctx, dev->iv_prefix, dev->iv_prefix_len);
dev->iv_hash->write (ctx, &tmp, sizeof (tmp)); dev->iv_hash->write (ctx, &tmp, sizeof (tmp));
dev->iv_hash->final (ctx); dev->iv_hash->final (ctx);
@@ -1061,6 +1070,7 @@ grub_cryptodisk_scan_device_real (const char *name,
grub_err_t ret = GRUB_ERR_NONE; grub_err_t ret = GRUB_ERR_NONE;
grub_cryptodisk_t dev; grub_cryptodisk_t dev;
grub_cryptodisk_dev_t cr; grub_cryptodisk_dev_t cr;
int i;
struct cryptodisk_read_hook_ctx read_hook_data = {0}; struct cryptodisk_read_hook_ctx read_hook_data = {0};
int askpass = 0; int askpass = 0;
char *part = NULL; char *part = NULL;
@@ -1113,41 +1123,175 @@ grub_cryptodisk_scan_device_real (const char *name,
goto error_no_close; goto error_no_close;
if (!dev) if (!dev)
continue; 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)
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);
}
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");
if (dev == NULL)
{
grub_error (GRUB_ERR_BAD_MODULE,
"no cryptodisk module can handle this device");
goto error_no_close;
}
if (cargs->protectors)
{
for (i = 0; cargs->protectors[i]; i++)
{
if (cargs->key_cache[i].invalid)
continue;
if (cargs->key_cache[i].key == NULL)
{
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 = cr->recover_key (source, dev, cargs);
if (ret != GRUB_ERR_NONE)
{
/* Reset key data to trigger the passphrase prompt later */
cargs->key_data = NULL;
cargs->key_len = 0;
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;
#ifndef GRUB_UTIL
grub_cli_set_auth_needed ();
#endif
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);
}
if (cargs->key_len)
{
ret = cr->recover_key (source, dev, cargs);
if (ret != GRUB_ERR_NONE)
goto error;
}
else
{
/* Get the passphrase from the user, if no key data. */
unsigned long tries = 3;
const char *tries_env;
/*
* Print the error from key protectors and clear grub_errno.
*
* Since '--protector' cannot coexist with '--password' and
* '--key-file', in case key protectors fail, only
* "cargs->key_len == 0" is expected, so cryptomount falls back
* here to request the passphrase.
*
* To avoid the error from key protectors stops the further code,
* print the error to notify the user why key protectors fail and
* clear grub_errno to have a fresh start.
*/
if (grub_errno != GRUB_ERR_NONE)
{
grub_print_error ();
grub_errno = GRUB_ERR_NONE;
}
askpass = 1;
cargs->key_data = grub_malloc (GRUB_CRYPTODISK_MAX_PASSPHRASE);
if (cargs->key_data == NULL)
goto error_no_close;
tries_env = grub_env_get ("cryptodisk_passphrase_tries");
if (tries_env != NULL && tries_env[0] != '\0')
{
unsigned long tries_env_val;
const char *p;
tries_env_val = grub_strtoul (tries_env, &p, 0);
if (*p == '\0' && tries_env_val != ~0UL)
tries = tries_env_val;
else
grub_printf_ (N_("Invalid cryptodisk_passphrase_tries value `%s'. Defaulting to %lu.\n"),
tries_env,
tries);
}
for (; tries > 0; tries--)
{
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);
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)
break;
if (ret != GRUB_ERR_ACCESS_DENIED || tries == 1)
goto error;
grub_puts_ (N_("Invalid passphrase."));
/*
* Since recover_key() calls a function that returns grub_errno,
* a leftover error value from a previously rejected passphrase
* will trigger a phantom failure. We therefore clear it before
* trying a new passphrase.
*/
grub_errno = GRUB_ERR_NONE;
}
}
ret = grub_cryptodisk_insert (dev, name, source);
if (ret != GRUB_ERR_NONE)
goto error;
goto cleanup; goto cleanup;
error: error:
@@ -1161,6 +1305,7 @@ grub_cryptodisk_scan_device_real (const char *name,
if (askpass) if (askpass)
{ {
grub_memset (cargs->key_data, 0, cargs->key_len);
cargs->key_len = 0; cargs->key_len = 0;
grub_free (cargs->key_data); grub_free (cargs->key_data);
} }
@@ -1236,7 +1381,8 @@ grub_cryptodisk_scan_device (const char *name,
dev = grub_cryptodisk_scan_device_real (name, source, cargs); dev = grub_cryptodisk_scan_device_real (name, source, cargs);
if (dev) if (dev)
{ {
ret = (cargs->search_uuid != NULL && grub_strcasecmp (cargs->search_uuid, dev->uuid) == 0); ret = (cargs->search_uuid != NULL
&& grub_uuidcasecmp (cargs->search_uuid, dev->uuid, sizeof (dev->uuid)) == 0);
goto cleanup; goto cleanup;
} }
@@ -1258,8 +1404,26 @@ grub_cryptodisk_scan_device (const char *name,
return ret; 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++)
{
if (cargs->key_cache[i].key)
grub_memset (cargs->key_cache[i].key, 0, cargs->key_cache[i].key_len);
grub_free (cargs->key_cache[i].key);
}
grub_free (cargs->key_cache);
}
static grub_err_t static grub_err_t
grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args) __grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
{ {
struct grub_arg_list *state = ctxt->state; struct grub_arg_list *state = ctxt->state;
struct grub_cryptomount_args cargs = {0}; struct grub_cryptomount_args cargs = {0};
@@ -1270,6 +1434,14 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
if (grub_cryptodisk_list == NULL) if (grub_cryptodisk_list == NULL)
return grub_error (GRUB_ERR_BAD_MODULE, "no cryptodisk modules loaded"); 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_KEYFILE].set && state[OPTION_PROTECTOR].set) /* key file and key protector */
return grub_error (GRUB_ERR_BAD_ARGUMENT,
"a key file and a key protector cannot both be set");
if (state[OPTION_PASSWORD].set) /* password */ if (state[OPTION_PASSWORD].set) /* password */
{ {
cargs.key_data = (grub_uint8_t *) state[OPTION_PASSWORD].arg; cargs.key_data = (grub_uint8_t *) state[OPTION_PASSWORD].arg;
@@ -1319,9 +1491,9 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
if (keyfile_offset > keyfile->size) if (keyfile_offset > keyfile->size)
return grub_error (GRUB_ERR_OUT_OF_RANGE, return grub_error (GRUB_ERR_OUT_OF_RANGE,
N_("Keyfile offset, %llu, is greater than" N_("Keyfile offset, %llu, is greater than "
"keyfile size, %" PRIuGRUB_UINT64_T), "keyfile size, %llu"),
keyfile_offset, keyfile->size); keyfile_offset, (unsigned long long) keyfile->size);
if (grub_file_seek (keyfile, (grub_off_t) keyfile_offset) == (grub_off_t) -1) if (grub_file_seek (keyfile, (grub_off_t) keyfile_offset) == (grub_off_t) -1)
return grub_errno; return grub_errno;
@@ -1362,6 +1534,15 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
return grub_errno; return grub_errno;
} }
if (state[OPTION_PROTECTOR].set) /* key protector(s) */
{
cargs.key_cache = grub_calloc (state[OPTION_PROTECTOR].set, sizeof (*cargs.key_cache));
if (cargs.key_cache == NULL)
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 */ if (state[OPTION_UUID].set) /* uuid */
{ {
int found_uuid; int found_uuid;
@@ -1370,6 +1551,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
dev = grub_cryptodisk_get_by_uuid (args[0]); dev = grub_cryptodisk_get_by_uuid (args[0]);
if (dev) if (dev)
{ {
grub_cryptodisk_clear_key_cache (&cargs);
grub_dprintf ("cryptodisk", grub_dprintf ("cryptodisk",
"already mounted as crypto%lu\n", dev->id); "already mounted as crypto%lu\n", dev->id);
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
@@ -1378,6 +1560,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
cargs.check_boot = state[OPTION_BOOT].set; cargs.check_boot = state[OPTION_BOOT].set;
cargs.search_uuid = args[0]; cargs.search_uuid = args[0];
found_uuid = grub_device_iterate (&grub_cryptodisk_scan_device, &cargs); found_uuid = grub_device_iterate (&grub_cryptodisk_scan_device, &cargs);
grub_cryptodisk_clear_key_cache (&cargs);
if (found_uuid) if (found_uuid)
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
@@ -1397,6 +1580,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
{ {
cargs.check_boot = state[OPTION_BOOT].set; cargs.check_boot = state[OPTION_BOOT].set;
grub_device_iterate (&grub_cryptodisk_scan_device, &cargs); grub_device_iterate (&grub_cryptodisk_scan_device, &cargs);
grub_cryptodisk_clear_key_cache (&cargs);
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
} }
else else
@@ -1420,6 +1604,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
disk = grub_disk_open (diskname); disk = grub_disk_open (diskname);
if (!disk) if (!disk)
{ {
grub_cryptodisk_clear_key_cache (&cargs);
if (disklast) if (disklast)
*disklast = ')'; *disklast = ')';
return grub_errno; return grub_errno;
@@ -1430,12 +1615,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_dprintf ("cryptodisk", "already mounted as crypto%lu\n", dev->id);
grub_disk_close (disk); grub_disk_close (disk);
grub_cryptodisk_clear_key_cache (&cargs);
if (disklast) if (disklast)
*disklast = ')'; *disklast = ')';
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
} }
dev = grub_cryptodisk_scan_device_real (diskname, disk, &cargs); dev = grub_cryptodisk_scan_device_real (diskname, disk, &cargs);
grub_cryptodisk_clear_key_cache (&cargs);
grub_disk_close (disk); grub_disk_close (disk);
if (disklast) if (disklast)
@@ -1445,6 +1632,23 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
} }
} }
static grub_err_t
grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
{
struct grub_arg_list *state = ctxt->state;
grub_err_t err;
if (state[OPTION_HWACCEL].set)
grub_enable_gcry_hwf ();
err = __grub_cmd_cryptomount (ctxt, argc, args);
if (state[OPTION_HWACCEL].set)
grub_reset_gcry_hwf ();
return err;
}
static struct grub_disk_dev grub_cryptodisk_dev = { static struct grub_disk_dev grub_cryptodisk_dev = {
.name = "cryptodisk", .name = "cryptodisk",
.id = GRUB_DISK_DEVICE_CRYPTODISK_ID, .id = GRUB_DISK_DEVICE_CRYPTODISK_ID,
@@ -1472,40 +1676,70 @@ static char *
luks_script_get (grub_size_t *sz) luks_script_get (grub_size_t *sz)
{ {
grub_cryptodisk_t i; grub_cryptodisk_t i;
grub_size_t size = 0; grub_size_t size = 0, mul;
char *ptr, *ret; char *ptr, *ret;
*sz = 0; *sz = 0;
for (i = cryptodisk_list; i != NULL; i = i->next) for (i = cryptodisk_list; i != NULL; i = i->next)
if (grub_strcmp (i->modname, "luks") == 0) if (grub_strcmp (i->modname, "luks") == 0 ||
grub_strcmp (i->modname, "luks2") == 0)
{ {
size += sizeof ("luks_mount "); /*
size += grub_strlen (i->uuid); * Add space in the line for (in order) spaces, cipher mode, cipher IV
size += grub_strlen (i->cipher->cipher->name); * mode, sector offset, sector size and the trailing newline. This is
size += 54; * an upper bound on the size of this data. There are 15 extra bytes
* in an earlier version of this code that are unaccounted for. It is
* left in the calculations in case it is needed. At worst, its short-
* lived wasted space.
*
* 60 = 5 + 5 + 8 + 20 + 6 + 1 + 15
*/
if (grub_add (size, grub_strlen (i->modname), &size) ||
grub_add (size, sizeof ("_mount") + 60, &size) ||
grub_add (size, grub_strlen (i->uuid), &size) ||
grub_add (size, grub_strlen (i->cipher->cipher->name), &size) ||
grub_mul (i->keysize, 2, &mul) ||
grub_add (size, mul, &size))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, "overflow detected while obtaining size of luks script");
return 0;
}
if (i->essiv_hash) if (i->essiv_hash)
size += grub_strlen (i->essiv_hash->name); {
size += i->keysize * 2; if (grub_add (size, grub_strlen (i->essiv_hash->name), &size))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, "overflow detected while obtaining size of luks script");
return 0;
}
}
} }
if (grub_add (size, 1, &size))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, "overflow detected while obtaining size of luks script");
return 0;
}
ret = grub_malloc (size + 1); ret = grub_malloc (size);
if (!ret) if (!ret)
return 0; return 0;
ptr = ret; ptr = ret;
for (i = cryptodisk_list; i != NULL; i = i->next) for (i = cryptodisk_list; i != NULL; i = i->next)
if (grub_strcmp (i->modname, "luks") == 0) if (grub_strcmp (i->modname, "luks") == 0 ||
grub_strcmp (i->modname, "luks2") == 0)
{ {
unsigned j; unsigned j;
const char *iptr; const char *iptr;
ptr = grub_stpcpy (ptr, "luks_mount "); ptr = grub_stpcpy (ptr, i->modname);
ptr = grub_stpcpy (ptr, "_mount ");
ptr = grub_stpcpy (ptr, i->uuid); ptr = grub_stpcpy (ptr, i->uuid);
*ptr++ = ' '; *ptr++ = ' ';
grub_snprintf (ptr, 21, "%" PRIuGRUB_UINT64_T " ", i->offset_sectors); ptr += grub_snprintf (ptr, 21, "%" PRIxGRUB_OFFSET, i->offset_sectors);
while (*ptr) *ptr++ = ' ';
ptr++; ptr += grub_snprintf (ptr, 7, "%u", 1 << i->log_sector_size);
*ptr++ = ' ';
for (iptr = i->cipher->cipher->name; *iptr; iptr++) for (iptr = i->cipher->cipher->name; *iptr; iptr++)
*ptr++ = grub_tolower (*iptr); *ptr++ = grub_tolower (*iptr);
switch (i->mode) switch (i->mode)
@@ -1562,6 +1796,114 @@ luks_script_get (grub_size_t *sz)
return ret; return ret;
} }
#ifdef GRUB_MACHINE_EFI
grub_err_t
grub_cryptodisk_challenge_password (void)
{
grub_cryptodisk_t cr_dev;
for (cr_dev = cryptodisk_list; cr_dev != NULL; cr_dev = cr_dev->next)
{
grub_cryptodisk_dev_t cr;
grub_disk_t source = NULL;
grub_err_t ret = GRUB_ERR_NONE;
grub_cryptodisk_t dev = NULL;
char *part = NULL;
struct grub_cryptomount_args cargs = {0};
cargs.check_boot = 0;
cargs.search_uuid = cr_dev->uuid;
source = grub_disk_open (cr_dev->source);
if (source == NULL)
{
ret = grub_errno;
goto error_out;
}
FOR_CRYPTODISK_DEVS (cr)
{
dev = cr->scan (source, &cargs);
if (grub_errno)
{
ret = grub_errno;
goto error_out;
}
if (dev == NULL)
continue;
break;
}
if (dev == NULL)
{
ret = grub_error (GRUB_ERR_BAD_MODULE, "no cryptodisk module can handle this device");
goto error_out;
}
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"), cr_dev->uuid);
grub_free (part);
cargs.key_data = grub_malloc (GRUB_CRYPTODISK_MAX_PASSPHRASE);
if (cargs.key_data == NULL)
{
ret = grub_errno;
goto error_out;
}
if (!grub_password_get ((char *) cargs.key_data, GRUB_CRYPTODISK_MAX_PASSPHRASE))
{
ret = grub_error (GRUB_ERR_BAD_ARGUMENT, "passphrase not supplied");
goto error_out;
}
cargs.key_len = grub_strlen ((char *) cargs.key_data);
ret = cr->recover_key (source, dev, &cargs);
error_out:
grub_disk_close (source);
if (dev != NULL)
cryptodisk_close (dev);
if (cargs.key_data)
{
grub_memset (cargs.key_data, 0, cargs.key_len);
grub_free (cargs.key_data);
}
return ret;
}
return GRUB_ERR_NONE;
}
void
grub_cryptodisk_erasesecrets (void)
{
grub_cryptodisk_t i;
grub_uint8_t *buf;
buf = grub_zalloc (GRUB_CRYPTODISK_MAX_KEYLEN);
if (buf == NULL)
grub_fatal ("grub_cryptodisk_erasesecrets: cannot allocate memory");
for (i = cryptodisk_list; i != NULL; i = i->next)
if (grub_cryptodisk_setkey (i, buf, i->keysize))
grub_fatal ("grub_cryptodisk_erasesecrets: cannot erase secrets for %s", i->source);
else
grub_printf ("Erased crypto secrets for %s\n", i->source);
/*
* Unfortunately, there is no way to "force unmount" a given disk, it may
* have mounted "child" disks as well, e.g., an LVM volume. So, this
* function MUST be called when there is no way back, e.g., when exiting.
* Otherwise, subsequent read calls for a cryptodisk will return garbage.
*/
grub_free (buf);
}
#endif /* GRUB_MACHINE_EFI */
struct grub_procfs_entry luks_script = struct grub_procfs_entry luks_script =
{ {
.name = "luks_script", .name = "luks_script",
@@ -1576,6 +1918,7 @@ GRUB_MOD_INIT (cryptodisk)
cmd = grub_register_extcmd ("cryptomount", grub_cmd_cryptomount, 0, cmd = grub_register_extcmd ("cryptomount", grub_cmd_cryptomount, 0,
N_("[ [-p password] | [-k keyfile" N_("[ [-p password] | [-k keyfile"
" [-O keyoffset] [-S keysize] ] ] [-H file]" " [-O keyoffset] [-S keysize] ] ] [-H file]"
" [-P protector [-P protector ...]] | [-A]"
" <SOURCE|-u UUID|-a|-b>"), " <SOURCE|-u UUID|-a|-b>"),
N_("Mount a crypto device."), options); N_("Mount a crypto device."), options);
grub_procfs_register ("luks_script", &luks_script); grub_procfs_register ("luks_script", &luks_script);
@@ -1583,6 +1926,9 @@ GRUB_MOD_INIT (cryptodisk)
GRUB_MOD_FINI (cryptodisk) GRUB_MOD_FINI (cryptodisk)
{ {
#ifdef GRUB_MACHINE_EFI
grub_cryptodisk_erasesecrets ();
#endif
grub_disk_dev_unregister (&grub_cryptodisk_dev); grub_disk_dev_unregister (&grub_cryptodisk_dev);
cryptodisk_cleanup (); cryptodisk_cleanup ();
grub_unregister_extcmd (cmd); grub_unregister_extcmd (cmd);
+122 -16
View File
@@ -20,10 +20,12 @@
#include <grub/dl.h> #include <grub/dl.h>
#include <grub/disk.h> #include <grub/disk.h>
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/command.h>
#include <grub/err.h> #include <grub/err.h>
#include <grub/misc.h> #include <grub/misc.h>
#include <grub/diskfilter.h> #include <grub/diskfilter.h>
#include <grub/partition.h> #include <grub/partition.h>
#include <grub/safemath.h>
#ifdef GRUB_UTIL #ifdef GRUB_UTIL
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/util/misc.h> #include <grub/util/misc.h>
@@ -226,15 +228,28 @@ scan_devices (const char *arname)
int need_rescan; int need_rescan;
for (pull = 0; pull < GRUB_DISK_PULL_MAX; pull++) for (pull = 0; pull < GRUB_DISK_PULL_MAX; pull++)
for (p = grub_disk_dev_list; p; p = p->next) {
if (p->id != GRUB_DISK_DEVICE_DISKFILTER_ID /* look up the crytodisk devices first */
&& p->disk_iterate) for (p = grub_disk_dev_list; p; p = p->next)
{ if (p->id == GRUB_DISK_DEVICE_CRYPTODISK_ID && p->disk_iterate)
if ((p->disk_iterate) (scan_disk_hook, NULL, pull)) {
return; if ((p->disk_iterate) (scan_disk_hook, NULL, pull))
if (arname && is_lv_readable (find_lv (arname), 1)) return;
return; if (arname && is_lv_readable (find_lv (arname), 1))
} return;
break;
}
/* check the devices other than crytodisk */
for (p = grub_disk_dev_list; p; p = p->next)
if (p->id != GRUB_DISK_DEVICE_DISKFILTER_ID && p->disk_iterate)
{
if ((p->disk_iterate) (scan_disk_hook, NULL, pull))
return;
if (arname && is_lv_readable (find_lv (arname), 1))
return;
}
}
scan_depth = 0; scan_depth = 0;
need_rescan = 1; need_rescan = 1;
@@ -720,7 +735,7 @@ read_segment (struct grub_diskfilter_segment *seg, grub_disk_addr_t sector,
case GRUB_DISKFILTER_RAID6: case GRUB_DISKFILTER_RAID6:
{ {
grub_disk_addr_t read_sector; grub_disk_addr_t read_sector;
grub_uint64_t b, p, n, disknr, e; grub_uint64_t b, p, n, disknr;
/* n = 1 for level 4 and 5, 2 for level 6. */ /* n = 1 for level 4 and 5, 2 for level 6. */
n = seg->type / 3; n = seg->type / 3;
@@ -770,7 +785,6 @@ read_segment (struct grub_diskfilter_segment *seg, grub_disk_addr_t sector,
if (read_size > size) if (read_size > size)
read_size = size; read_size = size;
e = 0;
/* Reset read error. */ /* Reset read error. */
if (grub_errno == GRUB_ERR_READ_ERROR if (grub_errno == GRUB_ERR_READ_ERROR
|| grub_errno == GRUB_ERR_UNKNOWN_DEVICE) || grub_errno == GRUB_ERR_UNKNOWN_DEVICE)
@@ -784,7 +798,6 @@ read_segment (struct grub_diskfilter_segment *seg, grub_disk_addr_t sector,
if ((err) && (err != GRUB_ERR_READ_ERROR if ((err) && (err != GRUB_ERR_READ_ERROR
&& err != GRUB_ERR_UNKNOWN_DEVICE)) && err != GRUB_ERR_UNKNOWN_DEVICE))
return err; return err;
e++;
if (err) if (err)
{ {
@@ -968,8 +981,6 @@ grub_diskfilter_vg_register (struct grub_diskfilter_vg *vg)
for (lv = vg->lvs; lv; lv = lv->next) for (lv = vg->lvs; lv; lv = lv->next)
{ {
grub_err_t err;
/* RAID 1 and single-disk RAID 0 don't use a chunksize but code /* RAID 1 and single-disk RAID 0 don't use a chunksize but code
assumes one so set one. */ assumes one so set one. */
for (i = 0; i < lv->segment_count; i++) for (i = 0; i < lv->segment_count; i++)
@@ -981,6 +992,10 @@ grub_diskfilter_vg_register (struct grub_diskfilter_vg *vg)
&& lv->segments[i].stripe_size == 0) && lv->segments[i].stripe_size == 0)
lv->segments[i].stripe_size = 64; lv->segments[i].stripe_size = 64;
} }
}
for (lv = vg->lvs; lv; lv = lv->next)
{
grub_err_t err;
err = validate_lv(lv); err = validate_lv(lv);
if (err) if (err)
@@ -1041,7 +1056,7 @@ grub_diskfilter_make_raid (grub_size_t uuidlen, char *uuid, int nmemb,
{ {
struct grub_diskfilter_vg *array; struct grub_diskfilter_vg *array;
int i; int i;
grub_size_t j; grub_size_t j, sz;
grub_uint64_t totsize; grub_uint64_t totsize;
struct grub_diskfilter_pv *pv; struct grub_diskfilter_pv *pv;
grub_err_t err; grub_err_t err;
@@ -1142,7 +1157,11 @@ grub_diskfilter_make_raid (grub_size_t uuidlen, char *uuid, int nmemb,
} }
array->lvs->vg = array; array->lvs->vg = array;
array->lvs->idname = grub_malloc (sizeof ("mduuid/") + 2 * uuidlen); if (grub_mul (uuidlen, 2, &sz) ||
grub_add (sz, sizeof ("mduuid/"), &sz))
goto fail;
array->lvs->idname = grub_malloc (sz);
if (!array->lvs->idname) if (!array->lvs->idname)
goto fail; goto fail;
@@ -1359,6 +1378,86 @@ grub_diskfilter_get_pv_from_disk (grub_disk_t disk,
} }
#endif #endif
static int
grub_diskfilter_check_pvs_encrypted (grub_disk_t disk, int *pvs_cnt)
{
struct grub_diskfilter_lv *lv = disk->data;
struct grub_diskfilter_pv *pv;
*pvs_cnt = 0;
if (lv->vg->pvs)
for (pv = lv->vg->pvs; pv; pv = pv->next)
{
(*pvs_cnt)++;
if (pv->disk == NULL)
{
/* Can be a partially activated VG, bail out. */
return GRUB_ERR_TEST_FAILURE;
}
if (pv->disk->dev->id != GRUB_DISK_DEVICE_CRYPTODISK_ID)
{
/* All backing devices must be cryptodisks, stop. */
return GRUB_ERR_TEST_FAILURE;
}
}
return GRUB_ERR_NONE;
}
static grub_err_t
grub_cmd_cryptocheck (grub_command_t cmd __attribute__ ((unused)),
int argc, char **args)
{
grub_disk_t disk;
int check_pvs_res;
int namelen;
int pvs_cnt;
int opt_quiet = 0;
if (argc == 2)
{
if (grub_strcmp (args[0], "--quiet") == 0)
{
opt_quiet = 1;
argc--;
args++;
}
else
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("unrecognized option: %s"), args[0]);
}
if (argc != 1)
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("disk name expected"));
namelen = grub_strlen (args[0]);
if (namelen > 2 && (args[0][0] == '(') && (args[0][namelen - 1] == ')'))
args[0][namelen - 1] = 0;
else
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("invalid disk: %s"),
args[0]);
if (!is_valid_diskfilter_name (&args[0][1]))
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("unrecognized disk: %s"),
&args[0][1]);
disk = grub_disk_open (&args[0][1]);
if (disk == NULL)
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("no such disk: %s"),
&args[0][1]);
check_pvs_res = grub_diskfilter_check_pvs_encrypted (disk, &pvs_cnt);
grub_disk_close (disk);
if (!opt_quiet)
grub_printf ("%s is %sencrypted (%d pv%s examined)\n", &args[0][1],
(check_pvs_res == GRUB_ERR_NONE) ? "" : "un",
pvs_cnt,
(pvs_cnt > 1) ? "s" : "");
return check_pvs_res;
}
static struct grub_disk_dev grub_diskfilter_dev = static struct grub_disk_dev grub_diskfilter_dev =
{ {
.name = "diskfilter", .name = "diskfilter",
@@ -1375,14 +1474,21 @@ static struct grub_disk_dev grub_diskfilter_dev =
.next = 0 .next = 0
}; };
static grub_command_t cmd;
GRUB_MOD_INIT(diskfilter) GRUB_MOD_INIT(diskfilter)
{ {
grub_disk_dev_register (&grub_diskfilter_dev); grub_disk_dev_register (&grub_diskfilter_dev);
cmd = grub_register_command ("cryptocheck", grub_cmd_cryptocheck,
N_("[--quiet] DEVICE"),
N_("Check if a logical volume resides on encrypted disks."));
} }
GRUB_MOD_FINI(diskfilter) GRUB_MOD_FINI(diskfilter)
{ {
grub_disk_dev_unregister (&grub_diskfilter_dev); grub_disk_dev_unregister (&grub_diskfilter_dev);
if (cmd != NULL)
grub_unregister_command (cmd);
free_array (); free_array ();
} }
+1 -3
View File
@@ -464,9 +464,7 @@ geli_recover_key (grub_disk_t source, grub_cryptodisk_t dev, grub_cryptomount_ar
grub_crypto_hmac_write (hnd, header.salt, sizeof (header.salt)); grub_crypto_hmac_write (hnd, header.salt, sizeof (header.salt));
grub_crypto_hmac_write (hnd, cargs->key_data, cargs->key_len); grub_crypto_hmac_write (hnd, cargs->key_data, cargs->key_len);
gcry_err = grub_crypto_hmac_fini (hnd, geomkey); grub_crypto_hmac_fini (hnd, geomkey);
if (gcry_err)
return grub_crypto_gcry_error (gcry_err);
} }
gcry_err = grub_crypto_hmac_buffer (dev->hash, geomkey, gcry_err = grub_crypto_hmac_buffer (dev->hash, geomkey,
+4 -1
View File
@@ -471,7 +471,7 @@ grub_biosdisk_rw (int cmd, grub_disk_t disk,
struct grub_biosdisk_dap *dap; struct grub_biosdisk_dap *dap;
dap = (struct grub_biosdisk_dap *) (GRUB_MEMORY_MACHINE_SCRATCH_ADDR dap = (struct grub_biosdisk_dap *) (GRUB_MEMORY_MACHINE_SCRATCH_ADDR
+ (data->sectors + (GRUB_DISK_MAX_LBA_SECTORS
<< disk->log_sector_size)); << disk->log_sector_size));
dap->length = sizeof (*dap); dap->length = sizeof (*dap);
dap->reserved = 0; dap->reserved = 0;
@@ -561,6 +561,9 @@ get_safe_sectors (grub_disk_t disk, grub_disk_addr_t sector)
struct grub_biosdisk_data *data = disk->data; struct grub_biosdisk_data *data = disk->data;
grub_uint32_t sectors = data->sectors; grub_uint32_t sectors = data->sectors;
if (data->flags & GRUB_BIOSDISK_FLAG_LBA)
sectors = GRUB_DISK_MAX_LBA_SECTORS;
/* OFFSET = SECTOR % SECTORS */ /* OFFSET = SECTOR % SECTORS */
grub_divmod64 (sector, sectors, &offset); grub_divmod64 (sector, sectors, &offset);
+43 -6
View File
@@ -26,6 +26,7 @@
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/scsicmd.h> #include <grub/scsicmd.h>
#include <grub/time.h> #include <grub/time.h>
#include <grub/safemath.h>
#include <grub/ieee1275/ieee1275.h> #include <grub/ieee1275/ieee1275.h>
#include <grub/ieee1275/obdisk.h> #include <grub/ieee1275/obdisk.h>
@@ -128,9 +129,17 @@ count_commas (const char *src)
static char * static char *
decode_grub_devname (const char *name) decode_grub_devname (const char *name)
{ {
char *devpath = grub_malloc (grub_strlen (name) + 1); char *devpath;
char *p, c; char *p, c;
grub_size_t sz;
if (grub_add (grub_strlen (name), 1, &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow detected while obtaining size of device name"));
return NULL;
}
devpath = grub_malloc (sz);
if (devpath == NULL) if (devpath == NULL)
return NULL; return NULL;
@@ -156,12 +165,20 @@ static char *
encode_grub_devname (const char *path) encode_grub_devname (const char *path)
{ {
char *encoding, *optr; char *encoding, *optr;
grub_size_t sz;
if (path == NULL) if (path == NULL)
return NULL; return NULL;
encoding = grub_malloc (sizeof (IEEE1275_DEV) + count_commas (path) + if (grub_add (sizeof (IEEE1275_DEV) + 1, count_commas (path), &sz) ||
grub_strlen (path) + 1); grub_add (sz, grub_strlen (path), &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow detected while obtaining encoding size"));
grub_print_error ();
return NULL;
}
encoding = grub_malloc (sz);
if (encoding == NULL) if (encoding == NULL)
{ {
@@ -396,8 +413,22 @@ canonicalise_disk (const char *devname)
real_unit_str_len = grub_strlen (op->name) + sizeof (IEEE1275_DISK_ALIAS) real_unit_str_len = grub_strlen (op->name) + sizeof (IEEE1275_DISK_ALIAS)
+ grub_strlen (real_unit_address); + grub_strlen (real_unit_address);
if (grub_add (grub_strlen (op->name), sizeof (IEEE1275_DISK_ALIAS), &real_unit_str_len) ||
grub_add (real_unit_str_len, grub_strlen (real_unit_address), &real_unit_str_len))
{
grub_free (parent);
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow detected while obtaining size of canonical name"));
grub_print_error ();
return NULL;
}
real_canon = grub_malloc (real_unit_str_len); real_canon = grub_malloc (real_unit_str_len);
if (real_canon == NULL)
{
grub_free (parent);
grub_print_error ();
return NULL;
}
grub_snprintf (real_canon, real_unit_str_len, "%s/disk@%s", grub_snprintf (real_canon, real_unit_str_len, "%s/disk@%s",
op->name, real_unit_address); op->name, real_unit_address);
@@ -413,6 +444,7 @@ canonicalise_disk (const char *devname)
static struct disk_dev * static struct disk_dev *
add_canon_disk (const char *cname) add_canon_disk (const char *cname)
{ {
grub_size_t sz;
struct disk_dev *dev; struct disk_dev *dev;
dev = grub_zalloc (sizeof (struct disk_dev)); dev = grub_zalloc (sizeof (struct disk_dev));
@@ -428,13 +460,18 @@ add_canon_disk (const char *cname)
* arguments and allows a client program to open * arguments and allows a client program to open
* the entire (raw) disk. Any disk label is ignored. * the entire (raw) disk. Any disk label is ignored.
*/ */
dev->raw_name = grub_malloc (grub_strlen (cname) + sizeof (":nolabel")); if (grub_add (grub_strlen (cname), sizeof (":nolabel"), &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, "overflow detected while appending :nolabel to end of canonical name");
goto failed;
}
dev->raw_name = grub_malloc (sz);
if (dev->raw_name == NULL) if (dev->raw_name == NULL)
goto failed; goto failed;
grub_snprintf (dev->raw_name, grub_strlen (cname) + sizeof (":nolabel"), grub_snprintf (dev->raw_name, sz, "%s:nolabel", cname);
"%s:nolabel", cname);
} }
/* /*
+58 -9
View File
@@ -24,6 +24,7 @@
#include <grub/ieee1275/ofdisk.h> #include <grub/ieee1275/ofdisk.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/time.h> #include <grub/time.h>
#include <grub/safemath.h>
static char *last_devpath; static char *last_devpath;
static grub_ieee1275_ihandle_t last_ihandle; static grub_ieee1275_ihandle_t last_ihandle;
@@ -80,6 +81,7 @@ ofdisk_hash_add_real (char *devpath)
struct ofdisk_hash_ent **head = &ofdisk_hash[ofdisk_hash_fn(devpath)]; struct ofdisk_hash_ent **head = &ofdisk_hash[ofdisk_hash_fn(devpath)];
const char *iptr; const char *iptr;
char *optr; char *optr;
grub_size_t sz;
p = grub_zalloc (sizeof (*p)); p = grub_zalloc (sizeof (*p));
if (!p) if (!p)
@@ -87,8 +89,15 @@ ofdisk_hash_add_real (char *devpath)
p->devpath = devpath; p->devpath = devpath;
p->grub_devpath = grub_malloc (sizeof ("ieee1275/") if (grub_mul (grub_strlen (p->devpath), 2, &sz) ||
+ 2 * grub_strlen (p->devpath)); grub_add (sz, sizeof ("ieee1275/"), &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow detected while obtaining size of device path"));
grub_free (p);
return NULL;
}
p->grub_devpath = grub_malloc (sz);
if (!p->grub_devpath) if (!p->grub_devpath)
{ {
@@ -98,7 +107,15 @@ ofdisk_hash_add_real (char *devpath)
if (! grub_ieee1275_test_flag (GRUB_IEEE1275_FLAG_NO_PARTITION_0)) if (! grub_ieee1275_test_flag (GRUB_IEEE1275_FLAG_NO_PARTITION_0))
{ {
p->open_path = grub_malloc (grub_strlen (p->devpath) + 3); if (grub_add (grub_strlen (p->devpath), 3, &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow detected while obtaining size of an open path"));
grub_free (p->grub_devpath);
grub_free (p);
return NULL;
}
p->open_path = grub_malloc (sz);
if (!p->open_path) if (!p->open_path)
{ {
grub_free (p->grub_devpath); grub_free (p->grub_devpath);
@@ -224,6 +241,7 @@ dev_iterate (const struct grub_ieee1275_devalias *alias)
args; args;
char *buf, *bufptr; char *buf, *bufptr;
unsigned i; unsigned i;
grub_size_t sz;
if (grub_ieee1275_open (alias->path, &ihandle)) if (grub_ieee1275_open (alias->path, &ihandle))
return; return;
@@ -243,9 +261,19 @@ dev_iterate (const struct grub_ieee1275_devalias *alias)
return; return;
} }
buf = grub_malloc (grub_strlen (alias->path) + 32); if (grub_add (grub_strlen (alias->path), 32, &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, "overflow detected while creating buffer for vscsi");
grub_ieee1275_close (ihandle);
return;
}
buf = grub_malloc (sz);
if (!buf) if (!buf)
return; {
grub_ieee1275_close (ihandle);
return;
}
bufptr = grub_stpcpy (buf, alias->path); bufptr = grub_stpcpy (buf, alias->path);
for (i = 0; i < args.nentries; i++) for (i = 0; i < args.nentries; i++)
@@ -287,9 +315,15 @@ dev_iterate (const struct grub_ieee1275_devalias *alias)
grub_uint64_t *table; grub_uint64_t *table;
grub_uint16_t table_size; grub_uint16_t table_size;
grub_ieee1275_ihandle_t ihandle; grub_ieee1275_ihandle_t ihandle;
grub_size_t sz;
buf = grub_malloc (grub_strlen (alias->path) + if (grub_add (grub_strlen (alias->path), sizeof ("/disk@7766554433221100"), &sz))
sizeof ("/disk@7766554433221100")); {
grub_error (GRUB_ERR_OUT_OF_RANGE, "overflow detected while creating buffer for sas_ioa");
return;
}
buf = grub_malloc (sz);
if (!buf) if (!buf)
return; return;
bufptr = grub_stpcpy (buf, alias->path); bufptr = grub_stpcpy (buf, alias->path);
@@ -427,9 +461,17 @@ grub_ofdisk_iterate (grub_disk_dev_iterate_hook_t hook, void *hook_data,
static char * static char *
compute_dev_path (const char *name) compute_dev_path (const char *name)
{ {
char *devpath = grub_malloc (grub_strlen (name) + 3); char *devpath;
char *p, c; char *p, c;
grub_size_t sz;
if (grub_add (grub_strlen (name), 3, &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow detected while obtaining size of device path"));
return NULL;
}
devpath = grub_malloc (sz);
if (!devpath) if (!devpath)
return NULL; return NULL;
@@ -625,6 +667,7 @@ insert_bootpath (void)
char *bootpath; char *bootpath;
grub_ssize_t bootpath_size; grub_ssize_t bootpath_size;
char *type; char *type;
grub_size_t sz;
if (grub_ieee1275_get_property_length (grub_ieee1275_chosen, "bootpath", if (grub_ieee1275_get_property_length (grub_ieee1275_chosen, "bootpath",
&bootpath_size) &bootpath_size)
@@ -635,7 +678,13 @@ insert_bootpath (void)
return; return;
} }
bootpath = (char *) grub_malloc ((grub_size_t) bootpath_size + 64); if (grub_add (bootpath_size, 64, &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow detected while obtaining bootpath size"));
return;
}
bootpath = (char *) grub_malloc (sz);
if (! bootpath) if (! bootpath)
{ {
grub_print_error (); grub_print_error ();
+73
View File
@@ -0,0 +1,73 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2022 Microsoft Corporation
* Copyright (C) 2024 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <grub/dl.h>
#include <grub/list.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/key_protector.h>
GRUB_MOD_LICENSE ("GPLv3+");
struct grub_key_protector *grub_key_protectors = NULL;
grub_err_t
grub_key_protector_register (struct grub_key_protector *protector)
{
if (protector == NULL || protector->name == NULL || protector->name[0] == '\0')
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid key protector for registration");
if (grub_key_protectors != NULL &&
grub_named_list_find (GRUB_AS_NAMED_LIST (grub_key_protectors), protector->name) != NULL)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Key protector '%s' already registered", protector->name);
grub_list_push (GRUB_AS_LIST_P (&grub_key_protectors), GRUB_AS_LIST (protector));
return GRUB_ERR_NONE;
}
grub_err_t
grub_key_protector_unregister (struct grub_key_protector *protector)
{
if (protector == NULL)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid key protector for unregistration");
grub_list_remove (GRUB_AS_LIST (protector));
return GRUB_ERR_NONE;
}
grub_err_t
grub_key_protector_recover_key (const char *protector, grub_uint8_t **key,
grub_size_t *key_size)
{
struct grub_key_protector *kp = NULL;
if (grub_key_protectors == NULL)
return grub_error (GRUB_ERR_OUT_OF_RANGE, "No key protector registered");
if (protector == NULL || protector[0] == '\0')
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid key protector");
kp = grub_named_list_find (GRUB_AS_NAMED_LIST (grub_key_protectors), protector);
if (kp == NULL)
return grub_error (GRUB_ERR_OUT_OF_RANGE, "Key protector '%s' not found", protector);
return kp->recover_key (key, key_size);
}
+110 -98
View File
@@ -179,6 +179,36 @@ gpt_ldm_sector (grub_disk_t dsk)
return sector; return sector;
} }
static void
free_pv (struct grub_diskfilter_pv *pv)
{
if (pv == NULL)
return;
grub_free (pv->internal_id);
grub_free (pv->id.uuid);
grub_free (pv);
}
static void
free_lv (struct grub_diskfilter_lv *lv)
{
if (lv == NULL)
return;
grub_free (lv->internal_id);
grub_free (lv->name);
grub_free (lv->fullname);
if (lv->segments)
{
unsigned int i;
for (i = 0; i < lv->segment_count; i++)
grub_free (lv->segments[i].nodes);
grub_free (lv->segments);
}
grub_free (lv);
}
static struct grub_diskfilter_vg * static struct grub_diskfilter_vg *
make_vg (grub_disk_t disk, make_vg (grub_disk_t disk,
const struct grub_ldm_label *label) const struct grub_ldm_label *label)
@@ -196,12 +226,8 @@ make_vg (grub_disk_t disk,
vg->name = grub_malloc (LDM_NAME_STRLEN + 1); vg->name = grub_malloc (LDM_NAME_STRLEN + 1);
vg->uuid = grub_malloc (LDM_GUID_STRLEN + 1); vg->uuid = grub_malloc (LDM_GUID_STRLEN + 1);
if (! vg->uuid || !vg->name) if (! vg->uuid || !vg->name)
{ goto fail1;
grub_free (vg->uuid);
grub_free (vg->name);
grub_free (vg);
return NULL;
}
grub_memcpy (vg->uuid, label->group_guid, LDM_GUID_STRLEN); grub_memcpy (vg->uuid, label->group_guid, LDM_GUID_STRLEN);
grub_memcpy (vg->name, label->group_name, LDM_NAME_STRLEN); grub_memcpy (vg->name, label->group_name, LDM_NAME_STRLEN);
vg->name[LDM_NAME_STRLEN] = 0; vg->name[LDM_NAME_STRLEN] = 0;
@@ -220,6 +246,7 @@ make_vg (grub_disk_t disk,
struct grub_ldm_vblk vblk[GRUB_DISK_SECTOR_SIZE struct grub_ldm_vblk vblk[GRUB_DISK_SECTOR_SIZE
/ sizeof (struct grub_ldm_vblk)]; / sizeof (struct grub_ldm_vblk)];
unsigned i; unsigned i;
grub_size_t sz;
err = grub_disk_read (disk, cursec, 0, err = grub_disk_read (disk, cursec, 0,
sizeof(vblk), &vblk); sizeof(vblk), &vblk);
if (err) if (err)
@@ -251,12 +278,18 @@ make_vg (grub_disk_t disk,
grub_free (pv); grub_free (pv);
goto fail2; goto fail2;
} }
pv->internal_id = grub_malloc (ptr[0] + 2); if (grub_add (ptr[0], 2, &sz))
if (!pv->internal_id)
{ {
grub_free (pv); grub_free (pv);
goto fail2; goto fail2;
} }
pv->internal_id = grub_malloc (sz);
if (!pv->internal_id)
{
free_pv (pv);
goto fail2;
}
grub_memcpy (pv->internal_id, ptr, (grub_size_t) ptr[0] + 1); grub_memcpy (pv->internal_id, ptr, (grub_size_t) ptr[0] + 1);
pv->internal_id[(grub_size_t) ptr[0] + 1] = 0; pv->internal_id[(grub_size_t) ptr[0] + 1] = 0;
@@ -264,7 +297,7 @@ make_vg (grub_disk_t disk,
if (ptr + *ptr + 1 >= vblk[i].dynamic if (ptr + *ptr + 1 >= vblk[i].dynamic
+ sizeof (vblk[i].dynamic)) + sizeof (vblk[i].dynamic))
{ {
grub_free (pv); free_pv (pv);
goto fail2; goto fail2;
} }
/* ptr = name. */ /* ptr = name. */
@@ -272,11 +305,23 @@ make_vg (grub_disk_t disk,
if (ptr + *ptr + 1 if (ptr + *ptr + 1
>= vblk[i].dynamic + sizeof (vblk[i].dynamic)) >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (pv); free_pv (pv);
goto fail2; goto fail2;
} }
pv->id.uuidlen = *ptr; pv->id.uuidlen = *ptr;
pv->id.uuid = grub_malloc (pv->id.uuidlen + 1);
if (grub_add (pv->id.uuidlen, 1, &sz))
{
free_pv (pv);
goto fail2;
}
pv->id.uuid = grub_malloc (sz);
if (pv->id.uuid == NULL)
{
free_pv (pv);
goto fail2;
}
grub_memcpy (pv->id.uuid, ptr + 1, pv->id.uuidlen); grub_memcpy (pv->id.uuid, ptr + 1, pv->id.uuidlen);
pv->id.uuid[pv->id.uuidlen] = 0; pv->id.uuid[pv->id.uuidlen] = 0;
@@ -322,7 +367,7 @@ make_vg (grub_disk_t disk,
lv->segments = grub_zalloc (sizeof (*lv->segments)); lv->segments = grub_zalloc (sizeof (*lv->segments));
if (!lv->segments) if (!lv->segments)
{ {
grub_free (lv); free_lv (lv);
goto fail2; goto fail2;
} }
lv->segments->start_extent = 0; lv->segments->start_extent = 0;
@@ -333,20 +378,25 @@ make_vg (grub_disk_t disk,
sizeof (*lv->segments->nodes)); sizeof (*lv->segments->nodes));
if (!lv->segments->nodes) if (!lv->segments->nodes)
{ {
grub_free (lv); free_lv (lv);
goto fail2; goto fail2;
} }
ptr = vblk[i].dynamic; ptr = vblk[i].dynamic;
if (ptr + *ptr + 1 >= vblk[i].dynamic if (ptr + *ptr + 1 >= vblk[i].dynamic
+ sizeof (vblk[i].dynamic)) + sizeof (vblk[i].dynamic))
{ {
grub_free (lv); free_lv (lv);
goto fail2; goto fail2;
} }
lv->internal_id = grub_malloc ((grub_size_t) ptr[0] + 2); if (grub_add (ptr[0], 2, &sz))
{
free_lv (lv);
goto fail2;
}
lv->internal_id = grub_malloc (sz);
if (!lv->internal_id) if (!lv->internal_id)
{ {
grub_free (lv); free_lv (lv);
goto fail2; goto fail2;
} }
grub_memcpy (lv->internal_id, ptr, ptr[0] + 1); grub_memcpy (lv->internal_id, ptr, ptr[0] + 1);
@@ -356,20 +406,18 @@ make_vg (grub_disk_t disk,
if (ptr + *ptr + 1 >= vblk[i].dynamic if (ptr + *ptr + 1 >= vblk[i].dynamic
+ sizeof (vblk[i].dynamic)) + sizeof (vblk[i].dynamic))
{ {
grub_free (lv); free_lv (lv);
goto fail2; goto fail2;
} }
if (grub_add (*ptr, 1, &sz)) if (grub_add (*ptr, 1, &sz))
{ {
grub_free (lv->internal_id); free_lv (lv);
grub_free (lv);
goto fail2; goto fail2;
} }
lv->name = grub_malloc (sz); lv->name = grub_malloc (sz);
if (!lv->name) if (!lv->name)
{ {
grub_free (lv->internal_id); free_lv (lv);
grub_free (lv);
goto fail2; goto fail2;
} }
grub_memcpy (lv->name, ptr + 1, *ptr); grub_memcpy (lv->name, ptr + 1, *ptr);
@@ -378,36 +426,28 @@ make_vg (grub_disk_t disk,
vg->uuid, lv->name); vg->uuid, lv->name);
if (!lv->fullname) if (!lv->fullname)
{ {
grub_free (lv->internal_id); free_lv (lv);
grub_free (lv->name);
grub_free (lv);
goto fail2; goto fail2;
} }
ptr += *ptr + 1; ptr += *ptr + 1;
if (ptr + *ptr + 1 if (ptr + *ptr + 1
>= vblk[i].dynamic + sizeof (vblk[i].dynamic)) >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (lv->internal_id); free_lv (lv);
grub_free (lv->name);
grub_free (lv);
goto fail2; goto fail2;
} }
/* ptr = volume type. */ /* ptr = volume type. */
ptr += *ptr + 1; ptr += *ptr + 1;
if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)) if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (lv->internal_id); free_lv (lv);
grub_free (lv->name);
grub_free (lv);
goto fail2; goto fail2;
} }
/* ptr = flags. */ /* ptr = flags. */
ptr += *ptr + 1; ptr += *ptr + 1;
if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)) if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (lv->internal_id); free_lv (lv);
grub_free (lv->name);
grub_free (lv);
goto fail2; goto fail2;
} }
@@ -416,17 +456,13 @@ make_vg (grub_disk_t disk,
/* ptr = number of children. */ /* ptr = number of children. */
if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)) if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (lv->internal_id); free_lv (lv);
grub_free (lv->name);
grub_free (lv);
goto fail2; goto fail2;
} }
ptr += *ptr + 1; ptr += *ptr + 1;
if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)) if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (lv->internal_id); free_lv (lv);
grub_free (lv->name);
grub_free (lv);
goto fail2; goto fail2;
} }
@@ -436,9 +472,7 @@ make_vg (grub_disk_t disk,
|| ptr + *ptr + 1>= vblk[i].dynamic || ptr + *ptr + 1>= vblk[i].dynamic
+ sizeof (vblk[i].dynamic)) + sizeof (vblk[i].dynamic))
{ {
grub_free (lv->internal_id); free_lv (lv);
grub_free (lv->name);
grub_free (lv);
goto fail2; goto fail2;
} }
lv->size = read_int (ptr + 1, *ptr); lv->size = read_int (ptr + 1, *ptr);
@@ -455,6 +489,7 @@ make_vg (grub_disk_t disk,
struct grub_ldm_vblk vblk[GRUB_DISK_SECTOR_SIZE struct grub_ldm_vblk vblk[GRUB_DISK_SECTOR_SIZE
/ sizeof (struct grub_ldm_vblk)]; / sizeof (struct grub_ldm_vblk)];
unsigned i; unsigned i;
grub_size_t sz;
err = grub_disk_read (disk, cursec, 0, err = grub_disk_read (disk, cursec, 0,
sizeof(vblk), &vblk); sizeof(vblk), &vblk);
if (err) if (err)
@@ -487,13 +522,18 @@ make_vg (grub_disk_t disk,
ptr = vblk[i].dynamic; ptr = vblk[i].dynamic;
if (ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic)) if (ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (comp); free_lv (comp);
goto fail2; goto fail2;
} }
comp->internal_id = grub_malloc ((grub_size_t) ptr[0] + 2); if (grub_add (ptr[0], 2, &sz))
{
free_lv (comp);
goto fail2;
}
comp->internal_id = grub_malloc (sz);
if (!comp->internal_id) if (!comp->internal_id)
{ {
grub_free (comp); free_lv (comp);
goto fail2; goto fail2;
} }
grub_memcpy (comp->internal_id, ptr, ptr[0] + 1); grub_memcpy (comp->internal_id, ptr, ptr[0] + 1);
@@ -502,16 +542,14 @@ make_vg (grub_disk_t disk,
ptr += *ptr + 1; ptr += *ptr + 1;
if (ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic)) if (ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (comp->internal_id); free_lv (comp);
grub_free (comp);
goto fail2; goto fail2;
} }
/* ptr = name. */ /* ptr = name. */
ptr += *ptr + 1; ptr += *ptr + 1;
if (ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic)) if (ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (comp->internal_id); free_lv (comp);
grub_free (comp);
goto fail2; goto fail2;
} }
/* ptr = state. */ /* ptr = state. */
@@ -521,8 +559,7 @@ make_vg (grub_disk_t disk,
ptr += 4; ptr += 4;
if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)) if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (comp->internal_id); free_lv (comp);
grub_free (comp);
goto fail2; goto fail2;
} }
@@ -530,16 +567,14 @@ make_vg (grub_disk_t disk,
ptr += *ptr + 1; ptr += *ptr + 1;
if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)) if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
{ {
grub_free (comp->internal_id); free_lv (comp);
grub_free (comp);
goto fail2; goto fail2;
} }
ptr += 8 + 8; ptr += 8 + 8;
if (ptr + *ptr + 1 >= vblk[i].dynamic if (ptr + *ptr + 1 >= vblk[i].dynamic
+ sizeof (vblk[i].dynamic)) + sizeof (vblk[i].dynamic))
{ {
grub_free (comp->internal_id); free_lv (comp);
grub_free (comp);
goto fail2; goto fail2;
} }
for (lv = vg->lvs; lv; lv = lv->next) for (lv = vg->lvs; lv; lv = lv->next)
@@ -550,8 +585,7 @@ make_vg (grub_disk_t disk,
} }
if (!lv) if (!lv)
{ {
grub_free (comp->internal_id); free_lv (comp);
grub_free (comp);
continue; continue;
} }
comp->size = lv->size; comp->size = lv->size;
@@ -563,8 +597,7 @@ make_vg (grub_disk_t disk,
sizeof (*comp->segments)); sizeof (*comp->segments));
if (!comp->segments) if (!comp->segments)
{ {
grub_free (comp->internal_id); free_lv (comp);
grub_free (comp);
goto fail2; goto fail2;
} }
} }
@@ -575,8 +608,7 @@ make_vg (grub_disk_t disk,
comp->segments = grub_malloc (sizeof (*comp->segments)); comp->segments = grub_malloc (sizeof (*comp->segments));
if (!comp->segments) if (!comp->segments)
{ {
grub_free (comp->internal_id); free_lv (comp);
grub_free (comp);
goto fail2; goto fail2;
} }
comp->segments->start_extent = 0; comp->segments->start_extent = 0;
@@ -591,27 +623,21 @@ make_vg (grub_disk_t disk,
} }
else else
{ {
grub_free (comp->segments); free_lv (comp);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2; goto fail2;
} }
ptr += *ptr + 1; ptr += *ptr + 1;
ptr++; ptr++;
if (!(vblk[i].flags & 0x10)) if (!(vblk[i].flags & 0x10))
{ {
grub_free (comp->segments); free_lv (comp);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2; goto fail2;
} }
if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic) if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)
|| ptr + *ptr + 1 >= vblk[i].dynamic || ptr + *ptr + 1 >= vblk[i].dynamic
+ sizeof (vblk[i].dynamic)) + sizeof (vblk[i].dynamic))
{ {
grub_free (comp->segments); free_lv (comp);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2; goto fail2;
} }
comp->segments->stripe_size = read_int (ptr + 1, *ptr); comp->segments->stripe_size = read_int (ptr + 1, *ptr);
@@ -619,20 +645,16 @@ make_vg (grub_disk_t disk,
if (ptr + *ptr + 1 >= vblk[i].dynamic if (ptr + *ptr + 1 >= vblk[i].dynamic
+ sizeof (vblk[i].dynamic)) + sizeof (vblk[i].dynamic))
{ {
grub_free (comp->segments); free_lv (comp);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2; goto fail2;
} }
comp->segments->node_count = read_int (ptr + 1, *ptr); comp->segments->node_count = read_int (ptr + 1, *ptr);
comp->segments->node_alloc = comp->segments->node_count; comp->segments->node_alloc = comp->segments->node_count;
comp->segments->nodes = grub_calloc (comp->segments->node_alloc, comp->segments->nodes = grub_calloc (comp->segments->node_alloc,
sizeof (*comp->segments->nodes)); sizeof (*comp->segments->nodes));
if (!lv->segments->nodes) if (comp->segments->nodes == NULL)
{ {
grub_free (comp->segments); free_lv (comp);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2; goto fail2;
} }
} }
@@ -640,25 +662,18 @@ make_vg (grub_disk_t disk,
if (lv->segments->node_alloc == lv->segments->node_count) if (lv->segments->node_alloc == lv->segments->node_count)
{ {
void *t; void *t;
grub_size_t sz;
if (grub_mul (lv->segments->node_alloc, 2, &lv->segments->node_alloc) || if (grub_mul (lv->segments->node_alloc, 2, &lv->segments->node_alloc) ||
grub_mul (lv->segments->node_alloc, sizeof (*lv->segments->nodes), &sz)) grub_mul (lv->segments->node_alloc, sizeof (*lv->segments->nodes), &sz))
{ {
grub_free (comp->segments->nodes); free_lv (comp);
grub_free (comp->segments);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2; goto fail2;
} }
t = grub_realloc (lv->segments->nodes, sz); t = grub_realloc (lv->segments->nodes, sz);
if (!t) if (!t)
{ {
grub_free (comp->segments->nodes); free_lv (comp);
grub_free (comp->segments);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2; goto fail2;
} }
lv->segments->nodes = t; lv->segments->nodes = t;
@@ -798,7 +813,10 @@ make_vg (grub_disk_t disk,
comp->segments[comp->segment_count].nodes comp->segments[comp->segment_count].nodes
= grub_malloc (sizeof (*comp->segments[comp->segment_count].nodes)); = grub_malloc (sizeof (*comp->segments[comp->segment_count].nodes));
if (!comp->segments[comp->segment_count].nodes) if (!comp->segments[comp->segment_count].nodes)
goto fail2; {
grub_free (comp->segments);
goto fail2;
}
comp->segments[comp->segment_count].nodes[0] = part; comp->segments[comp->segment_count].nodes[0] = part;
comp->segment_count++; comp->segment_count++;
} }
@@ -813,25 +831,19 @@ make_vg (grub_disk_t disk,
struct grub_diskfilter_pv *pv, *next_pv; struct grub_diskfilter_pv *pv, *next_pv;
for (lv = vg->lvs; lv; lv = next_lv) for (lv = vg->lvs; lv; lv = next_lv)
{ {
unsigned i;
for (i = 0; i < lv->segment_count; i++)
grub_free (lv->segments[i].nodes);
next_lv = lv->next; next_lv = lv->next;
grub_free (lv->segments); free_lv (lv);
grub_free (lv->internal_id);
grub_free (lv->name);
grub_free (lv->fullname);
grub_free (lv);
} }
for (pv = vg->pvs; pv; pv = next_pv) for (pv = vg->pvs; pv; pv = next_pv)
{ {
next_pv = pv->next; next_pv = pv->next;
grub_free (pv->id.uuid); free_pv (pv);
grub_free (pv);
} }
} }
fail1:
grub_free (vg->uuid); grub_free (vg->uuid);
grub_free (vg->name);
grub_free (vg); grub_free (vg);
return NULL; return NULL;
} }
+18
View File
@@ -24,6 +24,7 @@
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/extcmd.h> #include <grub/extcmd.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -33,6 +34,7 @@ struct grub_loopback
grub_file_t file; grub_file_t file;
struct grub_loopback *next; struct grub_loopback *next;
unsigned long id; unsigned long id;
grub_uint64_t refcnt;
}; };
static struct grub_loopback *loopback_list; static struct grub_loopback *loopback_list;
@@ -64,6 +66,8 @@ delete_loopback (const char *name)
if (! dev) if (! dev)
return grub_error (GRUB_ERR_BAD_DEVICE, "device not found"); return grub_error (GRUB_ERR_BAD_DEVICE, "device not found");
if (dev->refcnt > 0)
return grub_error (GRUB_ERR_STILL_REFERENCED, "device still referenced");
/* Remove the device from the list. */ /* Remove the device from the list. */
*prev = dev->next; *prev = dev->next;
@@ -120,6 +124,7 @@ grub_cmd_loopback (grub_extcmd_context_t ctxt, int argc, char **args)
newdev->file = file; newdev->file = file;
newdev->id = last_id++; newdev->id = last_id++;
newdev->refcnt = 0;
/* Add the new entry to the list. */ /* Add the new entry to the list. */
newdev->next = loopback_list; newdev->next = loopback_list;
@@ -161,6 +166,9 @@ grub_loopback_open (const char *name, grub_disk_t disk)
if (! dev) if (! dev)
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, "can't open device"); return grub_error (GRUB_ERR_UNKNOWN_DEVICE, "can't open device");
if (grub_add (dev->refcnt, 1, &dev->refcnt))
grub_fatal ("Reference count overflow");
/* Use the filesize for the disk size, round up to a complete sector. */ /* Use the filesize for the disk size, round up to a complete sector. */
if (dev->file->size != GRUB_FILE_SIZE_UNKNOWN) if (dev->file->size != GRUB_FILE_SIZE_UNKNOWN)
disk->total_sectors = ((dev->file->size + GRUB_DISK_SECTOR_SIZE - 1) disk->total_sectors = ((dev->file->size + GRUB_DISK_SECTOR_SIZE - 1)
@@ -178,6 +186,15 @@ grub_loopback_open (const char *name, grub_disk_t disk)
return 0; return 0;
} }
static void
grub_loopback_close (grub_disk_t disk)
{
struct grub_loopback *dev = disk->data;
if (grub_sub (dev->refcnt, 1, &dev->refcnt))
grub_fatal ("Reference count underflow");
}
static grub_err_t static grub_err_t
grub_loopback_read (grub_disk_t disk, grub_disk_addr_t sector, grub_loopback_read (grub_disk_t disk, grub_disk_addr_t sector,
grub_size_t size, char *buf) grub_size_t size, char *buf)
@@ -220,6 +237,7 @@ static struct grub_disk_dev grub_loopback_dev =
.id = GRUB_DISK_DEVICE_LOOPBACK_ID, .id = GRUB_DISK_DEVICE_LOOPBACK_ID,
.disk_iterate = grub_loopback_iterate, .disk_iterate = grub_loopback_iterate,
.disk_open = grub_loopback_open, .disk_open = grub_loopback_open,
.disk_close = grub_loopback_close,
.disk_read = grub_loopback_read, .disk_read = grub_loopback_read,
.disk_write = grub_loopback_write, .disk_write = grub_loopback_write,
.next = 0 .next = 0
+44 -5
View File
@@ -26,6 +26,7 @@
#include <grub/crypto.h> #include <grub/crypto.h>
#include <grub/partition.h> #include <grub/partition.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/safemath.h>
#include <base64.h> #include <base64.h>
#include <json.h> #include <json.h>
@@ -38,6 +39,7 @@ GRUB_MOD_LICENSE ("GPLv3+");
enum grub_luks2_kdf_type enum grub_luks2_kdf_type
{ {
LUKS2_KDF_TYPE_ARGON2I, LUKS2_KDF_TYPE_ARGON2I,
LUKS2_KDF_TYPE_ARGON2ID,
LUKS2_KDF_TYPE_PBKDF2 LUKS2_KDF_TYPE_PBKDF2
}; };
typedef enum grub_luks2_kdf_type grub_luks2_kdf_type_t; typedef enum grub_luks2_kdf_type grub_luks2_kdf_type_t;
@@ -158,13 +160,21 @@ luks2_parse_keyslot (grub_luks2_keyslot_t *out, const grub_json_t *keyslot)
grub_json_getstring (&type, &kdf, "type") || grub_json_getstring (&type, &kdf, "type") ||
grub_json_getstring (&out->kdf.salt, &kdf, "salt")) grub_json_getstring (&out->kdf.salt, &kdf, "salt"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing or invalid KDF"); return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing or invalid KDF");
else if (!grub_strcmp (type, "argon2i") || !grub_strcmp (type, "argon2id")) else if (!grub_strcmp (type, "argon2i"))
{ {
out->kdf.type = LUKS2_KDF_TYPE_ARGON2I; out->kdf.type = LUKS2_KDF_TYPE_ARGON2I;
if (grub_json_getint64 (&out->kdf.u.argon2i.time, &kdf, "time") || if (grub_json_getint64 (&out->kdf.u.argon2i.time, &kdf, "time") ||
grub_json_getint64 (&out->kdf.u.argon2i.memory, &kdf, "memory") || grub_json_getint64 (&out->kdf.u.argon2i.memory, &kdf, "memory") ||
grub_json_getint64 (&out->kdf.u.argon2i.cpus, &kdf, "cpus")) grub_json_getint64 (&out->kdf.u.argon2i.cpus, &kdf, "cpus"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing Argon2i parameters"); return grub_error (GRUB_ERR_BAD_ARGUMENT, "missing Argon2i parameters");
}
else if (!grub_strcmp (type, "argon2id"))
{
out->kdf.type = LUKS2_KDF_TYPE_ARGON2ID;
if (grub_json_getint64 (&out->kdf.u.argon2i.time, &kdf, "time") ||
grub_json_getint64 (&out->kdf.u.argon2i.memory, &kdf, "memory") ||
grub_json_getint64 (&out->kdf.u.argon2i.cpus, &kdf, "cpus"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "missing Argon2id parameters");
} }
else if (!grub_strcmp (type, "pbkdf2")) else if (!grub_strcmp (type, "pbkdf2"))
{ {
@@ -443,6 +453,8 @@ luks2_decrypt_key (grub_uint8_t *out_key,
grub_uint8_t salt[GRUB_CRYPTODISK_MAX_KEYLEN]; grub_uint8_t salt[GRUB_CRYPTODISK_MAX_KEYLEN];
grub_uint8_t *split_key = NULL; grub_uint8_t *split_key = NULL;
idx_t saltlen = sizeof (salt); idx_t saltlen = sizeof (salt);
int subalgo;
unsigned long param[4];
char cipher[32], *p; char cipher[32], *p;
const gcry_md_spec_t *hash; const gcry_md_spec_t *hash;
gcry_err_code_t gcry_ret; gcry_err_code_t gcry_ret;
@@ -459,8 +471,29 @@ luks2_decrypt_key (grub_uint8_t *out_key,
switch (k->kdf.type) switch (k->kdf.type)
{ {
case LUKS2_KDF_TYPE_ARGON2I: case LUKS2_KDF_TYPE_ARGON2I:
ret = grub_error (GRUB_ERR_BAD_ARGUMENT, "Argon2 not supported"); case LUKS2_KDF_TYPE_ARGON2ID:
goto err; if (k->kdf.type == LUKS2_KDF_TYPE_ARGON2I)
subalgo = GRUB_GCRY_KDF_ARGON2I;
else
subalgo = GRUB_GCRY_KDF_ARGON2ID;
param[0] = k->area.key_size;
param[1] = k->kdf.u.argon2i.time;
param[2] = k->kdf.u.argon2i.memory;
param[3] = k->kdf.u.argon2i.cpus;
gcry_ret = grub_crypto_argon2 (subalgo, param, 4,
passphrase, passphraselen,
salt, saltlen,
NULL, 0, NULL, 0,
k->area.key_size, area_key);
if (gcry_ret)
{
ret = grub_crypto_gcry_error (gcry_ret);
goto err;
}
break;
case LUKS2_KDF_TYPE_PBKDF2: case LUKS2_KDF_TYPE_PBKDF2:
hash = grub_crypto_lookup_md_by_name (k->kdf.u.pbkdf2.hash); hash = grub_crypto_lookup_md_by_name (k->kdf.u.pbkdf2.hash);
if (!hash) if (!hash)
@@ -569,6 +602,7 @@ luks2_recover_key (grub_disk_t source,
gcry_err_code_t gcry_ret; gcry_err_code_t gcry_ret;
grub_json_t *json = NULL, keyslots; grub_json_t *json = NULL, keyslots;
grub_err_t ret; grub_err_t ret;
grub_size_t sz;
if (cargs->key_data == NULL || cargs->key_len == 0) if (cargs->key_data == NULL || cargs->key_len == 0)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "no key data"); return grub_error (GRUB_ERR_BAD_ARGUMENT, "no key data");
@@ -577,7 +611,12 @@ luks2_recover_key (grub_disk_t source,
if (ret) if (ret)
return ret; return ret;
json_header = grub_zalloc (grub_be_to_cpu64 (header.hdr_size) - sizeof (header)); grub_puts_ (N_("Attempting to decrypt master key..."));
if (grub_sub (grub_be_to_cpu64 (header.hdr_size), sizeof (header), &sz))
return grub_error (GRUB_ERR_OUT_OF_RANGE, "underflow detected while calculating json header size");
json_header = grub_zalloc (sz);
if (!json_header) if (!json_header)
return GRUB_ERR_OUT_OF_MEMORY; return GRUB_ERR_OUT_OF_MEMORY;
+149 -142
View File
@@ -34,12 +34,11 @@
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
struct cache_lv struct ignored_feature_lv
{ {
struct grub_diskfilter_lv *lv; struct grub_diskfilter_lv *lv;
char *cache_pool;
char *origin; char *origin;
struct cache_lv *next; struct ignored_feature_lv *next;
}; };
@@ -105,30 +104,29 @@ grub_lvm_check_flag (const char *p, const char *str, const char *flag)
} }
static void static void
grub_lvm_free_cache_lvs (struct cache_lv *cache_lvs) grub_lvm_free_ignored_feature_lvs (struct ignored_feature_lv *ignored_feature_lvs)
{ {
struct cache_lv *cache; struct ignored_feature_lv *ignored_feature;
while ((cache = cache_lvs)) while ((ignored_feature = ignored_feature_lvs))
{ {
cache_lvs = cache_lvs->next; ignored_feature_lvs = ignored_feature_lvs->next;
if (cache->lv) if (ignored_feature->lv)
{ {
unsigned int i; unsigned int i;
for (i = 0; i < cache->lv->segment_count; ++i) for (i = 0; i < ignored_feature->lv->segment_count; ++i)
if (cache->lv->segments) if (ignored_feature->lv->segments)
grub_free (cache->lv->segments[i].nodes); grub_free (ignored_feature->lv->segments[i].nodes);
grub_free (cache->lv->segments); grub_free (ignored_feature->lv->segments);
grub_free (cache->lv->fullname); grub_free (ignored_feature->lv->fullname);
grub_free (cache->lv->idname); grub_free (ignored_feature->lv->idname);
grub_free (cache->lv->name); grub_free (ignored_feature->lv->name);
} }
grub_free (cache->lv); grub_free (ignored_feature->lv);
grub_free (cache->origin); grub_free (ignored_feature->origin);
grub_free (cache->cache_pool); grub_free (ignored_feature);
grub_free (cache);
} }
} }
@@ -290,7 +288,7 @@ grub_lvm_detect (grub_disk_t disk,
p = q = (char *)ptr; p = q = (char *)ptr;
if (grub_add ((grub_size_t)metadatabuf, (grub_size_t)mda_size, &ptr)) if (grub_add (ptr, (grub_size_t) grub_le_to_cpu64 (rlocn->size), &ptr))
goto error_parsing_metadata; goto error_parsing_metadata;
mda_end = (char *)ptr; mda_end = (char *)ptr;
@@ -325,7 +323,7 @@ grub_lvm_detect (grub_disk_t disk,
if (! vg) if (! vg)
{ {
struct cache_lv *cache_lvs = NULL; struct ignored_feature_lv *ignored_feature_lvs = NULL;
/* First time we see this volume group. We've to create the /* First time we see this volume group. We've to create the
whole volume group structure. */ whole volume group structure. */
@@ -370,6 +368,8 @@ grub_lvm_detect (grub_disk_t disk,
break; break;
pv = grub_zalloc (sizeof (*pv)); pv = grub_zalloc (sizeof (*pv));
if (pv == NULL)
goto fail4;
q = p; q = p;
while (*q != ' ' && q < mda_end) while (*q != ' ' && q < mda_end)
q++; q++;
@@ -379,6 +379,8 @@ grub_lvm_detect (grub_disk_t disk,
s = q - p; s = q - p;
pv->name = grub_malloc (s + 1); pv->name = grub_malloc (s + 1);
if (pv->name == NULL)
goto pvs_fail_noname;
grub_memcpy (pv->name, p, s); grub_memcpy (pv->name, p, s);
pv->name[s] = '\0'; pv->name[s] = '\0';
@@ -451,6 +453,8 @@ grub_lvm_detect (grub_disk_t disk,
break; break;
lv = grub_zalloc (sizeof (*lv)); lv = grub_zalloc (sizeof (*lv));
if (lv == NULL)
goto fail4;
q = p; q = p;
while (*q != ' ' && q < mda_end) while (*q != ' ' && q < mda_end)
@@ -545,6 +549,8 @@ grub_lvm_detect (grub_disk_t disk,
goto lvs_fail; goto lvs_fail;
} }
lv->segments = grub_calloc (lv->segment_count, sizeof (*seg)); lv->segments = grub_calloc (lv->segment_count, sizeof (*seg));
if (lv->segments == NULL)
goto lvs_fail;
seg = lv->segments; seg = lv->segments;
for (i = 0; i < lv->segment_count; i++) for (i = 0; i < lv->segment_count; i++)
@@ -612,6 +618,8 @@ grub_lvm_detect (grub_disk_t disk,
seg->nodes = grub_calloc (seg->node_count, seg->nodes = grub_calloc (seg->node_count,
sizeof (*stripe)); sizeof (*stripe));
if (seg->nodes == NULL)
goto lvs_segment_fail;
stripe = seg->nodes; stripe = seg->nodes;
p = grub_strstr (p, "stripes = ["); p = grub_strstr (p, "stripes = [");
@@ -671,8 +679,9 @@ grub_lvm_detect (grub_disk_t disk,
goto lvs_segment_fail; goto lvs_segment_fail;
} }
seg->nodes = grub_zalloc (sizeof (seg->nodes[0]) seg->nodes = grub_calloc (seg->node_count, sizeof (seg->nodes[0]));
* seg->node_count); if (seg->nodes == NULL)
goto lvs_segment_fail;
p = grub_strstr (p, "mirrors = ["); p = grub_strstr (p, "mirrors = [");
if (p == NULL) if (p == NULL)
@@ -760,8 +769,9 @@ grub_lvm_detect (grub_disk_t disk,
} }
} }
seg->nodes = grub_zalloc (sizeof (seg->nodes[0]) seg->nodes = grub_calloc (seg->node_count, sizeof (seg->nodes[0]));
* seg->node_count); if (seg->nodes == NULL)
goto lvs_segment_fail;
p = grub_strstr (p, "raids = ["); p = grub_strstr (p, "raids = [");
if (p == NULL) if (p == NULL)
@@ -807,108 +817,98 @@ grub_lvm_detect (grub_disk_t disk,
seg->nodes[seg->node_count - 1].name = tmp; seg->nodes[seg->node_count - 1].name = tmp;
} }
} }
else if (grub_memcmp (p, "cache\"", /*
sizeof ("cache\"") - 1) == 0) * Cache and integrity LVs have extra parts that
* we can ignore for our read-only access.
*/
else if (grub_strncmp (p, "cache\"", sizeof ("cache\"") - 1) == 0 ||
grub_strncmp (p, "cache+CACHE_USES_CACHEVOL\"", sizeof ("cache+CACHE_USES_CACHEVOL\"") - 1) == 0 ||
grub_strncmp (p, "integrity\"", sizeof ("integrity\"") - 1) == 0)
{ {
struct cache_lv *cache = NULL; struct ignored_feature_lv *ignored_feature = NULL;
char *p2, *p3; char *p2, *p3;
grub_size_t sz; grub_size_t sz;
#ifdef GRUB_UTIL
p2 = grub_strchr (p, '"');
if (p2)
*p2 = '\0';
grub_util_info ("Ignoring extra metadata type '%s' for %s", p, lv->name);
if (p2)
*p2 ='"';
#endif
cache = grub_zalloc (sizeof (*cache)); ignored_feature = grub_zalloc (sizeof (*ignored_feature));
if (!cache) if (!ignored_feature)
goto cache_lv_fail; goto ignored_feature_lv_fail;
cache->lv = grub_zalloc (sizeof (*cache->lv)); ignored_feature->lv = grub_zalloc (sizeof (*ignored_feature->lv));
if (!cache->lv) if (!ignored_feature->lv)
goto cache_lv_fail; goto ignored_feature_lv_fail;
grub_memcpy (cache->lv, lv, sizeof (*cache->lv)); grub_memcpy (ignored_feature->lv, lv, sizeof (*ignored_feature->lv));
if (lv->fullname) if (lv->fullname)
{ {
cache->lv->fullname = grub_strdup (lv->fullname); ignored_feature->lv->fullname = grub_strdup (lv->fullname);
if (!cache->lv->fullname) if (!ignored_feature->lv->fullname)
goto cache_lv_fail; goto ignored_feature_lv_fail;
} }
if (lv->idname) if (lv->idname)
{ {
cache->lv->idname = grub_strdup (lv->idname); ignored_feature->lv->idname = grub_strdup (lv->idname);
if (!cache->lv->idname) if (!ignored_feature->lv->idname)
goto cache_lv_fail; goto ignored_feature_lv_fail;
} }
if (lv->name) if (lv->name)
{ {
cache->lv->name = grub_strdup (lv->name); ignored_feature->lv->name = grub_strdup (lv->name);
if (!cache->lv->name) if (!ignored_feature->lv->name)
goto cache_lv_fail; goto ignored_feature_lv_fail;
} }
skip_lv = 1; skip_lv = 1;
p2 = grub_strstr (p, "cache_pool = \"");
if (!p2)
goto cache_lv_fail;
p2 = grub_strchr (p2, '"');
if (!p2)
goto cache_lv_fail;
p3 = ++p2;
if (p3 == mda_end)
goto cache_lv_fail;
p3 = grub_strchr (p3, '"');
if (!p3)
goto cache_lv_fail;
sz = p3 - p2;
cache->cache_pool = grub_malloc (sz + 1);
if (!cache->cache_pool)
goto cache_lv_fail;
grub_memcpy (cache->cache_pool, p2, sz);
cache->cache_pool[sz] = '\0';
p2 = grub_strstr (p, "origin = \""); p2 = grub_strstr (p, "origin = \"");
if (!p2) if (!p2)
goto cache_lv_fail; goto ignored_feature_lv_fail;
p2 = grub_strchr (p2, '"'); p2 = grub_strchr (p2, '"');
if (!p2) if (!p2)
goto cache_lv_fail; goto ignored_feature_lv_fail;
p3 = ++p2; p3 = ++p2;
if (p3 == mda_end) if (p3 == mda_end)
goto cache_lv_fail; goto ignored_feature_lv_fail;
p3 = grub_strchr (p3, '"'); p3 = grub_strchr (p3, '"');
if (!p3) if (!p3)
goto cache_lv_fail; goto ignored_feature_lv_fail;
sz = p3 - p2; sz = p3 - p2;
cache->origin = grub_malloc (sz + 1); ignored_feature->origin = grub_malloc (sz + 1);
if (!cache->origin) if (!ignored_feature->origin)
goto cache_lv_fail; goto ignored_feature_lv_fail;
grub_memcpy (cache->origin, p2, sz); grub_memcpy (ignored_feature->origin, p2, sz);
cache->origin[sz] = '\0'; ignored_feature->origin[sz] = '\0';
cache->next = cache_lvs; ignored_feature->next = ignored_feature_lvs;
cache_lvs = cache; ignored_feature_lvs = ignored_feature;
break; break;
cache_lv_fail: ignored_feature_lv_fail:
if (cache) if (ignored_feature)
{ {
grub_free (cache->origin); grub_free (ignored_feature->origin);
grub_free (cache->cache_pool); if (ignored_feature->lv)
if (cache->lv)
{ {
grub_free (cache->lv->fullname); grub_free (ignored_feature->lv->fullname);
grub_free (cache->lv->idname); grub_free (ignored_feature->lv->idname);
grub_free (cache->lv->name); grub_free (ignored_feature->lv->name);
} }
grub_free (cache->lv); grub_free (ignored_feature->lv);
grub_free (cache); grub_free (ignored_feature);
} }
grub_lvm_free_cache_lvs (cache_lvs); grub_lvm_free_ignored_feature_lvs (ignored_feature_lvs);
goto fail4; goto fail4;
} }
else else
@@ -917,7 +917,7 @@ grub_lvm_detect (grub_disk_t disk,
char *p2; char *p2;
p2 = grub_strchr (p, '"'); p2 = grub_strchr (p, '"');
if (p2) if (p2)
*p2 = 0; *p2 = '\0';
grub_util_info ("unknown LVM type %s", p); grub_util_info ("unknown LVM type %s", p);
if (p2) if (p2)
*p2 ='"'; *p2 ='"';
@@ -961,10 +961,68 @@ grub_lvm_detect (grub_disk_t disk,
} }
} }
/* Match lvs. */
{
struct ignored_feature_lv *ignored_feature;
for (ignored_feature = ignored_feature_lvs; ignored_feature; ignored_feature = ignored_feature->next)
{
struct grub_diskfilter_lv *lv;
for (lv = vg->lvs; lv; lv = lv->next)
if (grub_strcmp (lv->name, ignored_feature->origin) == 0)
break;
if (lv)
{
ignored_feature->lv->segments = grub_calloc (lv->segment_count, sizeof (*lv->segments));
if (!ignored_feature->lv->segments)
{
grub_lvm_free_ignored_feature_lvs (ignored_feature_lvs);
goto fail4;
}
grub_memcpy (ignored_feature->lv->segments, lv->segments, lv->segment_count * sizeof (*lv->segments));
for (i = 0; i < lv->segment_count; ++i)
{
struct grub_diskfilter_node *nodes = lv->segments[i].nodes;
grub_size_t node_count = lv->segments[i].node_count;
ignored_feature->lv->segments[i].nodes = grub_calloc (node_count, sizeof (*nodes));
if (!ignored_feature->lv->segments[i].nodes)
{
for (j = 0; j < i; ++j)
grub_free (ignored_feature->lv->segments[j].nodes);
grub_free (ignored_feature->lv->segments);
ignored_feature->lv->segments = NULL;
grub_lvm_free_ignored_feature_lvs (ignored_feature_lvs);
goto fail4;
}
grub_memcpy (ignored_feature->lv->segments[i].nodes, nodes, node_count * sizeof (*nodes));
}
if (ignored_feature->lv->segments)
{
ignored_feature->lv->segment_count = lv->segment_count;
ignored_feature->lv->vg = vg;
ignored_feature->lv->next = vg->lvs;
vg->lvs = ignored_feature->lv;
ignored_feature->lv = NULL;
}
}
else
{
#ifdef GRUB_UTIL
grub_util_info ("Couldn't find LVM part of ignored feature on %s", ignored_feature->origin);
#endif
}
}
}
/* Match LVs. Must be done after cache and integrity are found. */
{ {
struct grub_diskfilter_lv *lv1; struct grub_diskfilter_lv *lv1;
struct grub_diskfilter_lv *lv2; struct grub_diskfilter_lv *lv2;
for (lv1 = vg->lvs; lv1; lv1 = lv1->next) for (lv1 = vg->lvs; lv1; lv1 = lv1->next)
for (i = 0; i < lv1->segment_count; i++) for (i = 0; i < lv1->segment_count; i++)
for (j = 0; j < lv1->segments[i].node_count; j++) for (j = 0; j < lv1->segments[i].node_count; j++)
@@ -989,60 +1047,9 @@ grub_lvm_detect (grub_disk_t disk,
lv1->segments[i].nodes[j].lv = lv2; lv1->segments[i].nodes[j].lv = lv2;
} }
} }
} }
{ grub_lvm_free_ignored_feature_lvs (ignored_feature_lvs);
struct cache_lv *cache;
for (cache = cache_lvs; cache; cache = cache->next)
{
struct grub_diskfilter_lv *lv;
for (lv = vg->lvs; lv; lv = lv->next)
if (grub_strcmp (lv->name, cache->origin) == 0)
break;
if (lv)
{
cache->lv->segments = grub_calloc (lv->segment_count, sizeof (*lv->segments));
if (!cache->lv->segments)
{
grub_lvm_free_cache_lvs (cache_lvs);
goto fail4;
}
grub_memcpy (cache->lv->segments, lv->segments, lv->segment_count * sizeof (*lv->segments));
for (i = 0; i < lv->segment_count; ++i)
{
struct grub_diskfilter_node *nodes = lv->segments[i].nodes;
grub_size_t node_count = lv->segments[i].node_count;
cache->lv->segments[i].nodes = grub_calloc (node_count, sizeof (*nodes));
if (!cache->lv->segments[i].nodes)
{
for (j = 0; j < i; ++j)
grub_free (cache->lv->segments[j].nodes);
grub_free (cache->lv->segments);
cache->lv->segments = NULL;
grub_lvm_free_cache_lvs (cache_lvs);
goto fail4;
}
grub_memcpy (cache->lv->segments[i].nodes, nodes, node_count * sizeof (*nodes));
}
if (cache->lv->segments)
{
cache->lv->segment_count = lv->segment_count;
cache->lv->vg = vg;
cache->lv->next = vg->lvs;
vg->lvs = cache->lv;
cache->lv = NULL;
}
}
}
}
grub_lvm_free_cache_lvs (cache_lvs);
if (grub_diskfilter_vg_register (vg)) if (grub_diskfilter_vg_register (vg))
goto fail4; goto fail4;
} }
+78
View File
@@ -23,6 +23,7 @@
#include <grub/err.h> #include <grub/err.h>
#include <grub/misc.h> #include <grub/misc.h>
#include <grub/diskfilter.h> #include <grub/diskfilter.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -103,6 +104,9 @@ struct grub_raid_super_1x
#define WriteMostly1 1 /* Mask for writemostly flag in above devflags. */ #define WriteMostly1 1 /* Mask for writemostly flag in above devflags. */
#define GRUB_MD_SECTOR_SHIFT 9 /* Follow Linux kernel v6.8. */
#define GRUB_MD_SECTOR_SIZE (1 << GRUB_MD_SECTOR_SHIFT)
static struct grub_diskfilter_vg * static struct grub_diskfilter_vg *
grub_mdraid_detect (grub_disk_t disk, grub_mdraid_detect (grub_disk_t disk,
struct grub_diskfilter_pv_id *id, struct grub_diskfilter_pv_id *id,
@@ -129,6 +133,7 @@ grub_mdraid_detect (grub_disk_t disk,
grub_uint32_t level; grub_uint32_t level;
struct grub_diskfilter_vg *array; struct grub_diskfilter_vg *array;
char *uuid; char *uuid;
grub_uint64_t sb_sz, data_end, sb_end;
if (size == GRUB_DISK_SIZE_UNKNOWN && minor_version == 0) if (size == GRUB_DISK_SIZE_UNKNOWN && minor_version == 0)
continue; continue;
@@ -154,6 +159,79 @@ grub_mdraid_detect (grub_disk_t disk,
|| grub_le_to_cpu64 (sb.super_offset) != sector) || grub_le_to_cpu64 (sb.super_offset) != sector)
continue; continue;
/*
* The first check follows the Linux kernel's data_size
* validation from v6.8-rc5.
*/
if (grub_le_to_cpu64 (sb.data_size) < 10 ||
grub_le_to_cpu64 (sb.raid_disks) > GRUB_MDRAID_MAX_DISKS)
{
grub_dprintf ("mdraid1x", "Corrupted superblock\n");
return NULL;
}
/*
* Total size of superblock: 256 bytes plus 2 bytes per device
* in the array.
*/
sb_sz = sizeof (struct grub_raid_super_1x) + grub_le_to_cpu64 (sb.raid_disks) * 2;
if (grub_add (grub_le_to_cpu64 (sb.super_offset),
(ALIGN_UP(sb_sz, GRUB_MD_SECTOR_SIZE) >> GRUB_MD_SECTOR_SHIFT), &sb_end))
{
grub_dprintf ("mdraid1x", "Invalid superblock end.\n");
return NULL;
}
if (grub_add (grub_le_to_cpu64 (sb.data_offset),
grub_le_to_cpu64 (sb.data_size), &data_end))
{
grub_dprintf ("mdraid1x", "Invalid data end.\n");
return NULL;
}
/* In minor versions 1 and 2, superblock is positioned before data. */
if (minor_version)
{
if (grub_le_to_cpu64 (sb.data_offset) < sb_end)
{
grub_dprintf ("mdraid1x",
"The superblock either overlaps with the data "
"or is behind it.\n");
return NULL;
}
if (data_end > size)
{
grub_dprintf ("mdraid1x",
"The data region ends at %" PRIuGRUB_UINT64_T ", "
"past the end of the disk (%" PRIuGRUB_UINT64_T ")\n",
data_end, size);
return NULL;
}
}
else
{
/* In minor version 0, superblock is at the end of the device. */
if (grub_le_to_cpu64 (sb.super_offset) < data_end)
{
grub_dprintf ("mdraid1x",
"The data either overlaps with the superblock "
"or is behind it.\n");
return NULL;
}
if (sb_end > size)
{
grub_dprintf ("mdraid1x",
"The superblock region ends at "
"%" PRIuGRUB_UINT64_T ", past the end of "
"the disk (%" PRIuGRUB_UINT64_T ")\n",
sb_end, size);
return NULL;
}
}
if (sb.major_version != grub_cpu_to_le32_compile_time (1)) if (sb.major_version != grub_cpu_to_le32_compile_time (1))
/* Unsupported version. */ /* Unsupported version. */
return NULL; return NULL;
+8 -1
View File
@@ -23,6 +23,7 @@
#include <grub/misc.h> #include <grub/misc.h>
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/types.h> #include <grub/types.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -96,8 +97,14 @@ GRUB_MOD_INIT(memdisk)
grub_dprintf ("memdisk", "Found memdisk image at %p\n", memdisk_orig_addr); grub_dprintf ("memdisk", "Found memdisk image at %p\n", memdisk_orig_addr);
memdisk_size = header->size - sizeof (struct grub_module_header); if (grub_sub (header->size, sizeof (struct grub_module_header), &memdisk_size))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, "underflow detected while obtaining memdisk size");
return;
}
memdisk_addr = grub_malloc (memdisk_size); memdisk_addr = grub_malloc (memdisk_size);
if (memdisk_addr == NULL)
return;
grub_dprintf ("memdisk", "Copying memdisk image to dynamic memory\n"); grub_dprintf ("memdisk", "Copying memdisk image to dynamic memory\n");
grub_memmove (memdisk_addr, memdisk_orig_addr, memdisk_size); grub_memmove (memdisk_addr, memdisk_orig_addr, memdisk_size);
+7 -2
View File
@@ -24,6 +24,7 @@
#include <grub/extcmd.h> #include <grub/extcmd.h>
#include <grub/partition.h> #include <grub/partition.h>
#include <grub/file.h> #include <grub/file.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -126,7 +127,7 @@ plainmount_configure_password (grub_cryptodisk_t dev, const char *hash,
grub_uint8_t *derived_hash, *dh; grub_uint8_t *derived_hash, *dh;
char *p; char *p;
unsigned int round, i, len, size; unsigned int round, i, len, size;
grub_size_t alloc_size; grub_size_t alloc_size, sz;
grub_err_t err = GRUB_ERR_NONE; grub_err_t err = GRUB_ERR_NONE;
/* Support none (plain) hash */ /* Support none (plain) hash */
@@ -145,7 +146,11 @@ plainmount_configure_password (grub_cryptodisk_t dev, const char *hash,
* Allocate buffer for the password and for an added prefix character * Allocate buffer for the password and for an added prefix character
* for each hash round ('alloc_size' may not be a multiple of 'len'). * for each hash round ('alloc_size' may not be a multiple of 'len').
*/ */
p = grub_zalloc (alloc_size + (alloc_size / len) + 1); if (grub_add (alloc_size, (alloc_size / len), &sz) ||
grub_add (sz, 1, &sz))
return grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow detected while allocating size of password buffer"));
p = grub_zalloc (sz);
derived_hash = grub_zalloc (GRUB_CRYPTODISK_MAX_KEYLEN * 2); derived_hash = grub_zalloc (GRUB_CRYPTODISK_MAX_KEYLEN * 2);
if (p == NULL || derived_hash == NULL) if (p == NULL || derived_hash == NULL)
{ {
+3
View File
@@ -203,6 +203,9 @@ grub_efiemu_count_symbols (const Elf_Ehdr *e)
grub_efiemu_elfsyms = (struct grub_efiemu_elf_sym *) grub_efiemu_elfsyms = (struct grub_efiemu_elf_sym *)
grub_calloc (grub_efiemu_nelfsyms, sizeof (struct grub_efiemu_elf_sym)); grub_calloc (grub_efiemu_nelfsyms, sizeof (struct grub_efiemu_elf_sym));
if (grub_efiemu_elfsyms == NULL)
return grub_errno;
/* Relocators */ /* Relocators */
for (i = 0, s = (Elf_Shdr *) ((char *) e + e->e_shoff); for (i = 0, s = (Elf_Shdr *) ((char *) e + e->e_shoff);
i < e->e_shnum; i < e->e_shnum;
+31 -10
View File
@@ -66,7 +66,7 @@ efiemu_convert_pointer (grub_efi_uintn_t debug_disposition,
grub_efi_status_t __grub_efi_api grub_efi_status_t __grub_efi_api
efiemu_get_variable (grub_efi_char16_t *variable_name, efiemu_get_variable (grub_efi_char16_t *variable_name,
const grub_guid_t *vendor_guid, const grub_packed_guid_t *vendor_guid,
grub_efi_uint32_t *attributes, grub_efi_uint32_t *attributes,
grub_efi_uintn_t *data_size, grub_efi_uintn_t *data_size,
void *data); void *data);
@@ -74,11 +74,11 @@ efiemu_get_variable (grub_efi_char16_t *variable_name,
grub_efi_status_t __grub_efi_api grub_efi_status_t __grub_efi_api
efiemu_get_next_variable_name (grub_efi_uintn_t *variable_name_size, efiemu_get_next_variable_name (grub_efi_uintn_t *variable_name_size,
grub_efi_char16_t *variable_name, grub_efi_char16_t *variable_name,
grub_guid_t *vendor_guid); grub_packed_guid_t *vendor_guid);
grub_efi_status_t __grub_efi_api grub_efi_status_t __grub_efi_api
efiemu_set_variable (grub_efi_char16_t *variable_name, efiemu_set_variable (grub_efi_char16_t *variable_name,
const grub_guid_t *vendor_guid, const grub_packed_guid_t *vendor_guid,
grub_efi_uint32_t attributes, grub_efi_uint32_t attributes,
grub_efi_uintn_t data_size, grub_efi_uintn_t data_size,
void *data); void *data);
@@ -416,7 +416,7 @@ EFI_FUNC (efiemu_convert_pointer) (grub_efi_uintn_t debug_disposition,
/* Find variable by name and GUID. */ /* Find variable by name and GUID. */
static struct efi_variable * static struct efi_variable *
find_variable (const grub_guid_t *vendor_guid, find_variable (const grub_packed_guid_t *vendor_guid,
grub_efi_char16_t *variable_name) grub_efi_char16_t *variable_name)
{ {
grub_uint8_t *ptr; grub_uint8_t *ptr;
@@ -438,7 +438,7 @@ find_variable (const grub_guid_t *vendor_guid,
grub_efi_status_t __grub_efi_api grub_efi_status_t __grub_efi_api
EFI_FUNC (efiemu_get_variable) (grub_efi_char16_t *variable_name, EFI_FUNC (efiemu_get_variable) (grub_efi_char16_t *variable_name,
const grub_guid_t *vendor_guid, const grub_packed_guid_t *vendor_guid,
grub_efi_uint32_t *attributes, grub_efi_uint32_t *attributes,
grub_efi_uintn_t *data_size, grub_efi_uintn_t *data_size,
void *data) void *data)
@@ -464,7 +464,7 @@ EFI_FUNC (efiemu_get_variable) (grub_efi_char16_t *variable_name,
grub_efi_status_t __grub_efi_api EFI_FUNC grub_efi_status_t __grub_efi_api EFI_FUNC
(efiemu_get_next_variable_name) (grub_efi_uintn_t *variable_name_size, (efiemu_get_next_variable_name) (grub_efi_uintn_t *variable_name_size,
grub_efi_char16_t *variable_name, grub_efi_char16_t *variable_name,
grub_guid_t *vendor_guid) grub_packed_guid_t *vendor_guid)
{ {
struct efi_variable *efivar; struct efi_variable *efivar;
LOG ('l'); LOG ('l');
@@ -503,7 +503,7 @@ grub_efi_status_t __grub_efi_api EFI_FUNC
grub_efi_status_t __grub_efi_api grub_efi_status_t __grub_efi_api
EFI_FUNC (efiemu_set_variable) (grub_efi_char16_t *variable_name, EFI_FUNC (efiemu_set_variable) (grub_efi_char16_t *variable_name,
const grub_guid_t *vendor_guid, const grub_packed_guid_t *vendor_guid,
grub_efi_uint32_t attributes, grub_efi_uint32_t attributes,
grub_efi_uintn_t data_size, grub_efi_uintn_t data_size,
void *data) void *data)
@@ -597,9 +597,30 @@ struct grub_efi_runtime_services efiemu_runtime_services =
.set_virtual_address_map = efiemu_set_virtual_address_map, .set_virtual_address_map = efiemu_set_virtual_address_map,
.convert_pointer = efiemu_convert_pointer, .convert_pointer = efiemu_convert_pointer,
.get_variable = efiemu_get_variable, /*
.get_next_variable_name = efiemu_get_next_variable_name, The code is structured in a way to accept unaligned inputs
.set_variable = efiemu_set_variable, in most cases and supply 4-byte aligned outputs.
Efiemu case is a bit ugly because there inputs and outputs are
reversed and so we need careful casts to account for this
inversion.
*/
.get_variable = (grub_efi_status_t
(__grub_efi_api *) (grub_efi_char16_t *variable_name,
const grub_guid_t *vendor_guid,
grub_efi_uint32_t *attributes,
grub_efi_uintn_t *data_size,
void *data)) efiemu_get_variable,
.get_next_variable_name = (grub_efi_status_t
(__grub_efi_api *) (grub_efi_uintn_t *variable_name_size,
grub_efi_char16_t *variable_name,
grub_guid_t *vendor_guid)) efiemu_get_next_variable_name,
.set_variable = (grub_efi_status_t
(__grub_efi_api *) (grub_efi_char16_t *variable_name,
const grub_guid_t *vendor_guid,
grub_efi_uint32_t attributes,
grub_efi_uintn_t data_size,
void *data)) efiemu_set_variable,
.get_next_high_monotonic_count = efiemu_get_next_high_monotonic_count, .get_next_high_monotonic_count = efiemu_get_next_high_monotonic_count,
.reset_system = efiemu_reset_system .reset_system = efiemu_reset_system
+8 -2
View File
@@ -26,6 +26,7 @@
#include <grub/types.h> #include <grub/types.h>
#include <grub/fshelp.h> #include <grub/fshelp.h>
#include <grub/charset.h> #include <grub/charset.h>
#include <grub/lockdown.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -703,11 +704,16 @@ static struct grub_fs grub_affs_fs =
GRUB_MOD_INIT(affs) GRUB_MOD_INIT(affs)
{ {
grub_fs_register (&grub_affs_fs); if (!grub_is_lockdown ())
{
grub_affs_fs.mod = mod;
grub_fs_register (&grub_affs_fs);
}
my_mod = mod; my_mod = mod;
} }
GRUB_MOD_FINI(affs) GRUB_MOD_FINI(affs)
{ {
grub_fs_unregister (&grub_affs_fs); if (!grub_is_lockdown ())
grub_fs_unregister (&grub_affs_fs);
} }
+16 -1
View File
@@ -21,6 +21,7 @@
#include <grub/fs.h> #include <grub/fs.h>
#include <grub/disk.h> #include <grub/disk.h>
#include <grub/dl.h> #include <grub/dl.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -68,6 +69,7 @@ handle_symlink (struct grub_archelp_data *data,
char *rest; char *rest;
char *linktarget; char *linktarget;
grub_size_t linktarget_len; grub_size_t linktarget_len;
grub_size_t sz;
*restart = 0; *restart = 0;
@@ -98,7 +100,12 @@ handle_symlink (struct grub_archelp_data *data,
if (linktarget[0] == '\0') if (linktarget[0] == '\0')
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
linktarget_len = grub_strlen (linktarget); linktarget_len = grub_strlen (linktarget);
target = grub_malloc (linktarget_len + grub_strlen (*name) + 2);
if (grub_add (linktarget_len, grub_strlen (*name), &sz) ||
grub_add (sz, 2, &sz))
return grub_error (GRUB_ERR_OUT_OF_RANGE, N_("link target length overflow"));
target = grub_malloc (sz);
if (!target) if (!target)
return grub_errno; return grub_errno;
@@ -180,6 +187,14 @@ grub_archelp_dir (struct grub_archelp_data *data,
if (p) if (p)
*p = 0; *p = 0;
if ((*n == 0) && ((mode & GRUB_ARCHELP_ATTR_TYPE)
!= GRUB_ARCHELP_ATTR_DIR))
{
grub_error (GRUB_ERR_BAD_FILE_TYPE, N_("not a directory"));
grub_free (name);
goto fail;
}
if (((!prev) || (grub_strcmp (prev, name) != 0)) && *n != 0) if (((!prev) || (grub_strcmp (prev, name) != 0)) && *n != 0)
{ {
struct grub_dirhook_info info; struct grub_dirhook_info info;
+9 -3
View File
@@ -30,6 +30,7 @@
#include <grub/types.h> #include <grub/types.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/fshelp.h> #include <grub/fshelp.h>
#include <grub/lockdown.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -808,7 +809,7 @@ find_file (const char *path, grub_disk_t disk,
.disk = disk, .disk = disk,
.sb = sb, .sb = sb,
}; };
struct grub_fshelp_node *found; struct grub_fshelp_node *found = NULL;
err = read_extent (disk, sb, &sb->root_dir, 0, 0, &root.ino, err = read_extent (disk, sb, &sb->root_dir, 0, 0, &root.ino,
sizeof (root.ino)); sizeof (root.ino));
@@ -1106,7 +1107,11 @@ GRUB_MOD_INIT (bfs)
{ {
COMPILE_TIME_ASSERT (1 << LOG_EXTENT_SIZE == COMPILE_TIME_ASSERT (1 << LOG_EXTENT_SIZE ==
sizeof (struct grub_bfs_extent)); sizeof (struct grub_bfs_extent));
grub_fs_register (&grub_bfs_fs); if (!grub_is_lockdown ())
{
grub_bfs_fs.mod = mod;
grub_fs_register (&grub_bfs_fs);
}
} }
#ifdef MODE_AFS #ifdef MODE_AFS
@@ -1115,5 +1120,6 @@ GRUB_MOD_FINI (afs)
GRUB_MOD_FINI (bfs) GRUB_MOD_FINI (bfs)
#endif #endif
{ {
grub_fs_unregister (&grub_bfs_fs); if (!grub_is_lockdown ())
grub_fs_unregister (&grub_bfs_fs);
} }
+49 -11
View File
@@ -1276,8 +1276,8 @@ grub_btrfs_mount (grub_device_t dev)
} }
data->n_devices_allocated = 16; data->n_devices_allocated = 16;
data->devices_attached = grub_malloc (sizeof (data->devices_attached[0]) data->devices_attached = grub_calloc (data->n_devices_allocated,
* data->n_devices_allocated); sizeof (data->devices_attached[0]));
if (!data->devices_attached) if (!data->devices_attached)
{ {
grub_free (data); grub_free (data);
@@ -1538,7 +1538,10 @@ grub_btrfs_extent_read (struct grub_btrfs_data *data,
err = lower_bound (data, &key_in, &key_out, tree, err = lower_bound (data, &key_in, &key_out, tree,
&elemaddr, &elemsize, &desc, 0); &elemaddr, &elemsize, &desc, 0);
if (err) if (err)
return -1; {
grub_free (desc.data);
return -1;
}
if (key_out.object_id != ino if (key_out.object_id != ino
|| key_out.type != GRUB_BTRFS_ITEM_TYPE_EXTENT_ITEM) || key_out.type != GRUB_BTRFS_ITEM_TYPE_EXTENT_ITEM)
{ {
@@ -1603,6 +1606,8 @@ grub_btrfs_extent_read (struct grub_btrfs_data *data,
csize = grub_le_to_cpu64 (key_out.offset) - pos; csize = grub_le_to_cpu64 (key_out.offset) - pos;
if (csize > len) if (csize > len)
csize = len; csize = len;
grub_memset (buf, 0, csize);
buf += csize; buf += csize;
pos += csize; pos += csize;
len -= csize; len -= csize;
@@ -1799,6 +1804,7 @@ find_path (struct grub_btrfs_data *data,
char *path_alloc = NULL; char *path_alloc = NULL;
char *origpath = NULL; char *origpath = NULL;
unsigned symlinks_max = 32; unsigned symlinks_max = 32;
grub_size_t sz;
err = get_root (data, key, tree, type); err = get_root (data, key, tree, type);
if (err) if (err)
@@ -1889,9 +1895,15 @@ find_path (struct grub_btrfs_data *data,
struct grub_btrfs_dir_item *cdirel; struct grub_btrfs_dir_item *cdirel;
if (elemsize > allocated) if (elemsize > allocated)
{ {
allocated = 2 * elemsize; if (grub_mul (2, elemsize, &allocated) ||
grub_add (allocated, 1, &sz))
{
grub_free (path_alloc);
grub_free (origpath);
return grub_error (GRUB_ERR_OUT_OF_RANGE, N_("directory item size overflow"));
}
grub_free (direl); grub_free (direl);
direl = grub_malloc (allocated + 1); direl = grub_malloc (sz);
if (!direl) if (!direl)
{ {
grub_free (path_alloc); grub_free (path_alloc);
@@ -1953,8 +1965,16 @@ find_path (struct grub_btrfs_data *data,
grub_free (origpath); grub_free (origpath);
return err; return err;
} }
tmp = grub_malloc (grub_le_to_cpu64 (inode.size)
+ grub_strlen (path) + 1); if (grub_add (grub_le_to_cpu64 (inode.size), grub_strlen (path), &sz) ||
grub_add (sz, 1, &sz))
{
grub_free (direl);
grub_free (path_alloc);
grub_free (origpath);
return grub_error (GRUB_ERR_OUT_OF_RANGE, N_("buffer size overflow"));
}
tmp = grub_malloc (sz);
if (!tmp) if (!tmp)
{ {
grub_free (direl); grub_free (direl);
@@ -2076,6 +2096,7 @@ grub_btrfs_dir (grub_device_t device, const char *path,
grub_uint64_t tree; grub_uint64_t tree;
grub_uint8_t type; grub_uint8_t type;
grub_size_t est_size = 0; grub_size_t est_size = 0;
grub_size_t sz;
if (!data) if (!data)
return grub_errno; return grub_errno;
@@ -2097,6 +2118,7 @@ grub_btrfs_dir (grub_device_t device, const char *path,
if (err) if (err)
{ {
grub_btrfs_unmount (data); grub_btrfs_unmount (data);
grub_free (desc.data);
return err; return err;
} }
if (key_out.type != GRUB_BTRFS_ITEM_TYPE_DIR_ITEM if (key_out.type != GRUB_BTRFS_ITEM_TYPE_DIR_ITEM
@@ -2117,9 +2139,15 @@ grub_btrfs_dir (grub_device_t device, const char *path,
} }
if (elemsize > allocated) if (elemsize > allocated)
{ {
allocated = 2 * elemsize; if (grub_mul (2, elemsize, &allocated) ||
grub_add (allocated, 1, &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("directory element size overflow"));
r = -grub_errno;
break;
}
grub_free (direl); grub_free (direl);
direl = grub_malloc (allocated + 1); direl = grub_malloc (sz);
if (!direl) if (!direl)
{ {
r = -grub_errno; r = -grub_errno;
@@ -2306,14 +2334,20 @@ struct embed_region {
}; };
/* /*
* https://btrfs.wiki.kernel.org/index.php/Manpage/btrfs(5)#BOOTLOADER_SUPPORT * https://btrfs.readthedocs.io/en/latest/btrfs-man5.html#man-btrfs5-bootloader-support
* or invoke "man 5 btrfs" and visit the "BOOTLOADER SUPPORT" subsection.
* The first 1 MiB on each device is unused with the exception of primary * The first 1 MiB on each device is unused with the exception of primary
* superblock that is on the offset 64 KiB and spans 4 KiB. * superblock that is on the offset 64 KiB and spans 4 KiB.
*
* Note: If this table is modified, also update
* util/grub-editenv.c::fs_envblk_spec, which describes the file-system
* specific layout of reserved raw blocks used as environment blocks so that
* both stay consistent.
*/ */
static const struct { static const struct {
struct embed_region available; struct embed_region available;
struct embed_region used[6]; struct embed_region used[9];
} btrfs_head = { } btrfs_head = {
.available = {0, GRUB_DISK_KiB_TO_SECTORS (1024)}, /* The first 1 MiB. */ .available = {0, GRUB_DISK_KiB_TO_SECTORS (1024)}, /* The first 1 MiB. */
.used = { .used = {
@@ -2321,6 +2355,9 @@ static const struct {
{GRUB_DISK_KiB_TO_SECTORS (64) - 1, 1}, /* Overflow guard. */ {GRUB_DISK_KiB_TO_SECTORS (64) - 1, 1}, /* Overflow guard. */
{GRUB_DISK_KiB_TO_SECTORS (64), GRUB_DISK_KiB_TO_SECTORS (4)}, /* 4 KiB superblock. */ {GRUB_DISK_KiB_TO_SECTORS (64), GRUB_DISK_KiB_TO_SECTORS (4)}, /* 4 KiB superblock. */
{GRUB_DISK_KiB_TO_SECTORS (68), 1}, /* Overflow guard. */ {GRUB_DISK_KiB_TO_SECTORS (68), 1}, /* Overflow guard. */
{(GRUB_ENV_BTRFS_OFFSET >> GRUB_DISK_SECTOR_BITS) - 1, 1}, /* Overflow guard. */
{(GRUB_ENV_BTRFS_OFFSET >> GRUB_DISK_SECTOR_BITS), 1}, /* Environment Block. */
{(GRUB_ENV_BTRFS_OFFSET >> GRUB_DISK_SECTOR_BITS) + 1, 1}, /* Overflow guard. */
{GRUB_DISK_KiB_TO_SECTORS (1024) - 1, 1}, /* Overflow guard. */ {GRUB_DISK_KiB_TO_SECTORS (1024) - 1, 1}, /* Overflow guard. */
{0, 0} /* Array terminator. */ {0, 0} /* Array terminator. */
} }
@@ -2411,6 +2448,7 @@ static struct grub_fs grub_btrfs_fs = {
GRUB_MOD_INIT (btrfs) GRUB_MOD_INIT (btrfs)
{ {
grub_btrfs_fs.mod = mod;
grub_fs_register (&grub_btrfs_fs); grub_fs_register (&grub_btrfs_fs);
} }
+8 -2
View File
@@ -26,6 +26,7 @@
#include <grub/dl.h> #include <grub/dl.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/cbfs_core.h> #include <grub/cbfs_core.h>
#include <grub/lockdown.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -390,12 +391,17 @@ GRUB_MOD_INIT (cbfs)
#if (defined (__i386__) || defined (__x86_64__)) && !defined (GRUB_UTIL) && !defined (GRUB_MACHINE_EMU) && !defined (GRUB_MACHINE_XEN) #if (defined (__i386__) || defined (__x86_64__)) && !defined (GRUB_UTIL) && !defined (GRUB_MACHINE_EMU) && !defined (GRUB_MACHINE_XEN)
init_cbfsdisk (); init_cbfsdisk ();
#endif #endif
grub_fs_register (&grub_cbfs_fs); if (!grub_is_lockdown ())
{
grub_cbfs_fs.mod = mod;
grub_fs_register (&grub_cbfs_fs);
}
} }
GRUB_MOD_FINI (cbfs) GRUB_MOD_FINI (cbfs)
{ {
grub_fs_unregister (&grub_cbfs_fs); if (!grub_is_lockdown ())
grub_fs_unregister (&grub_cbfs_fs);
#if (defined (__i386__) || defined (__x86_64__)) && !defined (GRUB_UTIL) && !defined (GRUB_MACHINE_EMU) && !defined (GRUB_MACHINE_XEN) #if (defined (__i386__) || defined (__x86_64__)) && !defined (GRUB_UTIL) && !defined (GRUB_MACHINE_EMU) && !defined (GRUB_MACHINE_XEN)
fini_cbfsdisk (); fini_cbfsdisk ();
#endif #endif
+1
View File
@@ -52,6 +52,7 @@ read_number (const grub_uint16_t *arr, grub_size_t size)
GRUB_MOD_INIT (cpio) GRUB_MOD_INIT (cpio)
{ {
grub_cpio_fs.mod = mod;
grub_fs_register (&grub_cpio_fs); grub_fs_register (&grub_cpio_fs);
} }
+1
View File
@@ -52,6 +52,7 @@ read_number (const grub_uint16_t *arr, grub_size_t size)
GRUB_MOD_INIT (cpio_be) GRUB_MOD_INIT (cpio_be)
{ {
grub_cpio_fs.mod = mod;
grub_fs_register (&grub_cpio_fs); grub_fs_register (&grub_cpio_fs);
} }
+28 -6
View File
@@ -24,6 +24,7 @@
#include <grub/dl.h> #include <grub/dl.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/archelp.h> #include <grub/archelp.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -48,6 +49,7 @@ grub_cpio_find_file (struct grub_archelp_data *data, char **name,
struct head hd; struct head hd;
grub_size_t namesize; grub_size_t namesize;
grub_uint32_t modeval; grub_uint32_t modeval;
grub_size_t sz;
data->hofs = data->next_hofs; data->hofs = data->next_hofs;
@@ -60,11 +62,21 @@ grub_cpio_find_file (struct grub_archelp_data *data, char **name,
#endif #endif
) )
return grub_error (GRUB_ERR_BAD_FS, "invalid cpio archive"); return grub_error (GRUB_ERR_BAD_FS, "invalid cpio archive");
data->size = read_number (hd.filesize, ARRAY_SIZE (hd.filesize));
if (grub_cast (read_number (hd.filesize, ARRAY_SIZE (hd.filesize)), &data->size))
return grub_error (GRUB_ERR_BAD_FS, N_("data size overflow"));
if (mtime) if (mtime)
*mtime = read_number (hd.mtime, ARRAY_SIZE (hd.mtime)); {
modeval = read_number (hd.mode, ARRAY_SIZE (hd.mode)); if (grub_cast (read_number (hd.mtime, ARRAY_SIZE (hd.mtime)), mtime))
namesize = read_number (hd.namesize, ARRAY_SIZE (hd.namesize)); return grub_error (GRUB_ERR_BAD_FS, N_("mtime overflow"));
}
if (grub_cast (read_number (hd.mode, ARRAY_SIZE (hd.mode)), &modeval))
return grub_error (GRUB_ERR_BAD_FS, N_("mode overflow"));
if (grub_cast (read_number (hd.namesize, ARRAY_SIZE (hd.namesize)), &namesize))
return grub_error (GRUB_ERR_BAD_FS, N_("namesize overflow"));
/* Don't allow negative numbers. */ /* Don't allow negative numbers. */
if (namesize >= 0x80000000) if (namesize >= 0x80000000)
@@ -76,7 +88,10 @@ grub_cpio_find_file (struct grub_archelp_data *data, char **name,
*mode = modeval; *mode = modeval;
*name = grub_malloc (namesize + 1); if (grub_add (namesize, 1, &sz))
return grub_error (GRUB_ERR_OUT_OF_RANGE, N_("file name size overflow"));
*name = grub_malloc (sz);
if (*name == NULL) if (*name == NULL)
return grub_errno; return grub_errno;
@@ -110,10 +125,17 @@ grub_cpio_get_link_target (struct grub_archelp_data *data)
{ {
char *ret; char *ret;
grub_err_t err; grub_err_t err;
grub_size_t sz;
if (data->size == 0) if (data->size == 0)
return grub_strdup (""); return grub_strdup ("");
ret = grub_malloc (data->size + 1);
if (grub_add (data->size, 1, &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("target data size overflow"));
return NULL;
}
ret = grub_malloc (sz);
if (!ret) if (!ret)
return NULL; return NULL;
+1006
View File
File diff suppressed because it is too large. Load diff
+23 -1
View File
@@ -495,6 +495,11 @@ grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
struct grub_ext4_extent *ext; struct grub_ext4_extent *ext;
int i; int i;
grub_disk_addr_t ret; grub_disk_addr_t ret;
grub_uint16_t nent;
/* Maximum number of extent entries in the inode's inline extent area. */
const grub_uint16_t max_inline_ext = sizeof (inode->blocks) / sizeof (*ext) - 1; /* Minus 1 extent header. */
/* Maximum number of extent entries in the external extent block. */
const grub_uint16_t max_external_ext = EXT2_BLOCK_SIZE (data) / sizeof (*ext) - 1; /* Minus 1 extent header. */
if (grub_ext4_find_leaf (data, (struct grub_ext4_extent_header *) inode->blocks.dir_blocks, if (grub_ext4_find_leaf (data, (struct grub_ext4_extent_header *) inode->blocks.dir_blocks,
fileblock, &leaf) != GRUB_ERR_NONE) fileblock, &leaf) != GRUB_ERR_NONE)
@@ -508,7 +513,23 @@ grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
return 0; return 0;
ext = (struct grub_ext4_extent *) (leaf + 1); ext = (struct grub_ext4_extent *) (leaf + 1);
for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++)
nent = grub_le_to_cpu16 (leaf->entries);
/*
* Determine the effective number of extent entries (nent) to process.
* If the extent header (leaf) is stored inline in the inode’s block
* area, i.e. at inode->blocks.dir_blocks, then only max_inline_ext
* entries can fit. Otherwise, if the header was read from an external
* extent block use the larger limit, max_external_ext, based on the
* full block size.
*/
if (leaf == (struct grub_ext4_extent_header *) inode->blocks.dir_blocks)
nent = grub_min (nent, max_inline_ext);
else
nent = grub_min (nent, max_external_ext);
for (i = 0; i < nent; i++)
{ {
if (fileblock < grub_le_to_cpu32 (ext[i].block)) if (fileblock < grub_le_to_cpu32 (ext[i].block))
break; break;
@@ -1123,6 +1144,7 @@ static struct grub_fs grub_ext2_fs =
GRUB_MOD_INIT(ext2) GRUB_MOD_INIT(ext2)
{ {
grub_ext2_fs.mod = mod;
grub_fs_register (&grub_ext2_fs); grub_fs_register (&grub_ext2_fs);
my_mod = mod; my_mod = mod;
} }
+19 -2
View File
@@ -28,6 +28,7 @@
#include <grub/types.h> #include <grub/types.h>
#include <grub/charset.h> #include <grub/charset.h>
#include <grub/fshelp.h> #include <grub/fshelp.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -872,6 +873,9 @@ grub_f2fs_mount (grub_disk_t disk)
return data; return data;
fail: fail:
if (grub_errno == GRUB_ERR_NONE)
grub_error (GRUB_ERR_BAD_FS, "not a F2FS filesystem");
grub_free (data); grub_free (data);
return NULL; return NULL;
@@ -955,6 +959,7 @@ grub_f2fs_read_symlink (grub_fshelp_node_t node)
char *symlink; char *symlink;
struct grub_fshelp_node *diro = node; struct grub_fshelp_node *diro = node;
grub_uint64_t filesize; grub_uint64_t filesize;
grub_size_t sz;
if (!diro->inode_read) if (!diro->inode_read)
{ {
@@ -965,7 +970,12 @@ grub_f2fs_read_symlink (grub_fshelp_node_t node)
filesize = grub_f2fs_file_size(&diro->inode.i); filesize = grub_f2fs_file_size(&diro->inode.i);
symlink = grub_malloc (filesize + 1); if (grub_add (filesize, 1, &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("symlink size overflow"));
return 0;
}
symlink = grub_malloc (sz);
if (!symlink) if (!symlink)
return 0; return 0;
@@ -994,6 +1004,7 @@ grub_f2fs_check_dentries (struct grub_f2fs_dir_iter_ctx *ctx)
enum FILE_TYPE ftype; enum FILE_TYPE ftype;
int name_len; int name_len;
int ret; int ret;
int sz;
if (grub_f2fs_test_bit_le (i, ctx->bitmap) == 0) if (grub_f2fs_test_bit_le (i, ctx->bitmap) == 0)
{ {
@@ -1007,7 +1018,12 @@ grub_f2fs_check_dentries (struct grub_f2fs_dir_iter_ctx *ctx)
if (name_len >= F2FS_NAME_LEN) if (name_len >= F2FS_NAME_LEN)
return 0; return 0;
filename = grub_malloc (name_len + 1); if (grub_add (name_len, 1, &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("directory entry name length overflow"));
return 0;
}
filename = grub_malloc (sz);
if (!filename) if (!filename)
return 0; return 0;
@@ -1350,6 +1366,7 @@ static struct grub_fs grub_f2fs_fs = {
GRUB_MOD_INIT (f2fs) GRUB_MOD_INIT (f2fs)
{ {
grub_f2fs_fs.mod = mod;
grub_fs_register (&grub_f2fs_fs); grub_fs_register (&grub_f2fs_fs);
my_mod = mod; my_mod = mod;
} }
+1
View File
@@ -1312,6 +1312,7 @@ GRUB_MOD_INIT(fat)
#endif #endif
{ {
COMPILE_TIME_ASSERT (sizeof (struct grub_fat_dir_entry) == 32); COMPILE_TIME_ASSERT (sizeof (struct grub_fat_dir_entry) == 32);
grub_fat_fs.mod = mod;
grub_fs_register (&grub_fat_fs); grub_fs_register (&grub_fat_fs);
my_mod = mod; my_mod = mod;
} }
Loaded 100 of 986 files, more files were not shown because too many files have changed in this diff. Show more