Compare commits

..
Author SHA1 Message Date
Javier Martinez Canillas c0e647eb0e util/mkimage: Fix wrong PE32+ section sizes for some arches
The commit f60ba9e594 (util/mkimage: Refactor section setup to use a helper)
added a helper function to setup PE sections. But it also changed how the
raw data offsets were calculated since all the section sizes are aligned.
However, for some platforms, i.e ia64-efi and arm64-efi, the kernel image
size is not aligned using the section alignment. This leads to the situation
in which the mods section offset in its PE section header does not match its
real placement in the PE file. So, finally the GRUB is not able to locate
and load built-in modules.

The problem surfaces on ia64-efi and arm64-efi because both platforms
require additional relocation data which is added behind .bss section.
So, we have to add some padding behind this extra data to make the
beginning of mods section properly aligned in the PE file. Fix it by
aligning the kernel_size to the section alignment. That makes the sizes
and offsets in the PE section headers to match relevant sections in the
PE32+ binary file.

Reported-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Tested-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-05-10 15:18:34 +02:00
Daniel Kiper 88e856a5b3 term/terminfo: Fix the terminfo command help and documentation
Additionally, fix the terminfo spelling mistake in
the GRUB development documentation.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
2021-05-10 15:08:39 +02:00
Daniel Kiper 3a1afa19ca i18n: Align N_() formatting with the rest of GRUB code
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
2021-05-10 15:07:58 +02:00
Daniel Kiper 66be067e61 i18n: Format large integers before the translation message - take 2
This is an additional fix which has been missing from the commit 837fe48de
(i18n: Format large integers before the translation message).

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
2021-05-10 15:06:33 +02:00
Miguel Ángel Arruga Vivas 837fe48deb i18n: Format large integers before the translation message
The GNU gettext only supports the ISO C99 macros for integral
types. If there is a need to use unsupported formatting macros,
e.g. PRIuGRUB_UINT64_T, according to [1] the number to a string
conversion should be separated from the code printing message
requiring the internationalization. So, the function grub_snprintf()
is used to print the numeric values to an intermediate buffer and
the internationalized message contains a string format directive.

[1] https://www.gnu.org/software/gettext/manual/html_node/Preparing-Strings.html#No-string-concatenation

Signed-off-by: Miguel Ángel Arruga Vivas <rosen644835@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-04-13 17:16:04 +02:00
Daniel Axtens e48fc8880d video/fb/fbfill: Use unsigned integers for width/height
Since commit 7ce3259f67 (video/fb/fbfill: Fix potential integer
overflow), clang builds of grub-emu have failed with messages like:

  /usr/bin/ld: libgrubmods.a(libgrubmods_a-fbfill.o): in function `grub_video_fbfill_direct24':
  fbfill.c:(.text+0x28e): undefined reference to `__muloti4'

This appears to be due to a weird quirk in how clang compiles

  grub_mul(dst->mode_info->bytes_per_pixel, width, &rowskip)

which is grub_mul(unsigned int, int, &grub_size_t).

It looks like clang somewhere promotes everything to 128-bit maths
before ultimately reducing down to 64 bit for grub_size_t. I think
this is because width is signed, and indeed converting width to an
unsigned int makes the problem go away.

This conversion also makes more sense generally:
  - the caller of all the fbfill_directN functions is
    grub_video_fb_fill_dispatch() and it takes width and height as
    unsigned ints already,
  - it doesn't make sense to fill a negative width or height.

Convert the width and height arguments and associated loop counters
to unsigned ints.

Fixes: 7ce3259f67 (video/fb/fbfill: Fix potential integer overflow)

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-04-12 16:56:45 +02:00
Glenn Washburn 406dde6f27 docs: Conform badmem and cutmem description indentations with other commands
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-04-12 16:49:40 +02:00
Glenn Washburn cb715be37d docs: Add note to cryptomount that UUIDs should be specified without dashes
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-04-12 16:46:27 +02:00
Aru Sahni 7227376308 templates: Fix user-facing typo with an incorrect use of "it's"
Since the possessive form of "it" is being used, the apostrophe must be omitted.

Signed-off-by: Aru Sahni <aru@arusahni.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-04-12 16:40:34 +02:00
Colin Watson edbe7076cb buffer: Sync up out-of-range error message
The messages associated with other similar GRUB_ERR_OUT_OF_RANGE errors
were lacking the trailing full stop. Syncing up the strings saves a small
amount of precious core image space on i386-pc.

  DOWN: obj/i386-pc/grub-core/kernel.img (31740 > 31708) - change: -32
  DOWN: i386-pc core image (biosdisk ext2 part_msdos) (27453 > 27452) - change: -1
  DOWN: i386-pc core image (biosdisk ext2 part_msdos diskfilter mdraid09) (32367 > 32359) - change: -8

Signed-off-by: Colin Watson <cjwatson@debian.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-04-12 16:31:18 +02:00
Glenn Washburn c9c22dc803 usb/usbhub: Use GRUB_USB_MAX_CONF macro instead of literal in hub for maximum configs
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-04-12 16:26:49 +02:00
Daniel Drake 25d64bb273 fs/minix: Avoid mistakenly probing ext2 filesystems
The ext2 (and ext3, ext4) filesystems write the number of free inodes to
location 0x410.

On a MINIX filesystem, that same location is used for the MINIX superblock
magic number.

If the number of free inodes on an ext2 filesystem is equal to any
of the four MINIX superblock magic values plus any multiple of 65536,
GRUB's MINIX filesystem code will probe it as a MINIX filesystem.

In the case of an OS using ext2 as the root filesystem, since there will
ordinarily be some amount of file creation and deletion on every bootup,
it effectively means that this situation has a 1:16384 chance of being hit
on every reboot.

This will cause GRUB's filesystem probing code to mistakenly identify an
ext2 filesystem as MINIX. This can be seen by e.g. "search --label"
incorrectly indicating that no such ext2 partition with matching label
exists, whereas in fact it does.

After spotting the rough cause of the issue I was facing here, I borrowed
much of the diagnosis/explanation from meierfra who found and investigated
the same issue in util-linux in 2010:

  https://bugs.launchpad.net/ubuntu/+source/util-linux/+bug/518582

This was fixed in util-linux by having the MINIX code check for the
ext2 magic. Do the same here.

Signed-off-by: Daniel Drake <drake@endlessm.com>
Reviewed-by: Derek Foreman <derek@endlessos.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-04-12 16:22:44 +02:00
Daniel Kiper a53e530f8a Release 2.06~rc1
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-12 16:09:51 +01:00
Ard Biesheuvel a166484483 arm/linux: Fix ARM Linux header layout
The hdr_offset member of the ARM Linux image header appears at
offset 0x3c, matching the PE/COFF spec's placement of the COFF
header offset in the MS-DOS header. We're currently off by four,
so fix that.

Signed-off-by: Ard Biesheuvel <ard.biesheuvel@arm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-11 20:57:42 +01:00
Glenn Washburn 39cfb3eb5c style: Format string macro should have a space between quotes
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 15:23:34 +01:00
Glenn Washburn 57236f2dd9 grub/err: Do compile-time format string checking on grub_error()
This should help prevent format string errors and thus improve the quality
of error reporting.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 15:23:34 +01:00
Glenn Washburn e458caffb8 fs/zfs/zfs: Use format code "%llu" for 64-bit uint bp->blk_prop in grub_error()
This is a temporary, less-intrusive change to get the build to success with
compiler format string checking turned on. There is a better fix which
addresses this issue, but it needs more testing. Use this change so that
format string checking on grub_error() can be turned on until the better
change is fully tested.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 15:23:33 +01:00
Glenn Washburn e72139a76e fs/hfsplus: Use format code PRIuGRUB_UINT64_T for 64-bit typed fileblock in grub_error()
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 15:23:33 +01:00
Glenn Washburn d028b1a35e dl/elf: Use format code PRIxGRUB_UINT64_T for 64-bit arg in grub_error()
The macro ELF_R_TYPE does not change the underlying type. Here its argument
is a 64-bit Elf64_Xword. Make sure the format code matches.

For the RISC-V architecture, rel->r_info could be either Elf32_Xword or
Elf64_Xword depending on if 32 or 64-bit RISC-V is being built. So cast
to 64-bit value regardless.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 15:22:18 +01:00
Glenn Washburn c95ec30d48 disk/ata: Use format code PRIxGRUB_UINT64_T for 64-bit uint argument in grub_error()
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 15:01:08 +01:00
Glenn Washburn 5625825434 loader/i386/pc/linux: Use PRI* macros to get correct format string code across architectures
Also remove casting of format string args so that the architecture dependent
type is preserved.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 14:59:26 +01:00
Glenn Washburn e2ac93f09a kern/efi/mm: Format string error in grub_error()
The second format string argument, GRUB_EFI_MAX_USABLE_ADDRESS, is a macro
to a number literal. However, depending on what the target architecture, the
type can be 32 or 64 bits. Cast to a 64-bit integer. Also, change the
format string literals "%llx" to use PRIxGRUB_UINT64_T.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 14:56:06 +01:00
Glenn Washburn 12371e40ea commands/pgp: Format code for grub_error() is incorrect
The format code is for a 32-bit int, but the argument, keyid, is declared as
a 64 bit int. The comment above says keyid is 32-bit. I'm not sure if the
comment or declaration is wrong, so force the display of a 64-bit int for now.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 14:52:36 +01:00
Glenn Washburn e96c7645f4 grub_error: Use format code PRIuGRUB_SIZE for variables of type grub_size_t
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 14:50:44 +01:00
Glenn Washburn 334c0ef3d0 disk/dmraid_nvidia: Format string error in grub_error()
The grub_error() has a format string expecting two arguments, but only one
provided. According to the comments in the struct grub_nv_super definition,
the version field looks like a version number where major.minor is encoded
as each a byte in the two-byte short.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 14:50:44 +01:00
Glenn Washburn 9f5af956fa video/bochs: grub_error() format string add missing format code
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 14:50:44 +01:00
Glenn Washburn dc828b7d8b parttool/msdospart: grub_error() missing format string argument
Its obvious from the error message that the variable named "type" was
accidentally omitted.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 14:50:44 +01:00
Glenn Washburn 60875f4e15 misc: Format string for grub_error() should be a literal
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 14:50:44 +01:00
Philip Müller 54e0a1bbf1 templates: Properly disable the os-prober by default
This patch does the following:
 - really disables os-prober by default in the util/grub-mkconfig.in
   by setting GRUB_DISABLE_OS_PROBER to true,
 - fixes the logic in the util/grub.d/30_os-prober.in,
 - updates the grub_warn() lines.

Reason for the code shuffling in the util/grub-mkconfig.in:

  The default was GRUB_DISABLE_OS_PROBER=false if you don't set
  GRUB_DISABLE_OS_PROBER at all. To prevent os-prober from starting we
  have to set it by default to true and shuffle GRUB_DISABLE_OS_PROBER to
  code section, which is executed by the script. However we still give an
  option to the user to overwrite it with false, if he wants to execute
  os-prober after all.

Fixes: e3464147 (templates: Disable the os-prober by default)

Reported-by: Didier Spaier <didier@slint.fr>
Reported-by: Lennart Sorensen <lsorense@csclub.uwaterloo.ca>
Reported-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
Signed-off-by: Philip Müller <philm@manjaro.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 14:48:18 +01:00
Michael Chang 6d05264eec kern/efi/sb: Add chainloaded image as shim's verifiable object
While attempting to dual boot Microsoft Windows with UEFI chainloader,
it failed with below error when UEFI Secure Boot was enabled:

  error ../../grub-core/kern/verifiers.c:119:verification requested but
  nobody cares: /EFI/Microsoft/Boot/bootmgfw.efi.

It is a regression, as previously it worked without any problem.

It turns out chainloading PE image has been locked down by commit
578c95298 (kern: Add lockdown support). However, we should consider it
as verifiable object by shim to allow booting in UEFI Secure Boot mode.
The chainloaded PE image could also have trusted signature created by
vendor with their pubkey cert in db. For that matters it's usage should
not be locked down under UEFI Secure Boot, and instead shim should be
allowed to validate a PE binary signature before running it.

Fixes: 578c95298 (kern: Add lockdown support)

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 13:49:42 +01:00
Glenn Washburn 308b0495e1 disk/pata: Suppress error message "no device connected"
This error message comes from the grub_print_error() in
grub_pata_device_initialize(), which does not pass on the error, and is
raised in check_device(). The function check_device() needs to return this
as an error because check_device() is also used in grub_pata_open(), which
does pass on this error to indicate that the device can not be used.

This is actually not an error when displayed by grub_pata_device_initialize()
because it just indicates that there are no pata devices seen. This may be
confusing to end users who do not have pata devices yet are loading the
pata module (perhaps implicitly via nativedisk). This also causes unnecessary
output which may need to be accounted for in functional testing.

Instead print to the debug log when check_device() raises this "error" and
pop the error from the error stack. If there is another error on the stack
then print the error stack as those should be real errors.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Acked-by: Paul Menzel <pmenzel@molgen.mpg.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 13:22:45 +01:00
Yi Zhao bd8b36d8aa fs/ext2: Fix a file not found error when a symlink filesize is equal to 60
We encountered a file not found error when the symlink filesize is
equal to 60:

  $ ls -l initrd
  lrwxrwxrwx 1 root root 60 Jan  6 16:37 initrd -> secure-core-image-initramfs-5.10.2-yoctodev-standard.cpio.gz

When booting, we got the following error in the GRUB:

  error: file `/initrd' not found

The root cause is that the size of diro->inode.symlink is equal to 60
and a symlink name has to be terminated with NUL there. So, if the
symlink filesize is exactly 60 then it is also stored in a separate
block rather than in the inode itself.

Signed-off-by: Yi Zhao <yi.zhao@windriver.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-10 13:14:25 +01:00
Tianjia Zhang 8fcfd1e0fc loader/i386/linux: Do not use grub_le_to_cpu32() for relocatable variable
The relocatable variable is defined as grub_uint8_t. Relevant
member in setup_header structure is also defined as one byte
in Linux boot protocol. By semantic definition it is a bool type.
It is not appropriate to treat it as a four bytes. This patch
fixes the issue.

Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 17:46:13 +01:00
Tianjia Zhang 2bcf005298 loader/i386/linux: Remove redundant code from in grub_cmd_linux()
The preferred_address has been assigned to GRUB_LINUX_BZIMAGE_ADDR
during initialization in grub_cmd_linux(). The assignment here
is redundant and should be removed.

Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 17:41:32 +01:00
Heinrich Schuchardt 30858eb59a efi: The device-tree must be in EfiACPIReclaimMemory
According to the Embedded Base Boot Requirements (EBBR) specification the
device-tree passed to Linux as a configuration table must reside in
EfiACPIReclaimMemory.

Signed-off-by: Heinrich Schuchardt <xypron.glpk@gmx.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 17:39:42 +01:00
Heinrich Schuchardt 0860abe130 commands/efi/lsefisystab: Add short text for EFI_RT_PROPERTIES_TABLE_GUID
UEFI specification 2.8 errata B introduced the EFI_RT_PROPERTIES_TABLE
describing the services available at runtime.

The lsefisystab command is used to display installed EFI configuration
tables. Currently it only shows the GUID but not a short text for the
new table.

Provide a short text for the EFI_RT_PROPERTIES_TABLE_GUID.

Signed-off-by: Heinrich Schuchardt <xypron.glpk@gmx.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 17:35:30 +01:00
Petr Vorel 4199bf8bc5 docs/luks2: Mention key derivation function support
To give users hint why Argon2, the default in cryptsetup for LUKS2, does
not work.

Signed-off-by: Petr Vorel <pvorel@suse.cz>
Acked-by: Paul Menzel <pmenzel@molgen.mpg.de>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 17:17:34 +01:00
Derek Foreman 9340f5cbce commands/file: Fix array/enum desync
The commit f1957dc8a (RISC-V: Add to build system) added two entries to
the options array, but only 1 entry to the enum. This resulted in
everything after the insertion point being off by one.

This broke at least the "file --is-hibernated-hiberfil" command.

Bring the two back in sync by splitting the IS_RISCV_EFI enum entry into
two, as is done for other architectures.

Signed-off-by: Derek Foreman <derek@endlessos.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 16:46:09 +01:00
Marco A Benatto a9d8de9608 kern/mm: Fix grub_debug_calloc() compilation error
Fix compilation error due to missing parameter to
grub_printf() when MM_DEBUG is defined.

Fixes: 64e26162e (calloc: Make sure we always have an overflow-checking calloc() available)

Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:20 +01:00
Alex Burmashev e346414725 templates: Disable the os-prober by default
The os-prober is enabled by default what may lead to potentially
dangerous use cases and borderline opening attack vectors. This
patch disables the os-prober, adds warning messages and updates
GRUB_DISABLE_OS_PROBER configuration option documentation. This
way we make it clear that the os-prober usage is not recommended.

Simplistic nature of this change allows downstream vendors, who
really want os-prober to be enabled out of the box in their
relevant products, easily revert to it's old behavior.

Reported-by: NyankoSec (<nyanko@10x.moe>, https://twitter.com/NyankoSec),
             working with SSD Secure Disclosure
Signed-off-by: Alex Burmashev <alexander.burmashev@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:20 +01:00
Thomas Frauendorfer | Miray Software 42facd5772 gfxmenu/gui: Check printf() format in the gui_progress_bar and gui_label
The gui_progress_bar and gui_label components can display the timeout
value. The format string can be set through a theme file. This patch
adds a validation step to the format string.

If a user loads a theme file into the GRUB without this patch then
a GUI label with the following settings

  + label {
  ...
  id = "__timeout__"
  text = "%s"
  }

will interpret the current timeout value as string pointer and print the
memory at that position on the screen. It is not desired behavior.

Signed-off-by: Thomas Frauendorfer | Miray Software <tf@miray.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:20 +01:00
Thomas Frauendorfer | Miray Software 83603bea6c kern/misc: Add function to check printf() format against expected format
The grub_printf_fmt_check() function parses the arguments of an untrusted
printf() format and an expected printf() format and then compares the
arguments counts and arguments types. The arguments count in the untrusted
format string must be less or equal to the arguments count in the expected
format string and both arguments types must match.

To do this the parse_printf_arg_fmt() helper function is extended in the
following way:

  1. Add a return value to report errors to the grub_printf_fmt_check().

  2. Add the fmt_check argument to enable stricter format verification:
     - the function expects that arguments definitions are always
       terminated by a supported conversion specifier.
     - positional parameters, "$", are not allowed, as they cannot be
       validated correctly with the current implementation. For example
       "%s%1$d" would assign the first args entry twice while leaving the
       second one unchanged.
     - Return an error if preallocated space in args is too small and
       allocation fails for the needed size. The grub_printf_fmt_check()
       should verify all arguments. So, if validation is not possible for
       any reason it should return an error.
     This also adds a case entry to handle "%%", which is the escape
     sequence to print "%" character.

  3. Add the max_args argument to check for the maximum allowed arguments
     count in a printf() string. This should be set to the arguments count
     of the expected format. Then the parse_printf_arg_fmt() function will
     return an error if the arguments count is exceeded.

The two additional arguments allow us to use parse_printf_arg_fmt() in
printf() and grub_printf_fmt_check() calls.

When parse_printf_arg_fmt() is used by grub_printf_fmt_check() the
function parse user provided untrusted format string too. So, in
that case it is better to be too strict than too lenient.

Signed-off-by: Thomas Frauendorfer | Miray Software <tf@miray.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:20 +01:00
Thomas Frauendorfer | Miray Software 1a2a5aff71 kern/misc: Add STRING type for internal printf() format handling
Set printf() argument type for "%s" to new type STRING. This is in
preparation for a follow up patch to compare a printf() format string
against an expected printf() format string.

For "%s" the corresponding printf() argument is dereferenced as pointer
while all other argument types are defined as integer value. However,
when validating a printf() format it is necessary to differentiate "%s"
from "%p" and other integers. So, let's do that.

Signed-off-by: Thomas Frauendorfer | Miray Software <tf@miray.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:20 +01:00
Thomas Frauendorfer | Miray Software 7f11bde314 kern/misc: Split parse_printf_args() into format parsing and va_list handling
This patch is preparing for a follow up patch which will use
the format parsing part to compare the arguments in a printf()
format from an external source against a printf() format with
expected arguments.

Signed-off-by: Thomas Frauendorfer | Miray Software <tf@miray.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Dimitri John Ledkov 968de8c23c shim_lock: Only skip loading shim_lock verifier with explicit consent
Commit 32ddc42c (efi: Only register shim_lock verifier if shim_lock
protocol is found and SB enabled) reintroduced CVE-2020-15705 which
previously only existed in the out-of-tree linuxefi patches and was
fixed as part of the BootHole patch series.

Under Secure Boot enforce loading shim_lock verifier. Allow skipping
shim_lock verifier if SecureBoot/MokSBState EFI variables indicate
skipping validations, or if GRUB image is built with --disable-shim-lock.

Fixes: 132ddc42c (efi: Only register shim_lock verifier if shim_lock
       protocol is found and SB enabled)
Fixes: CVE-2020-15705
Fixes: CVE-2021-3418

Reported-by: Dimitri John Ledkov <xnox@ubuntu.com>
Signed-off-by: Dimitri John Ledkov <xnox@ubuntu.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Dimitri John Ledkov bb51ee2b49 grub-install-common: Add --sbat option
Signed-off-by: Dimitri John Ledkov <xnox@ubuntu.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Peter Jones b115471377 util/mkimage: Add an option to import SBAT metadata into a .sbat section
Add a --sbat option to the grub-mkimage tool which allows us to import
an SBAT metadata formatted as a CSV file into a .sbat section of the
EFI binary.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Peter Jones f60ba9e594 util/mkimage: Refactor section setup to use a helper
Add a init_pe_section() helper function to setup PE sections. This makes
the code simpler and easier to read.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Peter Jones ff406eff25 util/mkimage: Improve data_size value calculation
According to "Microsoft Portable Executable and Common Object File Format
Specification", the Optional Header SizeOfInitializedData field contains:

  Size of the initialized data section, or the sum of all such sections if
  there are multiple data sections.

Make this explicit by adding the GRUB kernel data size to the sum of all
the modules sizes. The ALIGN_UP() is not required by the PE spec but do
it to avoid alignment issues.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Peter Jones ba44c87e56 util/mkimage: Reorder PE optional header fields set-up
This makes the PE32 and PE32+ header fields set-up easier to follow by
setting them closer to the initialization of their related sections.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Peter Jones a4e8936f01 util/mkimage: Unify more of the PE32 and PE32+ header set-up
There's quite a bit of code duplication in the code that sets the optional
header for PE32 and PE32+. The two are very similar with the exception of
a few fields that have type grub_uint64_t instead of grub_uint32_t.

Factor out the common code and add a PE_OHDR() macro that simplifies the
set-up and make the code more readable.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Peter Jones ae8936f9c3 util/mkimage: Always use grub_host_to_target32() to initialize PE stack and heap stuff
This change does not impact final result of initialization itself.
However, it eases PE code unification in subsequent patches.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Peter Jones 1710452aca util/mkimage: Use grub_host_to_target32() instead of grub_cpu_to_le32()
The latter doesn't take into account the target image endianness. There is
a grub_cpu_to_le32_compile_time() but no compile time variant for function
grub_host_to_target32(). So, let's keep using the other one for this case.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Javier Martinez Canillas d52f78def1 util/mkimage: Remove unused code to add BSS section
The code is compiled out so there is no reason to keep it.

Additionally, don't set bss_size field since we do not add a BSS section.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Chris Coulson 133d73079c kern/efi: Add initial stack protector implementation
It works only on UEFI platforms but can be quite easily extended to
others architectures and platforms if needed.

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Marco A Benatto <mbenatto@redhat.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
2021-03-02 15:54:19 +01:00
Chris Coulson 4ea7bae51f kern/parser: Fix a stack buffer overflow
grub_parser_split_cmdline() expands variable names present in the supplied
command line in to their corresponding variable contents and uses a 1 kiB
stack buffer for temporary storage without sufficient bounds checking. If
the function is called with a command line that references a variable with
a sufficiently large payload, it is possible to overflow the stack
buffer via tab completion, corrupt the stack frame and potentially
control execution.

Fixes: CVE-2020-27749

Reported-by: Chris Coulson <chris.coulson@canonical.com>
Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Chris Coulson 030fb6c4fa kern/buffer: Add variable sized heap buffer
Add a new variable sized heap buffer type (grub_buffer_t) with simple
operations for appending data, accessing the data and maintaining
a read cursor.

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Chris Coulson 8bc817014c kern/parser: Refactor grub_parser_split_cmdline() cleanup
Introduce a common function epilogue used for cleaning up on all
return paths, which will simplify additional error handling to be
introduced in a subsequent commit.

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Chris Coulson 3d157bbd06 kern/parser: Introduce terminate_arg() helper
process_char() and grub_parser_split_cmdline() use similar code for
terminating the most recent argument. Add a helper function for this.

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Chris Coulson b1c9e9e889 kern/parser: Introduce process_char() helper
grub_parser_split_cmdline() iterates over each command line character.
In order to add error checking and to simplify the subsequent error
handling, split the character processing in to a separate function.

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Chris Coulson c6c426e5ab kern/parser: Fix a memory leak
The getline() function supplied to grub_parser_split_cmdline() returns
a newly allocated buffer and can be called multiple times, but the
returned buffer is never freed.

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Daniel Axtens b911884dd7 fs/btrfs: Squash some uninitialized reads
We need to check errors before calling into a function that uses the result.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Daniel Axtens b88a82e78c fs/btrfs: Validate the number of stripes/parities in RAID5/6
This prevents a divide by zero if nstripes == nparities, and
also prevents propagation of invalid values if nstripes ends up
less than nparities.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Daniel Axtens e18a000738 disk/lvm: Do not allow a LV to be it's own segment's node's LV
This prevents infinite recursion in the diskfilter verification code.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Daniel Axtens 7012936847 disk/lvm: Sanitize rlocn->offset to prevent wild read
rlocn->offset is read directly from disk and added to the metadatabuf
pointer to create a pointer to a block of metadata. It's a 64-bit
quantity so as long as you don't overflow you can set subsequent
pointers to point anywhere in memory.

Require that rlocn->offset fits within the metadata buffer size.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:19 +01:00
Daniel Axtens 1155d7dffd disk/lvm: Do not overread metadata
We could reach the end of valid metadata and not realize, leading to
some buffer overreads. Check if we have reached the end and bail.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens db29073fc7 disk/lvm: Do not crash if an expected string is not found
Clean up a bunch of cases where we could have strstr() fail and lead to
us dereferencing NULL.

We'll still leak memory in some cases (loops don't clean up allocations
from earlier iterations if a later iteration fails) but at least we're
not crashing.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 2958695c4c disk/lvm: Bail on missing PV list
There's an if block for the presence of "physical_volumes {", but if
that block is absent, then p remains NULL and a NULL-deref will result
when looking for logical volumes.

It doesn't seem like LVM makes sense without physical volumes, so error
out rather than crashing.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 27a79bf38e disk/lvm: Don't blast past the end of the circular metadata buffer
This catches at least some OOB reads, and it's possible I suppose that
if 2 * mda_size is less than GRUB_LVM_MDA_HEADER_SIZE it might catch some
OOB writes too (although that hasn't showed up as a crash in fuzzing yet).

It's a bit ugly and I'd appreciate better suggestions.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens a8cc95de74 disk/lvm: Don't go beyond the end of the data we read from disk
We unconditionally trusted offset_xl from the LVM label header, even if
it told us that the PV header/disk locations were way off past the end
of the data we read from disk.

Require that the offset be sane, fixing an OOB read and crash.

Fixes: CID 314367, CID 314371

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens b5a2b59cc5 io/gzio: Zero gzio->tl/td in init_dynamic_block() if huft_build() fails
If huft_build() fails, gzio->tl or gzio->td could contain pointers that
are no longer valid. Zero them out.

This prevents a double free when grub_gzio_close() comes through and
attempts to free them again.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 4e76b08f71 io/gzio: Catch missing values in huft_build() and bail
In huft_build(), "v" is a table of values in order of bit length.
The code later (when setting up table entries in "r") assumes that all
elements of this array corresponding to a code are initialized and less
than N_MAX. However, it doesn't enforce this.

With sufficiently manipulated inputs (e.g. from fuzzing), there can be
elements of "v" that are not filled. Therefore a lookup into "e" or "d"
will use an uninitialized value. This can lead to an invalid/OOB read on
those values, often leading to a crash.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 18490336d9 io/gzio: Add init_dynamic_block() clean up if unpacking codes fails
init_dynamic_block() didn't clean up gzio->tl and td in some error
paths. This left td pointing to part of tl. Then in grub_gzio_close(),
when tl was freed the storage for td would also be freed. The code then
attempts to free td explicitly, performing a UAF and then a double free.

Explicitly clean up tl and td in the error paths.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 3334a5e6c8 io/gzio: Bail if gzio->tl/td is NULL
This is an ugly fix that doesn't address why gzio->tl comes to be NULL.
However, it seems to be sufficient to patch up a bunch of NULL derefs.

It would be good to revisit this in future and see if we can have
a cleaner solution that addresses some of the causes of the unexpected
NULL pointers.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens ca5d9ac206 fs/nilfs2: Properly bail on errors in grub_nilfs2_btree_node_lookup()
We just introduced an error return in grub_nilfs2_btree_node_lookup().
Make sure the callers catch it.

At the same time, make sure that grub_nilfs2_btree_node_lookup() always
inits the index pointer passed to it.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 37c0eb05cd fs/nilfs2: Don't search children if provided number is too large
NILFS2 reads the number of children a node has from the node. Unfortunately,
that's not trustworthy. Check if it's beyond what the filesystem permits and
reject it if so.

This blocks some OOB reads. I'm not sure how controllable the read is and what
could be done with invalidly read data later on.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 20ab8cb44b fs/nilfs2: Reject too-large keys
NILFS2 has up to 7 keys, per the data structure. Do not permit array
indices in excess of that.

This catches some OOB reads. I don't know how controllable the invalidly
read data is or if that could be used later in the program.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 223120dd83 fs/jfs: Catch infinite recursion
It's possible with a fuzzed filesystem for JFS to keep getblk()-ing
the same data over and over again, leading to stack exhaustion.

Check if we'd be calling the function with exactly the same data as
was passed in, and if so abort.

I'm not sure what the performance impact of this is and am open to
better ideas.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens bd0cf8148c fs/jfs: Limit the extents that getblk() can consider
getblk() implicitly trusts that treehead->count is an accurate count of
the number of extents. However, that value is read from disk and is not
trustworthy, leading to OOB reads and crashes. I am not sure to what
extent the data read from OOB can influence subsequent program execution.

Require callers to pass in the maximum number of extents for which
they have storage.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens ffd5a46f68 fs/jfs: Do not move to leaf level if name length is negative
Fuzzing JFS revealed crashes where a negative number would be passed
to le_to_cpu16_copy(). There it would be cast to a large positive number
and the copy would read and write off the end of the respective buffers.

Catch this at the top as well as the bottom of the loop.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 8d3ae59dee fs/sfs: Fix over-read of root object name
There's a read of the name of the root object that assumes that the name
is nul-terminated within the root block. This isn't guaranteed - it seems
SFS would require you to read multiple blocks to get a full name in general,
but maybe that doesn't apply to the root object.

Either way, figure out how much space is left in the root block and don't
over-read it. This fixes some OOB reads.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 1c15848838 fs/hfs: Disable under lockdown
HFS has issues such as infinite mutual recursion that are simply too
complex to fix for such a legacy format. So simply do not permit
it to be loaded under lockdown.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 2ca0e5dbcd fs/hfsplus: Don't use uninitialized data on corrupt filesystems
Valgrind identified the following use of uninitialized data:

  ==2782220== Conditional jump or move depends on uninitialised value(s)
  ==2782220==    at 0x42B364: grub_hfsplus_btree_search (hfsplus.c:566)
  ==2782220==    by 0x42B21D: grub_hfsplus_read_block (hfsplus.c:185)
  ==2782220==    by 0x42A693: grub_fshelp_read_file (fshelp.c:386)
  ==2782220==    by 0x42C598: grub_hfsplus_read_file (hfsplus.c:219)
  ==2782220==    by 0x42C598: grub_hfsplus_mount (hfsplus.c:330)
  ==2782220==    by 0x42B8C5: grub_hfsplus_dir (hfsplus.c:958)
  ==2782220==    by 0x4C1AE6: grub_fs_probe (fs.c:73)
  ==2782220==    by 0x407C94: grub_ls_list_files (ls.c:186)
  ==2782220==    by 0x407C94: grub_cmd_ls (ls.c:284)
  ==2782220==    by 0x4D7130: grub_extcmd_dispatcher (extcmd.c:55)
  ==2782220==    by 0x4045A6: execute_command (grub-fstest.c:59)
  ==2782220==    by 0x4045A6: fstest (grub-fstest.c:433)
  ==2782220==    by 0x4045A6: main (grub-fstest.c:772)
  ==2782220==  Uninitialised value was created by a heap allocation
  ==2782220==    at 0x483C7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==2782220==    by 0x4C0305: grub_malloc (mm.c:42)
  ==2782220==    by 0x42C21D: grub_hfsplus_mount (hfsplus.c:239)
  ==2782220==    by 0x42B8C5: grub_hfsplus_dir (hfsplus.c:958)
  ==2782220==    by 0x4C1AE6: grub_fs_probe (fs.c:73)
  ==2782220==    by 0x407C94: grub_ls_list_files (ls.c:186)
  ==2782220==    by 0x407C94: grub_cmd_ls (ls.c:284)
  ==2782220==    by 0x4D7130: grub_extcmd_dispatcher (extcmd.c:55)
  ==2782220==    by 0x4045A6: execute_command (grub-fstest.c:59)
  ==2782220==    by 0x4045A6: fstest (grub-fstest.c:433)
  ==2782220==    by 0x4045A6: main (grub-fstest.c:772)

This happens when the process of reading the catalog file goes sufficiently
wrong that there's an attempt to read the extent overflow file, which has
not yet been loaded. Keep track of when the extent overflow file is
fully loaded and refuse to use it before then.

The load valgrind doesn't like is btree->nodesize, and that's then used
to allocate a data structure. It looks like there are subsequently a lot
of reads based on that pointer so OOB reads are likely, and indeed crashes
(albeit difficult-to-replicate ones) have been observed in fuzzing.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 58ea11d5b9 fs/hfsplus: Don't fetch a key beyond the end of the node
Otherwise you get a wild pointer, leading to a bunch of invalid reads.
Check it falls inside the given node.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens b5bc456f66 fs/fshelp: Catch impermissibly large block sizes in read helper
A fuzzed HFS+ filesystem had log2blocksize = 22. This gave
log2blocksize + GRUB_DISK_SECTOR_BITS = 31. 1 << 31 = 0x80000000,
which is -1 as an int. This caused some wacky behavior later on in
the function, leading to out-of-bounds writes on the destination buffer.

Catch log2blocksize + GRUB_DISK_SECTOR_BITS >= 31. We could be stricter,
but this is the minimum that will prevent integer size weirdness.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 829329bddb term/gfxterm: Don't set up a font with glyphs that are too big
Catch the case where we have a font so big that it causes the number of
rows or columns to be 0. Currently we continue and allocate a
virtual_screen.text_buffer of size 0. We then try to use that for glpyhs
and things go badly.

On the emu platform, malloc() may give us a valid pointer, in which case
we'll access heap memory which we shouldn't. Alternatively, it may give us
NULL, in which case we'll crash. For other platforms, if I understand
grub_memalign() correctly, we will receive a valid but small allocation
that we will very likely later overrun.

Prevent the creation of a virtual screen that isn't at least 40 cols
by 12 rows. This is arbitrary, but it seems that if your width or height
is half a standard 80x24 terminal, you're probably going to struggle to
read anything anyway.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 8338a8238f video/readers/jpeg: Don't decode data before start of stream
When a start of stream marker is encountered, we call grub_jpeg_decode_sos()
which allocates space for a bitmap.

When a restart marker is encountered, we call grub_jpeg_decode_data() which
then fills in that bitmap.

If we get a restart marker before the start of stream marker, we will
attempt to write to a bitmap_ptr that hasn't been allocated. Catch this
and bail out. This fixes an attempt to write to NULL.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 34b85a6e07 video/readers/jpeg: Catch OOB reads/writes in grub_jpeg_decode_du()
The key line is:

  du[jpeg_zigzag_order[pos]] = val * (int) data->quan_table[qt][pos];

jpeg_zigzag_order is grub_uint8_t[64].

I don't understand JPEG decoders quite well enough to explain what's
going on here. However, I observe sometimes pos=64, which leads to an
OOB read of the jpeg_zigzag_order global then an OOB write to du.
That leads to various unpleasant memory corruption conditions.

Catch where pos >= ARRAY_SIZE(jpeg_zigzag_order) and bail.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens 693989598f video/readers/jpeg: Catch files with unsupported quantization or Huffman tables
Our decoder only supports 2 quantization tables. If a file asks for
a quantization table with index > 1, reject it.

Similarly, our decoder only supports 4 Huffman tables. If a file asks
for a Huffman table with index > 3, reject it.

This fixes some out of bounds reads. It's not clear what degree of control
over subsequent execution could be gained by someone who can carefully
set up the contents of memory before loading an invalid JPEG file.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:18 +01:00
Daniel Axtens f41f0af48a kern/misc: Always set *end in grub_strtoull()
Currently, if there is an error in grub_strtoull(), *end is not set.
This differs from the usual behavior of strtoull(), and also means that
some callers may use an uninitialized value for *end.

Set *end unconditionally.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Daniel Axtens 2f533a89a8 commands/menuentry: Fix quoting in setparams_prefix()
Commit 9acdcbf325 (use single quotes in menuentry setparams command)
says that expressing a quoted single quote will require 3 characters. It
actually requires (and always did require!) 4 characters:

  str: a'b => a'\''b
  len:  3  => 6 (2 for the letters + 4 for the quote)

This leads to not allocating enough memory and thus out of bounds writes
that have been observed to cause heap corruption.

Allocate 4 bytes for each single quote.

Commit 22e7dbb2bb (Fix quoting in legacy parser.) does the same
quoting, but it adds 3 as extra overhead on top of the single byte that
the quote already needs. So it's correct.

Fixes: 9acdcbf325 (use single quotes in menuentry setparams command)
Fixes: CVE-2021-20233

Reported-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Daniel Axtens 0a05f88e2b script/execute: Don't crash on a "for" loop with no items
The following crashes the parser:

  for x in; do
  0
  done

This is because grub_script_arglist_to_argv() doesn't consider the
possibility that arglist is NULL. Catch that explicitly.

This avoids a NULL pointer dereference.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Daniel Axtens 2a330dba93 lib/arg: Block repeated short options that require an argument
Fuzzing found the following crash:

  search -hhhhhhhhhhhhhf

We didn't allocate enough option space for 13 hints because the
allocation code counts the number of discrete arguments (i.e. argc).
However, the shortopt parsing code will happily keep processing
a combination of short options without checking if those short
options require an argument. This means you can easily end writing
past the allocated option space.

This fixes a OOB write which can cause heap corruption.

Fixes: CVE-2021-20225

Reported-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Daniel Axtens fe0586347e script/execute: Avoid crash when using "$#" outside a function scope
"$#" represents the number of arguments to a function. It is only
defined in a function scope, where "scope" is non-NULL. Currently,
if we attempt to evaluate "$#" outside a function scope, "scope" will
be NULL and we will crash with a NULL pointer dereference.

Do not attempt to count arguments for "$#" if "scope" is NULL. This
will result in "$#" being interpreted as an empty string if evaluated
outside a function scope.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Daniel Axtens 6afbe6063c commands/ls: Require device_name is not NULL before printing
This can be triggered with:
  ls -l (0 0*)
and causes a NULL deref in grub_normal_print_device_info().

I'm not sure if there's any implication with the IEEE 1275 platform.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Daniel Axtens 41ae93b2e6 script/execute: Fix NULL dereference in grub_script_execute_cmdline()
Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 1641d74e16 util/glue-efi: Fix incorrect use of a possibly negative value
It is possible for the ftell() function to return a negative value,
although it is fairly unlikely here, we should be checking for
a negative value before we assign it to an unsigned value.

Fixes: CID 73744

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 5dc41edc4e util/grub-editenv: Fix incorrect casting of a signed value
The return value of ftell() may be negative (-1) on error. While it is
probably unlikely to occur, we should not blindly cast to an unsigned
value without first testing that it is not negative.

Fixes: CID 73856

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Daniel Kiper 8b3a95655b util/grub-install: Fix NULL pointer dereferences
Two grub_device_open() calls does not have associated NULL checks
for returned values. Fix that and appease the Coverity.

Fixes: CID 314583

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
2021-03-02 15:54:17 +01:00
Paulo Flabiano Smorigo 7c8a2b5d14 loader/xnu: Check if pointer is NULL before using it
Fixes: CID 73654

Signed-off-by: Paulo Flabiano Smorigo <pfsmorigo@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Marco A Benatto 4b4027b6b1 loader/xnu: Free driverkey data when an error is detected in grub_xnu_writetree_toheap()
... to avoid memory leaks.

Fixes: CID 96640

Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny bcb59ece32 loader/xnu: Fix memory leak
The code here is finished with the memory stored in name, but it only
frees it if there curvalue is valid, while it could actually free it
regardless.

The fix is a simple relocation of the grub_free() to before the test
of curvalue.

Fixes: CID 96646

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 5d5391b0a0 loader/bsd: Check for NULL arg up-front
The code in the next block suggests that it is possible for .set to be
true but .arg may still be NULL.

This code assumes that it is never NULL, yet later is testing if it is
NULL - that is inconsistent.

So we should check first if .arg is not NULL, and remove this check that
is being flagged by Coverity since it is no longer required.

Fixes: CID 292471

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 4a1aa59175 gfxmenu/gui_list: Remove code that coverity is flagging as dead
The test of value for NULL before calling grub_strdup() is not required,
since the if condition prior to this has already tested for value being
NULL and cannot reach this code if it is.

Fixes: CID 73659

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 5f5eb7ca8e video/readers/jpeg: Test for an invalid next marker reference from a jpeg file
While it may never happen, and potentially could be caught at the end of
the function, it is worth checking up front for a bad reference to the
next marker just in case of a maliciously crafted file being provided.

Fixes: CID 73694

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 08413f2f4e video/fb/video_fb: Fix possible integer overflow
It is minimal possibility that the values being used here will overflow.
So, change the code to use the safemath function grub_mul() to ensure
that doesn't happen.

Fixes: CID 73761

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 08e098b1db video/fb/video_fb: Fix multiple integer overflows
The calculation of the unsigned 64-bit value is being generated by
multiplying 2, signed or unsigned, 32-bit integers which may overflow
before promotion to unsigned 64-bit. Fix all of them.

Fixes: CID 73703, CID 73767, CID 73833

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 7ce3259f67 video/fb/fbfill: Fix potential integer overflow
The multiplication of 2 unsigned 32-bit integers may overflow before
promotion to unsigned 64-bit. We should ensure that the multiplication
is done with overflow detection. Additionally, use grub_sub() for
subtraction.

Fixes: CID 73640, CID 73697, CID 73702, CID 73823

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny fc5951d3b1 video/efi_gop: Remove unnecessary return value of grub_video_gop_fill_mode_info()
The return value of grub_video_gop_fill_mode_info() is never able to be
anything other than GRUB_ERR_NONE. So, rather than continue to return
a value and checking it each time, it is more correct to redefine the
function to not return anything and remove checks of its return value
altogether.

Fixes: CID 96701

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 1fc860bb76 commands/probe: Fix a resource leak when probing disks
Every other return statement in this code is calling grub_device_close()
to clean up dev before returning. This one should do that too.

Fixes: CID 292443

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Chris Coulson 8b6f528e52 commands/hashsum: Fix a memory leak
check_list() uses grub_file_getline(), which allocates a buffer.
If the hash list file contains invalid lines, the function leaks
this buffer when it returns an error.

Fixes: CID 176635

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 9213575b7a normal/completion: Fix leaking of memory when processing a completion
It is possible for the code to reach the end of the function without
freeing the memory allocated to argv and argc still to be 0.

We should always call grub_free(argv). The grub_free() will handle
a NULL argument correctly if it reaches that code without the memory
being allocated.

Fixes: CID 96672

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny 95bc016dba syslinux: Fix memory leak while parsing
In syslinux_parse_real() the 2 points where return is being called
didn't release the memory stored in buf which is no longer required.

Fixes: CID 176634

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:17 +01:00
Darren Kenny ae0f3fabeb libgcrypt/mpi: Fix possible NULL dereference
The code in gcry_mpi_scan() assumes that buffer is not NULL, but there
is no explicit check for that, so we add one.

Fixes: CID 73757

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny e8814c8111 libgcrypt/mpi: Fix possible unintended sign extension
The array of unsigned char gets promoted to a signed 32-bit int before
it is finally promoted to a size_t. There is the possibility that this
may result in the signed-bit being set for the intermediate signed
32-bit int. We should ensure that the promotion is to the correct type
before we bitwise-OR the values.

Fixes: CID 96697

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 178ac51073 affs: Fix memory leaks
The node structure reference is being allocated but not freed if it
reaches the end of the function. If any of the hooks had returned
a non-zero value, then node would have been copied in to the context
reference, but otherwise node is not stored and should be freed.

Similarly, the call to grub_affs_create_node() replaces the allocated
memory in node with a newly allocated structure, leaking the existing
memory pointed by node.

Finally, when dir->parent is set, then we again replace node with newly
allocated memory, which seems unnecessary when we copy in the values
from dir->parent immediately after.

Fixes: CID 73759

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 7aab03418e zfsinfo: Correct a check for error allocating memory
While arguably the check for grub_errno is correct, we should really be
checking the return value from the function since it is always possible
that grub_errno was set elsewhere, making this code behave incorrectly.

Fixes: CID 73668

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 302c12ff57 zfs: Fix possible integer overflows
In all cases the problem is that the value being acted upon by
a left-shift is a 32-bit number which is then being used in the
context of a 64-bit number.

To avoid overflow we ensure that the number being shifted is 64-bit
before the shift is done.

Fixes: CID 73684, CID 73695, CID 73764

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Paulo Flabiano Smorigo 89bdab9658 zfs: Fix resource leaks while constructing path
There are several exit points in dnode_get_path() that are causing possible
memory leaks.

In the while(1) the correct exit mechanism should not be to do a direct return,
but to instead break out of the loop, setting err first if it is not already set.

The reason behind this is that the dnode_path is a linked list, and while doing
through this loop, it is being allocated and built up - the only way to
correctly unravel it is to traverse it, which is what is being done at the end
of the function outside of the loop.

Several of the existing exit points correctly did a break, but not all so this
change makes that more consistent and should resolve the leaking of memory as
found by Coverity.

Fixes: CID 73741

Signed-off-by: Paulo Flabiano Smorigo <pfsmorigo@canonical.com>
Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny a02091834d zfs: Fix possible negative shift operation
While it is possible for the return value from zfs_log2() to be zero
(0), it is quite unlikely, given that the previous assignment to blksz
is shifted up by SPA_MINBLOCKSHIFT (9) before 9 is subtracted at the
assignment to epbs.

But, while unlikely during a normal operation, it may be that a carefully
crafted ZFS filesystem could result in a zero (0) value to the
dn_datalbkszsec field, which means that the shift left does nothing
and assigns zero (0) to blksz, resulting in a negative epbs value.

Fixes: CID 73608

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 2298f6e0d9 hfsplus: Check that the volume name length is valid
HFS+ documentation suggests that the maximum filename and volume name is
255 Unicode characters in length.

So, when converting from big-endian to little-endian, we should ensure
that the name of the volume has a length that is between 0 and 255,
inclusive.

Fixes: CID 73641

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny a201ad17ca disk/cryptodisk: Fix potential integer overflow
The encrypt and decrypt functions expect a grub_size_t. So, we need to
ensure that the constant bit shift is using grub_size_t rather than
unsigned int when it is performing the shift.

Fixes: CID 307788

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 156c281a16 disk/ldm: Fix memory leak on uninserted lv references
The problem here is that the memory allocated to the variable lv is not
yet inserted into the list that is being processed at the label fail2.

As we can already see at line 342, which correctly frees lv before going
to fail2, we should also be doing that at these earlier jumps to fail2.

Fixes: CID 73824

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Paulo Flabiano Smorigo e0b83df5da disk/ldm: If failed then free vg variable too
Fixes: CID 73809

Signed-off-by: Paulo Flabiano Smorigo <pfsmorigo@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Marco A Benatto 23e39f50ca disk/ldm: Make sure comp data is freed before exiting from make_vg()
Several error handling paths in make_vg() do not free comp data before
jumping to fail2 label and returning from the function. This will leak
memory. So, let's fix all issues of that kind.

Fixes: CID 73804

Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny bc9c468a2c kern/partition: Check for NULL before dereferencing input string
There is the possibility that the value of str comes from an external
source and continuing to use it before ever checking its validity is
wrong. So, needs fixing.

Additionally, drop unneeded part initialization.

Fixes: CID 292444

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 2777cf4466 zstd: Initialize seq_t structure fully
While many compilers will initialize this to zero, not all will, so it
is better to be sure that fields not being explicitly set are at known
values, and there is code that checks this fields value elsewhere in the
code.

Fixes: CID 292440

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 59666e520f io/lzopio: Resolve unnecessary self-assignment errors
These 2 assignments are unnecessary since they are just assigning
to themselves.

Fixes: CID 73643

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 03477085f9 gnulib/regcomp: Fix uninitialized re_token
This issue has been fixed in the latest version of gnulib, so to
maintain consistency, I've backported that change rather than doing
something different.

Fixes: CID 73828

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 0b7f347638 gnulib/regexec: Fix possible null-dereference
It appears to be possible that the mctx->state_log field may be NULL,
and the name of this function, clean_state_log_if_needed(), suggests
that it should be checking that it is valid to be cleaned before
assuming that it does.

Fixes: CID 86720

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 3a37bf120a gnulib/argp-help: Fix dereference of a possibly NULL state
All other instances of call to __argp_failure() where there is
a dgettext() call is first checking whether state is NULL before
attempting to dereference it to get the root_argp->argp_domain.

Fixes: CID 292436

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 75c3d3cec4 gnulib/regcomp: Fix uninitialized token structure
The code is assuming that the value of br_token.constraint was
initialized to zero when it wasn't.

While some compilers will ensure that, not all do, so it is better to
fix this explicitly than leave it to chance.

Fixes: CID 73749

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny a983d36bd9 gnulib/regexec: Resolve unused variable
This is a really minor issue where a variable is being assigned to but
not checked before it is overwritten again.

The reason for this issue is that we are not building with DEBUG set and
this in turn means that the assert() that reads the value of the
variable match_last is being processed out.

The solution, move the assignment to match_last in to an ifdef DEBUG too.

Fixes: CID 292459

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 6aee4bfd69 kern/efi/mm: Fix possible NULL pointer dereference
The model of grub_efi_get_memory_map() is that if memory_map is NULL,
then the purpose is to discover how much memory should be allocated to
it for the subsequent call.

The problem here is that with grub_efi_is_finished set to 1, there is no
check at all that the function is being called with a non-NULL memory_map.

While this MAY be true, we shouldn't assume it.

The solution to this is to behave as expected, and if memory_map is NULL,
then don't try to use it and allow memory_map_size to be filled in, and
return 0 as is done later in the code if the buffer is too small (or NULL).

Additionally, drop unneeded ret = 1.

Fixes: CID 96632

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny ed286ceba6 kern/efi: Fix memory leak on failure
Free the memory allocated to name before returning on failure.

Fixes: CID 296222

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny d06161b035 kern/parser: Fix resource leak if argc == 0
After processing the command-line yet arriving at the point where we are
setting argv, we are allocating memory, even if argc == 0, which makes
no sense since we never put anything into the allocated argv.

The solution is to simply return that we've successfully processed the
arguments but that argc == 0, and also ensure that argv is NULL when
we're not allocating anything in it.

There are only 2 callers of this function, and both are handling a zero
value in argc assuming nothing is allocated in argv.

Fixes: CID 96680

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 0cb838b281 net/tftp: Fix dangling memory pointer
The static code analysis tool, Parfait, reported that the valid of
file->data was left referencing memory that was freed by the call to
grub_free(data) where data was initialized from file->data.

To ensure that there is no unintentional access to this memory
referenced by file->data we should set the pointer to NULL.

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:16 +01:00
Darren Kenny 03f2515ae0 net/net: Fix possible dereference to of a NULL pointer
It is always possible that grub_zalloc() could fail, so we should check for
a NULL return. Otherwise we run the risk of dereferencing a NULL pointer.

Fixes: CID 296221

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Darren Kenny 8cb2848f96 mmap: Fix memory leak when iterating over mapped memory
When returning from grub_mmap_iterate() the memory allocated to present
is not being released causing it to leak.

Fixes: CID 96655

Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 128c16a682 usb: Avoid possible out-of-bound accesses caused by malicious devices
The maximum number of configurations and interfaces are fixed but there is
no out-of-bound checking to prevent a malicious USB device to report large
values for these and cause accesses outside the arrays' memory.

Fixes: CVE-2020-25647

Reported-by: Joseph Tartaro <joseph.tartaro@ioactive.com>
Reported-by: Ilja Van Sprundel <ivansprundel@ioactive.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 7630ec5397 dl: Only allow unloading modules that are not dependencies
When a module is attempted to be removed its reference counter is always
decremented. This means that repeated rmmod invocations will cause the
module to be unloaded even if another module depends on it.

This may lead to a use-after-free scenario allowing an attacker to execute
arbitrary code and by-pass the UEFI Secure Boot protection.

While being there, add the extern keyword to some function declarations in
that header file.

Fixes: CVE-2020-25632

Reported-by: Chris Coulson <chris.coulson@canonical.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas f05e79a014 docs: Document the cutmem command
The command is not present in the docs/grub.texi user documentation.

Reported-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 9c5565135f loader/xnu: Don't allow loading extension and packages when locked down
The shim_lock verifier validates the XNU kernels but no its extensions
and packages. Prevent these to be loaded when the GRUB is locked down.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 5082708389 gdb: Restrict GDB access when locked down
The gdbstub* commands allow to start and control a GDB stub running on
local host that can be used to connect from a remote debugger. Restrict
this functionality when the GRUB is locked down.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 5c97492a29 commands/hdparm: Restrict hdparm command when locked down
The command can be used to get/set ATA disk parameters. Some of these can
be dangerous since change the disk behavior. Restrict it when locked down.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 58b77d4069 commands/setpci: Restrict setpci command when locked down
This command can set PCI devices register values, which makes it dangerous
in a locked down configuration. Restrict it so can't be used on this setup.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 468a5699b2 commands: Restrict commands that can load BIOS or DT blobs when locked down
There are some more commands that should be restricted when the GRUB is
locked down. Following is the list of commands and reasons to restrict:

  * fakebios:   creates BIOS-like structures for backward compatibility with
                existing OSes. This should not be allowed when locked down.

  * loadbios:   reads a BIOS dump from storage and loads it. This action
                should not be allowed when locked down.

  * devicetree: loads a Device Tree blob and passes it to the OS. It replaces
                any Device Tree provided by the firmware. This also should
                not be allowed when locked down.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas d298b41f90 mmap: Don't register cutmem and badram commands when lockdown is enforced
The cutmem and badram commands can be used to remove EFI memory regions
and potentially disable the UEFI Secure Boot. Prevent the commands to be
registered if the GRUB is locked down.

Fixes: CVE-2020-27779

Reported-by: Teddy Reed <teddy.reed@gmail.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 3e8e4c0549 acpi: Don't register the acpi command when locked down
The command is not allowed when lockdown is enforced. Otherwise an
attacker can instruct the GRUB to load an SSDT table to overwrite
the kernel lockdown configuration and later load and execute
unsigned code.

Fixes: CVE-2020-14372

Reported-by: Máté Kukri <km@mkukri.xyz>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 8f73052885 efi: Use grub_is_lockdown() instead of hardcoding a disabled modules list
Now the GRUB can check if it has been locked down and this can be used to
prevent executing commands that can be utilized to circumvent the UEFI
Secure Boot mechanisms. So, instead of hardcoding a list of modules that
have to be disabled, prevent the usage of commands that can be dangerous.

This not only allows the commands to be disabled on other platforms, but
also properly separate the concerns. Since the shim_lock verifier logic
should be only about preventing to run untrusted binaries and not about
defining these kind of policies.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 98b00a403c efi: Lockdown the GRUB when the UEFI Secure Boot is enabled
If the UEFI Secure Boot is enabled then the GRUB must be locked down
to prevent executing code that can potentially be used to subvert its
verification mechanisms.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas d903674717 kern/lockdown: Set a variable if the GRUB is locked down
It may be useful for scripts to determine whether the GRUB is locked
down or not. Add the lockdown variable which is set to "y" when the GRUB
is locked down.

Suggested-by: Dimitri John Ledkov <xnox@ubuntu.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Javier Martinez Canillas 578c95298b kern: Add lockdown support
When the GRUB starts on a secure boot platform, some commands can be
used to subvert the protections provided by the verification mechanism and
could lead to booting untrusted system.

To prevent that situation, allow GRUB to be locked down. That way the code
may check if GRUB has been locked down and further restrict the commands
that are registered or what subset of their functionality could be used.

The lockdown support adds the following components:

* The grub_lockdown() function which can be used to lockdown GRUB if,
  e.g., UEFI Secure Boot is enabled.

* The grub_is_lockdown() function which can be used to check if the GRUB
  was locked down.

* A verifier that flags OS kernels, the GRUB modules, Device Trees and ACPI
  tables as GRUB_VERIFY_FLAGS_DEFER_AUTH to defer verification to other
  verifiers. These files are only successfully verified if another registered
  verifier returns success. Otherwise, the whole verification process fails.

  For example, PE/COFF binaries verification can be done by the shim_lock
  verifier which validates the signatures using the shim_lock protocol.
  However, the verification is not deferred directly to the shim_lock verifier.
  The shim_lock verifier is hooked into the verification process instead.

* A set of grub_{command,extcmd}_lockdown functions that can be used by
  code registering command handlers, to only register unsafe commands if
  the GRUB has not been locked down.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Marco A Benatto 5e280caa65 efi: Move the shim_lock verifier to the GRUB core
Move the shim_lock verifier from its own module into the core image. The
Secure Boot lockdown mechanism has the intent to prevent the load of any
unsigned code or binary when Secure Boot is enabled.

The reason is that GRUB must be able to prevent executing untrusted code
if UEFI Secure Boot is enabled, without depending on external modules.

Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Marco A Benatto 9e95f45cee verifiers: Move verifiers API to kernel image
Move verifiers API from a module to the kernel image, so it can be
used there as well. There are no functional changes in this patch.

Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2021-03-02 15:54:15 +01:00
Glenn Washburn 635ef55ed1 docs: Add documentation of disk size limitations
Document the artificially imposed 1 EiB disk size limit and size limitations
with LUKS volumes.

Fix a few punctuation issues.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-18 23:18:04 +01:00
Glenn Washburn ec46685ed4 luks2: Use grub_log2ull() to calculate log_sector_size and improve readability
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-18 23:15:05 +01:00
Glenn Washburn 3ab19ba3b1 misc: Add grub_log2ull() macro for calculating log base 2 of 64-bit integers
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-18 23:08:14 +01:00
Glenn Washburn 9b4e8f0c4b mips: Enable __clzdi2()
This patch is similar to commit 9dab2f51e (sparc: Enable __clzsi2() and
__clzdi2()) but for MIPS target and __clzdi2() only, __clzsi2() was
already enabled.

Suggested-by: Daniel Kiper <dkiper@net-space.pl>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-18 23:04:36 +01:00
Glenn Washburn 9c3149a2f2 luks2: Better error handling when setting up the cryptodisk
Do some sanity checking on data coming from the LUKS2 header. If segment.size
is "dynamic", verify that the offset is not past the end of disk. Otherwise,
check for errors from grub_strtoull() when converting segment size from
string. If a GRUB_ERR_BAD_NUMBER error was returned, then the string was
not a valid parsable number, so skip the key. If GRUB_ERR_OUT_OF_RANGE was
returned, then there was an overflow in converting to a 64-bit unsigned
integer. So this could be a very large disk (perhaps large RAID array).
In this case skip the key too. Additionally, enforce some other limits
and fail if needed.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-18 23:00:28 +01:00
Glenn Washburn 278201bc31 luks2: Do not handle disks of size GRUB_DISK_SIZE_UNKNOWN for now
Check to make sure that source disk has a known size. If not, print
a message and return error. There are 4 cases where GRUB_DISK_SIZE_UNKNOWN
is set (biosdisk, obdisk, ofdisk, and uboot), and in all those cases
processing continues. So this is probably a bit conservative. However,
3 of the cases seem pathological, and the other, biosdisk, happens when
booting from a CD-ROM. Since I doubt booting from a LUKS2 volume on
a CD-ROM is a big use case, we'll error until someone complains.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-18 15:19:40 +01:00
Glenn Washburn 90fb18632e luks2: Convert to crypt sectors from GRUB native sectors
The function grub_disk_native_sectors(source) returns the number of sectors
of source in GRUB native (512-byte) sectors, not source sized sectors. So
the conversion needs to use GRUB_DISK_SECTOR_BITS, the GRUB native sector
size.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-18 14:49:56 +01:00
Glenn Washburn b298eed001 luks2: Error check segment.sector_size
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:05 +01:00
Glenn Washburn cf3a3acff0 cryptodisk: Properly handle non-512 byte sized sectors
By default, dm-crypt internally uses an IV that corresponds to 512-byte
sectors, even when a larger sector size is specified. What this means is
that when using a larger sector size, the IV is incremented every sector.
However, the amount the IV is incremented is the number of 512 byte blocks
in a sector (i.e. 8 for 4K sectors). Confusingly the IV does not correspond
to the number of, for example, 4K sectors. So each 512 byte cipher block in
a sector will be encrypted with the same IV and the IV will be incremented
afterwards by the number of 512 byte cipher blocks in the sector.

There are some encryption utilities which do it the intuitive way and have
the IV equal to the sector number regardless of sector size (ie. the fifth
sector would have an IV of 4 for each cipher block). And this is supported
by dm-crypt with the iv_large_sectors option and also cryptsetup as of 2.3.3
with the --iv-large-sectors, though not with LUKS headers (only with --type
plain). However, support for this has not been included as grub does not
support plain devices right now.

One gotcha here is that the encrypted split keys are encrypted with a hard-
coded 512-byte sector size. So even if your data is encrypted with 4K sector
sizes, the split key encrypted area must be decrypted with a block size of
512 (ie the IV increments every 512 bytes). This made these changes less
aesthetically pleasing than desired.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:05 +01:00
Glenn Washburn 7ed69b1d1c luks2: grub_cryptodisk_t->total_sectors is the max number of device native sectors
We need to convert the sectors from the size of the underlying device to the
cryptodisk sector size; segment.size is in bytes which need to be converted
to cryptodisk sectors as well.

Also, removed an empty statement.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn b34cb38795 cryptodisk: Add macros GRUB_TYPE_U_MAX/MIN(type) to replace literals
Add GRUB_TYPE_U_MAX/MIN(type) macros to get the max/min values for an
unsigned number with size of type.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn 3e5f7f5112 cryptodisk: Add macro GRUB_TYPE_BITS() to replace some literals
The new macro GRUB_TYPE_BITS(type) returns the number of bits
allocated for type.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn 40abe8576a luks2: Add string "index" to user strings using a json index
This allows error messages to be more easily distinguishable between indexes
and slot keys. The former include the string "index" in the error/debug
string, and the later are surrounded in quotes.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn 2c7933cd9c luks2: Rename json index variables to names that they are obviously json indexes
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn 64691dddb2 luks2: Use more intuitive object name instead of json index in user messages
Use the object name in the json array rather than the 0 based index in the
json array for keyslots, segments, and digests. This is less confusing for
the end user. For example, say you have a LUKS2 device with a key in slot 1
and slot 4. When using the password for slot 4 to unlock the device, the
messages using the index of the keyslot will mention keyslot 1 (its a
zero-based index). Furthermore, with this change the keyslot number will
align with the number used to reference the keyslot when using the
--key-slot argument to cryptsetup.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn 1f006c4c05 luks2: Add idx member to struct grub_luks2_keyslot/segment/digest
This allows code using these structs to know the named key associated with
these json data structures. In the future we can use these to provide better
error messages to the user.

Get rid of idx local variable in luks2_get_keyslot() which was overloaded to
be used for both keyslot and segment slot keys.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn 7904c5ce67 luks2: Make sure all fields of output argument in luks2_parse_digest() are written to
We should assume that the output argument "out" is uninitialized and could
have random data. So, make sure to initialize the segments and keyslots bit
fields because potentially not all bits of those fields are written to.
Otherwise, the digest could say it belongs to keyslots and segments that it
does not.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn fe902c3f4c luks2: Remove unused argument in grub_error() call
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn a06549d398 luks2: Convert 8 spaces to tabs
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn 8e8b2316ac misc: Add parentheses around ALIGN_UP() and ALIGN_DOWN() arguments
This ensures that expected order of operations is preserved when arguments
are expressions.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:04 +01:00
Glenn Washburn 880dfd8f40 disk: Rename grub_disk_get_size() to grub_disk_native_sectors()
The function grub_disk_get_size() is confusingly named because it actually
returns a sector count where the sectors are sized in the GRUB native sector
size. Rename to something more appropriate.

Suggested-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:03 +01:00
Glenn Washburn 85307c34e8 loopback: Do not automaticaly replace existing loopback dev, error instead
If there is a loopback device with the same name as the one to be created,
instead of closing the old one and replacing it with the new one, return an
error instead. If the loopback device was created, its probably being used
by something and just replacing it may cause GRUB to crash unexpectedly.
This fixes obvious problems like "loopback d (d)/somefile". Its not too
onerous to force the user to delete the loopback first with the "-d" switch.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:03 +01:00
Glenn Washburn 407ddead69 disk: Move hardcoded max disk size literal to a GRUB_DISK_MAX_SECTORS in disk.h
There is a hardcoded maximum disk size that can be read or written from,
currently set at 1 EiB in grub_disk_adjust_range(). Move the literal into a
macro in disk.h, so our assumptions are more visible. This hard coded limit
does not prevent using larger disks, just GRUB won't read/write past the
limit. The comment accompanying this restriction didn't quite make sense to
me, so its been modified too.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:03 +01:00
Glenn Washburn 8919eecd84 fs: Fix block lists not being able to address to end of disk sometimes
When checking if a block list goes past the end of the disk, make sure
the total size of the disk is in GRUB native sector sizes, otherwise there
will be blocks at the end of the disk inaccessible by block lists.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:03 +01:00
Vladimir Serbinenko 505d92f5e7 mbr: Document new limitations on MBR gap support
Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:03 +01:00
Vladimir Serbinenko 5fd18f77ee mbr: Warn if MBR gap is small and user uses advanced modules
We don't want to support small MBR gap in pair with anything but the
simplest config of biosdisk + part_msdos + simple filesystem. In this
path "simple filesystems" are all current filesystems except ZFS and
Btrfs.

Signed-off-by: Vladimir Serbinenko <phcoder@google.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:03 +01:00
Tianjia Zhang ba4b3a7b1e efi/tpm: Extract duplicate code into independent functions
Part of the code logic for processing the return value of efi
log_extend_event is repetitive and complicated. Extract the
repetitive code into an independent function.

Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:03 +01:00
Tianjia Zhang 3ccbaf36d4 efi/tpm: Add debug information for device protocol and eventlog
Add a number of debug logs to the tpm module. The condition tag
for opening debugging is "tpm". On TPM machines, this will bring
great convenience to diagnosis and debugging.

Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:03 +01:00
Daniel Kiper a195dbb677 loader/linux: Report the UEFI Secure Boot status to the Linux kernel
Now that the GRUB has a grub_efi_get_secureboot() function to check the
UEFI Secure Boot status, use it to report that to the Linux kernel.

Signed-off-by: Ignat Korchagin <ignat@cloudflare.com>
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:19:03 +01:00
Javier Martinez Canillas 132ddc42c7 efi: Only register shim_lock verifier if shim_lock protocol is found and SB enabled
The shim_lock module registers a verifier to call shim's verify, but the
handler is registered even when the shim_lock protocol was not installed.

This doesn't cause a NULL pointer dereference in shim_lock_write() because
the shim_lock_init() function just returns GRUB_ERR_NONE if sl isn't set.

But in that case there's no point to even register the shim_lock verifier
since won't do anything. Additionally, it is only useful when Secure Boot
is enabled.

Finally, don't assume that the shim_lock protocol will always be present
when the shim_lock_write() function is called, and check for it on every
call to this function.

Reported-by: Michael Chang <mchang@suse.com>
Reported-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-12 01:17:25 +01:00
Daniel Kiper d7e54b2e5f efi: Add secure boot detection
Introduce grub_efi_get_secureboot() function which returns whether
UEFI Secure Boot is enabled or not on UEFI systems.

Signed-off-by: Ignat Korchagin <ignat@cloudflare.com>
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-11 13:56:22 +01:00
Daniel Kiper ac5c936754 efi: Add a function to read EFI variables with attributes
It will be used to properly detect and report UEFI Secure Boot status to
the x86 Linux kernel. The functionality will be added by subsequent patches.

Signed-off-by: Ignat Korchagin <ignat@cloudflare.com>
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-11 13:55:31 +01:00
Daniel Kiper 04ae030d0e efi: Return grub_efi_status_t from grub_efi_get_variable()
This is needed to properly detect and report UEFI Secure Boot status
to the x86 Linux kernel. The functionality will be added by subsequent
patches.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-11 13:54:54 +01:00
Daniel Kiper f76a27996c efi: Make shim_lock GUID and protocol type public
The GUID will be used to properly detect and report UEFI Secure Boot
status to the x86 Linux kernel. The functionality will be added by
subsequent patches. The shim_lock protocol type is made public for
completeness.

Additionally, fix formatting of four preceding GUIDs.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Marco A Benatto <mbenatto@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-11 13:54:23 +01:00
Javier Martinez Canillas 860be435cb arm/term: Fix linking error due multiple ps2_state definitions
When building with --target=arm-linux-gnu --with-platform=coreboot
a linking error occurs caused by multiple definitions of the
ps2_state variable.

Mark them as static since they aren't used outside their compilation unit.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-11 13:53:54 +01:00
Javier Martinez Canillas 97c20f2412 include/grub/i386/linux.h: Include missing <grub/types.h> header
This header uses types defined in <grub/types.h> but does not include it,
which leads to compile errors like the following:

In file included from ../include/grub/cpu/linux.h:19,
                 from kern/efi/sb.c:21:
../include/grub/i386/linux.h:80:3: error: unknown type name ‘grub_uint64_t’
   80 |   grub_uint64_t addr;

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-11 13:53:18 +01:00
Javier Martinez Canillas b87781feaf i386: Don't include <grub/cpu/linux.h> in coreboot and ieee1275 startup.S
Nothing defined in the header file is used in the assembly code but it
may lead to build errors if some headers are included through this and
contains definitions that are not recognized by the assembler, e.g.:

../include/grub/types.h: Assembler messages:
../include/grub/types.h:76: Error: no such instruction: `typedef signed char grub_int8_t'
../include/grub/types.h:77: Error: no such instruction: `typedef short grub_int16_t'
../include/grub/types.h:78: Error: no such instruction: `typedef int grub_int32_t'

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-12-11 13:52:18 +01:00
Glenn Washburn 6213184b26 luks2: Rename index variable "j" to "i" in luks2_get_keyslot()
Looping variable "j" was named such because the variable name "i" was taken.
Since "i" has been renamed in the previous patch, we can rename "j" to "i".

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 15:33:41 +01:00
Glenn Washburn f36193ddf1 luks2: Rename variable "i" to "keyslot_idx" in luks2_get_keyslot()
Variables named "i" are usually looping variables. So, rename it to
"keyslot_idx" to ease luks2_get_keyslot() reading.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 15:33:41 +01:00
Glenn Washburn c28907e235 luks2: Use correct index variable when looping in luks2_get_keyslot()
The loop variable "j" should be used to index the digests and segments json
array, instead of the variable "i", which is the keyslot index.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 15:33:41 +01:00
Glenn Washburn 0eb44d3196 luks2: Rename source disk variable named "disk" to "source" as in luks.c
This makes it more obvious to the reader that the disk referred to is the
source disk, as opposed to say the disk holding the cryptodisk.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 15:33:41 +01:00
Glenn Washburn d78ce33e60 cryptodisk: Rename "offset" in grub_cryptodisk_t to "offset_sectors"
This makes it clear that the offset represents sectors, not bytes, in
order to improve readability.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 15:33:41 +01:00
Glenn Washburn 535998c2e0 cryptodisk: Rename "total_length" field in grub_cryptodisk_t to "total_sectors"
This creates an alignment with grub_disk_t naming of the same field and is
more intuitive as to how it should be used.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 15:33:41 +01:00
Glenn Washburn f0715577c2 types: Define GRUB_CHAR_BIT based on compiler macro instead of using literal
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 15:33:40 +01:00
Javier Martinez Canillas 71dd2ef76f include/grub/arm64/linux.h: Include missing <grub/types.h> header
This header uses types defined in <grub/types.h> but does not include it,
which leads to compile errors like the following:

../include/grub/cpu/linux.h:27:3: error: unknown type name ‘grub_uint32_t’
   27 |   grub_uint32_t code0;  /* Executable code */
      |   ^~~~~~~~~~~~~

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 15:33:40 +01:00
Javier Martinez Canillas 11fa824dde include/grub/arm/system.h: Include missing <grub/symbol.h> header
The header uses the EXPORT_FUNC() macro defined in <grub/types.h> but
doesn't include it, which leads to the following compile error on arm:

../include/grub/cpu/system.h:12:13: error: ‘EXPORT_FUNC’ declared as function returning a function
   12 | extern void EXPORT_FUNC(grub_arm_disable_caches_mmu) (void);
      |             ^~~~~~~~~~~
../include/grub/cpu/system.h:12:1: warning: parameter names (without types) in function declaration
   12 | extern void EXPORT_FUNC(grub_arm_disable_caches_mmu) (void);
      | ^~~~~~
make[3]: *** [Makefile:36581: kern/efi/kernel_exec-sb.o] Error 1

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 15:33:40 +01:00
Daniel Axtens cc316ea337 docs: grub-install --pubkey has been supported for some time
grub-install --pubkey is supported, so we can now document it.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 14:37:21 +01:00
Daniel Axtens c0c9da5c64 docs: grub-install is no longer a shell script
Since commit cd46aa6cef in 2013, grub-install hasn't been a shell
script. The para doesn't really add that much, especially since it's
the user manual, so just drop it.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-11-20 14:36:50 +01:00
Jacob Kroon d7cac52eb2 Makefile: Remove unused GRUB_PKGLIBDIR definition
Signed-off-by: Jacob Kroon <jacob.kroon@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-10-30 21:53:00 +01:00
Daniel Axtens 59c8e9fb53 lzma: Fix compilation error under clang 10
Compiling under clang 10 gives:

grub-core/lib/LzmaEnc.c:1362:9: error: misleading indentation; statement is not part of the previous 'if' [-Werror,-Wmisleading-indentation]
        {
        ^
grub-core/lib/LzmaEnc.c:1358:7: note: previous statement is here
      if (repIndex == 0)
      ^
1 error generated.

It's not really that unclear in context: there's a commented-out
if-statement. But tweak the alignment anyway so that clang is happy.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-10-30 21:53:00 +01:00
Cao jin 2b106a2a4e kern/i386/realmode: Update comment
Commit b81d609e4c did not update it.

Signed-off-by: Cao jin <caoj.fnst@cn.fujitsu.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-10-30 21:53:00 +01:00
Glenn Washburn 6355ba91e5 cryptodisk: Fix cipher IV mode "plain64" always being set as "plain"
When setting cipher IV mode, detection is done by prefix matching the
cipher IV mode part of the cipher mode string. Since "plain" matches
"plain64", we must check for "plain64" first. Otherwise, "plain64" will
be detected as "plain".

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-10-30 15:37:20 +01:00
Glenn Washburn 2df2912266 crypto: Remove GPG_ERROR_CFLAGS from gpg_err_code_t enum
This was probably added by accident when originally creating the file.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:31:30 +02:00
Glenn Washburn ac301e4dd0 script: Do not allow a delimiter between function name and block start
Currently the following is valid syntax but should be a syntax error:

  grub> function f; { echo HERE; }
  grub> f
  HERE

This fix is not backward compatible, but current syntax is not documented
either and has no functional value. So any scripts with this unintended
syntax are technically syntactically incorrect and should not be relying
on this behavior.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:31:30 +02:00
Glenn Washburn c30f378e00 docs: Support for loading and concatenating multiple initrds
This has been available since January of 2012 but has not been documented.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:31:30 +02:00
Glenn Washburn c98a78ae81 lexer: char const * should be const char *
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:31:30 +02:00
Glenn Washburn 84ff10b1c0 cryptodisk: Use cipher name instead of object in error message
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:31:30 +02:00
Glenn Washburn 8471d8e254 tests: F2FS test should use MOUNTDEVICE like other tests
LODEVICES is not an array variable and should not be accessed as such.
This allows the f2fs test to pass as it was failing because a device
name had a space prepended to the path.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Acked-by: Jaegeuk Kim <jaegeuk@kernel.org>
Tested-by: Paul Menzel <pmenzel@molgen.mpg.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:31:30 +02:00
Florian La Roche 3ec59f14f4 grub-mkconfig: If $hints is not set reduce the output into grub.cfg to just 1 line
Signed-off-by: Florian La Roche <Florian.LaRoche@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:31:30 +02:00
Petr Vorel c55480daca travis: Run bootstrap to fix build
autogen.sh isn't enough:

  $ ./autogen.sh
  Gnulib not yet bootstrapped; run ./bootstrap instead.
  The command "./autogen.sh" exited with 1.

Additionally, using bootstrap requires to install autopoint package.

Signed-off-by: Petr Vorel <pvorel@suse.cz>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:31:30 +02:00
Patrick Steinhardt ee12785f75 luks2: Strip dashes off of the UUID
The UUID header for LUKS2 uses a format with dashes, same as for
LUKS(1). But while we strip these dashes for the latter, we don't for
the former. This isn't wrong per se, but it's definitely inconsistent
for users as they need to use the dashed format for LUKS2 and the
non-dashed format for LUKS when e.g. calling "cryptomount -u $UUID".

Fix this inconsistency by stripping dashes off of the LUKS2 UUID.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:31:29 +02:00
Tianjia Zhang 6efd04f314 efi/tpm: Remove unused functions and structures
Although the tpm_execute() series of functions are defined they are not
used anywhere. Several structures in the include/grub/efi/tpm.h header
file are not used too. There is even nonexistent grub_tpm_init()
declaration in this header. Delete all that unneeded stuff.

If somebody needs the functionality implemented in the dropped code then
he/she can re-add it later. Now it needlessly increases the GRUB
code/image size.

Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:31:29 +02:00
Tianjia Zhang de094060ac shim_lock: Enable module for all EFI architectures
Like the tpm the shim_lock module is only enabled for x86_64 target.
However, there's nothing specific to x86_64 in the implementation and
it can be enabled for all EFI architectures.

Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-18 22:26:48 +02:00
Daniel Kiper 1e81bf6d2d efi/tpm: Fix typo in grub_efi_tpm2_protocol struct
Rename get_active_pcr_blanks() to get_active_pcr_banks().

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
2020-09-18 21:23:21 +02:00
Daniel Kiper c386331364 i386/efi/init: Drop bogus include
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
2020-09-18 21:22:32 +02:00
Daniel Kiper 30c4e3ca40 docs: Fix devicetree command description
Specifically fix the subsection and drop bogus reference to the GNU/Linux.

Reported-by: Patrick Higgins <higgi1pt@gmail.com>
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
2020-09-18 21:20:43 +02:00
Martin Whitaker 8451454889 grub-install: Fix inverted test for NLS enabled when copying locales
Commit 3d8439da8 (grub-install: Locale depends on nls) attempted to avoid
copying locale files to the target directory when NLS was disabled.
However the test is inverted, and it does the opposite.

Signed-off-by: Martin Whitaker <fsf@martin-whitaker.me.uk>
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
2020-09-18 21:17:07 +02:00
Javier Martinez Canillas a6838bbc67 tftp: Roll-over block counter to prevent data packets timeouts
Commit 781b3e5efc (tftp: Do not use priority queue) caused a regression
when fetching files over TFTP whose size is bigger than 65535 * block size.

  grub> linux /images/pxeboot/vmlinuz
  grub> echo $?
  0
  grub> initrd /images/pxeboot/initrd.img
  error: timeout reading '/images/pxeboot/initrd.img'.
  grub> echo $?
  28

It is caused by the block number counter being a 16-bit field, which leads
to a maximum file size of ((1 << 16) - 1) * block size. Because GRUB sets
the block size to 1024 octets (by using the TFTP Blocksize Option from RFC
2348 [0]), the maximum file size that can be transferred is 67107840 bytes.

The TFTP PROTOCOL (REVISION 2) RFC 1350 [1] does not mention what a client
should do when a file size is bigger than the maximum, but most TFTP hosts
support the block number counter to be rolled over. That is, acking a data
packet with a block number of 0 is taken as if the 65356th block was acked.

It was working before because the block counter roll-over was happening due
an overflow. But that got fixed by the mentioned commit, which led to the
regression when attempting to fetch files larger than the maximum size.

To allow TFTP file transfers of unlimited size again, re-introduce a block
counter roll-over so the data packets are acked preventing the timeouts.

[0]: https://tools.ietf.org/html/rfc2348
[1]: https://tools.ietf.org/html/rfc1350

Fixes: 781b3e5efc (tftp: Do not use priority queue)

Suggested-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-11 15:52:07 +02:00
Florian La Roche 3e9d8c4ce4 templates: Remove unnecessary trailing semicolon
Signed-off-by: Florian La Roche <Florian.LaRoche@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-11 15:51:25 +02:00
Glenn Washburn e1b0992a8d cryptodisk: Fix incorrect calculation of start sector
Here dev is a grub_cryptodisk_t and dev->offset is offset in sectors of size
native to the cryptodisk device. The sector is correctly transformed into
native grub sector size, but then added to dev->offset which is not
transformed. It would be nice if the type system would help us with this.

Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-11 15:51:04 +02:00
Glenn Washburn 3b3ac0c982 cryptodisk: Unregister cryptomount command when removing module
Signed-off-by: Glenn Washburn <development@efficientek.com>
Reviewed-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-11 15:48:50 +02:00
Patrick Steinhardt eb77486141 luks2: Improve error reporting when decrypting/verifying key
While we already set up error messages in both luks2_verify_key() and
luks2_decrypt_key(), we do not ever print them. This makes it really
hard to discover why a given key actually failed to decrypt a disk.

Improve this by including the error message in the user-visible output.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-11 15:48:13 +02:00
Patrick Steinhardt 1066336dc8 luks: Fix out-of-bounds copy of UUID
When configuring a LUKS disk, we copy over the UUID from the LUKS header
into the new grub_cryptodisk_t structure via grub_memcpy(). As size
we mistakenly use the size of the grub_cryptodisk_t UUID field, which
is guaranteed to be strictly bigger than the LUKS UUID field we're
copying. As a result, the copy always goes out-of-bounds and copies some
garbage from other surrounding fields. During runtime, this isn't
noticed due to the fact that we always NUL-terminate the UUID and thus
never hit the trailing garbage.

Fix the issue by using the size of the local stripped UUID field.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-11 15:47:39 +02:00
Patrick Steinhardt b35792dccb json: Remove invalid typedef redefinition
The C standard does not allow for typedef redefinitions, even if they
map to the same underlying type. In order to avoid including the
jsmn.h in json.h and thus exposing jsmn's internals, we have exactly
such a forward-declaring typedef in json.h. If enforcing the GNU99 C
standard, clang may generate a warning about this non-standard
construct.

Fix the issue by using a simple "struct jsmntok" forward declaration
instead of using a typedef.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Tested-by: Chuck Tuffli <chuck@freebsd.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-11 15:46:55 +02:00
Cao jin 74259522d7 i386/relocator_common: Drop empty #ifdef
Signed-off-by: Cao jin <caoj.fnst@cn.fujitsu.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-11 15:46:36 +02:00
Ave Milia a0ba8fae61 video/bochs: Fix typo
Signed-off-by: Ave Milia <avemilia@protonmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-09-11 15:45:56 +02:00
Colin Watson e7b8856f8b linux: Fix integer overflows in initrd size handling
These could be triggered by a crafted filesystem with very large files.

Fixes: CVE-2020-15707

Signed-off-by: Colin Watson <cjwatson@debian.org>
Reviewed-by: Jan Setje-Eilers <jan.setjeeilers@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Peter Jones 0dcbf3652b loader/linux: Avoid overflow on initrd size calculation
Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Alexey Makhalov f7bd9986f6 efi: Fix use-after-free in halt/reboot path
commit 92bfc33db9 ("efi: Free malloc regions on exit")
introduced memory freeing in grub_efi_fini(), which is
used not only by exit path but by halt/reboot one as well.
As result of memory freeing, code and data regions used by
modules, such as halt, reboot, acpi (used by halt) also got
freed. After return to module code, CPU executes, filled
by UEFI firmware (tested with edk2), 0xAFAFAFAF pattern as
a code. Which leads to #UD exception later.

grub> halt
!!!! X64 Exception Type - 06(#UD - Invalid Opcode)  CPU Apic ID - 00000000 !!!!
RIP  - 0000000003F4EC28, CS  - 0000000000000038, RFLAGS - 0000000000200246
RAX  - 0000000000000000, RCX - 00000000061DA188, RDX - 0A74C0854DC35D41
RBX  - 0000000003E10E08, RSP - 0000000007F0F860, RBP - 0000000000000000
RSI  - 00000000064DB768, RDI - 000000000832C5C3
R8   - 0000000000000002, R9  - 0000000000000000, R10 - 00000000061E2E52
R11  - 0000000000000020, R12 - 0000000003EE5C1F, R13 - 00000000061E0FF4
R14  - 0000000003E10D80, R15 - 00000000061E2F60
DS   - 0000000000000030, ES  - 0000000000000030, FS  - 0000000000000030
GS   - 0000000000000030, SS  - 0000000000000030
CR0  - 0000000080010033, CR2 - 0000000000000000, CR3 - 0000000007C01000
CR4  - 0000000000000668, CR8 - 0000000000000000
DR0  - 0000000000000000, DR1 - 0000000000000000, DR2 - 0000000000000000
DR3  - 0000000000000000, DR6 - 00000000FFFF0FF0, DR7 - 0000000000000400
GDTR - 00000000079EEA98 0000000000000047, LDTR - 0000000000000000
IDTR - 0000000007598018 0000000000000FFF,   TR - 0000000000000000
FXSAVE_STATE - 0000000007F0F4C0

Proposal here is to continue to free allocated memory for
exit boot services path but keep it for halt/reboot path
as it won't be much security concern here.
Introduced GRUB_LOADER_FLAG_EFI_KEEP_ALLOCATED_MEMORY
loader flag to be used by efi halt/reboot path.

Signed-off-by: Alexey Makhalov <amakhalov@vmware.com>
Reviewed-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Daniel Kiper 098058752e efi/chainloader: Propagate errors from copy_file_path()
Without any error propagated to the caller, make_file_path()
would then try to advance the invalid device path node with
GRUB_EFI_NEXT_DEVICE_PATH(), which would fail, returning a NULL
pointer that would subsequently be dereferenced. Hence, propagate
errors from copy_file_path().

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Peter Jones d2cf823d0e efi: Fix some malformed device path arithmetic errors
Several places we take the length of a device path and subtract 4 from
it, without ever checking that it's >= 4. There are also cases where
this kind of malformation will result in unpredictable iteration,
including treating the length from one dp node as the type in the next
node. These are all errors, no matter where the data comes from.

This patch adds a checking macro, GRUB_EFI_DEVICE_PATH_VALID(), which
can be used in several places, and makes GRUB_EFI_NEXT_DEVICE_PATH()
return NULL and GRUB_EFI_END_ENTIRE_DEVICE_PATH() evaluate as true when
the length is too small. Additionally, it makes several places in the
code check for and return errors in these cases.

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Peter Jones b73cee7f1f emu: Make grub_free(NULL) safe
The grub_free() implementation in grub-core/kern/mm.c safely handles
NULL pointers, and code at many places depends on this. We don't know
that the same is true on all host OSes, so we need to handle the same
behavior in grub-emu's implementation.

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Peter Jones 879c4a8342 lvm: Fix two more potential data-dependent alloc overflows
It appears to be possible to make a (possibly invalid) lvm PV with
a metadata size field that overflows our type when adding it to the
address we've allocated. Even if it doesn't, it may be possible to do so
with the math using the outcome of that as an operand. Check them both.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Peter Jones f5703eb062 hfsplus: Fix two more overflows
Both node->size and node->namelen come from the supplied filesystem,
which may be user-supplied. We can't trust them for the math unless we
know they don't overflow. Making sure they go through grub_add() or
grub_calloc() first will give us that.

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Alexey Makhalov 07e5b79e22 relocator: Fix grub_relocator_alloc_chunk_align() top memory allocation
Current implementation of grub_relocator_alloc_chunk_align()
does not allow allocation of the top byte.

Assuming input args are:
  max_addr = 0xfffff000;
  size = 0x1000;

And this is valid. But following overflow protection will
unnecessarily move max_addr one byte down (to 0xffffefff):
  if (max_addr > ~size)
    max_addr = ~size;

~size + 1 will fix the situation. In addition, check size
for non zero to do not zero max_addr.

Signed-off-by: Alexey Makhalov <amakhalov@vmware.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Chris Coulson 426f57383d script: Avoid a use-after-free when redefining a function during execution
Defining a new function with the same name as a previously defined
function causes the grub_script and associated resources for the
previous function to be freed. If the previous function is currently
executing when a function with the same name is defined, this results
in use-after-frees when processing subsequent commands in the original
function.

Instead, reject a new function definition if it has the same name as
a previously defined function, and that function is currently being
executed. Although a behavioural change, this should be backwards
compatible with existing configurations because they can't be
dependent on the current behaviour without being broken.

Fixes: CVE-2020-15706

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Chris Coulson 1a8d9c9b4a script: Remove unused fields from grub_script_function struct
Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Alexey Makhalov 61ff5602fe relocator: Protect grub_relocator_alloc_chunk_align() max_addr against integer underflow
This commit introduces integer underflow mitigation in max_addr calculation
in grub_relocator_alloc_chunk_align() invocation.

It consists of 2 fixes:
  1. Introduced grub_relocator_alloc_chunk_align_safe() wrapper function to perform
     sanity check for min/max and size values, and to make safe invocation of
     grub_relocator_alloc_chunk_align() with validated max_addr value. Replace all
     invocations such as grub_relocator_alloc_chunk_align(..., min_addr, max_addr - size, size, ...)
     by grub_relocator_alloc_chunk_align_safe(..., min_addr, max_addr, size, ...).
  2. Introduced UP_TO_TOP32(s) macro for the cases where max_addr is 32-bit top
     address (0xffffffff - size + 1) or similar.

Signed-off-by: Alexey Makhalov <amakhalov@vmware.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Alexey Makhalov caea56d1f8 relocator: Protect grub_relocator_alloc_chunk_addr() input args against integer underflow/overflow
Use arithmetic macros from safemath.h to accomplish it. In this commit,
I didn't want to be too paranoid to check every possible math equation
for overflow/underflow. Only obvious places (with non zero chance of
overflow/underflow) were refactored.

Signed-off-by: Alexey Makhalov <amakhalov@vmware.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Alexey Makhalov 781b3e5efc tftp: Do not use priority queue
There is not need to reassemble the order of blocks. Per RFC 1350,
server must wait for the ACK, before sending next block. Data packets
can be served immediately without putting them to priority queue.

Logic to handle incoming packet is this:
  - if packet block id equal to expected block id, then
    process the packet,
  - if packet block id is less than expected - this is retransmit
    of old packet, then ACK it and drop the packet,
  - if packet block id is more than expected - that shouldn't
    happen, just drop the packet.

It makes the tftp receive path code simpler, smaller and faster.
As a benefit, this change fixes CID# 73624 and CID# 96690, caused
by following while loop:

  while (cmp_block (grub_be_to_cpu16 (tftph->u.data.block), data->block + 1) == 0)

where tftph pointer is not moving from one iteration to another, causing
to serve same packet again. Luckily, double serving didn't happen due to
data->block++ during the first iteration.

Fixes: CID 73624, CID 96690

Signed-off-by: Alexey Makhalov <amakhalov@vmware.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Konrad Rzeszutek Wilk f8ad7a3dd8 multiboot2: Fix memory leak if grub_create_loader_cmdline() fails
Fixes: CID 292468

Signed-off-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Konrad Rzeszutek Wilk d17770857e udf: Fix memory leak
Fixes: CID 73796

Signed-off-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Jan Setje-Eilers <jan.setjeeilers@oracle.com>
2020-07-29 16:55:48 +02:00
Konrad Rzeszutek Wilk 61b7ca08d1 term: Fix overflow on user inputs
This requires a very weird input from the serial interface but can cause
an overflow in input_buf (keys) overwriting the next variable (npending)
with the user choice:

(pahole output)

struct grub_terminfo_input_state {
        int                        input_buf[6];         /*     0    24 */
        int                        npending;             /*    24     4 */ <- CORRUPT
        ...snip...

The magic string requires causing this is "ESC,O,],0,1,2,q" and we overflow
npending with "q" (aka increase npending to 161). The simplest fix is to
just to disallow overwrites input_buf, which exactly what this patch does.

Fixes: CID 292449

Signed-off-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Konrad Rzeszutek Wilk 16c0dbf4bc lzma: Make sure we don't dereference past array
The two dimensional array p->posSlotEncoder[4][64] is being dereferenced
using the GetLenToPosState() macro which checks if len is less than 5,
and if so subtracts 2 from it. If len = 0, that is 0 - 2 = 4294967294.
Obviously we don't want to dereference that far out so we check if the
position found is greater or equal kNumLenToPosStates (4) and bail out.

N.B.: Upstream LZMA 18.05 and later has this function completely rewritten
without any history.

Fixes: CID 51526

Signed-off-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Chris Coulson dc052e5ac7 json: Avoid a double-free when parsing fails.
When grub_json_parse() succeeds, it returns the root object which
contains a pointer to the provided JSON string. Callers are
responsible for ensuring that this string outlives the root
object and for freeing its memory when it's no longer needed.

If grub_json_parse() fails to parse the provided JSON string,
it frees the string before returning an error. This results
in a double free in luks2_recover_key(), which also frees the
same string after grub_json_parse() returns an error.

This changes grub_json_parse() to never free the JSON string
passed to it, and updates the documentation for it to make it
clear that callers are responsible for ensuring that the string
outlives the root JSON object.

Fixes: CID 292465

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Alexey Makhalov 6d7a59a2a1 xnu: Fix double free in grub_xnu_devprop_add_property()
grub_xnu_devprop_add_property() should not free utf8 and utf16 as it get
allocated and freed in the caller.

Minor improvement: do prop fields initialization after memory allocations.

Fixes: CID 292442, CID 292457, CID 292460, CID 292466

Signed-off-by: Alexey Makhalov <amakhalov@vmware.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Alexey Makhalov 26a8c19307 gfxmenu: Fix double free in load_image()
self->bitmap should be zeroed after free. Otherwise, there is a chance
to double free (USE_AFTER_FREE) it later in rescale_image().

Fixes: CID 292472

Signed-off-by: Alexey Makhalov <amakhalov@vmware.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Daniel Kiper 89f3da1a3d font: Do not load more than one NAME section
The GRUB font file can have one NAME section only. Though if somebody
crafts a broken font file with many NAME sections and loads it then the
GRUB leaks memory. So, prevent against that by loading first NAME
section and failing in controlled way on following one.

Reported-by: Chris Coulson <chris.coulson@canonical.com>
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Jan Setje-Eilers <jan.setjeeilers@oracle.com>
2020-07-29 16:55:48 +02:00
Peter Jones 2a1edcf2ed iso9660: Don't leak memory on realloc() failures
Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:48 +02:00
Peter Jones 3f05d693d1 malloc: Use overflow checking primitives where we do complex allocations
This attempts to fix the places where we do the following where
arithmetic_expr may include unvalidated data:

  X = grub_malloc(arithmetic_expr);

It accomplishes this by doing the arithmetic ahead of time using grub_add(),
grub_sub(), grub_mul() and testing for overflow before proceeding.

Among other issues, this fixes:
  - allocation of integer overflow in grub_video_bitmap_create()
    reported by Chris Coulson,
  - allocation of integer overflow in grub_png_decode_image_header()
    reported by Chris Coulson,
  - allocation of integer overflow in grub_squash_read_symlink()
    reported by Chris Coulson,
  - allocation of integer overflow in grub_ext2_read_symlink()
    reported by Chris Coulson,
  - allocation of integer overflow in read_section_as_string()
    reported by Chris Coulson.

Fixes: CVE-2020-14309, CVE-2020-14310, CVE-2020-14311

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:47 +02:00
Peter Jones f725fa7cb2 calloc: Use calloc() at most places
This modifies most of the places we do some form of:

  X = malloc(Y * Z);

to use calloc(Y, Z) instead.

Among other issues, this fixes:
  - allocation of integer overflow in grub_png_decode_image_header()
    reported by Chris Coulson,
  - allocation of integer overflow in luks_recover_key()
    reported by Chris Coulson,
  - allocation of integer overflow in grub_lvm_detect()
    reported by Chris Coulson.

Fixes: CVE-2020-14308

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:47 +02:00
Peter Jones 64e26162eb calloc: Make sure we always have an overflow-checking calloc() available
This tries to make sure that everywhere in this source tree, we always have
an appropriate version of calloc() (i.e. grub_calloc(), xcalloc(), etc.)
available, and that they all safely check for overflow and return NULL when
it would occur.

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:47 +02:00
Peter Jones 68708c4503 safemath: Add some arithmetic primitives that check for overflow
This adds a new header, include/grub/safemath.h, that includes easy to
use wrappers for __builtin_{add,sub,mul}_overflow() declared like:

  bool OP(a, b, res)

where OP is grub_add, grub_sub or grub_mul. OP() returns true in the
case where the operation would overflow and res is not modified.
Otherwise, false is returned and the operation is executed.

These arithmetic primitives require newer compiler versions. So, bump
these requirements in the INSTALL file too.

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:47 +02:00
Peter Jones a4d3fbdff1 yylex: Make lexer fatal errors actually be fatal
When presented with a command that can't be tokenized to anything
smaller than YYLMAX characters, the parser calls YY_FATAL_ERROR(errmsg),
expecting that will stop further processing, as such:

  #define YY_DO_BEFORE_ACTION \
        yyg->yytext_ptr = yy_bp; \
        yyleng = (int) (yy_cp - yy_bp); \
        yyg->yy_hold_char = *yy_cp; \
        *yy_cp = '\0'; \
        if ( yyleng >= YYLMAX ) \
                YY_FATAL_ERROR( "token too large, exceeds YYLMAX" ); \
        yy_flex_strncpy( yytext, yyg->yytext_ptr, yyleng + 1 , yyscanner); \
        yyg->yy_c_buf_p = yy_cp;

The code flex generates expects that YY_FATAL_ERROR() will either return
for it or do some form of longjmp(), or handle the error in some way at
least, and so the strncpy() call isn't in an "else" clause, and thus if
YY_FATAL_ERROR() is *not* actually fatal, it does the call with the
questionable limit, and predictable results ensue.

Unfortunately, our implementation of YY_FATAL_ERROR() is:

   #define YY_FATAL_ERROR(msg)                     \
     do {                                          \
       grub_printf (_("fatal error: %s\n"), _(msg));     \
     } while (0)

The same pattern exists in yyless(), and similar problems exist in users
of YY_INPUT(), several places in the main parsing loop,
yy_get_next_buffer(), yy_load_buffer_state(), yyensure_buffer_stack,
yy_scan_buffer(), etc.

All of these callers expect YY_FATAL_ERROR() to actually be fatal, and
the things they do if it returns after calling it are wildly unsafe.

Fixes: CVE-2020-10713

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-07-29 16:55:47 +02:00
Marc Zyngier 6a34fdb76a arm: Fix 32-bit ARM handling of the CTR register
When booting on an ARMv8 core that implements either CTR.IDC or CTR.DIC
(indicating that some of the cache maintenance operations can be
removed when dealing with I/D-cache coherency, GRUB dies with a
"Unsupported cache type 0x........" message.

This is pretty likely to happen when running in a virtual machine
hosted on an arm64 machine (I've triggered it on a system built around
a bunch of Cortex-A55 cores, which implements CTR.IDC).

It turns out that the way GRUB deals with the CTR register is a bit
harsh for anything from ARMv7 onwards. The layout of the register is
backward compatible, meaning that nothing that gets added is allowed to
break earlier behaviour. In this case, ignoring IDC is completely fine,
and only results in unnecessary cache maintenance.

We can thus avoid being paranoid, and align the 32bit behaviour with
its 64bit equivalent.

This patch has the added benefit that it gets rid of a (gnu-specific)
case range too.

Signed-off-by: Marc Zyngier <maz@kernel.org>
Reviewed-by: Leif Lindholm <leif@nuviainc.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-25 15:02:51 +02:00
Ian Jackson a81401ff49 templates/20_linux_xen: Support Xen Security Modules (XSM/FLASK)
XSM is enabled by adding "flask=enforcing" as a Xen command line
argument, and providing the policy file as a grub module.

We make entries for both with and without XSM. If XSM is not compiled
into Xen, then there are no policy files, so no change to the boot
options.

Signed-off-by: Ian Jackson <ian.jackson@eu.citrix.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-25 15:00:56 +02:00
Ian Jackson 7a9b30143b templates/20_linux_xen: Ignore xenpolicy and config files too
file_is_not_sym() currently only checks for xen-syms. Extend it to
disregard xenpolicy (XSM policy files) and files ending .config (which
are built by the Xen upstream build system in some configurations and
can therefore end up in /boot).

Rename the function accordingly, to file_is_not_xen_garbage().

Signed-off-by: Ian Jackson <ian.jackson@eu.citrix.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-25 15:00:37 +02:00
Javier Martinez Canillas 96be75ecbd net: Break out nested function
Nested functions are not supported in C, but are permitted as an extension
in the GNU C dialect. Commit cb2f15c544 ("normal/main: Search for specific
config files for netboot") added a nested function which caused the build
to break when compiling with clang.

Break that out into a static helper function to make the code portable again.

Reported-by: Daniel Axtens <dja@axtens.net>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Tested-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-25 14:52:10 +02:00
Javier Martinez Canillas cc6bd49a52 tpm: Enable module for all EFI platforms
The module is only enabled for x86_64, but there's nothing specific to
x86_64 in the implementation and can be enabled for all EFI platforms.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-25 14:50:42 +02:00
Daniel Kiper 15d76540a7 INSTALL/configure: Update install doc and configure comment
..to reflect the GRUB build reality in them.

Additionally, fix text formatting a bit.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Leif Lindholm <leif@nuviainc.com>
2020-05-25 14:49:53 +02:00
Daniel Kiper c894713836 configure: Set gnu99 C language standard by default
Commit d5a32255d (misc: Make grub_strtol() "end" pointers have safer
const qualifiers) introduced "restrict" keyword into some functions
definitions. This keyword was introduced in C99 standard. However, some
compilers by default may use C89 or something different. This behavior
leads to the breakage during builds when c89 or gnu89 is in force. So,
let's set gnu99 C language standard for all compilers by default. This
way a bit random build issue will be fixed and the GRUB source will be
build consistently regardless of type and version of the compiler.

It was decided to use gnu99 C language standard because it fixes the
issue mentioned above and also provides some useful extensions which are
used here and there in the GRUB source. Potentially we can use gnu11
too. However, this may reduce pool of older compilers which can be used
to build the GRUB. So, let's live with gnu99 until we discover that we
strongly require a feature from newer C standard.

The user is still able to override C language standard using relevant
*_CFLAGS variables.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Leif Lindholm <leif@nuviainc.com>
2020-05-25 14:43:16 +02:00
Tianjia Zhang c867185b81 tpm: Rename function grub_tpm_log_event() to grub_tpm_measure()
grub_tpm_log_event() and grub_tpm_measure() are two functions that
have the same effect. So, keep grub_tpm_log_event() and rename it
to grub_tpm_measure(). This way we get also a more clear semantics.

Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 15:37:28 +02:00
Daniel Kiper f39f1ec5d9 autogen: Replace -iname with -ipath in find command
..because -iname cannot be used to match paths.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Leif Lindholm <leif@nuviainc.com>
Reviewed-by: Daniel Axtens <dja@axtens.net>
2020-05-15 15:35:59 +02:00
Daniel Kiper f2d56dea9d INSTALL: Update configure example
..to make it more relevant.

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Leif Lindholm <leif@nuviainc.com>
2020-05-15 15:34:43 +02:00
Daniel Kiper 4aa9614e0a configure: Drop unneeded TARGET_CFLAGS expansion
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Leif Lindholm <leif@nuviainc.com>
2020-05-15 15:33:08 +02:00
Jacob Kroon 5ab40eb9f7 docs/grub: Support for probing partition UUID on MSDOS disks
Support was implemented in commit c7cb11b21 (probe: Support probing for
msdos PARTUUID).

Signed-off-by: Jacob Kroon <jacob.kroon@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 15:27:58 +02:00
Tianjia Zhang 0fa9ed41ac verifiers: Add verify string debug message
Like grub_verifiers_open(), the grub_verify_string() should also
display this debug message, which is very helpful for debugging.

Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 15:26:41 +02:00
Javier Martinez Canillas 0f3600bf1b envblk: Fix buffer overrun when attempting to shrink a variable value
If an existing variable is set with a value whose length is smaller than
the current value, a memory corruption can happen due copying padding '#'
characters outside of the environment block buffer.

This is caused by a wrong calculation of the previous free space position
after moving backward the characters that followed the old variable value.

That position is calculated to fill the remaining of the buffer with the
padding '#' characters. But since isn't calculated correctly, it can lead
to copies outside of the buffer.

The issue can be reproduced by creating a variable with a large value and
then try to set a new value that is much smaller:

$ grub2-editenv --version
grub2-editenv (GRUB) 2.04

$ grub2-editenv env create

$ grub2-editenv env set a="$(for i in {1..500}; do var="b$var"; done; echo $var)"

$ wc -c env
1024 grubenv

$ grub2-editenv env set a="$(for i in {1..50}; do var="b$var"; done; echo $var)"
malloc(): corrupted top size
Aborted (core dumped)

$ wc -c env
0 grubenv

Reported-by: Renaud Métrich <rmetrich@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 15:24:59 +02:00
Hans Ulrich Niedermann 2f317c8f19 docs: Remove docs for non-existing uppermem command
Remove all documentation of and mentions of the uppermem
command from the docs/grub.texi file.

The uppermem command is not implemented in the GRUB source
at all and appears to never have been implemented despite
former plans to add an uppermem command.

To reduce user confusion, this even removes the paragraph
describing how GRUB's uppermem command was supposed to
complement the Linux kernel's mem= parameter.

Signed-off-by: Hans Ulrich Niedermann <hun@n-dimensional.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 15:23:00 +02:00
Hans Ulrich Niedermann f7dcb6a5c2 docs: Remove docs for non-existing pxe_unload command
Remove the documentation of the pxe_unload command from the
docs/grub.texi file.

The pxe_unload command is not implemented in the grub source
at this time at all. It appears to have been removed in commit
671a78acb (cleanup pxe and efi network release).

Signed-off-by: Hans Ulrich Niedermann <hun@n-dimensional.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 15:20:55 +02:00
Hans Ulrich Niedermann 2ceae0ae25 gitignore: Add a few forgotten file patterns
Add a few patterns to .gitignore to cover files which are generated
by building grub ("make", "make check", "make dist") but which have
been forgotten to add to .gitignore in the past.

Signed-off-by: Hans Ulrich Niedermann <hun@n-dimensional.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 15:06:21 +02:00
Hans Ulrich Niedermann 641a144085 gitignore: Add leading slashes where appropriate
Going through the list of gitignore patterns without a leading slash,
this adds a leading slash where it appears to have been forgotten.

Some gitignore patterns like ".deps/" or "Makefile" clearly should
match everywhere, so those definitively need no leading slash.

For some patterns like "ascii.bitmaps", it is unclear where in the
source tree they should match. Those patterns are kept as they are,
matching the patterns in the whole tree of subdirectories.

Signed-off-by: Hans Ulrich Niedermann <hun@n-dimensional.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 15:06:13 +02:00
Hans Ulrich Niedermann 6cfa746654 gitignore: Add trailing slashes for directories
Add trailing slashes for all patterns matching directories.

Note that we do *not* add trailing slashes for *symlinks*
to directories.

Signed-off-by: Hans Ulrich Niedermann <hun@n-dimensional.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 15:04:17 +02:00
Hans Ulrich Niedermann c745f02165 gitignore: Sort both pattern groups alphabetically
Alphabetically sort the two groups of gitignore patterns:

  * The group of patterns without slashes, matching anywhere
    in the directory subtree.

  * The group of patterns with slashes, matching relative to the
    .gitignore file's directory

Signed-off-by: Hans Ulrich Niedermann <hun@n-dimensional.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 15:04:07 +02:00
Hans Ulrich Niedermann 26b7d55d82 gitignore: Group patterns with and without slash
Group the .gitignore patterns into two groups:

  * Pattern not including a slash, i.e. matching files anywhere in
    the .gitignore file's directory and all of its subdirectories.

  * Patterns including a slash, i.e. matching only relative to the
    .gitignore file's directory.

Signed-off-by: Hans Ulrich Niedermann <hun@n-dimensional.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 14:59:47 +02:00
Hans Ulrich Niedermann 16923f88ad gitignore: Consistent leading slash is easier to read
As all gitignore patterns containing a left or middle slash match
only relative to the .gitignore file's directory, we write them
all in the same manner with a leading slash.

This makes the file significantly easier to read.

Signed-off-by: Hans Ulrich Niedermann <hun@n-dimensional.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 14:50:30 +02:00
Daniel Kiper eb46ee98bc mips/cache: Add missing nop's in delay slots
Lack of them causes random instructions to be executed before the
jump really happens.

Signed-off-by: Vladimir Serbinenko <phcoder@google.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-05-15 14:30:07 +02:00
Patrick Steinhardt c543d67810 luks2: Propagate error when reading area key fails
When decrypting a given keyslot, all error cases except for one set up
an error and return the error code. The only exception is when we try to
read the area key: instead of setting up an error message, we directly
print it via grub_dprintf().

Convert the outlier to use grub_error() to allow more uniform handling
of errors.

Signed-off-by: Patrick Steinhardt <ps@kps.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:18:26 +02:00
Patrick Steinhardt e933feb578 json: Get rid of casts for "jsmntok_t"
With the upstream change having landed that adds a name to the
previously anonymous "jsmntok" typedef, we can now add a forward
declaration for that struct in our code. As a result, we no longer have
to store the "tokens" member of "struct grub_json" as a void pointer but
can instead use the forward declaration, allowing us to get rid of casts
of that field.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:16:41 +02:00
Patrick Steinhardt 3b81607b55 json: Update jsmn library to upstream commit 053d3cd
Update our embedded version of the jsmn library to upstream commit
053d3cd (Merge pull request #175 from pks-t/pks/struct-type,
2020-04-02).

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:15:14 +02:00
Steve Langasek 46d76f8fef templates: Output a menu entry for firmware setup on UEFI FastBoot systems
The fwsetup command allows to reboot into the EFI firmware setup menu, add
a template to include a menu entry on EFI systems that makes use of that
command to reboot into the EFI firmware settings.

This is useful for users since the hotkey to enter into the EFI setup menu
may not be the same on all systems so users can use the menu entry without
needing to figure out what key needs to be pressed.

Also, if fastboot is enabled in the BIOS then often it is not possible to
enter the firmware setup menu. So the entry is again useful for this case.

Signed-off-by: Steve Langasek <steve.langasek@ubuntu.com>
Signed-off-by: Dimitri John Ledkov <xnox@ubuntu.com>
Signed-off-by: Hans de Goede <hdegoede@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:14:12 +02:00
Hans de Goede 12341958d2 kern/term: Accept ESC, F4 and holding SHIFT as user interrupt keys
On some devices the ESC key is the hotkey to enter the BIOS/EFI setup
screen, making it really hard to time pressing it right. Besides that
ESC is also pretty hard to discover for a user who does not know it
will unhide the menu.

This commit makes F4, which was chosen because is not used as a hotkey
to enter the BIOS setup by any vendor, also interrupt sleeps / stop the
menu countdown.

This solves the ESC gets into the BIOS setup and also somewhat solves
the discoverability issue, but leaves the timing issue unresolved.

This commit fixes the timing issue by also adding support for keeping
SHIFT pressed during boot to stop the menu countdown. This matches
what Ubuntu is doing, which should also help with discoverability.

Signed-off-by: Hans de Goede <hdegoede@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:13:44 +02:00
Hans de Goede 2d7c3abd87 efi/console: Do not set text-mode until we actually need it
If we're running with a hidden menu we may never need text mode, so do not
change the video-mode to text until we actually need it.

This allows to boot a machine without unnecessary graphical transitions and
provide a seamless boot experience to users.

Signed-off-by: Hans de Goede <hdegoede@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:13:14 +02:00
Hans de Goede ea138d11be efi/console: Implement getkeystatus() support
Implement getkeystatus() support in the EFI console driver.

This is needed because the logic to determine if a key was pressed to make
the menu countdown stop will be changed by a later patch to also take into
account the SHIFT key being held down.

For this reason the EFI console driver has to support getkeystatus() to
allow detecting that event.

Note that if a non-modifier key gets pressed and repeated calls to
getkeystatus() are made then it will return the modifier status at the
time of the non-modifier key, until that key-press gets consumed by a
getkey() call.

This is a side-effect of how the EFI simple-text-input protocol works
and cannot be avoided.

Signed-off-by: Hans de Goede <hdegoede@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:12:50 +02:00
Hans de Goede 8bab36af60 efi/console: Add grub_console_read_key_stroke() helper function
This is a preparatory patch for adding getkeystatus() support to the
EFI console driver.

We can get modifier status through the simple_text_input read_key_stroke()
method, but if a non-modifier key is (also) pressed the read_key_stroke()
call will consume that key from the firmware's queue.

The new grub_console_read_key_stroke() helper buffers upto 1 key-stroke.
If it has a non-modifier key buffered, it will return that one, if its
buffer is empty, it will fills its buffer by getting a new key-stroke.

If called with consume=1 it will empty its buffer after copying the
key-data to the callers buffer, this is how getkey() will use it.

If called with consume=0 it will keep the last key-stroke buffered, this
is how getkeystatus() will call it. This means that if a non-modifier
key gets pressed, repeated getkeystatus() calls will return the modifiers
of that key-press until it is consumed by a getkey() call.

Signed-off-by: Hans de Goede <hdegoede@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:11:17 +02:00
Hans de Goede 5bcdf67642 kern/term: Make grub_getkeystatus() helper function available everywhere
Move grub_getkeystatushelper() function from grub-core/commands/keystatus.c
to grub-core/kern/term.c and export it so that it can be used outside of
the keystatus command code too.

There's no logic change in this patch. The function definition is moved so
it can be called from grub-core/kern/term.c in a subsequent patch. It will
be used to determine if a SHIFT key has was held down and use that also to
interrupt the countdown, without the need to press a key at the right time.

Signed-off-by: Hans de Goede <hdegoede@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:08:52 +02:00
Javier Martinez Canillas 30586747f1 efi/console: Move grub_console_set{colorstate,cursor} higher in the file
This is just a preparatory patch to move the functions higher in the file,
since these will be called by the grub_prepare_for_text_output() function
that will be introduced in a later patch.

The logic is unchanged by this patch. Functions definitions are just moved
to avoid a forward declaration in a later patch, keeping the code clean.

Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:07:56 +02:00
Paul Menzel b0c7769a41 docs/grub: Fix typo in *preferred*
Signed-off-by: Paul Menzel <pmenzel@molgen.mpg.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:03:09 +02:00
Daniel Axtens 06fd69a3fd powerpc/mkimage: Fix CHRP note descsz
Currently, an image generated with 'grub-mkimage -n' causes an error when
read with 'readelf -a':

Displaying notes found at file offset 0x000106f0 with length 0x0000002c:
  Owner                Data size        Description
readelf: Warning: note with invalid namesz and/or descsz found at offset 0x0
readelf: Warning:  type: 0x1275, namesize: 0x00000008, descsize: 0x0000002c, alignment: 4

This is because the descsz of the CHRP note is set to
 sizeof (struct grub_ieee1275_note)
which is the size of the entire note, including name and elf header. The
desczs should contain only the contents, not the name and header sizes.

Set the descsz instead to 'sizeof (struct grub_ieee1275_note_desc)'

Resultant readelf output:

Displaying notes found at file offset 0x00010710 with length 0x0000002c:
  Owner                Data size        Description
  PowerPC              0x00000018       Unknown note type: (0x00001275)
   description data: ff ff ff ff 00 c0 00 00 ff ff ff ff ff ff ff ff ff ff ff ff 00 00 40 00

So far as I can tell this issue has existed for as long as the note
generation code has existed, but I guess nothing really checks descsz.

Signed-off-by: Daniel Axtens <dja@axtens.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-04-21 22:00:59 +02:00
Flavio Suligoi 2a6308b954 efi: Add missed space in GRUB_EFI_GLOBAL_VARIABLE_GUID
Signed-off-by: Flavio Suligoi <f.suligoi@asem.it>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-31 12:17:03 +02:00
Michael Chang 68006d1732 zfs: Fix gcc10 error -Werror=zero-length-bounds
We bumped into the build error while testing gcc-10 pre-release.

In file included from ../../include/grub/file.h:22,
		from ../../grub-core/fs/zfs/zfs.c:34:
../../grub-core/fs/zfs/zfs.c: In function 'zap_leaf_lookup':
../../grub-core/fs/zfs/zfs.c:2263:44: error: array subscript '<unknown>' is outside the bounds of an interior zero-length array 'grub_uint16_t[0]' {aka 'short unsigned int[0]'} [-Werror=zero-length-bounds]
2263 |   for (chunk = grub_zfs_to_cpu16 (l->l_hash[LEAF_HASH (blksft, h, l)], endian);
../../include/grub/types.h:241:48: note: in definition of macro 'grub_le_to_cpu16'
 241 | # define grub_le_to_cpu16(x) ((grub_uint16_t) (x))
     |                                                ^
../../grub-core/fs/zfs/zfs.c:2263:16: note: in expansion of macro 'grub_zfs_to_cpu16'
2263 |   for (chunk = grub_zfs_to_cpu16 (l->l_hash[LEAF_HASH (blksft, h, l)], endian);
     |                ^~~~~~~~~~~~~~~~~
In file included from ../../grub-core/fs/zfs/zfs.c:48:
../../include/grub/zfs/zap_leaf.h:72:16: note: while referencing 'l_hash'
  72 |  grub_uint16_t l_hash[0];
     |                ^~~~~~

Here I'd like to quote from the gcc document [1] which seems best to
explain what is going on here.

"Although the size of a zero-length array is zero, an array member of
this kind may increase the size of the enclosing type as a result of
tail padding. The offset of a zero-length array member from the
beginning of the enclosing structure is the same as the offset of an
array with one or more elements of the same type. The alignment of a
zero-length array is the same as the alignment of its elements.

Declaring zero-length arrays in other contexts, including as interior
members of structure objects or as non-member objects, is discouraged.
Accessing elements of zero-length arrays declared in such contexts is
undefined and may be diagnosed."

The l_hash[0] is apparnetly an interior member to the enclosed structure
while l_entries[0] is the trailing member. And the offending code tries
to access members in l_hash[0] array that triggers the diagnose.

Given that the l_entries[0] is used to get proper alignment to access
leaf chunks, we can accomplish the same thing through the ALIGN_UP macro
thus eliminating l_entries[0] from the structure. In this way we can
pacify the warning as l_hash[0] now becomes the last member to the
enclosed structure.

[1] https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-31 12:17:03 +02:00
Michael Chang bdf170d101 mdraid1x_linux: Fix gcc10 error -Werror=array-bounds
We bumped into the build error while testing gcc-10 pre-release.

../../grub-core/disk/mdraid1x_linux.c: In function 'grub_mdraid_detect':
../../grub-core/disk/mdraid1x_linux.c:181:15: error: array subscript <unknown> is outside array bounds of 'grub_uint16_t[0]' {aka 'short unsigned int[0]'} [-Werror=array-bounds]
  181 |      (char *) &sb.dev_roles[grub_le_to_cpu32 (sb.dev_number)]
      |               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../../grub-core/disk/mdraid1x_linux.c:98:17: note: while referencing 'dev_roles'
   98 |   grub_uint16_t dev_roles[0]; /* Role in array, or 0xffff for a spare, or 0xfffe for faulty.  */
      |                 ^~~~~~~~~
../../grub-core/disk/mdraid1x_linux.c:127:33: note: defined here 'sb'
  127 |       struct grub_raid_super_1x sb;
      |                                 ^~
cc1: all warnings being treated as errors

Apparently gcc issues the warning when trying to access sb.dev_roles
array's member, since it is a zero length array as the last element of
struct grub_raid_super_1x that is allocated sparsely without extra
chunks for the trailing bits, so the warning looks legitimate in this
regard.

As the whole thing here is doing offset computation, it is undue to use
syntax that would imply array member access then take address from it
later. Instead we could accomplish the same thing through basic array
pointer arithmetic to pacify the warning.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-31 12:17:02 +02:00
Simon Hardy 6643507ce3 build: Fix GRUB i386-pc build with Ubuntu gcc
With recent versions of gcc on Ubuntu a very large lzma_decompress.img file is
output. (e.g. 134479600 bytes instead of 2864.) This causes grub-mkimage to
fail with: "error: Decompressor is too big."

This seems to be caused by a section .note.gnu.property that is placed at an
offset such that objcopy needs to pad the img file with zeros.

This issue is present on:
Ubuntu 19.10 with gcc (Ubuntu 8.3.0-26ubuntu1~19.10) 8.3.0
Ubuntu 19.10 with gcc (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008

This issue is not present on:
Ubuntu 19.10 with gcc (Ubuntu 7.5.0-3ubuntu1~19.10) 7.5.0
RHEL 8.0 with gcc 8.3.1 20190507 (Red Hat 8.3.1-4)

The issue can be fixed by removing the section using objcopy as shown in
this patch.

Signed-off-by: Simon Hardy <simon.hardy@itdev.co.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-31 12:17:02 +02:00
Tianjia Zhang 800de4a1d0 efi/tpm: Fix memory leak in grub_tpm1/2_log_event()
The memory requested for the event is not released here,
causing memory leaks. This patch fixes this problem.

Signed-off-by: Jia Zhang <zhang.jia@linux.alibaba.com>
Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-31 12:16:32 +02:00
Michael Chang 5e5a47b8a7 docs: Document notes on LVM cache booting
Add notes on LVM cache booting to the GRUB manual to help user understanding
the outstanding issue and status.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-31 12:01:41 +02:00
Michael Chang 0454b04453 lvm: Add LVM cache logical volume handling
The LVM cache logical volume is the logical volume consisting of the original
and the cache pool logical volume. The original is usually on a larger and
slower storage device while the cache pool is on a smaller and faster one. The
performance of the original volume can be improved by storing the frequently
used data on the cache pool to utilize the greater performance of faster
device.

The default cache mode "writethrough" ensures that any data written will be
stored both in the cache and on the origin LV, therefore grub can be straight
to read the original lv as no data loss is guarenteed.

The second cache mode is "writeback", which delays writing from the cache pool
back to the origin LV to have increased performance. The drawback is potential
data loss if losing the associated cache device.

During the boot time grub reads the LVM offline i.e. LVM volumes are not
activated and mounted, hence it should be fine to read directly from original
lv since all cached data should have been flushed back in the process of taking
it offline.

It is also not much helpful to the situation by adding fsync calls to the
install code. The fsync did not force to write back dirty cache to the original
device and rather it would update associated cache metadata to complete the
write transaction with the cache device. IOW the writes to cached blocks still
go only to the cache device.

To write back dirty cache, as LVM cache did not support dirty cache flush per
block range, there'no way to do it for file. On the other hand the "cleaner"
policy is implemented and can be used to write back "all" dirty blocks in a
cache, which effectively drain all dirty cache gradually to attain and last in
the "clean" state, which can be useful for shrinking or decommissioning a
cache. The result and effect is not what we are looking for here.

In conclusion, as it seems no way to enforce file writes to the original
device, grub may suffer from power failure as it cannot assemble the cache
device and read the dirty data from it. However since the case is only
applicable to writeback mode which is sensitive to data lost in nature, I'd
still like to propose my (relatively simple) patch and treat reading dirty
cache as improvement.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-31 11:59:35 +02:00
Patrick Steinhardt 552c9fd081 gnulib: Fix build of base64 when compiling with memory debugging
When building GRUB with memory management debugging enabled, then the
build fails because of `grub_debug_malloc()` and `grub_debug_free()`
being undefined in the luks2 module. The cause is that we patch
"base64.h" to unconditionaly include "config-util.h", which shouldn't be
included for modules at all. As a result, `MM_DEBUG` is defined when
building the module, causing it to use the debug memory allocation
functions. As these are not built into modules, we end up with a linker
error.

Fix the issue by removing the <config-util.h> include altogether. The
sole reason it was included was for the `_GL_ATTRIBUTE_CONST` macro,
which we can simply define as empty in case it's not set.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:58:36 +01:00
Patrick Steinhardt 2c43ab4ef7 build: Fix option to explicitly disable memory debugging
The memory management system supports a debug mode that can be enabled
at build time by passing "--enable-mm-debug" to the configure script.
Passing the option will cause us define MM_DEBUG as expected, but in
fact the reverse option "--disable-mm-debug" will do the exact same
thing and also set up the define. This currently causes the build of
"lib/gnulib/base64.c" to fail as it tries to use `grub_debug_malloc()`
and `grub_debug_free()` even though both symbols aren't defined.

Seemingly, `AC_ARG_ENABLE()` will always execute the third argument if
either the positive or negative option was passed. Let's thus fix the
issue by moving the call to`AC_DEFINE()` into an explicit `if test
$xenable_mm_debug` block, similar to how other defines work.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Paul Menzel <pmenzel@molgen.mpg.de>
2020-03-10 21:56:39 +01:00
David Michael 20def1a3c3 fat: Support file modification times
This allows comparing file ages on EFI system partitions.

Signed-off-by: David Michael <fedora.dm0@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:52:07 +01:00
David Michael 8ad7c23864 exfat: Save the matching directory entry struct when searching
This provides the node's attributes outside the iterator function
so the file modification time can be accessed and reported.

Signed-off-by: David Michael <fedora.dm0@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:48:05 +01:00
Mike Gilbert 1657e72f5b datetime: Enable the datetime module for the emu platform
Fixes a build failure:

  grub-core/commands/date.c:49: undefined reference to `grub_get_weekday_name'
  grub-core/commands/ls.c:155: undefined reference to `grub_unixtime2datetime'

Bug: https://bugs.gentoo.org/711512

Signed-off-by: Mike Gilbert <floppym@gentoo.org>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
Tested-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:45:11 +01:00
John Paul Adrian Glaubitz 2bfd3654a6 build: Add soft-float handling for SuperH (sh4)
While GRUB has no platform support for SuperH (sh4) yet, this change
adds the target-specific handling of soft-floats such that the GRUB
utilities can be built on this target.

Signed-off-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:43:56 +01:00
Peter Jones 9b89b1dedb efi: Fix the type of grub_efi_status_t
Currently, in some builds with some checkers, we see:

1. grub-core/disk/efi/efidisk.c:601: error[shiftTooManyBitsSigned]: Shifting signed 64-bit value by 63 bits is undefined behaviour

This is because grub_efi_status_t is defined as grub_efi_intn_t, which is
signed, and shifting into the sign bit is not defined behavior.  UEFI fixed
this in the spec in 2.3:

2.3 | Change the defined type of EFI_STATUS from INTN to UINTN | May 7, 2009

And the current EDK2 code has:
MdePkg/Include/Base.h-//
MdePkg/Include/Base.h-// Status codes common to all execution phases
MdePkg/Include/Base.h-//
MdePkg/Include/Base.h:typedef UINTN RETURN_STATUS;
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-/**
MdePkg/Include/Base.h-  Produces a RETURN_STATUS code with the highest bit set.
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-  @param  StatusCode    The status code value to convert into a warning code.
MdePkg/Include/Base.h-                        StatusCode must be in the range 0x00000000..0x7FFFFFFF.
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-  @return The value specified by StatusCode with the highest bit set.
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-**/
MdePkg/Include/Base.h-#define ENCODE_ERROR(StatusCode)     ((RETURN_STATUS)(MAX_BIT | (StatusCode)))
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-/**
MdePkg/Include/Base.h-  Produces a RETURN_STATUS code with the highest bit clear.
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-  @param  StatusCode    The status code value to convert into a warning code.
MdePkg/Include/Base.h-                        StatusCode must be in the range 0x00000000..0x7FFFFFFF.
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-  @return The value specified by StatusCode with the highest bit clear.
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-**/
MdePkg/Include/Base.h-#define ENCODE_WARNING(StatusCode)   ((RETURN_STATUS)(StatusCode))
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-/**
MdePkg/Include/Base.h-  Returns TRUE if a specified RETURN_STATUS code is an error code.
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-  This function returns TRUE if StatusCode has the high bit set.  Otherwise, FALSE is returned.
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-  @param  StatusCode    The status code value to evaluate.
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-  @retval TRUE          The high bit of StatusCode is set.
MdePkg/Include/Base.h-  @retval FALSE         The high bit of StatusCode is clear.
MdePkg/Include/Base.h-
MdePkg/Include/Base.h-**/
MdePkg/Include/Base.h-#define RETURN_ERROR(StatusCode)     (((INTN)(RETURN_STATUS)(StatusCode)) < 0)
...
Uefi/UefiBaseType.h:typedef RETURN_STATUS             EFI_STATUS;

This patch makes grub's implementation match the Edk2 declaration with regards
to the signedness of the type.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:42:31 +01:00
Peter Jones 3e8c338bfa efi/gop: Add debug output on GOP probing
Add debug information to EFI GOP video driver probing function.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:42:13 +01:00
Peter Jones c73cda3495 efi/uga: Use video instead of fb as debug condition
All other video drivers use "video" as the debug condition instead of "fb"
so change this in the efi/uga driver to make it consistent with the others.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:41:38 +01:00
Peter Jones df84d6e94c efi: Print error messages to grub_efi_allocate_pages_real()
No messages were printed in this function, add some to ease debugging.

Also, the function returns a void * pointer so return NULL instead of
0 to make the code more readable.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:41:16 +01:00
Andrei Borzenkov df5d96de42 efi/uga: Use 64 bit for fb_base
We get 64 bit from PCI BAR but then truncate by assigning to 32 bit.
Make sure to check that pointer does not overflow on 32 bit platform.

Closes: 50931

Signed-off-by: Andrei Borzenkov <arvidjaar@gmail.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:40:40 +01:00
Alexander Graf e642c95ab6 efi/gop: Add support for BLT_ONLY adapters
EFI GOP has support for multiple different bitness types of frame buffers
and for a special "BLT only" type which is always defined to be RGBx.

Because grub2 doesn't ever directly access the frame buffer but instead
only renders graphics via the BLT interface anyway, we can easily support
these adapters.

The reason this has come up now is the emerging support for virtio-gpu
in OVMF. That adapter does not have the notion of a memory mapped frame
buffer and thus is BLT only.

Signed-off-by: Alexander Graf <agraf@suse.de>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:40:31 +01:00
Peter Jones f0f97576e0 normal/completion: Fix possible NULL pointer dereference
Coverity Scan reports that the grub_strrchr() function can return NULL if
the character is not found. Check if that's the case for dirfile pointer.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:40:23 +01:00
Peter Jones 8d88ae92b5 kern: Add grub_debug_enabled()
Add a grub_debug_enabled() helper function instead of open coding it.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:40:06 +01:00
Peter Jones 42f4054faf Makefile: Make libgrub.pp depend on config-util.h
If you build with "make -j48" a lot, sometimes you see:

gcc -E -DHAVE_CONFIG_H -I. -I..  -Wall -W -DGRUB_UTIL=1 -D_FILE_OFFSET_BITS=64 -I./include -DGRUB_FILE=\"grub_script.tab.h\" -I. -I.. -I. -I.. -I../include -I./include -I../grub-core/lib/libgcrypt-grub/src/  -I../grub-core/lib/minilzo -I../grub-core/lib/xzembed -DMINILZO_HAVE_CONFIG_H -Wall -W -DGRUB_UTIL=1 -D_FILE_OFFSET_BITS=64 -I./include -DGRUB_FILE=\"grub_script.tab.h\" -I. -I.. -I. -I.. -I../include -I./include -I../grub-core/lib/libgcrypt-grub/src/  -I./grub-core/gnulib -I../grub-core/gnulib -I/builddir/build/BUILD/grub-2.02/grub-aarch64-efi-2.02 -D_FILE_OFFSET_BITS=64 \
  -D'GRUB_MOD_INIT(x)=@MARKER@x@' grub_script.tab.h grub_script.yy.h ../grub-core/commands/blocklist.c ../grub-core/commands/macbless.c ../grub-core/commands/xnu_uuid.c ../grub-core/commands/testload.c ../grub-core/commands/ls.c ../grub-core/disk/dmraid_nvidia.c ../grub-core/disk/loopback.c ../grub-core/disk/lvm.c ../grub-core/disk/mdraid_linux.c ../grub-core/disk/mdraid_linux_be.c ../grub-core/disk/mdraid1x_linux.c ../grub-core/disk/raid5_recover.c ../grub-core/disk/raid6_recover.c ../grub-core/font/font.c ../grub-core/gfxmenu/font.c ../grub-core/normal/charset.c ../grub-core/video/fb/fbblit.c ../grub-core/video/fb/fbutil.c ../grub-core/video/fb/fbfill.c ../grub-core/video/fb/video_fb.c ../grub-core/video/video.c ../grub-core/video/capture.c ../grub-core/video/colors.c ../grub-core/unidata.c ../grub-core/io/bufio.c ../grub-core/fs/affs.c ../grub-core/fs/afs.c ../grub-core/fs/bfs.c ../grub-core/fs/btrfs.c ../grub-core/fs/cbfs.c ../grub-core/fs/cpio.c ../grub-core/fs/cpio_be.c ../grub-core/fs/odc.c ../grub-core/fs/newc.c ../grub-core/fs/ext2.c ../grub-core/fs/fat.c ../grub-core/fs/exfat.c ../grub-core/fs/fshelp.c ../grub-core/fs/hfs.c ../grub-core/fs/hfsplus.c ../grub-core/fs/hfspluscomp.c ../grub-core/fs/iso9660.c ../grub-core/fs/jfs.c ../grub-core/fs/minix.c ../grub-core/fs/minix2.c ../grub-core/fs/minix3.c ../grub-core/fs/minix_be.c ../grub-core/fs/minix2_be.c ../grub-core/fs/minix3_be.c ../grub-core/fs/nilfs2.c ../grub-core/fs/ntfs.c ../grub-core/fs/ntfscomp.c ../grub-core/fs/reiserfs.c ../grub-core/fs/romfs.c ../grub-core/fs/sfs.c ../grub-core/fs/squash4.c ../grub-core/fs/tar.c ../grub-core/fs/udf.c ../grub-core/fs/ufs2.c ../grub-core/fs/ufs.c ../grub-core/fs/ufs_be.c ../grub-core/fs/xfs.c ../grub-core/fs/zfs/zfscrypt.c ../grub-core/fs/zfs/zfs.c ../grub-core/fs/zfs/zfsinfo.c ../grub-core/fs/zfs/zfs_lzjb.c ../grub-core/fs/zfs/zfs_lz4.c ../grub-core/fs/zfs/zfs_sha256.c ../grub-core/fs/zfs/zfs_fletcher.c ../grub-core/lib/envblk.c ../grub-core/lib/hexdump.c ../grub-core/lib/LzFind.c ../grub-core/lib/LzmaEnc.c ../grub-core/lib/crc.c ../grub-core/lib/adler32.c ../grub-core/lib/crc64.c ../grub-core/normal/datetime.c ../grub-core/normal/misc.c ../grub-core/partmap/acorn.c ../grub-core/partmap/amiga.c ../grub-core/partmap/apple.c ../grub-core/partmap/sun.c ../grub-core/partmap/plan.c ../grub-core/partmap/dvh.c ../grub-core/partmap/sunpc.c ../grub-core/partmap/bsdlabel.c ../grub-core/partmap/dfly.c ../grub-core/script/function.c ../grub-core/script/lexer.c ../grub-core/script/main.c ../grub-core/script/script.c ../grub-core/script/argv.c ../grub-core/io/gzio.c ../grub-core/io/xzio.c ../grub-core/io/lzopio.c ../grub-core/kern/ia64/dl_helper.c ../grub-core/kern/arm/dl_helper.c ../grub-core/kern/arm64/dl_helper.c ../grub-core/lib/minilzo/minilzo.c ../grub-core/lib/xzembed/xz_dec_bcj.c ../grub-core/lib/xzembed/xz_dec_lzma2.c ../grub-core/lib/xzembed/xz_dec_stream.c ../util/misc.c ../grub-core/kern/command.c ../grub-core/kern/device.c ../grub-core/kern/disk.c ../grub-core/lib/disk.c ../util/getroot.c ../grub-core/osdep/unix/getroot.c ../grub-core/osdep/getroot.c ../grub-core/osdep/devmapper/getroot.c ../grub-core/osdep/relpath.c ../grub-core/kern/emu/hostdisk.c ../grub-core/osdep/devmapper/hostdisk.c ../grub-core/osdep/hostdisk.c ../grub-core/osdep/unix/hostdisk.c ../grub-core/osdep/exec.c ../grub-core/osdep/sleep.c ../grub-core/osdep/password.c ../grub-core/kern/emu/misc.c ../grub-core/kern/emu/mm.c ../grub-core/kern/env.c ../grub-core/kern/err.c ../grub-core/kern/file.c ../grub-core/kern/fs.c ../grub-core/kern/list.c ../grub-core/kern/misc.c ../grub-core/kern/partition.c ../grub-core/lib/crypto.c ../grub-core/disk/luks.c ../grub-core/disk/geli.c ../grub-core/disk/cryptodisk.c ../grub-core/disk/AFSplitter.c ../grub-core/lib/pbkdf2.c ../grub-core/commands/extcmd.c ../grub-core/lib/arg.c ../grub-core/disk/ldm.c ../grub-core/disk/diskfilter.c ../grub-core/partmap/gpt.c ../grub-core/partmap/msdos.c ../grub-core/fs/proc.c ../grub-core/fs/archelp.c > libgrub.pp || (rm -f libgrub.pp; exit 1)
rm -f stamp-h1
touch ../config-util.h.in
cd . && /bin/sh ./config.status config-util.h
config.status: creating config-util.h
In file included from ../include/grub/mm.h:25:0,
                 from ../include/grub/disk.h:29,
                 from ../include/grub/file.h:26,
                 from ../grub-core/fs/btrfs.c:21:
./config.h:38:10: fatal error: ./config-util.h: No such file or directory
 #include <config-util.h>
          ^~~~~~~~~~~~~~~
compilation terminated.
make: *** [Makefile:13098: libgrub.pp] Error 1

This is because libgrub.pp is built with -DGRUB_UTIL=1, which means
it'll try to include config-util.h, but a parallel make is actually
building that file.  I think.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:39:53 +01:00
Peter Jones cc93c5a849 efi: Print more debug info in our module loader
The function that searches the mods section base address does not have
any debug information. Add some debugging outputs that could be useful.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:39:44 +01:00
Peter Jones ea04f131a4 linux/getroot: Handle rssd storage device names
The Micron PCIe SSDs Linux driver (mtip32xx) exposes block devices
as /dev/rssd[a-z]+[0-9]*. Add support for these rssd device names.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:39:34 +01:00
Julian Andres Klode 87049f9716 smbios: Add a --linux argument to apply linux modalias-like filtering
Linux creates modalias strings by filtering out non-ASCII, space,
and colon characters. Provide an option that does the same filtering
so people can create a modalias string in GRUB, and then match their
modalias patterns against it.

Signed-off-by: Julian Andres Klode <julian.klode@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:35:02 +01:00
Mike Gilbert 2e246b6fec po: Fix replacement of %m in sed programs
When running make dist, I hit this error:

  rm -f en@arabic.gmo && /usr/bin/gmsgfmt -c --statistics --verbose -o en@arabic.gmo en@arabic.po
  en@arabic.po:5312: 'msgstr' is not a valid C format string, unlike 'msgid'.
  Reason: The character that terminates the directive number 3 is not a valid conversion specifier.
  /usr/bin/gmsgfmt: found 1 fatal error

This was caused by "%m" being replaced with foreign Unicode characters.
For example:

  msgid "cannot rename the file %s to %s: %m"
  msgstr "ﺹﺎﻨﻧﻮﺗ ﺮﻌﻧﺎﻤﻋ ﺖﻬﻋ ﻒִﻴﻠﻋ %s ﺕﻭ %s: %ﻡ"

Mimic the workaround used for "%s" by reversing the replacement of "%m" at
the end of the sed programs.

Signed-off-by: Mike Gilbert <floppym@gentoo.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:32:09 +01:00
Colin Watson ac116bd659 gettext: Restore patches to po/Makefile.in.in
These were inadvertently lost during the conversion to Gnulib (gnulib:
Upgrade Gnulib and switch to bootstrap tool; commit 35b909062). The
files in po/gettext-patches/ can be imported using "git am" on top of
the gettext tag corresponding to AM_GNU_GETTEXT_VERSION in configure.ac
(currently 0.18.3). They handle translation of messages in shell files,
make msgfmt output in little-endian format, and arrange to use @SHELL@
rather than /bin/sh.

There were some changes solely for the purpose of distributing extra
files; for ease of maintenance, I've added these to
conf/Makefile.extra-dist instead.

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

Signed-off-by: Colin Watson <cjwatson@ubuntu.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-03-10 21:17:54 +01:00
Peter Jones d5a32255de misc: Make grub_strtol() "end" pointers have safer const qualifiers
Currently the string functions grub_strtol(), grub_strtoul(), and
grub_strtoull() don't declare the "end" pointer in such a way as to
require the pointer itself or the character array to be immutable to the
implementation, nor does the C standard do so in its similar functions,
though it does require us not to change any of it.

The typical declarations of these functions follow this pattern:

long
strtol(const char * restrict nptr, char ** restrict endptr, int base);

Much of the reason for this is historic, and a discussion of that
follows below, after the explanation of this change.  (GRUB currently
does not include the "restrict" qualifiers, and we name the arguments a
bit differently.)

The implementation is semantically required to treat the character array
as immutable, but such accidental modifications aren't stopped by the
compiler, and the semantics for both the callers and the implementation
of these functions are sometimes also helped by adding that requirement.

This patch changes these declarations to follow this pattern instead:

long
strtol(const char * restrict nptr,
       const char ** const restrict endptr,
       int base);

This means that if any modification to these functions accidentally
introduces either an errant modification to the underlying character
array, or an accidental assignment to endptr rather than *endptr, the
compiler should generate an error.  (The two uses of "restrict" in this
case basically mean strtol() isn't allowed to modify the character array
by going through *endptr, and endptr isn't allowed to point inside the
array.)

It also means the typical use case changes to:

  char *s = ...;
  const char *end;
  long l;

  l = strtol(s, &end, 10);

Or even:

  const char *p = str;
  while (p && *p) {
	  long l = strtol(p, &p, 10);
	  ...
  }

This fixes 26 places where we discard our attempts at treating the data
safely by doing:

  const char *p = str;
  long l;

  l = strtol(p, (char **)&ptr, 10);

It also adds 5 places where we do:

  char *p = str;
  while (p && *p) {
	  long l = strtol(p, (const char ** const)&p, 10);
	  ...
	  /* more calls that need p not to be pointer-to-const */
  }

While moderately distasteful, this is a better problem to have.

With one minor exception, I have tested that all of this compiles
without relevant warnings or errors, and that /much/ of it behaves
correctly, with gcc 9 using 'gcc -W -Wall -Wextra'.  The one exception
is the changes in grub-core/osdep/aros/hostdisk.c , which I have no idea
how to build.

Because the C standard defined type-qualifiers in a way that can be
confusing, in the past there's been a slow but fairly regular stream of
churn within our patches, which add and remove the const qualifier in many
of the users of these functions.  This change should help avoid that in
the future, and in order to help ensure this, I've added an explanation
in misc.h so that when someone does get a compiler warning about a type
error, they have the fix at hand.

The reason we don't have "const" in these calls in the standard is
purely anachronistic: C78 (de facto) did not have type qualifiers in the
syntax, and the "const" type qualifier was added for C89 (I think; it
may have been later).  strtol() appears to date from 4.3BSD in 1986,
which means it could not be added to those functions in the standard
without breaking compatibility, which is usually avoided.

The syntax chosen for type qualifiers is what has led to the churn
regarding usage of const, and is especially confusing on string
functions due to the lack of a string type.  Quoting from C99, the
syntax is:

 declarator:
  pointer[opt] direct-declarator
 direct-declarator:
  identifier
  ( declarator )
  direct-declarator [ type-qualifier-list[opt] assignment-expression[opt] ]
  ...
  direct-declarator [ type-qualifier-list[opt] * ]
  ...
 pointer:
  * type-qualifier-list[opt]
  * type-qualifier-list[opt] pointer
 type-qualifier-list:
  type-qualifier
  type-qualifier-list type-qualifier
 ...
 type-qualifier:
  const
  restrict
  volatile

So the examples go like:

const char foo;			// immutable object
const char *foo;		// mutable pointer to object
char * const foo;		// immutable pointer to mutable object
const char * const foo;		// immutable pointer to immutable object
const char const * const foo; 	// XXX extra const keyword in the middle
const char * const * const foo; // immutable pointer to immutable
				//   pointer to immutable object
const char ** const foo;	// immutable pointer to mutable pointer
				//   to immutable object

Making const left-associative for * and right-associative for everything
else may not have been the best choice ever, but here we are, and the
inevitable result is people using trying to use const (as they should!),
putting it at the wrong place, fighting with the compiler for a bit, and
then either removing it or typecasting something in a bad way.  I won't
go into describing restrict, but its syntax has exactly the same issue
as with const.

Anyway, the last example above actually represents the *behavior* that's
required of strtol()-like functions, so that's our choice for the "end"
pointer.

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-28 12:41:29 +01:00
Mike Gilbert c71be831f1 build: Disable PIE in TARGET_CCASFLAGS if needed
PIE should be disabled in assembly sources as well, or else GRUB will
fail to boot.

Bug: https://bugs.gentoo.org/667852

Signed-off-by: Mike Gilbert <floppym@gentoo.org>
Signed-off-by: Matt Turner <mattst88@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
2020-02-28 12:35:30 +01:00
Mike Gilbert 3137ecd97c build: Move TARGET_* assignments earlier
On a 32-bit SPARC userland, configure fails to compile assembly and the
build fails:

    checking for options to compile assembly... configure: error: could not compile assembly

config.log shows:

    asm-tests/sparc64.S: Assembler messages:
    asm-tests/sparc64.S:5: Error: Architecture mismatch on "lduw [%o4+4],%o4".
    asm-tests/sparc64.S:5: (Requires v9|v9a|v9b|v9c|v9d|v9e|v9v|v9m|m8; requested architecture is sparclite.)
    asm-tests/sparc64.S:7: Error: Architecture mismatch on "stw %o5,[%o3]".
    asm-tests/sparc64.S:7: (Requires v9|v9a|v9b|v9c|v9d|v9e|v9v|v9m|m8; requested architecture is sparclite.)
    asm-tests/sparc64.S:8: Error: Architecture mismatch on "bne,pt %icc,1b ,pt %icc,1b".
    asm-tests/sparc64.S:8: (Requires v9|v9a|v9b|v9c|v9d|v9e|v9v|v9m|m8; requested architecture is sparclite.)

Simply moving these blocks earlier in configure.ac is sufficient to
ensure that the tests are executed with the appropriate flags
(specifically -m64 in this case).

Bug: https://bugs.gentoo.org/667850

Signed-off-by: Mike Gilbert <floppym@gentoo.org>
Signed-off-by: Matt Turner <mattst88@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
2020-02-28 12:29:39 +01:00
Patrick Steinhardt 9404c41953 luks2: Add missing newline to debug message
The debug message printed when decryption with a keyslot fails is
missing its trailing newline. Add it to avoid mangling it with
subsequent output.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-28 12:27:55 +01:00
Michael Chang d0de8b37f6 verifiers: Fix calling uninitialized function pointer
The necessary check for NULL before use of function ver->close is not
taking place in the failure path. This patch simply adds the missing
check and fixes the problem that GRUB hangs indefinitely after booting
rogue image without valid signature if secure boot is turned on.

Now it displays like this for booting rogue UEFI image:

  error: bad shim signature
  error: you need to load the kernel first

  Press any key to continue...

and then you can go back to boot menu by pressing any key or after a few
seconds expired.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-18 15:17:40 +01:00
Peter Jones 0ad07e928a grub-editenv: Make grub-editenv chase symlinks including those across devices
The grub-editenv create command will wrongly overwrite /boot/grub2/grubenv
with a regular file if grubenv is a symbolic link. But instead, it should
create a new file in the path the symlink points to.

This lets /boot/grub2/grubenv be a symlink to /boot/efi/EFI/fedora/grubenv
even when they're different mount points, which allows grub2-editenv to be
the same across platforms (i.e. UEFI vs BIOS).

For example, in Fedora the GRUB EFI builds have prefix set to /EFI/fedora
(on the EFI System Partition), but for BIOS machine it'll be /boot/grub2
(which may or may not be its own mountpoint).

With this patch, on EFI machines we can make /boot/grub2/grubenv a symlink
to /boot/efi/EFI/fedora/grubenv, and the same copy of grub-set-default will
work on both kinds of systems.

Windows doesn't implement a readlink primitive, so the current behaviour is
maintained for this operating system.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Jonathan Lebon <jlebon@redhat.com>
Reviewed-by: Adam Jackson <ajax@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-18 15:16:02 +01:00
Peter Jones 03e72830ab grub-editenv: Add grub_util_readlink()
Currently grub-editenv and related tools are not able to follow symbolic
links when finding their config file. For example the grub-editenv create
command will wrongly overwrite a symlink in /boot/grub2/grubenv with a new
regular file, instead of creating a file in the path the symlink points to.

A following patch will change that and add support in grub-editenv to
follow symbolic links when finding the grub environment variables file.

Add a grub_util_readlink() helper function that is just a wrapper around
the platform specific function to read the value of a symbolic link. This
helper function will be used by the following patch for grub-editenv.

The helper function is not added for Windows, since this operating system
doesn't have a primitive to read the contents of a symbolic link.

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Adam Jackson <ajax@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-18 15:14:13 +01:00
Robert Marshall 9f03dc5d7b docs: Update info with grub.cfg netboot selection order
Add documentation to the GRUB manual that specifies the order netboot
clients use to select a GRUB configuration file.

Also explain that the feature is enabled by default but can be disabled
by setting the "feature_net_search_cfg" environment variable to "n" in
an embedded configuration file.

Signed-off-by: Robert Marshall <rmarshall@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-18 15:12:07 +01:00
Paulo Flabiano Smorigo cb2f15c544 normal/main: Search for specific config files for netboot
This patch implements a search for a specific configuration when the config
file is on a remoteserver. It uses the following order:
   1) DHCP client UUID option.
   2) MAC address (in lower case hexadecimal with dash separators);
   3) IP (in upper case hexadecimal) or IPv6;
   4) The original grub.cfg file.

This procedure is similar to what is used by pxelinux and yaboot:
http://www.syslinux.org/wiki/index.php/PXELINUX#config

It is enabled by default but can be disabled by setting the environment
variable "feature_net_search_cfg" to "n" in an embedded configuration.

Fixes: https://bugzilla.redhat.com/show_bug.cgi?id=873406

Signed-off-by: Paulo Flabiano Smorigo <pfsmorigo@br.ibm.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-18 15:12:06 +01:00
Paulo Flabiano Smorigo febc761e67 net/dhcp: Set net_<interface>_client{id, uuid} variables from DHCP options
This patch sets a net_<interface>_clientid and net_<interface>_clientuuid
GRUB environment variables, using the DHCP client ID and UUID options if
these are found.

In the same way than net_<interface>_<option> variables are set for other
options such domain name, boot file, next server, etc.

Signed-off-by: Paulo Flabiano Smorigo <pfsmorigo@br.ibm.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-18 15:12:06 +01:00
Javier Martinez Canillas e921119857 net/dhcp: Consistently use decimal numbers for DHCP/BOOTP options enum
The DHCP Options and BOOTP Vendor Extensions enum values are a mixture of
decimal and hexadecimal numbers. Change this to consistently use decimal
numbers for all since that is how these values are defined by RFC 2132.

Suggested-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-18 15:12:06 +01:00
Paulo Flabiano Smorigo 8c2c35dcc0 kern: Add %X option to printf functions
The printf(3) function has support for the %X format specifier, to output
an unsigned hexadecimal integer in uppercase.

This can be achived in GRUB using the %x format specifier in grub_printf()
and calling grub_toupper(), but it is more convenient if there is support
for %X in grub_printf().

Signed-off-by: Paulo Flabiano Smorigo <pfsmorigo@br.ibm.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-18 15:12:06 +01:00
Javier Martinez Canillas aa096037ae normal: Move common datetime functions out of the normal module
The common datetime helper functions are currently included in the normal
module, but this makes any other module that calls these functions to have
a dependency with the normal module only for this reason.

Since the normal module does a lot of stuff, it calls functions from other
modules. But since other modules may depend on it for calling the datetime
helpers, this could lead to circular dependencies between modules.

As an example, when platform == xen the grub_get_datetime() function from
the datetime module calls to the grub_unixtime2datetime() helper function
from the normal module. Which leads to the following module dependency:

    datetime -> normal

and send_dhcp_packet() from the net module calls the grub_get_datetime()
function, which leads to the following module dependency:

    net -> datetime -> normal

but that means that the normal module is not allowed to depend on net or
any other module that depends on it due the transitive dependency caused
by datetime. A recent patch attempted to add support to fetch the config
file over the network, which leads to the following circular dependency:

    normal -> net -> datetime -> normal

So having the datetime helpers in the normal module makes it quite fragile
and easy to add circular dependencies like these, that break the build due
the genmoddep.awk script catching the issues.

Fix this by taking the datetime helper functions out of the normal module
and instead add them to the datetime module itself. Besides fixing these
issues, it makes more sense to have these helper functions there anyways.

Reported-by: Daniel Kiper <daniel.kiper@oracle.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-18 15:12:06 +01:00
Peter Jones 3165efcfc2 minilzo: Update to minilzo-2.08
This patch updates the miniLZO library to a newer version, which among other
things fixes "CVE-2014-4607 - lzo: lzo1x_decompress_safe() integer overflow"
that is present in the current used in GRUB.

It also updates the "GRUB Developers Manual", to mention that the library is
used and describes the process to update it to a newer release when needed.

Resolves: http://savannah.gnu.org/bugs/?42635

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-02-11 21:30:30 +01:00
Peter Jones 598de14d93 squash4: Fix an uninitialized variable
gcc says:

grub-core/fs/squash4.c: In function ‘direct_read’:
grub-core/fs/squash4.c:868:10: error: ‘err’ may be used uninitialized in
this function [-Werror=maybe-uninitialized]
  868 |       if (err)
      |          ^
cc1: all warnings being treated as errors

This patch initializes it to GRUB_ERR_NONE.

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-01-28 21:22:01 +01:00
C. Masloch e96e785580 freedos: Fix FreeDOS command booting large files (near or above 64 KiB)
While testing the 86-DOS lDebug [1] booting from GRUB2, newer versions of the
debugger would fail to load when booted using GRUB's freedos command. The
behaviour observed in a qemu i386 machine was that the ROM-BIOS's boot load
would start anew, instead of loading the selected debugger as kernel.

It came to light that there was a size limit: Kernel files that were 58880
bytes (E600h) long or shorter succeeded to boot, while files that were 64000
bytes or longer failed in the manner described.

Eventually it turned out that the relocator16 stub succeeded whenever it was
placed completely within the first 64 KiB of the Low Memory Area. The chunk
for the relocator is allocated with a minimum address of 0x8010 and a maximum
address just below 0xA0000 [2]. That means if the kernel is, for instance,
E600h bytes long, then the kernel will be allocated memory starting at 00600h
(the fixed FreeDOS kernel load address) up to E600h + 00600h = 0EC00h, which
leaves 1400h (5120) bytes for the relocator to stay in the first 64 KiB.
If the kernel is 64000 bytes (FA00h) long, then the relocator must go to
FA00h + 00600h = 10000h at least which is outside the first 64 KiB.

The problem is that the relocator16 initialises the DS register with a
"pseudo real mode" descriptor, which is defined with a segment limit of
64 KiB and a segment base of zero. After that, the relocator addressed
parts of itself (implicitly) using the DS register, with an offset from
ESI, which holds the linear address of the relocator's base [3]. With the
larger kernel files this would lead to accessing data beyond the 64 KiB
segment limit, presumably leading to a fault and perhaps a subsequent
triple-fault or such.

This patch fixes the relocator to set the segment base of the descriptors
to the base address of the relocator; then, the subsequent accesses to
the relocator's variables are done without the ESI register as an index.
This does not interfere with the relocator's or its target's normal
operation; the segment limits are still loaded with 64 KiB and all the
segment bases are subsequently reset by the relocator anyway.

Current versions of the debugger to test are uploaded to [4]. The file
ldebugnh.com (LZ4-compressed and built with -D_EXTHELP=0) at 58368 bytes
loads successfully, whereas ldebug.com at 64000 bytes fails. Loading one
of these files requires setting root to a FAT FS partition and using the
freedos command to specify the file as kernel:

set root='(hd0,msdos1)'
freedos /ldebug.com
boot

Booting the file using the multiboot command (which uses a WIP entrypoint
of the debugger) works, as it does not use GRUB's relocator16 but instead
includes a loader in the kernel itself, which drops it back to 86 Mode.

[1]: https://hg.ulukai.org/ecm/ldebug
[2]: http://git.savannah.gnu.org/cgit/grub.git/tree/grub-core/lib/i386/relocator.c?id=495781f5ed1b48bf27f16c53940d6700c181c74c#n127
[3]: http://git.savannah.gnu.org/cgit/grub.git/tree/grub-core/lib/i386/relocator16.S?id=495781f5ed1b48bf27f16c53940d6700c181c74c#n97
[4]: https://ulukai.org/ecm/lDebug-5479a7988d21-nohelp.zip

Signed-off-by: C. Masloch <pushbx@ulukai.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-01-28 21:16:48 +01:00
Patrick Steinhardt 365e0cc3e7 disk: Implement support for LUKS2
With cryptsetup 2.0, a new version of LUKS was introduced that breaks
compatibility with the previous version due to various reasons. GRUB
currently lacks any support for LUKS2, making it impossible to decrypt
disks encrypted with that version. This commit implements support for
this new format.

Note that LUKS1 and LUKS2 are quite different data formats. While they
do share the same disk signature in the first few bytes, representation
of encryption parameters is completely different between both versions.
While the former version one relied on a single binary header, only,
LUKS2 uses the binary header only in order to locate the actual metadata
which is encoded in JSON. Furthermore, the new data format is a lot more
complex to allow for more flexible setups, like e.g. having multiple
encrypted segments and other features that weren't previously possible.
Because of this, it was decided that it doesn't make sense to keep both
LUKS1 and LUKS2 support in the same module and instead to implement it
in two different modules luks and luks2.

The proposed support for LUKS2 is able to make use of the metadata to
decrypt such disks. Note though that in the current version, only the
PBKDF2 key derival function is supported. This can mostly attributed to
the fact that the libgcrypt library currently has no support for either
Argon2i or Argon2id, which are the remaining KDFs supported by LUKS2. It
wouldn't have been much of a problem to bundle those algorithms with
GRUB itself, but it was decided against that in order to keep down the
number of patches required for initial LUKS2 support. Adding it in the
future would be trivial, given that the code structure is already in
place.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-01-10 14:30:24 +01:00
Patrick Steinhardt dd3f49b106 luks: Move configuration of ciphers into cryptodisk
The luks module contains quite a lot of logic to parse cipher and
cipher-mode strings like aes-xts-plain64 into constants to apply them
to the grub_cryptodisk_t structure. This code will be required by the
upcoming luks2 module, as well, which is why this commit moves it into
its own function grub_cryptodisk_setcipher in the cryptodisk module.
While the strings are probably rather specific to the LUKS modules, it
certainly does make sense that the cryptodisk module houses code to set
up its own internal ciphers instead of hosting that code in the luks
module.

Except for necessary adjustments around error handling, this commit does
an exact move of the cipher configuration logic from luks.c to
cryptodisk.c. Any behavior changes are unintentional.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-01-10 14:29:37 +01:00
Patrick Steinhardt 5324c335b1 afsplitter: Move into its own module
While the AFSplitter code is currently used only by the luks module,
upcoming support for luks2 will add a second module that depends on it.
To avoid any linker errors when adding the code to both modules because
of duplicated symbols, this commit moves it into its own standalone
module afsplitter as a preparatory step.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-01-10 14:27:49 +01:00
Patrick Steinhardt 9fbdec2f6b bootstrap: Add gnulib's base64 module
The upcoming support for LUKS2 disc encryption requires us to include a
parser for base64-encoded data, as it is used to represent salts and
digests. As gnulib already has code to decode such data, we can just
add it to the boostrapping configuration in order to make it available
in GRUB.

The gnulib module makes use of booleans via the <stdbool.h> header. As
GRUB does not provide any POSIX wrapper header for this, but instead
implements support for bool in <sys/types.h>, we need to patch
base64.h to not use <stdbool.h> anymore. We unfortunately cannot include
<sys/types.h> instead, as it would then use gnulib's internal header
while compiling the gnulib object but our own <sys/types.h> when
including it in a GRUB module. Because of this, the patch replaces the
include with a direct typedef.

A second fix is required to make available _GL_ATTRIBUTE_CONST, which
is provided by the configure script. As base64.h does not include
<config.h>, it is thus not available and results in a compile error.
This is fixed by adding an include of <config-util.h>.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-01-10 14:26:40 +01:00
Patrick Steinhardt c6a84545a3 json: Implement wrapping interface
While the newly added jsmn library provides the parsing interface, it
does not provide any kind of interface to act on parsed tokens. Instead,
the caller is expected to handle pointer arithmetics inside of the token
array in order to extract required information. While simple, this
requires users to know some of the inner workings of the library and is
thus quite an unintuitive interface.

This commit adds a new interface on top of the jsmn parser that provides
convenience functions to retrieve values from the parsed json type, grub_json_t.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-01-10 14:13:22 +01:00
Patrick Steinhardt 528938d503 json: Import upstream jsmn-1.1.0
The upcoming support for LUKS2 encryption will require a JSON parser to
decode all parameters required for decryption of a drive. As there is
currently no other tool that requires JSON, and as gnulib does not
provide a parser, we need to introduce a new one into the code base. The
backend for the JSON implementation is going to be the jsmn library [1].
It has several benefits that make it a very good fit for inclusion in
GRUB:

    - It is licensed under MIT.
    - It is written in C89.
    - It has no dependencies, not even libc.
    - It is small with only about 500 lines of code.
    - It doesn't do any dynamic memory allocation.
    - It is testen on x86, amd64, ARM and AVR.

The library itself comes as a single header, only, that contains both
declarations and definitions. The exposed interface is kind of
simplistic, though, and does not provide any convenience features
whatsoever. Thus there will be a separate interface provided by GRUB
around this parser that is going to be implemented in the following
commit. This change only imports jsmn.h from tag v1.1.0 and adds it
unmodified to a new json module with the following command:

curl -L https://raw.githubusercontent.com/zserge/jsmn/v1.1.0/jsmn.h \
    -o grub-core/lib/json/jsmn.h

Upstream jsmn commit hash: fdcef3ebf886fa210d14956d3c068a653e76a24e
Upstream jsmn commit name: Modernize (#149), 2019-04-20

[1]: https://github.com/zserge/jsmn

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2020-01-10 14:12:12 +01:00
Lukasz Hawrylko 0f3f5b7c13 multiboot2: Set min address for mbi allocation to 0x1000
In some cases GRUB2 allocates multiboot2 structure at 0 address, that is
a confusing behavior. Consumers of that structure can have internal NULL-checks
that will throw an error when get a pointer to data allocated at address 0.
To prevent that, define min address for mbi allocation on x86 and x86_64
platforms.

Signed-off-by: Lukasz Hawrylko <lukasz.hawrylko@linux.intel.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-12-20 20:35:21 +01:00
Paul Menzel 7e28ca82bb docs: Export "superusers" variable to apply to submenus
Signed-off-by: Paul Menzel <pmenzel@molgen.mpg.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-12-20 20:35:21 +01:00
Daniel Kiper b53a2f2c66 loader/i386/linux: Fix an underflow in the setup_header length calculation
Recent work around x86 Linux kernel loader revealed an underflow in the
setup_header length calculation and another related issue. Both lead to
the memory overwrite and later machine crash.

Currently when the GRUB copies the setup_header into the linux_params
(struct boot_params, traditionally known as "zero page") it assumes the
setup_header size as sizeof(linux_i386_kernel_header/lh). This is
incorrect. It should use the value calculated accordingly to the Linux
kernel boot protocol. Otherwise in case of pretty old kernel, to be
exact Linux kernel boot protocol, the GRUB may write more into
linux_params than it was expected to. Fortunately this is not very big
issue. Though it has to be fixed. However, there is also an underflow
which is grave. It happens when

  sizeof(linux_i386_kernel_header/lh) > "real size of the setup_header".

Then len value wraps around and grub_file_read() reads whole kernel into
the linux_params overwriting memory past it. This leads to the GRUB
memory allocator breakage and finally to its crash during boot.

The patch fixes both issues. Additionally, it moves the code not related to
grub_memset(linux_params)/grub_memcpy(linux_params)/grub_file_read(linux_params)
section outside of it to not confuse the reader.

Fixes: e683cfb0cf (loader/i386/linux: Calculate the setup_header length)

Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Ross Philipson <ross.philipson@oracle.com>
Reviewed-by: Krystian Hebel <krystian.hebel@3mdeb.com>
2019-12-20 20:35:21 +01:00
David Sterba 495781f5ed btrfs: Add support for new RAID1C34 profiles
New 3- and 4-copy variants of RAID1 were merged into Linux kernel 5.5.
Add the two new profiles to the list of recognized ones. As this builds
on the same code as RAID1, only the redundancy level needs to be
adjusted, the rest is done by the existing code.

Signed-off-by: David Sterba <dsterba@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-12-06 20:38:01 +01:00
Lenny Szubowicz e2c09aed97 tftp: Normalize slashes in TFTP paths
Some TFTP servers do not handle multiple consecutive slashes correctly.
This patch avoids sending TFTP requests with non-normalized paths.

Signed-off-by: Lenny Szubowicz <lszubowi@redhat.com>
Signed-off-by: Mark Salter <msalter@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-12-06 20:26:36 +01:00
Michael Chang 5e5a15872d grub-editenv: Warn a user against editing environment block
The environment block is a preallocated 1024-byte file which serves as
persistent storage for environment variables. It has its own format
which is sensitive to corruption if an editor does not know how to
process it. Besides that the editor may inadvertently change grubenv
file size and/or make it sparse which can lead to unexpected results.

This patch adds a message to the grubenv file to warn a user against
editing it by tools other than grub-editenv.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-11-18 14:19:25 +01:00
Michael Chang 42acdd3b40 hostdisk: Set linux file descriptor to O_CLOEXEC as default
We are often bothered by this sort of lvm warning while running grub-install
every now and then:

  File descriptor 4 (/dev/vda1) leaked on vgs invocation. Parent PID 1991: /usr/sbin/grub2-install

The requirement related to the warning is dictated in the lvm man page:

  "On invocation, lvm requires that only the standard file descriptors stdin,
  stdout and stderr are available.  If others are found, they get closed and
  messages are issued warning about the leak.  This warning can be suppressed by
  setting the environment variable LVM_SUPPRESS_FD_WARNINGS."

While it could be disabled through settings, most Linux distributions seem to
enable it by default and the justification provided by the developer looks to
be valid to me: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=466138#15

Rather than trying to close and reopen the file descriptor to the same file
multiple times, which is rather cumbersome, for the sake of no vgs invocation
could happen in between. This patch enables the close-on-exec flag (O_CLOEXEC)
for new file descriptor returned by the open() system call, making it closed
thus not inherited by the child process forked and executed by the exec()
family of functions.

Fixes Debian bug #466138.

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-11-18 13:42:55 +01:00
Eli Schwartz 28a7e597de grub-mkconfig: Use portable "command -v" to detect installed programs
The "which" utility is not guaranteed to be installed either, and if it
is, its behavior is not portable either.

Conversely, the "command -v" shell builtin is required to exist in all
POSIX 2008 compliant shells, and is thus guaranteed to work everywhere.

Examples of open-source shells likely to be installed as /bin/sh on
Linux, which implement the 11-year-old standard: ash, bash, busybox,
dash, ksh, mksh and zsh.

A side benefit of using the POSIX portable option is that it requires
neither an external disk executable, nor (because unlike "which", the
exit code is reliable) a subshell fork. This therefore represents a mild
speedup.

Signed-off-by: Eli Schwartz <eschwartz@archlinux.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-10-28 15:38:48 +01:00
Peter Jones b78d570a36 templates: Add GRUB_DISABLE_UUID
The grub-mkconfig and 10_linux scripts by default attempt to use a UUID to
set the root kernel command line parameter and the $root GRUB environment
variable.

The former can be disabled by setting the GRUB_DISABLE_LINUX_UUID variable
to "true", but there is currently no way to disable the latter.

The generated grub config uses the search command with the --fs-uuid option
to find the device that has to be set as $root, i.e:

 search --no-floppy --fs-uuid --set=root ...

This is usually more reliable but in some cases it may not be appropriate,
so this patch introduces a new GRUB_DISABLE_UUID variable that can be used
to disable searching for the $root device by filesystem UUID.

When disabled, the $root device will be set to the value specified in the
device.map as found by the grub-probe --target=compatibility_hint option.

When setting GRUB_DISABLE_UUID=true, the GRUB_DISABLE_LINUX_UUID and
GRUB_DISABLE_LINUX_PARTUUID variables will also be set to "true" unless
these have been explicitly set to "false".

That way, the GRUB_DISABLE_UUID variable can be used to force using the
device names for both GRUB and Linux.

Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Nicholas Vinson <nvinson234@gmail.com>
2019-10-28 15:35:40 +01:00
Michael Bideau 33203ca348 at_keyboard: Fix unreliable key presses
This patch fixes an issue that prevented the at_keyboard module to work
(for me). The cause was a bad/wrong return value in the
grub_at_keyboard_getkey() function in grub-core/term/at_keyboard.c file
at line 237. My symptoms were to have an unresponsive keyboard. Keys
needed to be pressed 10x and more to effectively be printed sometimes
generating multiple key presses (after 1 or 2 sec of no printing). It
was very problematic when typing passphrase in early stage (with
GRUB_ENABLE_CRYPTODISK). When switched to "console" terminal input
keyboard worked perfectly. It also worked great with the GRUB 2.02
packaged by Debian (2.02+dfsg1-20). It was not an output issue but an
input one.

I've managed to analyze the issue and found that it came from the commit
216950a4e (at_keyboard: Split protocol from controller code.). Three
lines where moved from the fetch_key() function in
grub-core/term/at_keyboard.c file to the beginning of
grub_at_keyboard_getkey() function (same file). However, returning -1
made sense when it happened in fetch_key() function but not anymore in
grub_at_keyboard_getkey() function which should return GRUB_TERM_NO_KEY.
I think it was just an incomplete cut-paste missing a small manual
correction. Let's fix it.

Note: Commit message updated by Daniel Kiper.

Signed-off-by: Michael Bideau <mica.devel@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-10-21 14:07:47 +02:00
Prarit Bhargava ee4bd79ef2 templates: Fix bad test on GRUB_DISABLE_SUBMENU
The GRUB_DISABLE_SUBMENU option is different than the others in the sense
that it has to be set to "y" instead of "true" to be enabled.

That causes a lot of confusion to users, some may wrongly set it to "true"
expecting that will work the same than with most options, and some may set
it to "yes" since for other options the value to set is a word and not a
single character.

This patch changes all the grub.d scripts using the GRUB_DISABLE_SUBMENU
option, so they check if it was set to "true" instead of "y", making it
consistent with all the other options.

But to keep backward compatibility for users that set the option to "y" in
/etc/default/grub file, keep testing for this value. And also do it for
"yes", since it is a common mistake made by users caused by this option
being inconsistent with the others.

Signed-off-by: Prarit Bhargava <prarit@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-10-21 14:05:02 +02:00
Nicholas Vinson c7cb11b219 probe: Support probing for msdos PARTUUID
Extend partition UUID probing support in GRUB core to display pseudo
partition UUIDs for MBR (MSDOS) partitions.

Signed-off-by: Nicholas Vinson <nvinson234@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-10-21 14:00:54 +02:00
Colin Watson ff3e91be9c grub-mkconfig: Fix typo in --help output
The short form of "--version" that grub-mkconfig accepts is "-V", not "-v".

Fixes Debian bug #935504.

Signed-off-by: Colin Watson <cjwatson@ubuntu.com>
Reviewed-by: Vladimir 'phcoder' Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-09-23 13:20:02 +02:00
Andreas Schwab 11268841e2 grub-install: Define default platform for RISC-V
Signed-off-by: Andreas Schwab <schwab@suse.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Alexander Graf <agraf@csgraf.de>
2019-09-23 13:19:19 +02:00
Andreas Schwab a57977b5fa RISC-V: Add __clzdi2 symbol
This is needed for the zstd module build for riscv64-emu.

Signed-off-by: Andreas Schwab <schwab@suse.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-09-23 13:17:15 +02:00
Peter Jones f9e28d250a gitattributes: Mark po/exclude.pot as binary so git won't try to diff nonprintables
Signed-off-by: Peter Jones <pjones@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-09-23 13:17:15 +02:00
Marcel Kolaja ab2e53c8a1 grub-mkconfig: Honor a symlink when generating configuration by grub-mkconfig
Honor a symlink when generating configuration by grub-mkconfig, so that
the -o option follows it rather than overwriting it with a regular file.

Signed-off-by: Marcel Kolaja <mkolaja@redhat.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-09-23 13:17:15 +02:00
Gustavo Luiz Duarte fc085f7f18 net: Fix crash on http
Don't free file->data on receiving FIN flag since it is used all over
without checking. http_close() will be called later to free that memory.

Fixes bug: https://bugzilla.redhat.com/show_bug.cgi?id=860834

Signed-off-by: Gustavo Luiz Duarte <gustavold@linux.vnet.ibm.com>
Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-09-23 13:16:48 +02:00
Andre Przywara 3ea9bc3c06 docs: Document newly introduced net_dhcp command
Commit 5bc41db756 ("net/dhcp: Add explicit net_dhcp command")
introduced the new command "net_dhcp", which (for now) is an alias for
the existing "net_bootp". Unfortunately the TEXI documentation was not
adjusted accordingly.

Rename the existing paragraph about net_bootp to read net_dhcp instead,
and make the net_bootp stanza point to this new command.

On the way add the newly parsed TFTP_SERVER_NAME and BOOTFILE_NAME
packets to the list of supported DHCP options.

Fixes bug: https://savannah.gnu.org/bugs/?56725

Reported-by: Heinrich Schuchardt <xypron.glpk@gmx.de>
Signed-off-by: Andre Przywara <andre.przywara@arm.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-09-23 13:15:25 +02:00
James Clarke 4e75b2ae31 [PATCH] sparc64: Fix BIOS Boot Partition support
Currently, gpt_offset is uninitialised when using a BIOS Boot Partition
but is used unconditionally inside save_blocklists. Instead, ensure it
is always initialised to 0 (note that there is already separate code to
do the equivalent adjustment after we call save_blocklists on this code
path).

This patch has been tested on a T5-2 LDOM.

Signed-off-by: James Clarke <jrtc27@jrtc27.com>
Tested-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
Reviewed-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Eric Snowberg <eric.snowberg@oracle.com>

---
 util/setup.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
2019-07-18 14:33:16 +02:00
Vladimir Serbinenko 8f6843ce60 configure: Add -fno-ident when available
MinGW for i386-pc without this option generates a .rdata$zzz symbol that is
page-aligned and hence lzma_decompress no longer fits in its allocated space.
Additionally, MinGW with -fno-ident also saves a bit of space in modules. In
case of other compilers we already strip the relevant sections, so, this
option has no effect.

More info can be found at https://github.com/msys2/MINGW-packages/issues/21

Signed-off-by: Vladimir Serbinenko <phcoder@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-07-11 21:06:49 +02:00
Heinrich Schuchardt 15cfd02b74 lsefisystab: Add support for device tree table
The device tree may passed by the firmware as UEFI configuration
table. Let lsefisystab display a short text and not only the GUID
for the device tree.

Here is an example output:

  grub> lsefisystab
  Address: 0xbff694d8
  Signature: 5453595320494249 revision: 00020046
  Vendor: Das U-Boot, Version=20190700
  2 tables:
  0xbe741000  eb9d2d31-2d88-11d3-9a160090273fc14d   SMBIOS
  0x87f00000  b1b621d5-f19c-41a5-830bd9152c69aae0   DEVICE TREE

Signed-off-by: Heinrich Schuchardt <xypron.glpk@gmx.de>
Reviewed-by: Leif Lindholm <leif.lindholm@linaro.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-07-11 21:06:49 +02:00
David Michael 688023cd0a smbios: Add a module for retrieving SMBIOS information
The following are two use cases from Rajat Jain <rajatjain@juniper.net>:

  1) We have a board that boots Linux and this board itself can be plugged
     into one of different chassis types. We need to pass different
     parameters to the kernel based on the "CHASSIS_TYPE" information
     that is passed by the bios in the DMI/SMBIOS tables.

  2) We may have a USB stick that can go into multiple boards, and the
     exact kernel to be loaded depends on the machine information
     (PRODUCT_NAME etc) passed via the DMI.

Signed-off-by: David Michael <fedora.dm0@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-07-11 21:06:12 +02:00
David Michael 261df54f17 lsefisystab: Define SMBIOS3 entry point structures for EFI
This adds the GUID and includes it in lsefisystab output.

Signed-off-by: David Michael <fedora.dm0@gmail.com>
Reviewed-by: Leif Lindholm <leif.lindholm@linaro.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-07-11 18:13:15 +02:00
David Michael dabdfa1c6a verifiers: Blocklist fallout cleanup
Blocklist fallout cleanup after commit 5c6f9bc15 (generic/blocklist: Fix
implicit declaration of function grub_file_filter_disable_compression()).

Signed-off-by: David Michael <fedora.dm0@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-07-11 18:06:23 +02:00
Andreas Schwab 2bf40e9e5b RISC-V: Fix computation of pc-relative relocation offset
The offset calculation was missing the relocation addend.

Signed-off-by: Andreas Schwab <schwab@suse.de>
Tested-by: Chester Lin <clin@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-07-11 17:50:40 +02:00
Leif Lindholm 2d55ffecbb configure: Disable arm movw/movt relocations for GCC
When building for arm, we already disable movw/movt relocations for clang,
since they are incompatible with PE.

When building with bare metal GCC toolchains (like the one used in the
travis ci scripts), we end up with these relocations again. So add an
additional test for the '-mword-relocations' flag used by GCC.

Reported-by: Alexander Graf <agraf@csgraf.de>
Signed-off-by: Leif Lindholm <leif.lindholm@linaro.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-07-11 17:49:54 +02:00
Jacob Kroon f2b9083f85 probe: Support probing for partition UUID with --part-uuid
Linux supports root=PARTUUID=<partuuid> boot argument, so add
support for probing it. Compared to the fs UUID, the partition
UUID does not change when reformatting a partition.

For now, only disks using a GPT partition table are supported.

Signed-off-by: Jacob Kroon <jacob.kroon@gmail.com>
Reviewed-by: Paul Menzel <pmenzel@molgen.mpg.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-07-11 17:46:46 +02:00
Daniel Kiper 26094f5241 Bump version to 2.05
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-07-05 11:30:53 +02:00
Daniel Kiper 2a2e10c1b3 Release 2.04
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-07-04 15:57:30 +02:00
Thomas Schmitt f9811a92e6 docs: Document workaround for grub-mkrescue with older MacBooks
Add a description of the workaround for firmware of older MacBooks
which stalls with a grub-mkrescue ISO image for x86_64-efi target
on an USB stick.

Signed-off-by: Thomas Schmitt <scdbackup@gmx.net>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-06-24 12:11:25 +02:00
Eric Snowberg ff999c803e docs: Bootstrap changes required for older distros
Some older distros do not contain gettext 0.18. Document the workaround
to use the bootstrap utility on these systems.

Signed-off-by: Eric Snowberg <eric.snowberg@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-06-24 12:02:20 +02:00
Leif Lindholm 4e7b5bb3be ia64: build fix in cache.h
Add IA64 to the architectures excluding a declaration for
grub_arch_sync_dma_caches().

IA64 does not include any of the source files that require the function,
but was overlooked for d8901e3ba1 ("cache: Fix compilation for ppc,
sparc and arm64").

Add it to the list of excluding architectures in order to not get
missing symbol errors when running grub-mkimage.

Reported-by: Alexander Graf <agraf@csgraf.de>
Signed-off-by: Leif Lindholm <leif.lindholm@linaro.org>
Tested-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-06-07 15:37:55 +02:00
Vladimir 'phcoder' Serbinenko 5610734770 hostfs: #undef open and close.
Unlike in case of disks in this case it's just a single place, so it's easier
to just #undef

Signed-off-by: Vladimir Serbinenko <phcoder@google.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-06-07 15:36:28 +02:00
John Paul Adrian Glaubitz 8e8723a6be f2fs: Disable gcc9 -Waddress-of-packed-member
Disable the -Wadress-of-packaed-member diagnostic for the grub_f2fs_label
function since the result is found to be false postive.

A pointer to the 'volume_name' member of 'struct grub_f2fs_superblock' is
guaranteed to be aligned as the offset of 'volume_name' within the struct
is dividable by the natural alignment on both 32- and 64-bit targets.

grub-core/fs/f2fs.c: In function ‘grub_f2fs_label’:
grub-core/fs/f2fs.c:1253:60: error: taking address of packed member of ‘struct grub_f2fs_superblock’ may result in an unaligned pointer value [-Werror=address-of-packed-member]
 1253 |     *label = (char *) grub_f2fs_utf16_to_utf8 (data->sblock.volume_name);
      |                                                ~~~~~~~~~~~~^~~~~~~~~~~~
cc1: all warnings being treated as errors

Reported-by: Neil MacLeod <neil@nmacleod.com>
Signed-off-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
Tested-by: Neil MacLeod <neil@nmacleod.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-06-03 11:18:31 +02:00
Vincent Legoll 53e70d30cf grub-mkrescue: Fix error message about the wrong command having failed: mformat instead of mcopy
Signed-off-by: Vincent Legoll <vincent.legoll@gmail.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-05-20 13:01:11 +02:00
Mathieu Trudel-Lapierre afd6ad4297 video: skip 'text' gfxpayload if not supported, to fallback to default
On UEFI, 'text' gfxpayload is not supported, but we still reach parse_modespec()
with it, which will obviously fail. Fortunately, whatever gfxpayload is set,
we still still have the 'auto' default to fall back to. Allow getting to this
fallback by not trying to parse 'text' as a modespec.

This is because 'text' correctly doesn't parse as a modespec, and ought to have
been ignored before we got to that point, just like it is immediately picked if
we're running on a system where 'text' is a supported video mode.

Bug: https://savannah.gnu.org/bugs/index.php?56217

Signed-off-by: Mathieu Trudel-Lapierre <mathieu.trudel-lapierre@canonical.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-05-20 13:00:44 +02:00
Ovidiu Panait 4ff34fefe4 grub-mkconfig: Use -c instead of --printf for stat
"--printf" only works with the stat variant provided by coreutils.

With busybox, stat will fail with the following error:
stat: unrecognized option '--printf=%T'

Usage: stat [OPTIONS] FILE...

Signed-off-by: Ovidiu Panait <ovidiu.panait@windriver.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-05-20 12:59:36 +02:00
Michael Chang a06b079a36 f2fs: Fix gcc9 error -Werror=maybe-uninitialized
The function grub_get_node_path() could return uninitialized offset with
level == 0 if the block is greater than direct_index + 2 * direct_blks +
2 * indirect_blks + dindirect_blks. The uninitialized offset is then used
by function grub_f2fs_get_block() because level == 0 is valid and
meaningful return to be processed.

The fix is to set level = -1 as return value by grub_get_node_path() to
signify an error that the input block cannot be handled. Any caller
should therefore check level is negative or not before processing the
output.

Reported-by: Neil MacLeod <neil@nmacleod.com>
Signed-off-by: Michael Chang <mchang@suse.com>
Tested-by: Neil MacLeod <neil@nmacleod.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-05-20 12:59:00 +02:00
Alexander Graf ce946603cf arm: Align section alignment with manual relocation offset code
The arm relocation code has a manual special case for EFI binaries to
add the natural alignment to its own relocation awareness.

Since commit a51f953f4e ("mkimage: Align efi sections on 4k
boundary") we changed that alignment from 0x400 to 0x1000 bytes. Reflect
the change in that branch that we forgot as well.

This fixes running 32bit arm grub efi binaries for me again.

Fixes: a51f953f4e ("mkimage: Align efi sections on 4k boundary")
Reported-by: Heinrich Schuchardt <xypron.glpk@gmx.de>
Reported-by: Steve McIntyre <steve@einval.com>
Signed-off-by: Alexander Graf <agraf@csgraf.de>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
Tested-by: Julien ROBIN <julien.robin28@free.fr>
Reviewed-by: Leif Lindholm <leif.lindholm@linaro.org>
Tested-by: Leif Lindholm <leif.lindholm@linaro.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-05-06 12:10:54 +02:00
Alexander Graf 1ce93f944d arm: Move trampolines into code section
When creating T32->A32 transition jumps, the relocation code in grub
will generate trampolines. These trampolines live in the .data section
of our PE binary which means they are not marked as executable.

This misbehavior was unmasked by commit a51f953f4e ("mkimage: Align
efi sections on 4k boundary") which made the X/NX boundary more obvious
because everything became page aligned.

To put things into proper order, let's move the arm trampolines into the
.text section instead. That way everyone knows they are executable.

Fixes: a51f953f4e ("mkimage: Align efi sections on 4k boundary")
Reported-by: Julien ROBIN <julien.robin28@free.fr>
Reported-by: Leif Lindholm <leif.lindholm@linaro.org>
Signed-off-by: Alexander Graf <agraf@csgraf.de>
Tested-by: Julien ROBIN <julien.robin28@free.fr>
Reviewed-by: Leif Lindholm <leif.lindholm@linaro.org>
Tested-by: Leif Lindholm <leif.lindholm@linaro.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-05-06 12:10:27 +02:00
Michael Chang 4dd4ceec02 efi: Fix gcc9 error -Waddress-of-packed-member
The address of fp->path_name could be unaligned since seeking into the
device path buffer for a given node could end in byte boundary.

The fix is allocating aligned buffer by grub_malloc for holding the
UTF16 string copied from fp->path_name, and after using that buffer as
argument for grub_utf16_to_utf8 to convert it to UTF8 string.

[  255s] ../../grub-core/kern/efi/efi.c: In function 'grub_efi_get_filename':
[  255s] ../../grub-core/kern/efi/efi.c:410:60: error: taking address of packed member of 'struct grub_efi_file_path_device_path' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[  255s]   410 |    p = (char *) grub_utf16_to_utf8 ((unsigned char *) p, fp->path_name, len);
[  255s]       |                                                          ~~^~~~~~~~~~~
[  255s] ../../grub-core/kern/efi/efi.c: In function 'grub_efi_print_device_path':
[  255s] ../../grub-core/kern/efi/efi.c:900:33: error: taking address of packed member of 'struct grub_efi_file_path_device_path' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[  255s]   900 |     *grub_utf16_to_utf8 (buf, fp->path_name,
[  255s]       |                               ~~^~~~~~~~~~~

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-04-23 11:37:08 +02:00
Michael Chang 4868e17507 chainloader: Fix gcc9 error -Waddress-of-packed-member
The address of fp->path_name could be unaligned since seeking into the
device path buffer for a given node could end in byte boundary.

The fix is using aligned buffer allocated by grub_malloc for receiving
the converted UTF16 string by grub_utf8_to_utf16 and also the processing
after. The resulting string then gets copied to fp->path_name.

[  243s] ../../grub-core/loader/efi/chainloader.c: In function 'copy_file_path':
[  243s] ../../grub-core/loader/efi/chainloader.c:136:32: error: taking address of packed member of 'struct grub_efi_file_path_device_path' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[  243s]   136 |   size = grub_utf8_to_utf16 (fp->path_name, len * GRUB_MAX_UTF16_PER_UTF8,
[  243s]       |                              ~~^~~~~~~~~~~
[  243s] ../../grub-core/loader/efi/chainloader.c:138:12: error: taking address of packed member of 'struct grub_efi_file_path_device_path' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[  243s]   138 |   for (p = fp->path_name; p < fp->path_name + size; p++)
[  243s]       |            ^~

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-04-23 11:37:08 +02:00
Michael Chang 85e08e174e usbtest: Disable gcc9 -Waddress-of-packed-member
Disable the -Wadress-of-packaed-member diagnostic for the
grub_usb_get_string function since the result is false postive. The
descstrp->str is found to be aligned in the buffer allocated for 'struct
grub_usb_desc_str'.

[  229s] ../../grub-core/commands/usbtest.c: In function 'grub_usb_get_string':
[  229s] ../../grub-core/commands/usbtest.c:104:58: error: taking address of packed member of 'struct grub_usb_desc_str' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[  229s]   104 |   *grub_utf16_to_utf8 ((grub_uint8_t *) *string, descstrp->str,
[  229s]       |                                                  ~~~~~~~~^~~~~

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-04-23 11:37:08 +02:00
Michael Chang 0b1bf3932f acpi: Fix gcc9 error -Waddress-of-packed-member
Simply adds the missing packed attribute to 'struct grub_acpi_madt'.

[  233s] ../../grub-core/commands/lsacpi.c: In function 'disp_acpi_xsdt_table':
[  233s] ../../grub-core/commands/lsacpi.c:201:27: error: converting a packed 'struct grub_acpi_table_header' pointer (alignment 1) to a 'struct grub_acpi_madt' pointer (alignment 4) may result in an unaligned pointer value [-Werror=address-of-packed-member]
[  233s]   201 |  disp_madt_table ((struct grub_acpi_madt *) t);
[  233s]       |                           ^~~~~~~~~~~~~~
[  233s] In file included from ../../grub-core/commands/lsacpi.c:23:
[  233s] ../../include/grub/acpi.h:50:8: note: defined here
[  233s]    50 | struct grub_acpi_table_header
[  233s]       |        ^~~~~~~~~~~~~~~~~~~~~~
[  233s] ../../include/grub/acpi.h:90:8: note: defined here
[  233s]    90 | struct grub_acpi_madt
[  233s]       |        ^~~~~~~~~~~~~~
[  233s] ../../grub-core/commands/lsacpi.c: In function 'disp_acpi_rsdt_table':
[  233s] ../../grub-core/commands/lsacpi.c:225:27: error: converting a packed 'struct grub_acpi_table_header' pointer (alignment 1) to a 'struct grub_acpi_madt' pointer (alignment 4) may result in an unaligned pointer value [-Werror=address-of-packed-member]
[  233s]   225 |  disp_madt_table ((struct grub_acpi_madt *) t);
[  233s]       |                           ^~~~~~~~~~~~~~
[  233s] In file included from ../../grub-core/commands/lsacpi.c:23:
[  233s] ../../include/grub/acpi.h:50:8: note: defined here
[  233s]    50 | struct grub_acpi_table_header
[  233s]       |        ^~~~~~~~~~~~~~~~~~~~~~
[  233s] ../../include/grub/acpi.h:90:8: note: defined here
[  233s]    90 | struct grub_acpi_madt
[  233s]       |        ^~~~~~~~~~~~~~

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-04-23 11:37:08 +02:00
Michael Chang 621024090b hfsplus: Fix gcc9 error with -Waddress-of-packed-member
The catkey->name could be unaligned since the address of 'void* record'
is calculated as offset in bytes to a malloc buffer.

The fix is using aligned buffer allocated by grub_malloc for holding
the UTF16 string copied from catkey->name. And use that buffer as
argument for grub_utf16_to_utf8 to convert to UTF8 strings.

In addition, using a new copy of buffer rather than catkey->name itself
for processing the endianess conversion, we can also get rid of the hunk
restoring byte order of catkey->name to what it was previously.

[   59s] ../grub-core/fs/hfsplus.c: In function 'list_nodes':
[   59s] ../grub-core/fs/hfsplus.c:738:57: error: taking address of packed member of 'struct grub_hfsplus_catkey' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   59s]   738 |   *grub_utf16_to_utf8 ((grub_uint8_t *) filename, catkey->name,
[   59s]       |                                                   ~~~~~~^~~~~~
[   59s] ../grub-core/fs/hfsplus.c: In function 'grub_hfsplus_label':
[   59s] ../grub-core/fs/hfsplus.c:1019:57: error: taking address of packed member of 'struct grub_hfsplus_catkey' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   59s]  1019 |   *grub_utf16_to_utf8 ((grub_uint8_t *) (*label), catkey->name,
[   59s]       |                                                   ~~~~~~^~~~~~

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-04-23 11:37:08 +02:00
Michael Chang 0e49748fad hfs: Fix gcc9 error -Waddress-of-packed-member
Simply adds the missing packed attribute to 'struct grub_hfs_extent'.

[   83s] ../grub-core/fs/hfs.c: In function 'grub_hfs_iterate_records':
[   83s] ../grub-core/fs/hfs.c:699:9: error: taking address of packed member of 'struct grub_hfs_sblock' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   83s]   699 |      ? (&data->sblock.catalog_recs)
[   83s]       |        ~^~~~~~~~~~~~~~~~~~~~~~~~~~~
[   83s] ../grub-core/fs/hfs.c:700:9: error: taking address of packed member of 'struct grub_hfs_sblock' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   83s]   700 |      : (&data->sblock.extent_recs));
[   83s]       |        ~^~~~~~~~~~~~~~~~~~~~~~~~~~

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-04-23 11:37:08 +02:00
Michael Chang 4f4128defd jfs: Disable gcc9 -Waddress-of-packed-member
Disable the -Wadress-of-packaed-member diagnostic for the
grub_jfs_getent function since the result is found to be false postive.

The leaf is read into memory as continous chunks in size of 32 bytes and
the pointer to its base is aligned, which also guarentee its member
leaf->namepart is aligned.

[   60s] ../grub-core/fs/jfs.c: In function 'grub_jfs_getent':
[   60s] ../grub-core/fs/jfs.c:557:44: error: taking address of packed member of 'struct grub_jfs_leaf_dirent' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   60s]   557 |   le_to_cpu16_copy (filename + strpos, leaf->namepart, len < diro->data->namecomponentlen ? len
[   60s]       |                                        ~~~~^~~~~~~~~~
[   60s] ../grub-core/fs/jfs.c:570:48: error: taking address of packed member of 'struct grub_jfs_leaf_next_dirent' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   60s]   570 |  le_to_cpu16_copy (filename + strpos, next_leaf->namepart, len < 15 ? len : 15);
[   60s]       |                                       ~~~~~~~~~^~~~~~~~~~
[   60s] cc1: all warnings being treated as errors

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-04-23 11:37:08 +02:00
Michael Chang 7ea474c688 cpio: Disable gcc9 -Waddress-of-packed-member
Disable the -Wadress-of-packaed-member diagnostic for the
grub_cpio_find_file function since the result is found to be false
postive. Any pointers to member of the 'struct head hd' is aligned even
if the structure is packed without paddings.

[   59s] In file included from ../grub-core/fs/cpio.c:51:
[   59s] ../grub-core/fs/cpio_common.c: In function 'grub_cpio_find_file':
[   59s] ../grub-core/fs/cpio_common.c:58:31: error: taking address of packed member of 'struct head' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   59s]    58 |   data->size = read_number (hd.filesize, ARRAY_SIZE (hd.filesize));
[   59s]       |                             ~~^~~~~~~~~
[   59s] ../grub-core/fs/cpio_common.c:60:29: error: taking address of packed member of 'struct head' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   59s]    60 |     *mtime = read_number (hd.mtime, ARRAY_SIZE (hd.mtime));
[   59s]       |                           ~~^~~~~~
[   59s] ../grub-core/fs/cpio_common.c:61:28: error: taking address of packed member of 'struct head' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   59s]    61 |   modeval = read_number (hd.mode, ARRAY_SIZE (hd.mode));
[   59s]       |                          ~~^~~~~
[   59s] ../grub-core/fs/cpio_common.c:62:29: error: taking address of packed member of 'struct head' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   59s]    62 |   namesize = read_number (hd.namesize, ARRAY_SIZE (hd.namesize));
[   59s]       |                           ~~^~~~~~~~~
[   59s] In file included from ../grub-core/fs/cpio_be.c:51:
[   59s] ../grub-core/fs/cpio_common.c: In function 'grub_cpio_find_file':
[   59s] ../grub-core/fs/cpio_common.c:58:31: error: taking address of packed member of 'struct head' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   59s]    58 |   data->size = read_number (hd.filesize, ARRAY_SIZE (hd.filesize));
[   59s]       |                             ~~^~~~~~~~~
[   59s] ../grub-core/fs/cpio_common.c:60:29: error: taking address of packed member of 'struct head' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   59s]    60 |     *mtime = read_number (hd.mtime, ARRAY_SIZE (hd.mtime));
[   59s]       |                           ~~^~~~~~
[   59s] ../grub-core/fs/cpio_common.c:61:28: error: taking address of packed member of 'struct head' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   59s]    61 |   modeval = read_number (hd.mode, ARRAY_SIZE (hd.mode));
[   59s]       |                          ~~^~~~~
[   59s] ../grub-core/fs/cpio_common.c:62:29: error: taking address of packed member of 'struct head' may result in an unaligned pointer value [-Werror=address-of-packed-member]
[   59s]    62 |   namesize = read_number (hd.namesize, ARRAY_SIZE (hd.namesize));
[   59s]       |                           ~~^~~~~~~~~

Signed-off-by: Michael Chang <mchang@suse.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-04-23 11:37:08 +02:00
Heinrich Schuchardt bc58fded50 efi: Avoid NULL dereference if FilePath is NULL
The UEFI specification allows LoadImage() to be called with a memory
location only and without a device path. In this case FilePath will not be
set in the EFI_LOADED_IMAGE_PROTOCOL.

So in function grub_efi_get_filename() the device path argument may be
NULL. As we cannot determine the device path in this case just return NULL
from the function.

Signed-off-by: Heinrich Schuchardt <xypron.glpk@gmx.de>
Reviewed-by: Leif Lindholm <leif.lindholm@linaro.org>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
2019-04-23 11:33:02 +02:00
Daniel Kiper acc726f812 x86/msr: Fix build with older GCC versions
Some older GCC versions produce following error when x86 MSR modules are build:

  In file included from commands/i386/rdmsr.c:29:0:
  ../include/grub/i386/rdmsr.h:27:29: error: no previous prototype for ‘grub_msr_read’ [-Werror=missing-prototypes]
   extern inline grub_uint64_t grub_msr_read (grub_uint32_t msr_id)
                               ^
  cc1: all warnings being treated as errors

This happens due to lack of support for a such usage of extern keyword
in older GCCs. Additionally, this usage is not consistent with the rest
of codebase. So, replace it with static keyword.

Additionally, fix incorrect coding style.

Reported-by: Eric Snowberg <eric.snowberg@oracle.com>
Reported-by: adrian15 <adrian15sgd@gmail.com>
Signed-off-by: Daniel Kiper <daniel.kiper@oracle.com>
Reviewed-by: Vladimir 'phcoder' Serbinenko <phcoder@gmail.com>
Reviewed-by: Eric Snowberg <eric.snowberg@oracle.com>
Tested-by: adrian15 <adrian15sgd@gmail.com>
2019-04-23 11:04:07 +02:00
358 changed files with 13524 additions and 4708 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
po/exclude.pot binary
+254 -214
View File
@@ -1,237 +1,277 @@
*~ #
00_header # Ignore patterns in this directory and all subdirectories.
10_* #
20_linux_xen
30_os-prober
40_custom
41_custom
*.1 *.1
*.8 *.8
ABOUT-NLS *.a
aclocal.m4
ahci_test
ascii.bitmaps
ascii.h
autom4te.cache
build-aux
build-grub-gen-asciih
build-grub-gen-widthspec
build-grub-mkfont
cdboot_test
cmp_test
config.cache
config.guess
config.h
config-util.h
config-util.h.in
config.log
config.status
config.sub
configure
core_compress_test
DISTLIST
docs/*.info
docs/stamp-vti
docs/version.texi
ehci_test
example_grub_script_test
example_scripted_test
example_unit_test
*.exec *.exec
*.exec.exe *.exec.exe
fddboot_test
genkernsyms.sh
gensymlist.sh
gentrigtables
gentrigtables.exe
gettext_strings_test
/gnulib
grub-bin2h
/grub-bios-setup
/grub-bios-setup.exe
grub_cmd_date
grub_cmd_echo
grub_cmd_regexp
grub_cmd_set_date
grub_cmd_sleep
/grub-editenv
/grub-editenv.exe
grub-emu
grub-emu-lite
grub-emu.exe
grub-emu-lite.exe
grub_emu_init.c
grub_emu_init.h
/grub-file
/grub-file.exe
grub-fstest
grub-fstest.exe
grub_fstest_init.c
grub_fstest_init.h
grub_func_test
grub-install
grub-install.exe
grub-kbdcomp
/grub-macbless
/grub-macbless.exe
grub-macho2img
/grub-menulst2cfg
/grub-menulst2cfg.exe
/grub-mk*
grub-mount
/grub-ofpathname
/grub-ofpathname.exe
grub-core/build-grub-pe2elf.exe
/grub-probe
/grub-probe.exe
grub_probe_init.c
grub_probe_init.h
/grub-reboot
grub_script_blanklines
grub_script_blockarg
grub_script_break
grub-script-check
grub-script-check.exe
grub_script_check_init.c
grub_script_check_init.h
grub_script_comments
grub_script_continue
grub_script_dollar
grub_script_echo1
grub_script_echo_keywords
grub_script_escape_comma
grub_script_eval
grub_script_expansion
grub_script_final_semicolon
grub_script_for1
grub_script_functions
grub_script_gettext
grub_script_if
grub_script_leading_whitespace
grub_script_no_commands
grub_script_not
grub_script_return
grub_script_setparams
grub_script_shift
grub_script_strcmp
grub_script_test
grub_script_vars1
grub_script_while1
grub_script.tab.c
grub_script.tab.h
grub_script.yy.c
grub_script.yy.h
grub-set-default
grub_setup_init.c
grub_setup_init.h
grub-shell
grub-shell-tester
grub-sparc64-setup
grub-sparc64-setup.exe
/grub-syslinux2cfg
/grub-syslinux2cfg.exe
gzcompress_test
hddboot_test
help_test
*.img
*.image *.image
*.image.exe *.image.exe
include/grub/cpu *.img
include/grub/machine
INSTALL.grub
install-sh
lib/libgcrypt-grub
libgrub_a_init.c
*.log *.log
*.lst *.lst
lzocompress_test
*.marker *.marker
Makefile
/m4
*.mod *.mod
mod-*.c
missing
netboot_test
*.o *.o
*.a
ohci_test
partmap_test
pata_test
*.pf2 *.pf2
*.pp *.pp
po/*.mo
po/grub.pot
po/Makefile.in.in
po/Makevars
po/Makevars.template
po/POTFILES
po/Rules-quot
po/stamp-po
printf_test
priority_queue_unit_test
pseries_test
stamp-h
stamp-h1
stamp-h.in
symlist.c
symlist.h
trigtables.c
*.trs *.trs
uhci_test *~
update-grub_lib .deps-core/
unidata.c .deps-util/
xzcompress_test .deps/
Makefile.in .dirstamp
DISTLIST
GPATH GPATH
GRTAGS GRTAGS
GSYMS GSYMS
GTAGS GTAGS
compile Makefile
depcomp Makefile.in
ascii.bitmaps
genkernsyms.sh
gensymlist.sh
grub-bin2h
grub-emu
grub-emu-lite
grub-emu-lite.exe
grub-emu.exe
grub-macho2img
grub_emu_init.c
grub_emu_init.h
grub_probe_init.c
grub_probe_init.h
grub_script.tab.c
grub_script.tab.h
grub_script.yy.c
grub_script.yy.h
grub_script_check_init.c
grub_script_check_init.h
grub_setup_init.c
grub_setup_init.h
mdate-sh mdate-sh
texinfo.tex mod-*.c
grub-core/lib/libgcrypt-grub update-grub_lib
.deps
.deps-util
.deps-core
.dirstamp
Makefile.util.am
contrib
grub-core/bootinfo.txt
grub-core/Makefile.core.am
grub-core/Makefile.gcry.def
grub-core/contrib
grub-core/gdb_grub
grub-core/genmod.sh
grub-core/gensyminfo.sh
grub-core/gmodule.pl
grub-core/grub.chrp
grub-core/modinfo.sh
grub-core/*.module
grub-core/*.module.exe
grub-core/*.pp
grub-core/kernel.img.bin
util/bash-completion.d/grub
grub-core/lib/gnulib
grub-core/rs_decoder.h
widthspec.bin widthspec.bin
widthspec.h
docs/stamp-1 #
docs/version-dev.texi # Ignore patterns relative to this .gitignore file's directory.
Makefile.utilgcry.def #
po/*.po /00_header
po/*.gmo /10_*
po/LINGUAS /20_linux_xen
po/remove-potcdate.sed /30_os-prober
include/grub/gcrypt/gcrypt.h /30_uefi-firmware
include/grub/gcrypt/g10lib.h /40_custom
po/POTFILES.in /41_custom
po/POTFILES-shell.in /ABOUT-NLS
/grub-glue-efi /ChangeLog
/grub-render-label /INSTALL.grub
/grub-glue-efi.exe /Makefile.util.am
/grub-render-label.exe /Makefile.utilgcry.def
/aclocal.m4
/ahci_test
/ascii.h
/autom4te.cache/
/btrfs_test
/build-aux/
/build-grub-gen-asciih
/build-grub-gen-widthspec
/build-grub-mkfont
/cdboot_test
/cmp_test
/compile
/config-util.h
/config-util.h.in
/config.cache
/config.guess
/config.h
/config.log
/config.status
/config.sub
/configure
/contrib
/core_compress_test
/cpio_test
/date_test
/depcomp
/docs/*.info
/docs/*.info-[0-9]*
/docs/stamp-1
/docs/stamp-vti
/docs/version-dev.texi
/docs/version.texi
/ehci_test
/example_grub_script_test
/example_scripted_test
/example_unit_test
/exfat_test
/ext234_test
/f2fs_test
/fat_test
/fddboot_test
/file_filter_test
/garbage-gen /garbage-gen
/garbage-gen.exe /garbage-gen.exe
/gettext_strings_test
/gnulib/
/grub-2.[0-9]*/
/grub-2.[0-9]*.tar.gz
/grub-bios-setup
/grub-bios-setup.exe
/grub-core/*.module
/grub-core/*.module.exe
/grub-core/*.pp
/grub-core/Makefile.core.am
/grub-core/Makefile.gcry.def
/grub-core/bootinfo.txt
/grub-core/build-grub-module-verifier
/grub-core/build-grub-pe2elf.exe
/grub-core/contrib
/grub-core/gdb_grub
/grub-core/genmod.sh
/grub-core/gensyminfo.sh
/grub-core/gentrigtables
/grub-core/gentrigtables.exe
/grub-core/gmodule.pl
/grub-core/grub.chrp
/grub-core/kernel.img.bin
/grub-core/lib/gnulib
/grub-core/lib/libgcrypt-grub
/grub-core/modinfo.sh
/grub-core/rs_decoder.h
/grub-core/symlist.c
/grub-core/symlist.h
/grub-core/trigtables.c
/grub-core/unidata.c
/grub-editenv
/grub-editenv.exe
/grub-file
/grub-file.exe
/grub-fs-tester /grub-fs-tester
grub-core/build-grub-module-verifier /grub-fstest
/grub-fstest.exe
/grub-glue-efi
/grub-glue-efi.exe
/grub-install
/grub-install.exe
/grub-kbdcomp
/grub-macbless
/grub-macbless.exe
/grub-menulst2cfg
/grub-menulst2cfg.exe
/grub-mk*
/grub-mount
/grub-ofpathname
/grub-ofpathname.exe
/grub-probe
/grub-probe.exe
/grub-reboot
/grub-render-label
/grub-render-label.exe
/grub-script-check
/grub-script-check.exe
/grub-set-default
/grub-shell
/grub-shell-tester
/grub-sparc64-setup
/grub-sparc64-setup.exe
/grub-syslinux2cfg
/grub-syslinux2cfg.exe
/grub_cmd_date
/grub_cmd_echo
/grub_cmd_regexp
/grub_cmd_set_date
/grub_cmd_sleep
/grub_cmd_test
/grub_cmd_tr
/grub_fstest_init.c
/grub_fstest_init.h
/grub_func_test
/grub_script_blanklines
/grub_script_blockarg
/grub_script_break
/grub_script_comments
/grub_script_continue
/grub_script_dollar
/grub_script_echo1
/grub_script_echo_keywords
/grub_script_escape_comma
/grub_script_eval
/grub_script_expansion
/grub_script_final_semicolon
/grub_script_for1
/grub_script_functions
/grub_script_gettext
/grub_script_if
/grub_script_leading_whitespace
/grub_script_no_commands
/grub_script_not
/grub_script_return
/grub_script_setparams
/grub_script_shift
/grub_script_strcmp
/grub_script_test
/grub_script_vars1
/grub_script_while1
/gzcompress_test
/hddboot_test
/help_test
/hfs_test
/hfsplus_test
/include/grub/cpu
/include/grub/gcrypt/g10lib.h
/include/grub/gcrypt/gcrypt.h
/include/grub/machine
/install-sh
/iso9660_test
/jfs_test
/lib/libgcrypt-grub
/libgrub_a_init.c
/lzocompress_test
/m4/
/minixfs_test
/missing
/netboot_test
/nilfs2_test
/ntfs_test
/ohci_test
/partmap_test
/pata_test
/po/*.gmo
/po/*.mo
/po/*.po
/po/LINGUAS
/po/Makefile.in.in
/po/Makevars
/po/Makevars.template
/po/POTFILES
/po/POTFILES-shell.in
/po/POTFILES.in
/po/Rules-quot
/po/grub.pot
/po/remove-potcdate.sed
/po/stamp-po
/printf_test
/priority_queue_unit_test
/pseries_test
/reiserfs_test
/romfs_test
/squashfs_test
/stamp-h
/stamp-h.in
/stamp-h1
/syslinux_test
/tar_test
/test_sha512sum
/test_unset
/tests/syslinux/ubuntu10.04_grub.cfg
/texinfo.tex
/udf_test
/uhci_test
/util/bash-completion.d/grub
/widthspec.h
/xfs_test
/xzcompress_test
/zfs_test
+2 -1
View File
@@ -12,6 +12,7 @@ language: c
addons: addons:
apt: apt:
packages: packages:
- autopoint
- libsdl1.2-dev - libsdl1.2-dev
- lzop - lzop
- ovmf - ovmf
@@ -35,7 +36,7 @@ before_script:
script: script:
# Comments must be outside the command strings below, or the Travis parser # Comments must be outside the command strings below, or the Travis parser
# will get confused. # will get confused.
- ./autogen.sh - ./bootstrap
# Build all selected GRUB targets. # Build all selected GRUB targets.
- for target in $GRUB_TARGETS; do - for target in $GRUB_TARGETS; do
+33 -36
View File
@@ -11,27 +11,9 @@ GRUB depends on some software packages installed into your system. If
you don't have any of them, please obtain and install them before you don't have any of them, please obtain and install them before
configuring the GRUB. configuring the GRUB.
* GCC 4.1.3 or later * GCC 5.1.0 or later
Note: older versions may work but support is limited Experimental support for clang 3.8.0 or later (results in much bigger binaries)
Experimental support for clang 3.3 or later (results in much bigger binaries)
for i386, x86_64, arm (including thumb), arm64, mips(el), powerpc, sparc64 for i386, x86_64, arm (including thumb), arm64, mips(el), powerpc, sparc64
Note: clang 3.2 or later works for i386 and x86_64 targets but results in
much bigger binaries.
earlier versions not tested
Note: clang 3.2 or later works for arm
earlier versions not tested
Note: clang on arm64 is not supported due to
https://llvm.org/bugs/show_bug.cgi?id=26030
Note: clang 3.3 or later works for mips(el)
earlier versions fail to generate .reginfo and hence gprel relocations
fail.
Note: clang 3.2 or later works for powerpc
earlier versions not tested
Note: clang 3.5 or later works for sparc64
earlier versions return "error: unable to interface with target machine"
Note: clang has no support for ia64 and hence you can't compile GRUB
for ia64 with clang
* GNU Make * GNU Make
* GNU Bison 2.3 or later * GNU Bison 2.3 or later
* GNU gettext 0.17 or later * GNU gettext 0.17 or later
@@ -160,12 +142,20 @@ For this example the configure line might look like (more details below)
(some options are optional and included here for completeness but some rarely (some options are optional and included here for completeness but some rarely
used options are omitted): used options are omitted):
./configure BUILD_CC=gcc BUILD_PKG_CONFIG=pkg-config --host=amd64-linux-gnu ./configure --host=x86_64-linux-gnu --target=arm-linux-gnueabihf \
CC=amd64-linux-gnu-gcc CFLAGS="-g -O2" PKG_CONFIG=amd64-linux-gnu-pkg-config --with-platform=efi BUILD_CC=gcc BUILD_PKG_CONFIG=pkg-config \
--target=arm --with-platform=uboot TARGET_CC=arm-elf-gcc HOST_CC=x86_64-linux-gnu-gcc HOST_CFLAGS='-g -O2' \
TARGET_CFLAGS="-Os -march=armv6" TARGET_CCASFLAGS="-march=armv6" PKG_CONFIG=x86_64-linux-gnu-pkg-config TARGET_CC=arm-linux-gnueabihf-gcc \
TARGET_OBJCOPY="arm-elf-objcopy" TARGET_STRIP="arm-elf-strip" TARGET_CFLAGS='-Os -march=armv8.3-a' TARGET_CCASFLAGS='-march=armv8.3-a' \
TARGET_NM=arm-elf-nm TARGET_RANLIB=arm-elf-ranlib LEX=gflex TARGET_OBJCOPY=arm-linux-gnueabihf-objcopy \
TARGET_STRIP=arm-linux-gnueabihf-strip TARGET_NM=arm-linux-gnueabihf-nm \
TARGET_RANLIB=arm-linux-gnueabihf-ranlib LEX=flex
Normally, for building a GRUB on amd64 with tools to run on amd64 to
generate images to run on ARM, using your Linux distribution's
packaged cross compiler, the following would suffice:
./configure --target=arm-linux-gnueabihf --with-platform=efi
You need to use following options to specify tools and platforms. For minimum You need to use following options to specify tools and platforms. For minimum
version look at prerequisites. All tools not mentioned in this section under version look at prerequisites. All tools not mentioned in this section under
@@ -182,20 +172,23 @@ corresponding platform are not needed for the platform in question.
- For host - For host
1. --host= to autoconf name of host. 1. --host= to autoconf name of host.
2. CC= for gcc able to compile for host 2. CC= for gcc able to compile for host.
3. HOST_CFLAGS= for C options for host. 3. CFLAGS= for C options for host.
4. HOST_CPPFLAGS= for C preprocessor options for host. 4. HOST_CC= for gcc able to compile for host.
5. HOST_LDFLAGS= for linker options for host. 5. HOST_CFLAGS= for C options for host.
6. PKG_CONFIG= for pkg-config for host (optional). 6. HOST_CPPFLAGS= for C preprocessor options for host.
7. Libdevmapper if any must be in standard linker folders (-ldevmapper) (optional). 7. HOST_LDFLAGS= for linker options for host.
8. Libfuse if any must be in standard linker folders (-lfuse) (optional). 8. PKG_CONFIG= for pkg-config for host (optional).
9. Libzfs if any must be in standard linker folders (-lzfs) (optional). 9. Libdevmapper if any must be in standard linker folders (-ldevmapper) (optional).
10. Liblzma if any must be in standard linker folders (-llzma) (optional). 10. Libfuse if any must be in standard linker folders (-lfuse) (optional).
11. Libzfs if any must be in standard linker folders (-lzfs) (optional).
12. Liblzma if any must be in standard linker folders (-llzma) (optional).
Note: The HOST_* variables override not prefixed variables.
- For target - For target
1. --target= to autoconf cpu name of target. 1. --target= to autoconf cpu name of target.
2. --with-platform to choose firmware. 2. --with-platform to choose firmware.
3. TARGET_CC= for gcc able to compile for target 3. TARGET_CC= for gcc able to compile for target.
4. TARGET_CFLAGS= for C options for target. 4. TARGET_CFLAGS= for C options for target.
5. TARGET_CPPFLAGS= for C preprocessor options for target. 5. TARGET_CPPFLAGS= for C preprocessor options for target.
6. TARGET_CCASFLAGS= for assembler options for target. 6. TARGET_CCASFLAGS= for assembler options for target.
@@ -204,6 +197,10 @@ corresponding platform are not needed for the platform in question.
9. TARGET_STRIP= for strip for target. 9. TARGET_STRIP= for strip for target.
10. TARGET_NM= for nm for target. 10. TARGET_NM= for nm for target.
11. TARGET_RANLIB= for ranlib for target. 11. TARGET_RANLIB= for ranlib for target.
Note: If the TARGET_* variables are not specified then they will default
to be the same as the host variables. If host variables are not
specified then the TARGET_* variables will default to be the same
as not prefixed variables.
- Additionally for emu, for host and target. - Additionally for emu, for host and target.
1. SDL is looked for in standard linker directories (-lSDL) (optional) 1. SDL is looked for in standard linker directories (-lSDL) (optional)
+1 -1
View File
@@ -37,7 +37,7 @@ grub_script.yy.c: grub_script.yy.h
CLEANFILES += grub_script.yy.c grub_script.yy.h CLEANFILES += grub_script.yy.c grub_script.yy.h
# For libgrub.a # For libgrub.a
libgrub.pp: grub_script.tab.h grub_script.yy.h $(libgrubmods_a_SOURCES) $(libgrubkern_a_SOURCES) libgrub.pp: config-util.h grub_script.tab.h grub_script.yy.h $(libgrubmods_a_SOURCES) $(libgrubkern_a_SOURCES)
$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libgrubmods_a_CPPFLAGS) $(libgrubkern_a_CPPFLAGS) $(CPPFLAGS) \ $(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libgrubmods_a_CPPFLAGS) $(libgrubkern_a_CPPFLAGS) $(CPPFLAGS) \
-D'GRUB_MOD_INIT(x)=@MARKER@x@' $^ > $@ || (rm -f $@; exit 1) -D'GRUB_MOD_INIT(x)=@MARKER@x@' $^ > $@ || (rm -f $@; exit 1)
CLEANFILES += libgrub.pp CLEANFILES += libgrub.pp
+21 -3
View File
@@ -3,7 +3,7 @@ AutoGen definitions Makefile.tpl;
library = { library = {
name = libgrubkern.a; name = libgrubkern.a;
cflags = '$(CFLAGS_GNULIB)'; cflags = '$(CFLAGS_GNULIB)';
cppflags = '$(CPPFLAGS_GNULIB)'; cppflags = '$(CPPFLAGS_GNULIB) -I$(srcdir)/grub-core/lib/json';
common = util/misc.c; common = util/misc.c;
common = grub-core/kern/command.c; common = grub-core/kern/command.c;
@@ -36,7 +36,9 @@ 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/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/geli.c; common = grub-core/disk/geli.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;
@@ -139,7 +141,7 @@ library = {
common = grub-core/lib/crc.c; common = grub-core/lib/crc.c;
common = grub-core/lib/adler32.c; common = grub-core/lib/adler32.c;
common = grub-core/lib/crc64.c; common = grub-core/lib/crc64.c;
common = grub-core/normal/datetime.c; common = grub-core/lib/datetime.c;
common = grub-core/normal/misc.c; common = grub-core/normal/misc.c;
common = grub-core/partmap/acorn.c; common = grub-core/partmap/acorn.c;
common = grub-core/partmap/amiga.c; common = grub-core/partmap/amiga.c;
@@ -201,7 +203,6 @@ program = {
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)';
cppflags = '-DGRUB_PKGLIBDIR=\"$(pkglibdir)\"';
}; };
program = { program = {
@@ -240,8 +241,19 @@ program = {
common = util/grub-editenv.c; common = util/grub-editenv.c;
common = util/editenv.c; common = util/editenv.c;
common = util/grub-install-common.c;
common = grub-core/osdep/init.c; common = grub-core/osdep/init.c;
common = grub-core/osdep/compress.c;
extra_dist = grub-core/osdep/unix/compress.c;
extra_dist = grub-core/osdep/basic/compress.c;
common = util/mkimage.c;
common = util/grub-mkimage32.c;
common = util/grub-mkimage64.c;
common = grub-core/osdep/config.c;
common = util/config.c;
common = util/resolve.c;
ldadd = '$(LIBLZMA)';
ldadd = libgrubmods.a; ldadd = libgrubmods.a;
ldadd = libgrubgcry.a; ldadd = libgrubgcry.a;
ldadd = libgrubkern.a; ldadd = libgrubkern.a;
@@ -502,6 +514,12 @@ script = {
installdir = grubconf; installdir = grubconf;
}; };
script = {
name = '30_uefi-firmware';
common = util/grub.d/30_uefi-firmware.in;
installdir = grubconf;
};
script = { script = {
name = '40_custom'; name = '40_custom';
common = util/grub.d/40_custom.in; common = util/grub.d/40_custom.in;
+18
View File
@@ -1,3 +1,21 @@
New in 2.04:
* GCC 8 and 9 support.
* Gnulib integration overhaul.
* RISC-V support.
* Xen PVH support.
* Native UEFI secure boot support.
* UEFI TPM driver.
* New IEEE 1275 obdisk driver.
* Btrfs RAID 5 and RIAD 6 support.
* PARTUUID support.
* VLAN support.
* Native DHCP support.
* Many ARM and ARM64 fixes.
* Many SPARC fixes.
* Many IEEE 1275 fixes.
* ...and tons of other fixes and cleanups...
New in 2.02: New in 2.02:
* New/improved filesystem and disk support: * New/improved filesystem and disk support:
+36 -2
View File
@@ -305,9 +305,9 @@ fi
]) ])
dnl Check if the C compiler supports `-fstack-protector'. dnl Check if the C compiler supports the stack protector
AC_DEFUN([grub_CHECK_STACK_PROTECTOR],[ AC_DEFUN([grub_CHECK_STACK_PROTECTOR],[
[# Smashing stack protector. [# Stack smashing protector.
ssp_possible=yes] ssp_possible=yes]
AC_MSG_CHECKING([whether `$CC' accepts `-fstack-protector']) AC_MSG_CHECKING([whether `$CC' accepts `-fstack-protector'])
# Is this a reliable test case? # Is this a reliable test case?
@@ -324,6 +324,40 @@ else
ssp_possible=no] ssp_possible=no]
AC_MSG_RESULT([no]) AC_MSG_RESULT([no])
[fi] [fi]
[# Strong stack smashing protector.
ssp_strong_possible=yes]
AC_MSG_CHECKING([whether `$CC' accepts `-fstack-protector-strong'])
# Is this a reliable test case?
AC_LANG_CONFTEST([AC_LANG_SOURCE([[
void foo (void) { volatile char a[8]; a[3]; }
]])])
[# `$CC -c -o ...' might not be portable. But, oh, well... Is calling
# `ac_compile' like this correct, after all?
if eval "$ac_compile -S -fstack-protector-strong -o conftest.s" 2> /dev/null; then]
AC_MSG_RESULT([yes])
[# Should we clear up other files as well, having called `AC_LANG_CONFTEST'?
rm -f conftest.s
else
ssp_strong_possible=no]
AC_MSG_RESULT([no])
[fi]
[# Global stack smashing protector.
ssp_global_possible=yes]
AC_MSG_CHECKING([whether `$CC' accepts `-mstack-protector-guard=global'])
# Is this a reliable test case?
AC_LANG_CONFTEST([AC_LANG_SOURCE([[
void foo (void) { volatile char a[8]; a[3]; }
]])])
[# `$CC -c -o ...' might not be portable. But, oh, well... Is calling
# `ac_compile' like this correct, after all?
if eval "$ac_compile -S -fstack-protector -mstack-protector-guard=global -o conftest.s" 2> /dev/null; then]
AC_MSG_RESULT([yes])
[# Should we clear up other files as well, having called `AC_LANG_CONFTEST'?
rm -f conftest.s
else
ssp_global_possible=no]
AC_MSG_RESULT([no])
[fi]
]) ])
dnl Check if the C compiler supports `-mstack-arg-probe' (Cygwin). dnl Check if the C compiler supports `-mstack-arg-probe' (Cygwin).
+1 -1
View File
@@ -13,7 +13,7 @@ fi
export LC_COLLATE=C export LC_COLLATE=C
unset LC_ALL unset LC_ALL
find . -iname '*.[ch]' ! -ipath './grub-core/lib/libgcrypt-grub/*' ! -ipath './build-aux/*' ! -ipath './grub-core/lib/libgcrypt/src/misc.c' ! -ipath './grub-core/lib/libgcrypt/src/global.c' ! -ipath './grub-core/lib/libgcrypt/src/secmem.c' ! -ipath './util/grub-gen-widthspec.c' ! -ipath './util/grub-gen-asciih.c' ! -ipath './gnulib/*' ! -iname './grub-core/lib/gnulib/*' |sort > po/POTFILES.in find . -iname '*.[ch]' ! -ipath './grub-core/lib/libgcrypt-grub/*' ! -ipath './build-aux/*' ! -ipath './grub-core/lib/libgcrypt/src/misc.c' ! -ipath './grub-core/lib/libgcrypt/src/global.c' ! -ipath './grub-core/lib/libgcrypt/src/secmem.c' ! -ipath './util/grub-gen-widthspec.c' ! -ipath './util/grub-gen-asciih.c' ! -ipath './gnulib/*' ! -ipath './grub-core/lib/gnulib/*' |sort > po/POTFILES.in
find util -iname '*.in' ! -name Makefile.in |sort > po/POTFILES-shell.in find util -iname '*.in' ! -name Makefile.in |sort > po/POTFILES-shell.in
echo "Importing unicode..." echo "Importing unicode..."
+11 -1
View File
@@ -23,6 +23,7 @@ GNULIB_REVISION=d271f868a8df9bbec29049d01e056481b7a1a263
# directly. # directly.
gnulib_modules=" gnulib_modules="
argp argp
base64
error error
fnmatch fnmatch
getdelim getdelim
@@ -78,10 +79,19 @@ cp -a INSTALL INSTALL.grub
bootstrap_post_import_hook () { bootstrap_post_import_hook () {
set -e set -e
for patchname in fix-null-deref fix-width no-abort; do for patchname in fix-base64 fix-null-deref fix-null-state-deref fix-regcomp-uninit-token \
fix-regexec-null-deref fix-uninit-structure fix-unused-value fix-width no-abort; do
patch -d grub-core/lib/gnulib -p2 \ patch -d grub-core/lib/gnulib -p2 \
< "grub-core/lib/gnulib-patches/$patchname.patch" < "grub-core/lib/gnulib-patches/$patchname.patch"
done done
for patchname in \
0001-Support-POTFILES-shell \
0002-Handle-gettext_printf-shell-function \
0003-Make-msgfmt-output-in-little-endian \
0004-Use-SHELL-rather-than-bin-sh; do
patch -d po -p3 \
< "po/gettext-patches/$patchname.patch"
done
FROM_BOOTSTRAP=1 ./autogen.sh FROM_BOOTSTRAP=1 ./autogen.sh
set +e # bootstrap expects this set +e # bootstrap expects this
} }
+2
View File
@@ -84,7 +84,9 @@ CPPFLAGS_PARTTOOL_LIST = -Dgrub_parttool_register=PARTTOOL_LIST_MARKER
CPPFLAGS_TERMINAL_LIST = '-Dgrub_term_register_input(...)=INPUT_TERMINAL_LIST_MARKER(__VA_ARGS__)' CPPFLAGS_TERMINAL_LIST = '-Dgrub_term_register_input(...)=INPUT_TERMINAL_LIST_MARKER(__VA_ARGS__)'
CPPFLAGS_TERMINAL_LIST += '-Dgrub_term_register_output(...)=OUTPUT_TERMINAL_LIST_MARKER(__VA_ARGS__)' CPPFLAGS_TERMINAL_LIST += '-Dgrub_term_register_output(...)=OUTPUT_TERMINAL_LIST_MARKER(__VA_ARGS__)'
CPPFLAGS_COMMAND_LIST = '-Dgrub_register_command(...)=COMMAND_LIST_MARKER(__VA_ARGS__)' CPPFLAGS_COMMAND_LIST = '-Dgrub_register_command(...)=COMMAND_LIST_MARKER(__VA_ARGS__)'
CPPFLAGS_COMMAND_LIST += '-Dgrub_register_command_lockdown(...)=COMMAND_LOCKDOWN_LIST_MARKER(__VA_ARGS__)'
CPPFLAGS_COMMAND_LIST += '-Dgrub_register_extcmd(...)=EXTCOMMAND_LIST_MARKER(__VA_ARGS__)' CPPFLAGS_COMMAND_LIST += '-Dgrub_register_extcmd(...)=EXTCOMMAND_LIST_MARKER(__VA_ARGS__)'
CPPFLAGS_COMMAND_LIST += '-Dgrub_register_extcmd_lockdown(...)=EXTCOMMAND_LOCKDOWN_LIST_MARKER(__VA_ARGS__)'
CPPFLAGS_COMMAND_LIST += '-Dgrub_register_command_p1(...)=P1COMMAND_LIST_MARKER(__VA_ARGS__)' CPPFLAGS_COMMAND_LIST += '-Dgrub_register_command_p1(...)=P1COMMAND_LIST_MARKER(__VA_ARGS__)'
CPPFLAGS_FDT_LIST := '-Dgrub_fdtbus_register(...)=FDT_DRIVER_LIST_MARKER(__VA_ARGS__)' CPPFLAGS_FDT_LIST := '-Dgrub_fdtbus_register(...)=FDT_DRIVER_LIST_MARKER(__VA_ARGS__)'
CPPFLAGS_MARKER = $(CPPFLAGS_FS_LIST) $(CPPFLAGS_VIDEO_LIST) \ CPPFLAGS_MARKER = $(CPPFLAGS_FS_LIST) $(CPPFLAGS_VIDEO_LIST) \
+21
View File
@@ -28,7 +28,13 @@ EXTRA_DIST += grub-core/gensymlist.sh
EXTRA_DIST += grub-core/genemuinit.sh 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-base64.patch
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-null-deref.patch EXTRA_DIST += grub-core/lib/gnulib-patches/fix-null-deref.patch
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-null-state-deref.patch
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-regcomp-uninit-token.patch
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-regexec-null-deref.patch
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-uninit-structure.patch
EXTRA_DIST += grub-core/lib/gnulib-patches/fix-unused-value.patch
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/no-abort.patch EXTRA_DIST += grub-core/lib/gnulib-patches/no-abort.patch
@@ -110,6 +116,21 @@ EXTRA_DIST += grub-core/osdep/windows/password.c
EXTRA_DIST += grub-core/osdep/windows/random.c EXTRA_DIST += grub-core/osdep/windows/random.c
EXTRA_DIST += grub-core/osdep/windows/sleep.c EXTRA_DIST += grub-core/osdep/windows/sleep.c
EXTRA_DIST += po/gettext-patches/0001-Support-POTFILES-shell.patch
EXTRA_DIST += po/gettext-patches/0002-Handle-gettext_printf-shell-function.patch
EXTRA_DIST += po/gettext-patches/0003-Make-msgfmt-output-in-little-endian.patch
EXTRA_DIST += po/gettext-patches/0004-Use-SHELL-rather-than-bin-sh.patch
EXTRA_DIST += po/POTFILES-shell.in
EXTRA_DIST += po/README
EXTRA_DIST += po/Rules-translit
EXTRA_DIST += po/Rules-windowsdir
EXTRA_DIST += po/arabic.sed
EXTRA_DIST += po/cyrillic.sed
EXTRA_DIST += po/greek.sed
EXTRA_DIST += po/grub.d.sed
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
+97 -34
View File
@@ -26,12 +26,15 @@ dnl This is necessary because the target type in autoconf does not
dnl describe such a system very well. dnl describe such a system very well.
dnl dnl
dnl The current strategy is to use variables with no prefix (such as dnl The current strategy is to use variables with no prefix (such as
dnl CC, CFLAGS, etc.) for the host type, variables with prefix "BUILD_" dnl CC, CFLAGS, etc.) for the host and target type, variables with
dnl (such as BUILD_CC, BUILD_CFLAGS, etc.) for the build type and variables dnl prefix "BUILD_" (such as BUILD_CC, BUILD_CFLAGS, etc.) for the
dnl with the prefix "TARGET_" (such as TARGET_CC, TARGET_CFLAGS, etc.) are dnl build type, variables with prefix "HOST_" (such as HOST_CC,
dnl used for the target type. See INSTALL for full list of variables. dnl HOST_CFLAGS, etc.) for the host type and variables with the prefix
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 description of the relationships between them.
AC_INIT([GRUB],[2.04~rc1],[bug-grub@gnu.org]) AC_INIT([GRUB],[2.06~rc1],[bug-grub@gnu.org])
AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_AUX_DIR([build-aux])
@@ -77,9 +80,15 @@ grub_TRANSFORM([grub-file])
# Optimization flag. Allow user to override. # Optimization flag. Allow user to override.
if test "x$TARGET_CFLAGS" = x; then if test "x$TARGET_CFLAGS" = x; then
TARGET_CFLAGS="$TARGET_CFLAGS -Os" TARGET_CFLAGS=-Os
fi fi
# Enable support for "restrict" keyword and other
# features from gnu99 C language standard.
BUILD_CFLAGS="-std=gnu99 $BUILD_CFLAGS"
HOST_CFLAGS="-std=gnu99 $HOST_CFLAGS"
TARGET_CFLAGS="-std=gnu99 $TARGET_CFLAGS"
# Default HOST_CPPFLAGS # Default HOST_CPPFLAGS
HOST_CPPFLAGS="$HOST_CPPFLAGS -Wall -W" HOST_CPPFLAGS="$HOST_CPPFLAGS -Wall -W"
HOST_CPPFLAGS="$HOST_CPPFLAGS -DGRUB_UTIL=1" HOST_CPPFLAGS="$HOST_CPPFLAGS -DGRUB_UTIL=1"
@@ -562,6 +571,24 @@ CPPFLAGS="$TARGET_CPPFLAGS"
LDFLAGS="$TARGET_LDFLAGS" LDFLAGS="$TARGET_LDFLAGS"
LIBS="" LIBS=""
if test "x$target_m32" = x1; then
# Force 32-bit mode.
TARGET_CFLAGS="$TARGET_CFLAGS -m32"
TARGET_CCASFLAGS="$TARGET_CCASFLAGS -m32"
TARGET_CPPFLAGS="$TARGET_CPPFLAGS -m32"
TARGET_LDFLAGS="$TARGET_LDFLAGS -m32"
TARGET_MODULE_FORMAT="elf32"
fi
if test "x$target_m64" = x1; then
# Force 64-bit mode.
TARGET_CFLAGS="$TARGET_CFLAGS -m64"
TARGET_CCASFLAGS="$TARGET_CCASFLAGS -m64"
TARGET_CPPFLAGS="$TARGET_CPPFLAGS -m64"
TARGET_LDFLAGS="$TARGET_LDFLAGS -m64"
TARGET_MODULE_FORMAT="elf64"
fi
# debug flags. # debug flags.
TARGET_CFLAGS="$TARGET_CFLAGS $WARN_FLAGS -g -Wredundant-decls -Wmissing-prototypes -Wmissing-declarations" TARGET_CFLAGS="$TARGET_CFLAGS $WARN_FLAGS -g -Wredundant-decls -Wmissing-prototypes -Wmissing-declarations"
TARGET_CCASFLAGS="$TARGET_CCASFLAGS -g" TARGET_CCASFLAGS="$TARGET_CCASFLAGS -g"
@@ -750,24 +777,6 @@ if test "x$target_cpu" = xi386 && test "x$platform" != xemu; then
TARGET_CFLAGS="$TARGET_CFLAGS -march=i386" TARGET_CFLAGS="$TARGET_CFLAGS -march=i386"
fi fi
if test "x$target_m32" = x1; then
# Force 32-bit mode.
TARGET_CFLAGS="$TARGET_CFLAGS -m32"
TARGET_CCASFLAGS="$TARGET_CCASFLAGS -m32"
TARGET_CPPFLAGS="$TARGET_CPPFLAGS -m32"
TARGET_LDFLAGS="$TARGET_LDFLAGS -m32"
TARGET_MODULE_FORMAT="elf32"
fi
if test "x$target_m64" = x1; then
# Force 64-bit mode.
TARGET_CFLAGS="$TARGET_CFLAGS -m64"
TARGET_CCASFLAGS="$TARGET_CCASFLAGS -m64"
TARGET_CPPFLAGS="$TARGET_CPPFLAGS -m64"
TARGET_LDFLAGS="$TARGET_LDFLAGS -m64"
TARGET_MODULE_FORMAT="elf64"
fi
if test "x$grub_cv_cc_target_clang" = xno && test "x$target_cpu" = xi386 && test "x$platform" != xemu && test "x$platform" != xefi; then if test "x$grub_cv_cc_target_clang" = xno && test "x$target_cpu" = xi386 && test "x$platform" != xemu && test "x$platform" != xefi; then
TARGET_CFLAGS="$TARGET_CFLAGS -mrtd -mregparm=3" TARGET_CFLAGS="$TARGET_CFLAGS -mrtd -mregparm=3"
fi fi
@@ -854,6 +863,11 @@ if test x"$platform" != xemu ; then
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[]])], AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[]])],
[grub_cv_target_cc_soft_float="-mno-inline-float-divide -mno-inline-sqrt"], []) [grub_cv_target_cc_soft_float="-mno-inline-float-divide -mno-inline-sqrt"], [])
fi fi
if test "x$target_cpu" = xsh4; then
CFLAGS="$TARGET_CFLAGS -m4-nofpu -Werror"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[]])],
[grub_cv_target_cc_soft_float="-m4-nofpu"], [])
fi
for cand in "-msoft-float -Xclang -msoft-float -Xclang -no-implicit-float" \ for cand in "-msoft-float -Xclang -msoft-float -Xclang -no-implicit-float" \
"-Xclang -msoft-float -Xclang -no-implicit-float" \ "-Xclang -msoft-float -Xclang -no-implicit-float" \
"-Xclang -msoft-float" "-msoft-float"; do "-Xclang -msoft-float" "-msoft-float"; do
@@ -999,6 +1013,17 @@ if test "x$grub_cv_cc_fno_unwind_tables" = xyes; then
TARGET_CFLAGS="$TARGET_CFLAGS -fno-unwind-tables" TARGET_CFLAGS="$TARGET_CFLAGS -fno-unwind-tables"
fi fi
# Do not generate .ident sections.
AC_CACHE_CHECK([whether -fno-ident works], [grub_cv_cc_fno_ident], [
CFLAGS="$TARGET_CFLAGS -fno-ident"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[]])],
[grub_cv_cc_fno_ident=yes],
[grub_cv_cc_fno_ident=no])
])
if test "x$grub_cv_cc_fno_ident" = xyes; then
TARGET_CFLAGS="$TARGET_CFLAGS -fno-ident"
fi
CFLAGS="$TARGET_CFLAGS" CFLAGS="$TARGET_CFLAGS"
@@ -1198,7 +1223,8 @@ if test "x$target_cpu" = xarm; then
AC_CACHE_CHECK([for options to disable movt and movw], grub_cv_target_cc_mno_movt, [ AC_CACHE_CHECK([for options to disable movt and movw], grub_cv_target_cc_mno_movt, [
grub_cv_target_cc_mno_movt=no grub_cv_target_cc_mno_movt=no
for cand in "-mno-movt" \ for cand in "-mno-movt" \
"-mllvm -arm-use-movt=0"; do "-mllvm -arm-use-movt=0" \
"-mword-relocations"; do
if test x"$grub_cv_target_cc_mno_movt" != xno ; then if test x"$grub_cv_target_cc_mno_movt" != xno ; then
break break
fi fi
@@ -1251,6 +1277,7 @@ grub_CHECK_LINK_PIE
# `-fPIE' or '-fpie' and '-pie' in the default specs. # `-fPIE' or '-fpie' and '-pie' in the default specs.
if [ x"$pie_possible" = xyes ]; then if [ x"$pie_possible" = xyes ]; then
TARGET_CFLAGS="$TARGET_CFLAGS -fno-PIE -fno-pie" TARGET_CFLAGS="$TARGET_CFLAGS -fno-PIE -fno-pie"
TARGET_CCASFLAGS="$TARGET_CCASFLAGS -fno-PIE -fno-pie"
fi fi
if [ x"$link_nopie_needed" = xyes ] || [ x"$pie_possible" = xyes ]; then if [ x"$link_nopie_needed" = xyes ] || [ x"$pie_possible" = xyes ]; then
@@ -1285,12 +1312,41 @@ fi]
CFLAGS="$TARGET_CFLAGS" CFLAGS="$TARGET_CFLAGS"
# Smashing stack protector. # Stack smashing protector.
grub_CHECK_STACK_PROTECTOR grub_CHECK_STACK_PROTECTOR
# Need that, because some distributions ship compilers that include AC_ARG_ENABLE([stack-protector],
# `-fstack-protector' in the default specs. AS_HELP_STRING([--enable-stack-protector],
if test "x$ssp_possible" = xyes; then [enable the stack protector]),
TARGET_CFLAGS="$TARGET_CFLAGS -fno-stack-protector" [],
[enable_stack_protector=no])
if test "x$enable_stack_protector" = xno; then
if test "x$ssp_possible" = xyes; then
# Need that, because some distributions ship compilers that include
# `-fstack-protector' in the default specs.
TARGET_CFLAGS="$TARGET_CFLAGS -fno-stack-protector"
fi
elif test "x$platform" != xefi; then
AC_MSG_ERROR([--enable-stack-protector is only supported on EFI platforms])
elif test "x$ssp_global_possible" != xyes; then
AC_MSG_ERROR([--enable-stack-protector is not supported (compiler doesn't support -mstack-protector-guard=global)])
else
TARGET_CFLAGS="$TARGET_CFLAGS -mstack-protector-guard=global"
if test "x$enable_stack_protector" = xyes; then
if test "x$ssp_possible" != xyes; then
AC_MSG_ERROR([--enable-stack-protector is not supported (compiler doesn't support -fstack-protector)])
fi
TARGET_CFLAGS="$TARGET_CFLAGS -fstack-protector"
elif test "x$enable_stack_protector" = xstrong; then
if test "x$ssp_strong_possible" != xyes; then
AC_MSG_ERROR([--enable-stack-protector=strong is not supported (compiler doesn't support -fstack-protector-strong)])
fi
TARGET_CFLAGS="$TARGET_CFLAGS -fstack-protector-strong"
else
# Note, -fstack-protector-all requires that the protector is disabled for
# functions that appear in the call stack when the canary is initialized.
AC_MSG_ERROR([invalid value $enable_stack_protector for --enable-stack-protector])
fi
TARGET_CPPFLAGS="$TARGET_CPPFLAGS -DGRUB_STACK_PROTECTOR=1"
fi fi
CFLAGS="$TARGET_CFLAGS" CFLAGS="$TARGET_CFLAGS"
@@ -1358,7 +1414,7 @@ fi
# Check for libgcc symbols # Check for libgcc symbols
if test x"$platform" = xemu; then if test x"$platform" = xemu; then
AC_CHECK_FUNCS(__udivsi3 __umodsi3 __divsi3 __modsi3 __divdi3 __moddi3 __udivdi3 __umoddi3 __ctzdi2 __ctzsi2 __aeabi_uidiv __aeabi_uidivmod __aeabi_idiv __aeabi_idivmod __aeabi_ulcmp __muldi3 __aeabi_lmul __aeabi_memcpy __aeabi_memcpy4 __aeabi_memcpy8 __aeabi_memclr __aeabi_memclr4 __aeabi_memclr8 __aeabi_memset __aeabi_lasr __aeabi_llsl __aeabi_llsr _restgpr_14_x __ucmpdi2 __ashldi3 __ashrdi3 __lshrdi3 __bswapsi2 __bswapdi2 __bzero __register_frame_info __deregister_frame_info ___chkstk_ms __chkstk_ms) AC_CHECK_FUNCS(__udivsi3 __umodsi3 __divsi3 __modsi3 __divdi3 __moddi3 __udivdi3 __umoddi3 __ctzdi2 __ctzsi2 __clzdi2 __aeabi_uidiv __aeabi_uidivmod __aeabi_idiv __aeabi_idivmod __aeabi_ulcmp __muldi3 __aeabi_lmul __aeabi_memcpy __aeabi_memcpy4 __aeabi_memcpy8 __aeabi_memclr __aeabi_memclr4 __aeabi_memclr8 __aeabi_memset __aeabi_lasr __aeabi_llsl __aeabi_llsr _restgpr_14_x __ucmpdi2 __ashldi3 __ashrdi3 __lshrdi3 __bswapsi2 __bswapdi2 __bzero __register_frame_info __deregister_frame_info ___chkstk_ms __chkstk_ms)
fi fi
if test "x$TARGET_APPLE_LINKER" = x1 ; then if test "x$TARGET_APPLE_LINKER" = x1 ; then
@@ -1435,9 +1491,11 @@ LIBS="$tmp_LIBS"
# Memory manager debugging. # Memory manager debugging.
AC_ARG_ENABLE([mm-debug], AC_ARG_ENABLE([mm-debug],
AS_HELP_STRING([--enable-mm-debug], AS_HELP_STRING([--enable-mm-debug],
[include memory manager debugging]), [include memory manager debugging]))
[AC_DEFINE([MM_DEBUG], [1], if test x$enable_mm_debug = xyes; then
[Define to 1 if you enable memory manager debugging.])]) AC_DEFINE([MM_DEBUG], [1],
[Define to 1 if you enable memory manager debugging.])
fi
AC_ARG_ENABLE([cache-stats], AC_ARG_ENABLE([cache-stats],
AS_HELP_STRING([--enable-cache-stats], AS_HELP_STRING([--enable-cache-stats],
@@ -2103,5 +2161,10 @@ echo "Without liblzma (no support for XZ-compressed mips images) ($liblzma_excus
else else
echo "With liblzma from $LIBLZMA (support for XZ-compressed mips images)" echo "With liblzma from $LIBLZMA (support for XZ-compressed mips images)"
fi fi
if test "x$enable_stack_protector" != xno; then
echo "With stack smashing protector: Yes"
else
echo "With stack smashing protector: No"
fi
echo "*******************************************************" echo "*******************************************************"
] ]
+99 -1
View File
@@ -86,6 +86,7 @@ This edition documents version @value{VERSION}.
* PFF2 Font File Format:: * PFF2 Font File Format::
* Graphical Menu Software Design:: * Graphical Menu Software Design::
* Verifiers framework:: * Verifiers framework::
* Lockdown framework::
* Copying This Manual:: Copying This Manual * Copying This Manual:: Copying This Manual
* Index:: * Index::
@end menu @end menu
@@ -490,6 +491,8 @@ to update it.
@menu @menu
* Gnulib:: * Gnulib::
* jsmn::
* minilzo::
@end menu @end menu
@node Gnulib @node Gnulib
@@ -511,6 +514,75 @@ To add a new Gnulib module or remove one that is no longer needed, change
@code{gnulib_modules} in @file{bootstrap.conf}. Again, run @kbd{./bootstrap} @code{gnulib_modules} in @file{bootstrap.conf}. Again, run @kbd{./bootstrap}
and whatever else you need to make sure it works. and whatever else you need to make sure it works.
Bootstrapping from an older distribution containing gettext version < 0.18.3,
will require a patch similar to this to be applied first before running the
@command{./bootstrap} utility:
@example
diff --git a/bootstrap.conf b/bootstrap.conf
index 988dda0..a3193a9 100644
--- a/bootstrap.conf
+++ b/bootstrap.conf
@@ -67,7 +67,7 @@ SKIP_PO=t
buildreq="\
autoconf 2.63
automake 1.11
-gettext 0.18.3
+gettext 0.17
git 1.5.5
tar -
"
diff --git a/configure.ac b/configure.ac
index 08b518f..99f5b36 100644
--- a/configure.ac
+++ b/configure.ac
@@ -362,7 +362,7 @@ AC_CHECK_PROG(HAVE_CXX, $CXX, yes, no)
AC_GNU_SOURCE
AM_GNU_GETTEXT([external])
-AM_GNU_GETTEXT_VERSION([0.18.3])
+AM_GNU_GETTEXT_VERSION([0.17])
AC_SYS_LARGEFILE
# Identify characteristics of the host architecture.
@end example
It will also be necessary to adjust the patches in
@file{po/gettext-patches/} to apply to an older version of gettext.
@node jsmn
@section jsmn
jsmn is a minimalistic JSON parser which is implemented in a single header file
@file{jsmn.h}. To import a different version of the jsmn parser, you may simply
download the @file{jsmn.h} header from the desired tag or commit to the target
directory:
@example
curl -L https://raw.githubusercontent.com/zserge/jsmn/v1.1.0/jsmn.h \
-o grub-core/lib/json/jsmn.h
@end example
@node minilzo
@section minilzo
miniLZO is a very lightweight subset of the LZO library intended for easy
inclusion in other projects. It is generated automatically from the LZO
source code and contains the most important LZO functions.
To upgrade to a new version of the miniLZO library, download the release
tarball and copy the files into the target directory:
@example
curl -L -O http://www.oberhumer.com/opensource/lzo/download/minilzo-2.08.tar.gz
tar -zxf minilzo-2.08.tar.gz
rm minilzo-2.08/testmini.c
rm -r grub-core/lib/minilzo/*
cp minilzo-2.08/*.[hc] grub-core/lib/minilzo
rm -r minilzo-2.08*
@end example
@node Porting @node Porting
@chapter Porting @chapter Porting
@@ -748,7 +820,7 @@ 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 are string of keys, terminfo and direct hardware. For string
of keys look at i386-pc (same files), for termino ieee1275 (same files) and for of keys look at i386-pc (same files), for terminfo ieee1275 (same files) and for
hardware loongson (kern/mips/loongson/init.c and term/at_keyboard.c). hardware loongson (kern/mips/loongson/init.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 as sole
@@ -2052,6 +2124,32 @@ Optionally at the end of the file @samp{fini}, if it exists, is called with just
the context. If you return no error during any of @samp{init}, @samp{write} and the context. If you return no error during any of @samp{init}, @samp{write} and
@samp{fini} then the file is considered as having succeded verification. @samp{fini} then the file is considered as having succeded verification.
@node Lockdown framework
@chapter Lockdown framework
The GRUB can be locked down, which is a restricted mode where some operations
are not allowed. For instance, some commands cannot be used when the GRUB is
locked down.
The function
@code{grub_lockdown()} is used to lockdown GRUB and the function
@code{grub_is_lockdown()} function can be used to check whether lockdown is
enabled or not. When enabled, the function returns @samp{GRUB_LOCKDOWN_ENABLED}
and @samp{GRUB_LOCKDOWN_DISABLED} when is not enabled.
The following functions can be used to register the commands that can only be
used when lockdown is disabled:
@itemize
@item @code{grub_cmd_lockdown()} registers command which should not run when the
GRUB is in lockdown mode.
@item @code{grub_cmd_lockdown()} registers extended command which should not run
when the GRUB is in lockdown mode.
@end itemize
@node Copying This Manual @node Copying This Manual
@appendix Copying This Manual @appendix Copying This Manual
+394 -132
View File
@@ -695,13 +695,6 @@ floppy instead of exposing the USB drive as a hard disk (they call it
This install doesn't conflict with standard install as long as they are in This install doesn't conflict with standard install as long as they are in
separate directories. separate directories.
Note that @command{grub-install} is actually just a shell script and the
real task is done by other tools such as @command{grub-mkimage}. Therefore,
you may run those commands directly to install GRUB, without using
@command{grub-install}. Don't do that, however, unless you are very familiar
with the internals of GRUB. Installing a boot loader on a running OS may be
extremely dangerous.
On EFI systems for fixed disk install you have to mount EFI System Partition. On EFI systems for fixed disk install you have to mount EFI System Partition.
If you mount it at @file{/boot/efi} then you don't need any special arguments: If you mount it at @file{/boot/efi} then you don't need any special arguments:
@@ -829,25 +822,46 @@ four primary partitions and additional logical partitions. With this
partition table format, there are two ways to install GRUB: it can be partition table format, there are two ways to install GRUB: it can be
embedded in the area between the MBR and the first partition (called by embedded in the area between the MBR and the first partition (called by
various names, such as the "boot track", "MBR gap", or "embedding area", and various names, such as the "boot track", "MBR gap", or "embedding area", and
which is usually at least 31 KiB), or the core image can be installed in a which is usually at least 1000 KiB), or the core image can be installed in a
file system and a list of the blocks that make it up can be stored in the file system and a list of the blocks that make it up can be stored in the
first sector of that partition. first sector of that partition.
Each of these has different problems. There is no way to reserve space in Modern tools usually leave MBR gap of at least 1023 KiB. This amount is
sufficient to cover most configurations. Hence this value is recommended
by the GRUB team.
Historically many tools left only 31 KiB of space. This is not enough to
parse reliably difficult structures like Btrfs, ZFS, RAID or LVM, or to
use difficult disk access methods like ahci. Hence GRUB will warn if attempted
to install into small MBR gap except in a small number of configurations
that were grandfathered. The grandfathered config must:
* use biosdisk as disk access module for @file{/boot}
* not use any additional partition maps to access @file{/boot}
* @file{/boot} must be on one of following filesystems:
* AFFS, AFS, BFS, cpio, newc, odc, ext2/3/4, FAT, exFAT,
F2FS, HFS, uncompressed HFS+, ISO9660, JFS, Minix, Minix2, Minix3, NILFS2,
NTFS, ReiserFS, ROMFS, SFS, tar, UDF, UFS1, UFS2, XFS
MBR gap has few technical problems. There is no way to reserve space in
the embedding area with complete safety, and some proprietary software is the embedding area with complete safety, and some proprietary software is
known to use it to make it difficult for users to work around licensing known to use it to make it difficult for users to work around licensing
restrictions; and systems are sometimes partitioned without leaving enough restrictions. GRUB works it around by detecting sectors by other software and
space before the first partition. On the other hand, installing to a avoiding them and protecting its own sectors using Reed-Solomon encoding.
filesystem means that GRUB is vulnerable to its blocks being moved around by
filesystem features such as tail packing, or even by aggressive fsck GRUB team recommends having MBR gap of at least 1000 KiB
implementations, so this approach is quite fragile; and this approach can
only be used if the @file{/boot} filesystem is on the same disk that the Should it be not possible GRUB has support for a fallback solution which is
BIOS boots from, so that GRUB does not have to rely on guessing BIOS drive heavily recommended against. Installing to a filesystem means that GRUB is
numbers. vulnerable to its blocks being moved around by filesystem features such as
tail packing, or even by aggressive fsck implementations, so this approach
is quite fragile; and this approach can only be used if the @file{/boot}
filesystem is on the same disk that the BIOS boots from, so that GRUB does
not have to rely on guessing BIOS drive numbers.
The GRUB development team generally recommends embedding GRUB before the The GRUB development team generally recommends embedding GRUB before the
first partition, unless you have special requirements. You must ensure that first partition, unless you have special requirements. You must ensure that
the first partition starts at least 31 KiB (63 sectors) from the start of the first partition starts at least 1000 KiB (2000 sectors) from the start of
the disk; on modern disks, it is often a performance advantage to align the disk; on modern disks, it is often a performance advantage to align
partitions on larger boundaries anyway, so the first partition might start 1 partitions on larger boundaries anyway, so the first partition might start 1
MiB from the start of the disk. MiB from the start of the disk.
@@ -894,6 +908,7 @@ magic.
@menu @menu
* General boot methods:: How to boot OSes with GRUB generally * General boot methods:: How to boot OSes with GRUB generally
* Loopback booting:: Notes on booting from loopbacks * Loopback booting:: Notes on booting from loopbacks
* LVM cache booting:: Notes on booting from LVM cache logical volume
* OS-specific notes:: Notes on some operating systems * OS-specific notes:: Notes on some operating systems
@end menu @end menu
@@ -991,6 +1006,26 @@ way. Please consider alternative boot methods like copying all files
from the image to actual partition. Consult your OS documentation for from the image to actual partition. Consult your OS documentation for
more details more details
@node LVM cache booting
@section Booting from LVM cache logical volume
The LVM cache logical volume is the logical volume consisting of the original
and the cache pool logical volume. The original is usually on a larger and
slower storage device while the cache pool is on a smaller and faster one. The
performance of the original volume can be improved by storing the frequently
used data on the cache pool to utilize the greater performance of faster
device.
GRUB boots from LVM cache logical volume merely by reading it's original
logical volume so that dirty data in cache pool volume is disregarded. This is
not a problem for "writethrough" cache mode as it ensures that any data written
will be stored both on the cache and the origin LV. For the other cache mode
"writeback", which delays writing from the cache pool back to the origin LV to
boost performance, GRUB may fail to boot in the wake of accidental power outage
due to it's inability to assemble the cache device for reading the required
dirty data left behind. The situation will be improved after adding full
support to the LVM cache logical volume in the future.
@node OS-specific notes @node OS-specific notes
@section Some caveats on OS-specific issues @section Some caveats on OS-specific issues
@@ -1093,12 +1128,6 @@ grub> @kbd{initrd16 /initrd}
Finally, run the command @command{boot} (@pxref{boot}). Finally, run the command @command{boot} (@pxref{boot}).
@end enumerate @end enumerate
@strong{Caution:} If you use an initrd and specify the @samp{mem=}
option to the kernel to let it use less than actual memory size, you
will also have to specify the same memory size to GRUB. To let GRUB know
the size, run the command @command{uppermem} @emph{before} loading the
kernel. @xref{uppermem}, for more information.
@node NetBSD @node NetBSD
@subsection NetBSD @subsection NetBSD
@@ -1309,12 +1338,12 @@ menu and then wait for the timeout set by @samp{GRUB_TIMEOUT} to expire
before booting the default entry. Pressing a key interrupts the timeout. before booting the default entry. Pressing a key interrupts the timeout.
If this option is set to @samp{countdown} or @samp{hidden}, then, before If this option is set to @samp{countdown} or @samp{hidden}, then, before
displaying the menu, GRUB will wait for the timeout set by displaying the menu, GRUB will wait for the timeout set by @samp{GRUB_TIMEOUT}
@samp{GRUB_TIMEOUT} to expire. If @key{ESC} is pressed during that time, it to expire. If @key{ESC} or @key{F4} are pressed, or @key{SHIFT} is held down
will display the menu and wait for input. If a hotkey associated with a during that time, it will display the menu and wait for input. If a hotkey
menu entry is pressed, it will boot the associated menu entry immediately. associated with a menu entry is pressed, it will boot the associated menu entry
If the timeout expires before either of these happens, it will boot the immediately. If the timeout expires before either of these happens, it will
default entry. In the @samp{countdown} case, it will show a one-line boot the default entry. In the @samp{countdown} case, it will show a one-line
indication of the remaining time. indication of the remaining time.
@item GRUB_DEFAULT_BUTTON @item GRUB_DEFAULT_BUTTON
@@ -1441,6 +1470,15 @@ enable the use of partition UUIDs, set this option to @samp{false}.
If this option is set to @samp{true}, disable the generation of recovery If this option is set to @samp{true}, disable the generation of recovery
mode menu entries. mode menu entries.
@item GRUB_DISABLE_UUID
Normally, @command{grub-mkconfig} will generate menu entries that use
universally-unique identifiers (UUIDs) to identify various filesystems to
search for files. This is usually more reliable, but in some cases it may
not be appropriate. To disable this use of UUIDs, set this option to
@samp{true}. Setting this option to @samp{true}, will also set the options
@samp{GRUB_DISABLE_LINUX_UUID} and @samp{GRUB_DISABLE_LINUX_PARTUUID} to
@samp{true}, unless they have been explicilty set to @samp{false}.
@item GRUB_VIDEO_BACKEND @item GRUB_VIDEO_BACKEND
If graphical video support is required, either because the @samp{gfxterm} If graphical video support is required, either because the @samp{gfxterm}
graphical terminal is in use or because @samp{GRUB_GFXPAYLOAD_LINUX} is set, graphical terminal is in use or because @samp{GRUB_GFXPAYLOAD_LINUX} is set,
@@ -1481,10 +1519,13 @@ boot sequence. If you have problems, set this option to @samp{text} and
GRUB will tell Linux to boot in normal text mode. GRUB will tell Linux to boot in normal text mode.
@item GRUB_DISABLE_OS_PROBER @item GRUB_DISABLE_OS_PROBER
Normally, @command{grub-mkconfig} will try to use the external The @command{grub-mkconfig} has a feature to use the external
@command{os-prober} program, if installed, to discover other operating @command{os-prober} program to discover other operating systems installed on
systems installed on the same system and generate appropriate menu entries the same machine and generate appropriate menu entries for them. It is disabled
for them. Set this option to @samp{true} to disable this. by default since automatic and silent execution of @command{os-prober}, and
creating boot entries based on that data, is a potential attack vector. Set
this option to @samp{false} to enable this feature in the
@command{grub-mkconfig} command.
@item GRUB_OS_PROBER_SKIP_LIST @item GRUB_OS_PROBER_SKIP_LIST
List of space-separated FS UUIDs of filesystems to be ignored from os-prober List of space-separated FS UUIDs of filesystems to be ignored from os-prober
@@ -1495,7 +1536,7 @@ Normally, @command{grub-mkconfig} will generate top level menu entry for
the kernel with highest version number and put all other found kernels the kernel with highest version number and put all other found kernels
or alternative menu entries for recovery mode in submenu. For entries returned or alternative menu entries for recovery mode in submenu. For entries returned
by @command{os-prober} first entry will be put on top level and all others by @command{os-prober} first entry will be put on top level and all others
in submenu. If this option is set to @samp{y}, flat menu with all entries in submenu. If this option is set to @samp{true}, flat menu with all entries
on top level will be generated instead. Changing this option will require on top level will be generated instead. Changing this option will require
changing existing values of @samp{GRUB_DEFAULT}, @samp{fallback} (@pxref{fallback}) changing existing values of @samp{GRUB_DEFAULT}, @samp{fallback} (@pxref{fallback})
and @samp{default} (@pxref{default}) environment variables as well as saved and @samp{default} (@pxref{default}) environment variables as well as saved
@@ -1529,16 +1570,16 @@ configurations, but have better replacements:
@table @samp @table @samp
@item GRUB_HIDDEN_TIMEOUT @item GRUB_HIDDEN_TIMEOUT
Wait this many seconds before displaying the menu. If @key{ESC} is pressed Wait this many seconds before displaying the menu. If @key{ESC} or @key{F4} are
during that time, display the menu and wait for input according to pressed, or @key{SHIFT} is held down during that time, display the menu and wait
@samp{GRUB_TIMEOUT}. If a hotkey associated with a menu entry is pressed, for input according to @samp{GRUB_TIMEOUT}. If a hotkey associated with a menu
boot the associated menu entry immediately. If the timeout expires before entry is pressed, boot the associated menu entry immediately. If the timeout
either of these happens, display the menu for the number of seconds expires before either of these happens, display the menu for the number of
specified in @samp{GRUB_TIMEOUT} before booting the default entry. seconds specified in @samp{GRUB_TIMEOUT} before booting the default entry.
If you set @samp{GRUB_HIDDEN_TIMEOUT}, you should also set If you set @samp{GRUB_HIDDEN_TIMEOUT}, you should also set
@samp{GRUB_TIMEOUT=0} so that the menu is not displayed at all unless @samp{GRUB_TIMEOUT=0} so that the menu is not displayed at all unless
@key{ESC} is pressed. @key{ESC} or @key{F4} are pressed, or @key{SHIFT} is held down.
This option is unset by default, and is deprecated in favour of the less This option is unset by default, and is deprecated in favour of the less
confusing @samp{GRUB_TIMEOUT_STYLE=countdown} or confusing @samp{GRUB_TIMEOUT_STYLE=countdown} or
@@ -1812,10 +1853,9 @@ than zero; otherwise 0.
@section Multi-boot manual config @section Multi-boot manual config
Currently autogenerating config files for multi-boot environments depends on Currently autogenerating config files for multi-boot environments depends on
os-prober and has several shortcomings. While fixing it is scheduled for the os-prober and has several shortcomings. Due to that it is disabled by default.
next release, meanwhile you can make use of the power of GRUB syntax and do it It is advised to use the power of GRUB syntax and do it yourself. A possible
yourself. A possible configuration is detailed here, feel free to adjust to your configuration is detailed here, feel free to adjust to your needs.
needs.
First create a separate GRUB partition, big enough to hold GRUB. Some of the First create a separate GRUB partition, big enough to hold GRUB. Some of the
following entries show how to load OS installer images from this same partition, following entries show how to load OS installer images from this same partition,
@@ -2486,6 +2526,57 @@ grub-mknetdir --net-directory=/srv/tftp --subdir=/boot/grub -d /usr/lib/grub/i38
Then follow instructions printed out by grub-mknetdir on configuring your DHCP Then follow instructions printed out by grub-mknetdir on configuring your DHCP
server. server.
The grub.cfg file is placed in the same directory as the path output by
grub-mknetdir hereafter referred to as FWPATH. GRUB will search for its
configuration files in order using the following rules where the appended
value corresponds to a value on the client machine.
@example
@group
@samp{(FWPATH)}/grub.cfg-@samp{(UUID OF MACHINE)}
@samp{(FWPATH)}/grub.cfg-@samp{(MAC ADDRESS OF NIC)}
@samp{(FWPATH)}/grub.cfg-@samp{(IPv4 OR IPv6 ADDRESS)}
@samp{(FWPATH)}/grub.cfg
@end group
@end example
The UUID is the Client Machine Identifier Option Definition as specified in
RFC 4578. The client will only attempt to loouk up a UUID config file if it
was provided by the DHCP server.
The client will only attempt to look up an IPv6 address config once, however,
it will try the IPv4 multiple times. The concrete example below shows what
would happen under the IPv4 case.
@example
@group
UUID: 7726a678-7fc0-4853-a4f6-c85ac36a120a
MAC: 52:54:00:ec:33:81
IPV4: 10.0.0.130 (0A000082)
@end group
@end example
@example
@group
@samp{(FWPATH)}/grub.cfg-7726a678-7fc0-4853-a4f6-c85ac36a120a
@samp{(FWPATH)}/grub.cfg-52-54-00-ec-33-81
@samp{(FWPATH)}/grub.cfg-0A000082
@samp{(FWPATH)}/grub.cfg-0A00008
@samp{(FWPATH)}/grub.cfg-0A0000
@samp{(FWPATH)}/grub.cfg-0A000
@samp{(FWPATH)}/grub.cfg-0A00
@samp{(FWPATH)}/grub.cfg-0A0
@samp{(FWPATH)}/grub.cfg-0A
@samp{(FWPATH)}/grub.cfg-0
@samp{(FWPATH)}/grub.cfg
@end group
@end example
This feature is enabled by default but it can be disabled by setting the
@samp{feature_net_search_cfg} to @samp{n}. Since this happens before the
configuration file is read by GRUB, this option has to be disabled in an
embedded configuration file (@pxref{Embedded configuration}).
After GRUB has started, files on the TFTP server will be accessible via the After GRUB has started, files on the TFTP server will be accessible via the
@samp{(tftp)} device. @samp{(tftp)} device.
@@ -3843,7 +3934,7 @@ names active.
@node terminfo @node terminfo
@subsection terminfo @subsection terminfo
@deffn Command terminfo [-a|-u|-v] [term] @deffn Command terminfo [@option{-a}|@option{-u}|@option{-v}] [@option{-g WxH}] [term] [type]
Define the capabilities of your terminal by giving the name of an entry in Define the capabilities of your terminal by giving the name of an entry in
the terminfo database, which should correspond roughly to a @samp{TERM} the terminfo database, which should correspond roughly to a @samp{TERM}
environment variable in Unix. environment variable in Unix.
@@ -3860,6 +3951,8 @@ specifies logically-ordered UTF-8; and @option{-v} specifies
emulator without bidirectional text support will display right-to-left text emulator without bidirectional text support will display right-to-left text
in the proper order; this is not really proper UTF-8, but a workaround). in the proper order; this is not really proper UTF-8, but a workaround).
The @option{-g} (@option{--geometry}) can be used to specify terminal geometry.
If no option or terminal type is specified, the current terminal type is If no option or terminal type is specified, the current terminal type is
printed. printed.
@end deffn @end deffn
@@ -3892,6 +3985,7 @@ you forget a command, you can run the command @command{help}
* cpuid:: Check for CPU features * cpuid:: Check for CPU features
* crc:: Compute or check CRC32 checksums * crc:: Compute or check CRC32 checksums
* cryptomount:: Mount a crypto device * cryptomount:: Mount a crypto device
* cutmem:: Remove memory regions
* date:: Display or set current date and time * date:: Display or set current date and time
* devicetree:: Load a device tree blob * devicetree:: Load a device tree blob
* distrust:: Remove a pubkey from trusted keys * distrust:: Remove a pubkey from trusted keys
@@ -3930,7 +4024,6 @@ you forget a command, you can run the command @command{help}
* password_pbkdf2:: Set a hashed password * password_pbkdf2:: Set a hashed password
* play:: Play a tune * play:: Play a tune
* probe:: Retrieve device info * probe:: Retrieve device info
* pxe_unload:: Unload the PXE environment
* rdmsr:: Read values from model-specific registers * rdmsr:: Read values from model-specific registers
* read:: Read user input * read:: Read user input
* reboot:: Reboot your computer * reboot:: Reboot your computer
@@ -3944,12 +4037,12 @@ you forget a command, you can run the command @command{help}
* sha256sum:: Compute or check SHA256 hash * sha256sum:: Compute or check SHA256 hash
* sha512sum:: Compute or check SHA512 hash * sha512sum:: Compute or check SHA512 hash
* sleep:: Wait for a specified number of seconds * sleep:: Wait for a specified number of seconds
* smbios:: Retrieve SMBIOS information
* source:: Read a configuration file in same context * source:: Read a configuration file in same context
* test:: Check file types and compare values * test:: Check file types and compare values
* true:: Do nothing, successfully * true:: Do nothing, successfully
* trust:: Add public key to list of trusted keys * trust:: Add public key to list of trusted keys
* unset:: Unset an environment variable * unset:: Unset an environment variable
* uppermem:: Set the upper memory size
@comment * vbeinfo:: List available video modes @comment * vbeinfo:: List available video modes
* verify_detached:: Verify detached digital signature * verify_detached:: Verify detached digital signature
* videoinfo:: List available video modes * videoinfo:: List available video modes
@@ -3986,6 +4079,11 @@ Normally, this command will replace the Root System Description Pointer
(RSDP) in the Extended BIOS Data Area to point to the new tables. If the (RSDP) in the Extended BIOS Data Area to point to the new tables. If the
@option{--no-ebda} option is used, the new tables will be known only to @option{--no-ebda} option is used, the new tables will be known only to
GRUB, but may be used by GRUB's EFI emulation. GRUB, but may be used by GRUB's EFI emulation.
Note: The command is not allowed when lockdown is enforced (@pxref{Lockdown}).
Otherwise an attacker can instruct the GRUB to load an SSDT table to
overwrite the kernel lockdown configuration and later load and execute
unsigned code.
@end deffn @end deffn
@@ -4029,7 +4127,6 @@ can be changed only when using @samp{gfxterm} for terminal output.
@deffn Command badram addr,mask[,addr,mask...] @deffn Command badram addr,mask[,addr,mask...]
Filter out bad RAM. Filter out bad RAM.
@end deffn
This command notifies the memory manager that specified regions of This command notifies the memory manager that specified regions of
RAM ought to be filtered out (usually, because they're damaged). This RAM ought to be filtered out (usually, because they're damaged). This
@@ -4046,6 +4143,13 @@ this page is to be filtered. This syntax makes it easy to represent patterns
that are often result of memory damage, due to physical distribution of memory that are often result of memory damage, due to physical distribution of memory
cells. cells.
The command is similar to @command{cutmem} command.
Note: The command is not allowed when lockdown is enforced (@pxref{Lockdown}).
This prevents removing EFI memory regions to potentially subvert the
security mechanisms provided by the UEFI secure boot.
@end deffn
@node blocklist @node blocklist
@subsection blocklist @subsection blocklist
@@ -4201,10 +4305,33 @@ is requested interactively. Option @var{device} configures specific grub device
with specified @var{uuid}; option @option{-a} configures all detected encrypted with specified @var{uuid}; option @option{-a} configures all detected encrypted
devices; option @option{-b} configures all geli containers that have boot flag set. devices; option @option{-b} configures all geli containers that have boot flag set.
GRUB suports devices encrypted using LUKS and geli. Note that necessary modules (@var{luks} and @var{geli}) have to be loaded manually before this command can GRUB suports devices encrypted using LUKS, LUKS2 and geli. Note that necessary
be used. modules (@var{luks}, @var{luks2} and @var{geli}) have to be loaded manually
before this command can be used. For LUKS2 only the PBKDF2 key derivation
function is supported, as Argon2 is not yet supported.
Also, note that, unlike filesystem UUIDs, UUIDs for encrypted devices must be
specified without dash separators.
@end deffn @end deffn
@node cutmem
@subsection cutmem
@deffn Command cutmem from[K|M|G] to[K|M|G]
Remove any memory regions in specified range.
This command notifies the memory manager that specified regions of RAM ought to
be filtered out. This remains in effect after a payload kernel has been loaded
by GRUB, as long as the loaded kernel obtains its memory map from GRUB. Kernels
that support this include Linux, GNU Mach, the kernel of FreeBSD and Multiboot
kernels in general.
The command is similar to @command{badram} command.
Note: The command is not allowed when lockdown is enforced (@pxref{Lockdown}).
This prevents removing EFI memory regions to potentially subvert the
security mechanisms provided by the UEFI secure boot.
@end deffn
@node date @node date
@subsection date @subsection date
@@ -4220,13 +4347,15 @@ hour, minute, and second unchanged.
@node devicetree @node devicetree
@subsection linux @subsection devicetree
@deffn Command devicetree file @deffn Command devicetree file
Load a device tree blob (.dtb) from a filesystem, for later use by a Linux Load a device tree blob (.dtb) from a filesystem, for later use by a Linux
kernel. Does not perform merging with any device tree supplied by firmware, kernel. Does not perform merging with any device tree supplied by firmware,
but rather replaces it completely. but rather replaces it completely.
@ref{GNU/Linux}.
Note: The command is not allowed when lockdown is enforced (@pxref{Lockdown}).
This is done to prevent subverting various security mechanisms.
@end deffn @end deffn
@node distrust @node distrust
@@ -4423,22 +4552,22 @@ about each of the commands whose names begin with those @var{patterns}.
@node initrd @node initrd
@subsection initrd @subsection initrd
@deffn Command initrd file @deffn Command initrd file [file @dots{}]
Load an initial ramdisk for a Linux kernel image, and set the appropriate Load, in order, all initial ramdisks for a Linux kernel image, and set
parameters in the Linux setup area in memory. This may only be used after the appropriate parameters in the Linux setup area in memory. This may only
the @command{linux} command (@pxref{linux}) has been run. See also be used after the @command{linux} command (@pxref{linux}) has been run. See
@ref{GNU/Linux}. also @ref{GNU/Linux}.
@end deffn @end deffn
@node initrd16 @node initrd16
@subsection initrd16 @subsection initrd16
@deffn Command initrd16 file @deffn Command initrd16 file [file @dots{}]
Load an initial ramdisk for a Linux kernel image to be booted in 16-bit Load, in order, all initial ramdisks for a Linux kernel image to be booted in
mode, and set the appropriate parameters in the Linux setup area in memory. 16-bit mode, and set the appropriate parameters in the Linux setup area in
This may only be used after the @command{linux16} command (@pxref{linux16}) memory. This may only be used after the @command{linux16} command
has been run. See also @ref{GNU/Linux}. (@pxref{linux16}) has been run. See also @ref{GNU/Linux}.
This command is only available on x86 systems. This command is only available on x86 systems.
@end deffn @end deffn
@@ -4646,7 +4775,7 @@ be reloaded after using this command (@pxref{module}).
Some kernels have known problems. You need to specify --quirk-* for those. Some kernels have known problems. You need to specify --quirk-* for those.
--quirk-bad-kludge is a problem seen in several products that they include --quirk-bad-kludge is a problem seen in several products that they include
loading kludge information with invalid data in ELF file. GRUB prior to 0.97 loading kludge information with invalid data in ELF file. GRUB prior to 0.97
and some custom builds prefered ELF information while 0.97 and GRUB 2 and some custom builds preferred ELF information while 0.97 and GRUB 2
use kludge. Use this option to ignore kludge. use kludge. Use this option to ignore kludge.
Known affected systems: old Solaris, SkyOS. Known affected systems: old Solaris, SkyOS.
@@ -4771,19 +4900,11 @@ a rest.
@node probe @node probe
@subsection probe @subsection probe
@deffn Command probe [@option{--set} var] @option{--driver}|@option{--partmap}|@option{--fs}|@option{--fs-uuid}|@option{--label} device @deffn Command probe [@option{--set} var] @option{--driver}|@option{--partmap}|@option{--fs}|@option{--fs-uuid}|@option{--label}|@option{--part-uuid} device
Retrieve device information. If option @option{--set} is given, assign result Retrieve device information. If option @option{--set} is given, assign result
to variable @var{var}, otherwise print information on the screen. to variable @var{var}, otherwise print information on the screen.
@end deffn
The option @option{--part-uuid} is currently only implemented for MSDOS and GPT formatted disks.
@node pxe_unload
@subsection pxe_unload
@deffn Command pxe_unload
Unload the PXE environment (@pxref{Network}).
This command is only available on PC BIOS systems.
@end deffn @end deffn
@@ -5077,9 +5198,84 @@ Alias for @code{hashsum --hash sha512 arg @dots{}}. See command @command{hashsum
@deffn Command sleep [@option{--verbose}] [@option{--interruptible}] count @deffn Command sleep [@option{--verbose}] [@option{--interruptible}] count
Sleep for @var{count} seconds. If option @option{--interruptible} is given, Sleep for @var{count} seconds. If option @option{--interruptible} is given,
allow @key{ESC} to interrupt sleep. With @option{--verbose} show countdown allow pressing @key{ESC}, @key{F4} or holding down @key{SHIFT} to interrupt
of remaining seconds. Exit code is set to 0 if timeout expired and to 1 sleep. With @option{--verbose} show countdown of remaining seconds. Exit code
if timeout was interrupted by @key{ESC}. is set to 0 if timeout expired and to 1 if timeout was interrupted using any
of the mentioned keys.
@end deffn
@node smbios
@subsection smbios
@deffn Command smbios @
[@option{--type} @var{type}] @
[@option{--handle} @var{handle}] @
[@option{--match} @var{match}] @
(@option{--get-byte} | @option{--get-word} | @option{--get-dword} | @
@option{--get-qword} | @option{--get-string} | @option{--get-uuid}) @
@var{offset} @
[@option{--set} @var{variable}]
Retrieve SMBIOS information.
The @command{smbios} command returns the value of a field in an SMBIOS
structure. The following options determine which structure to select.
@itemize @bullet
@item
Specifying @option{--type} will select structures with a matching
@var{type}. The type can be any integer from 0 to 255.
@item
Specifying @option{--handle} will select structures with a matching
@var{handle}. The handle can be any integer from 0 to 65535.
@item
Specifying @option{--match} will select structure number @var{match} in the
filtered list of structures; e.g. @code{smbios --type 4 --match 2} will select
the second Process Information (Type 4) structure. The list is always ordered
the same as the hardware's SMBIOS table. The match number must be a positive
integer. If unspecified, the first matching structure will be selected.
@end itemize
The remaining options determine which field in the selected SMBIOS structure to
return. Only one of these options may be specified at a time.
@itemize @bullet
@item
When given @option{--get-byte}, return the value of the byte
at @var{offset} bytes into the selected SMBIOS structure.
It will be formatted as an unsigned decimal integer.
@item
When given @option{--get-word}, return the value of the word (two bytes)
at @var{offset} bytes into the selected SMBIOS structure.
It will be formatted as an unsigned decimal integer.
@item
When given @option{--get-dword}, return the value of the dword (four bytes)
at @var{offset} bytes into the selected SMBIOS structure.
It will be formatted as an unsigned decimal integer.
@item
When given @option{--get-qword}, return the value of the qword (eight bytes)
at @var{offset} bytes into the selected SMBIOS structure.
It will be formatted as an unsigned decimal integer.
@item
When given @option{--get-string}, return the string with its index found
at @var{offset} bytes into the selected SMBIOS structure.
@item
When given @option{--get-uuid}, return the value of the UUID (sixteen bytes)
at @var{offset} bytes into the selected SMBIOS structure.
It will be formatted as lower-case hyphenated hexadecimal digits, with the
first three fields as little-endian, and the rest printed byte-by-byte.
@end itemize
The default action is to print the value of the requested field to the console,
but a variable name can be specified with @option{--set} to store the value
instead of printing it.
For example, this will store and then display the system manufacturer's name.
@example
smbios --type 1 --get-string 4 --set system_manufacturer
echo $system_manufacturer
@end example
@end deffn @end deffn
@@ -5199,12 +5395,6 @@ Unset the environment variable @var{envvar}.
@end deffn @end deffn
@node uppermem
@subsection uppermem
This command is not yet implemented for GRUB 2, although it is planned.
@ignore @ignore
@node vbeinfo @node vbeinfo
@subsection vbeinfo @subsection vbeinfo
@@ -5256,6 +5446,9 @@ only applies to the particular cpu/core/thread that runs the command.
Also, if you specify a reserved or unimplemented MSR address, it will Also, if you specify a reserved or unimplemented MSR address, it will
cause a general protection exception (which is not currently being handled) cause a general protection exception (which is not currently being handled)
and the system will reboot. and the system will reboot.
Note: The command is not allowed when lockdown is enforced (@pxref{Lockdown}).
This is done to prevent subverting various security mechanisms.
@end deffn @end deffn
@node xen_hypervisor @node xen_hypervisor
@@ -5288,10 +5481,11 @@ This command is only available on AArch64 systems.
* net_add_addr:: Add a network address * net_add_addr:: Add a network address
* net_add_dns:: Add a DNS server * net_add_dns:: Add a DNS server
* net_add_route:: Add routing entry * net_add_route:: Add routing entry
* net_bootp:: Perform a bootp autoconfiguration * net_bootp:: Perform a bootp/DHCP autoconfiguration
* net_del_addr:: Remove IP address from interface * net_del_addr:: Remove IP address from interface
* net_del_dns:: Remove a DNS server * net_del_dns:: Remove a DNS server
* net_del_route:: Remove a route entry * net_del_route:: Remove a route entry
* net_dhcp:: Perform a DHCP autoconfiguration
* net_get_dhcp_option:: Retrieve DHCP options * net_get_dhcp_option:: Retrieve DHCP options
* net_ipv6_autoconf:: Perform IPv6 autoconfiguration * net_ipv6_autoconf:: Perform IPv6 autoconfiguration
* net_ls_addr:: List interfaces * net_ls_addr:: List interfaces
@@ -5338,8 +5532,44 @@ by @var{shortname} which can be used to remove it (@pxref{net_del_route}).
@subsection net_bootp @subsection net_bootp
@deffn Command net_bootp [@var{card}] @deffn Command net_bootp [@var{card}]
Alias for net_dhcp, for compatibility with older Grub versions. Will perform
the same DHCP handshake with potential fallback to BOOTP as the net_dhcp
command (@pxref{net_dhcp}).
@end deffn
@node net_del_addr
@subsection net_del_addr
@deffn Command net_del_addr @var{interface}
Remove configured @var{interface} with associated address.
@end deffn
@node net_del_dns
@subsection net_del_dns
@deffn Command net_del_dns @var{address}
Remove @var{address} from list of servers used during name lookup.
@end deffn
@node net_del_route
@subsection net_del_route
@deffn Command net_del_route @var{shortname}
Remove route entry identified by @var{shortname}.
@end deffn
@node net_dhcp
@subsection net_dhcp
@deffn Command net_dhcp [@var{card}]
Perform configuration of @var{card} using DHCP protocol. If no card name Perform configuration of @var{card} using DHCP protocol. If no card name
is specified, try to configure all existing cards. If configuration was is specified, try to configure all existing cards.
Falls back to the BOOTP protocol, if needed. If configuration was
successful, interface with name @var{card}@samp{:dhcp} and configured successful, interface with name @var{card}@samp{:dhcp} and configured
address is added to @var{card}. address is added to @var{card}.
@comment If server provided gateway information in @comment If server provided gateway information in
@@ -5366,35 +5596,17 @@ Sets environment variable @samp{net_}@var{<card>}@samp{_dhcp_rootpath}
@item 18 (Extensions Path) @item 18 (Extensions Path)
Sets environment variable @samp{net_}@var{<card>}@samp{_dhcp_extensionspath} Sets environment variable @samp{net_}@var{<card>}@samp{_dhcp_extensionspath}
(@pxref{net_@var{<interface>}_extensionspath}) to the value of option. (@pxref{net_@var{<interface>}_extensionspath}) to the value of option.
@item 66 (TFTP Server Name)
Sets environment variable @samp{net_}@var{<card>}@samp{_dhcp_server_name}
(@pxref{net_@var{<interface>}_dhcp_server_name}) to the value of option.
@item 67 (Filename)
Sets environment variable @samp{net_}@var{<card>}@samp{_boot_file}
(@pxref{net_@var{<interface>}_boot_file}) to the value of option.
@end table @end table
@end deffn @end deffn
@node net_del_addr
@subsection net_del_addr
@deffn Command net_del_addr @var{interface}
Remove configured @var{interface} with associated address.
@end deffn
@node net_del_dns
@subsection net_del_dns
@deffn Command net_del_dns @var{address}
Remove @var{address} from list of servers used during name lookup.
@end deffn
@node net_del_route
@subsection net_del_route
@deffn Command net_del_route @var{shortname}
Remove route entry identified by @var{shortname}.
@end deffn
@node net_get_dhcp_option @node net_get_dhcp_option
@subsection net_get_dhcp_option @subsection net_get_dhcp_option
@@ -5580,7 +5792,9 @@ environment variables and commands are listed in the same order.
* Authentication and authorisation:: Users and access control * Authentication and authorisation:: Users and access control
* Using digital signatures:: Booting digitally signed code * Using digital signatures:: Booting digitally signed code
* UEFI secure boot and shim:: Booting digitally signed PE files * UEFI secure boot and shim:: Booting digitally signed PE files
* Secure Boot Advanced Targeting:: Embedded information for generation number based revocation
* Measured Boot:: Measuring boot components * Measured Boot:: Measuring boot components
* Lockdown:: Lockdown when booting on a secure setup
@end menu @end menu
@node Authentication and authorisation @node Authentication and authorisation
@@ -5612,7 +5826,8 @@ the GRUB command line, edit menu entries, and execute any menu entry. If
@samp{superusers} is set, then use of the command line and editing of menu @samp{superusers} is set, then use of the command line and editing of menu
entries are automatically restricted to superusers. Setting @samp{superusers} entries are automatically restricted to superusers. Setting @samp{superusers}
to empty string effectively disables both access to CLI and editing of menu to empty string effectively disables both access to CLI and editing of menu
entries. entries. Note: The environment variable needs to be exported to also affect
the section defined by the @samp{submenu} command (@pxref{submenu}).
Other users may be allowed to execute specific menu entries by giving a list of Other users may be allowed to execute specific menu entries by giving a list of
usernames (as above) using the @option{--users} option to the usernames (as above) using the @option{--users} option to the
@@ -5672,15 +5887,9 @@ verified with a public key currently trusted by GRUB
validation fails, then file @file{foo} cannot be opened. This failure validation fails, then file @file{foo} cannot be opened. This failure
may halt or otherwise impact the boot process. may halt or otherwise impact the boot process.
@comment Unfortunately --pubkey is not yet supported by grub-install, An initial trusted public key can be embedded within the GRUB @file{core.img}
@comment but we should not bring up internal detail grub-mkimage here using the @code{--pubkey} option to @command{grub-install}
@comment in the user guide (as opposed to developer's manual). (@pxref{Invoking grub-install}).
@comment An initial trusted public key can be embedded within the GRUB
@comment @file{core.img} using the @code{--pubkey} option to
@comment @command{grub-mkimage} (@pxref{Invoking grub-install}). Presently it
@comment is necessary to write a custom wrapper around @command{grub-mkimage}
@comment using the @code{--grub-mkimage} flag to @command{grub-install}.
GRUB uses GPG-style detached signatures (meaning that a file GRUB uses GPG-style detached signatures (meaning that a file
@file{foo.sig} will be produced when file @file{foo} is signed), and @file{foo.sig} will be produced when file @file{foo} is signed), and
@@ -5747,15 +5956,37 @@ secure boot chain.
@section UEFI secure boot and shim support @section UEFI secure boot and shim support
The GRUB, except the @command{chainloader} command, works with the UEFI secure The GRUB, except the @command{chainloader} command, works with the UEFI secure
boot and the shim. This functionality is provided by the shim_lock module. It boot and the shim. This functionality is provided by the shim_lock verifier. It
is recommend to build in this and other required modules into the @file{core.img}. is built into the @file{core.img} and is registered if the UEFI secure boot is
All modules not stored in the @file{core.img} and the ACPI tables for the enabled. The @samp{shim_lock} variable is set to @samp{y} when shim_lock verifier
@command{acpi} command have to be signed, e.g. using PGP. Additionally, the is registered. If it is desired to use UEFI secure boot without shim, one can
@command{iorw}, the @command{memrw} and the @command{wrmsr} commands are disable shim_lock by disabling shim verification with MokSbState UEFI variable
prohibited if the UEFI secure boot is enabled. This is done due to or by building grub image with @samp{--disable-shim-lock} option.
security reasons. All above mentioned requirements are enforced by the
shim_lock module. And itself it is a persistent module which means that All GRUB modules not stored in the @file{core.img}, OS kernels, ACPI tables,
it cannot be unloaded if it was loaded into the memory. Device Trees, etc. have to be signed, e.g, using PGP. Additionally, the commands
that can be used to subvert the UEFI secure boot mechanism, such as @command{iorw}
and @command{memrw} will not be available when the UEFI secure boot is enabled.
This is done for security reasons and are enforced by the GRUB Lockdown mechanism
(@pxref{Lockdown}).
@node Secure Boot Advanced Targeting
@section Embedded information for generation number based revocation
The Secure Boot Advanced Targeting (SBAT) is a mechanism to allow the revocation
of components in the boot path by using generation numbers embedded into the EFI
binaries. The SBAT metadata is located in an .sbat data section that has set of
UTF-8 strings as comma-separated values (CSV). See
@uref{https://github.com/rhboot/shim/blob/main/SBAT.md} for more details.
To add a data section containing the SBAT information into the binary, the
@option{--sbat} option of @command{grub-mkimage} command should be used. The content
of a CSV file, encoded with UTF-8, is copied as is to the .sbat data section into
the generated EFI binary. The CSV file can be stored anywhere on the file system.
@example
grub-mkimage -O x86_64-efi -o grubx64.efi -p '(tftp)/grub' --sbat sbat.csv efinet tftp
@end example
@node Measured Boot @node Measured Boot
@section Measuring boot components @section Measuring boot components
@@ -5794,6 +6025,16 @@ into @file{core.img} in order to avoid a potential gap in measurement between
Measured boot is currently only supported on EFI platforms. Measured boot is currently only supported on EFI platforms.
@node Lockdown
@section Lockdown when booting on a secure setup
The GRUB can be locked down when booted on a secure boot environment, for example
if the UEFI secure boot is enabled. On a locked down configuration, the GRUB will
be restricted and some operations/commands cannot be executed.
The @samp{lockdown} variable is set to @samp{y} when the GRUB is locked down.
Otherwise it does not exit.
@node Platform limitations @node Platform limitations
@chapter Platform limitations @chapter Platform limitations
@@ -5801,6 +6042,15 @@ GRUB2 is designed to be portable and is actually ported across platforms. We
try to keep all platforms at the level. Unfortunately some platforms are better try to keep all platforms at the level. Unfortunately some platforms are better
supported than others. This is detailed in current and 2 following sections. supported than others. This is detailed in current and 2 following sections.
All platforms have an artificially GRUB imposed disk size restriction of 1 EiB.
In some cases, larger disk sizes can be used, but access will not be allowed
beyond 1 EiB.
LUKS2 devices with size larger than 16 EiB are currently not supported. They
can not be created as crypto devices by cryptomount, so can not even be
partially read from. LUKS have no limitations other than those imposed by the
format.
ARC platform is unable to change datetime (firmware doesn't seem to provide a ARC platform is unable to change datetime (firmware doesn't seem to provide a
function for it). function for it).
EMU has similar limitation. EMU has similar limitation.
@@ -5819,8 +6069,8 @@ by national encoding compatible only in pseudographics.
Unicode is the most versatile charset which supports many languages. However Unicode is the most versatile charset which supports many languages. However
the actual console may be much more limited depending on firmware the actual console may be much more limited depending on firmware
On BIOS network is supported only if the image is loaded through network. On BIOS, network is supported only if the image is loaded through network.
On sparc64 GRUB is unable to determine which server it was booted from. On sparc64, GRUB is unable to determine which server it was booted from.
Direct ATA/AHCI support allows to circumvent various firmware limitations but Direct ATA/AHCI support allows to circumvent various firmware limitations but
isn't needed for normal operation except on baremetal ports. isn't needed for normal operation except on baremetal ports.
@@ -5849,7 +6099,7 @@ Bootlocation is ability of GRUB to automatically detect where it boots from.
``disk'' means the detection is limited to detecting the disk with partition ``disk'' means the detection is limited to detecting the disk with partition
being discovered on install time. ``partition'' means that disk and partiton being discovered on install time. ``partition'' means that disk and partiton
can be automatically discovered. ``file'' means that boot image file name as can be automatically discovered. ``file'' means that boot image file name as
well as disk and partition can be discovered. For consistency default install ignores well as disk and partition can be discovered. For consistency, default install ignores
partition and relies solely on disk detection. If no bootlocation discovery is available partition and relies solely on disk detection. If no bootlocation discovery is available
or boot and grub-root disks are different, UUID is used instead. On ARC if no device or boot and grub-root disks are different, UUID is used instead. On ARC if no device
to install to is specified, UUID is used instead as well. to install to is specified, UUID is used instead as well.
@@ -6131,6 +6381,7 @@ Required files are:
@menu @menu
* GRUB only offers a rescue shell:: * GRUB only offers a rescue shell::
* Firmware stalls instead of booting GRUB::
@end menu @end menu
@@ -6201,6 +6452,17 @@ support has not yet been added to GRUB.
@end itemize @end itemize
@node Firmware stalls instead of booting GRUB
@section Firmware stalls instead of booting GRUB
The EFI implementation of some older MacBook laptops stalls when it gets
presented a grub-mkrescue ISO image for x86_64-efi target on an USB stick.
Affected are models of year 2010 or earlier. Workaround is to zeroize the
bytes 446 to 461 of the EFI partition, where mformat has put a partition table
entry which claims partition start at block 0. This change will not hamper
bootability on other machines.
@node Invoking grub-install @node Invoking grub-install
@chapter Invoking grub-install @chapter Invoking grub-install
+1 -1
View File
@@ -766,7 +766,7 @@ def image(defn, platform):
if test x$(TARGET_APPLE_LINKER) = x1; then \ if test x$(TARGET_APPLE_LINKER) = x1; then \
$(MACHO2IMG) $< $@; \ $(MACHO2IMG) $< $@; \
else \ else \
$(TARGET_OBJCOPY) $(""" + cname(defn) + """_OBJCOPYFLAGS) --strip-unneeded -R .note -R .comment -R .note.gnu.build-id -R .MIPS.abiflags -R .reginfo -R .rel.dyn -R .note.gnu.gold-version -R .ARM.exidx $< $@; \ $(TARGET_OBJCOPY) $(""" + cname(defn) + """_OBJCOPYFLAGS) --strip-unneeded -R .note -R .comment -R .note.gnu.build-id -R .MIPS.abiflags -R .reginfo -R .rel.dyn -R .note.gnu.gold-version -R .note.gnu.property -R .ARM.exidx $< $@; \
fi fi
""") """)
+7 -1
View File
@@ -71,6 +71,7 @@ KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/command.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/device.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/device.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/disk.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/disk.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/dl.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/dl.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/efi/sb.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/env.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/env.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/env_private.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/env_private.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/err.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/err.h
@@ -79,6 +80,7 @@ KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/fs.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/i18n.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/i18n.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/kernel.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/kernel.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/list.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/list.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/lockdown.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/misc.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/misc.h
if COND_emu if COND_emu
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/compiler-rt-emu.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/compiler-rt-emu.h
@@ -88,8 +90,10 @@ 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/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
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/verify.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/mm_private.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/mm_private.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/net.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/net.h
KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/memory.h KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/memory.h
@@ -375,8 +379,10 @@ command.lst: $(MARKER_FILES)
b=`basename $$pp .marker`; \ b=`basename $$pp .marker`; \
sed -n \ sed -n \
-e "/EXTCOMMAND_LIST_MARKER *( *\"/{s/.*( *\"\([^\"]*\)\".*/*\1: $$b/;p;}" \ -e "/EXTCOMMAND_LIST_MARKER *( *\"/{s/.*( *\"\([^\"]*\)\".*/*\1: $$b/;p;}" \
-e "/EXTCOMMAND_LOCKDOWN_LIST_MARKER *( *\"/{s/.*( *\"\([^\"]*\)\".*/*\1: $$b/;p;}" \
-e "/P1COMMAND_LIST_MARKER *( *\"/{s/.*( *\"\([^\"]*\)\".*/*\1: $$b/;p;}" \ -e "/P1COMMAND_LIST_MARKER *( *\"/{s/.*( *\"\([^\"]*\)\".*/*\1: $$b/;p;}" \
-e "/COMMAND_LIST_MARKER *( *\"/{s/.*( *\"\([^\"]*\)\".*/\1: $$b/;p;}" $$pp; \ -e "/COMMAND_LIST_MARKER *( *\"/{s/.*( *\"\([^\"]*\)\".*/\1: $$b/;p;}" \
-e "/COMMAND_LOCKDOWN_LIST_MARKER *( *\"/{s/.*( *\"\([^\"]*\)\".*/\1: $$b/;p;}" $$pp; \
done) | sort -u > $@ done) | sort -u > $@
platform_DATA += command.lst platform_DATA += command.lst
CLEANFILES += command.lst CLEANFILES += command.lst
+39 -15
View File
@@ -123,6 +123,7 @@ kernel = {
riscv32_efi_startup = kern/riscv/efi/startup.S; riscv32_efi_startup = kern/riscv/efi/startup.S;
riscv64_efi_startup = kern/riscv/efi/startup.S; riscv64_efi_startup = kern/riscv/efi/startup.S;
common = kern/buffer.c;
common = kern/command.c; common = kern/command.c;
common = kern/corecmd.c; common = kern/corecmd.c;
common = kern/device.c; common = kern/device.c;
@@ -140,6 +141,7 @@ kernel = {
common = kern/rescue_parser.c; common = kern/rescue_parser.c;
common = kern/rescue_reader.c; common = kern/rescue_reader.c;
common = kern/term.c; common = kern/term.c;
common = kern/verifiers.c;
noemu = kern/compiler-rt.c; noemu = kern/compiler-rt.c;
noemu = kern/mm.c; noemu = kern/mm.c;
@@ -203,6 +205,8 @@ kernel = {
efi = term/efi/console.c; efi = term/efi/console.c;
efi = kern/acpi.c; efi = kern/acpi.c;
efi = kern/efi/acpi.c; efi = kern/efi/acpi.c;
efi = kern/efi/sb.c;
efi = kern/lockdown.c;
i386_coreboot = kern/i386/pc/acpi.c; i386_coreboot = kern/i386/pc/acpi.c;
i386_multiboot = kern/i386/pc/acpi.c; i386_multiboot = kern/i386/pc/acpi.c;
i386_coreboot = kern/acpi.c; i386_coreboot = kern/acpi.c;
@@ -942,17 +946,6 @@ module = {
cppflags = '-I$(srcdir)/lib/posix_wrap'; cppflags = '-I$(srcdir)/lib/posix_wrap';
}; };
module = {
name = verifiers;
common = commands/verifiers.c;
};
module = {
name = shim_lock;
common = commands/efi/shim_lock.c;
enable = x86_64_efi;
};
module = { module = {
name = hdparm; name = hdparm;
common = commands/hdparm.c; common = commands/hdparm.c;
@@ -1097,6 +1090,21 @@ module = {
common = commands/sleep.c; common = commands/sleep.c;
}; };
module = {
name = smbios;
common = commands/smbios.c;
efi = commands/efi/smbios.c;
i386_pc = commands/i386/pc/smbios.c;
i386_coreboot = commands/i386/pc/smbios.c;
i386_multiboot = commands/i386/pc/smbios.c;
enable = efi;
enable = i386_pc;
enable = i386_coreboot;
enable = i386_multiboot;
};
module = { module = {
name = suspend; name = suspend;
ieee1275 = commands/ieee1275/suspend.c; ieee1275 = commands/ieee1275/suspend.c;
@@ -1161,10 +1169,27 @@ module = {
common = disk/cryptodisk.c; common = disk/cryptodisk.c;
}; };
module = {
name = json;
common = lib/json/json.c;
};
module = {
name = afsplitter;
common = disk/AFSplitter.c;
};
module = { module = {
name = luks; name = luks;
common = disk/luks.c; common = disk/luks.c;
common = disk/AFSplitter.c; };
module = {
name = luks2;
common = disk/luks2.c;
common = lib/gnulib/base64.c;
cflags = '$(CFLAGS_POSIX) $(CFLAGS_GNULIB)';
cppflags = '$(CPPFLAGS_POSIX) $(CPPFLAGS_GNULIB) -I$(srcdir)/lib/json';
}; };
module = { module = {
@@ -1655,6 +1680,7 @@ module = {
module = { module = {
name = datetime; name = datetime;
common = lib/datetime.c;
cmos = lib/cmos_datetime.c; cmos = lib/cmos_datetime.c;
efi = lib/efi/datetime.c; efi = lib/efi/datetime.c;
uboot = lib/dummy/datetime.c; uboot = lib/dummy/datetime.c;
@@ -1667,7 +1693,6 @@ module = {
i386_xen_pvh = lib/xen/datetime.c; i386_xen_pvh = lib/xen/datetime.c;
mips_arc = lib/arc/datetime.c; mips_arc = lib/arc/datetime.c;
enable = noemu;
}; };
module = { module = {
@@ -1894,7 +1919,6 @@ module = {
common = normal/autofs.c; common = normal/autofs.c;
common = normal/color.c; common = normal/color.c;
common = normal/completion.c; common = normal/completion.c;
common = normal/datetime.c;
common = normal/menu.c; common = normal/menu.c;
common = normal/menu_entry.c; common = normal/menu_entry.c;
common = normal/menu_text.c; common = normal/menu_text.c;
@@ -2469,7 +2493,7 @@ module = {
name = tpm; name = tpm;
common = commands/tpm.c; common = commands/tpm.c;
efi = commands/efi/tpm.c; efi = commands/efi/tpm.c;
enable = x86_64_efi; enable = efi;
}; };
module = { module = {
+12 -3
View File
@@ -75,6 +75,9 @@ grub_usb_controller_iterate (grub_usb_controller_iterate_hook_t hook,
grub_usb_err_t grub_usb_err_t
grub_usb_clear_halt (grub_usb_device_t dev, int endpoint) grub_usb_clear_halt (grub_usb_device_t dev, int endpoint)
{ {
if (endpoint >= GRUB_USB_MAX_TOGGLE)
return GRUB_USB_ERR_BADDEVICE;
dev->toggle[endpoint] = 0; dev->toggle[endpoint] = 0;
return grub_usb_control_msg (dev, (GRUB_USB_REQTYPE_OUT return grub_usb_control_msg (dev, (GRUB_USB_REQTYPE_OUT
| GRUB_USB_REQTYPE_STANDARD | GRUB_USB_REQTYPE_STANDARD
@@ -134,10 +137,10 @@ grub_usb_device_initialize (grub_usb_device_t dev)
return err; return err;
descdev = &dev->descdev; descdev = &dev->descdev;
for (i = 0; i < 8; i++) for (i = 0; i < GRUB_USB_MAX_CONF; i++)
dev->config[i].descconf = NULL; dev->config[i].descconf = NULL;
if (descdev->configcnt == 0) if (descdev->configcnt == 0 || descdev->configcnt > GRUB_USB_MAX_CONF)
{ {
err = GRUB_USB_ERR_BADDEVICE; err = GRUB_USB_ERR_BADDEVICE;
goto fail; goto fail;
@@ -172,6 +175,12 @@ grub_usb_device_initialize (grub_usb_device_t dev)
/* Skip the configuration descriptor. */ /* Skip the configuration descriptor. */
pos = dev->config[i].descconf->length; pos = dev->config[i].descconf->length;
if (dev->config[i].descconf->numif > GRUB_USB_MAX_IF)
{
err = GRUB_USB_ERR_BADDEVICE;
goto fail;
}
/* Read all interfaces. */ /* Read all interfaces. */
for (currif = 0; currif < dev->config[i].descconf->numif; currif++) for (currif = 0; currif < dev->config[i].descconf->numif; currif++)
{ {
@@ -217,7 +226,7 @@ grub_usb_device_initialize (grub_usb_device_t dev)
fail: fail:
for (i = 0; i < 8; i++) for (i = 0; i < GRUB_USB_MAX_CONF; i++)
grub_free (dev->config[i].descconf); grub_free (dev->config[i].descconf);
return err; return err;
+6 -6
View File
@@ -82,7 +82,7 @@ grub_usb_hub_add_dev (grub_usb_controller_t controller,
if (i == GRUB_USBHUB_MAX_DEVICES) if (i == GRUB_USBHUB_MAX_DEVICES)
{ {
grub_error (GRUB_ERR_IO, "can't assign address to USB device"); grub_error (GRUB_ERR_IO, "can't assign address to USB device");
for (i = 0; i < 8; i++) for (i = 0; i < GRUB_USB_MAX_CONF; i++)
grub_free (dev->config[i].descconf); grub_free (dev->config[i].descconf);
grub_free (dev); grub_free (dev);
return NULL; return NULL;
@@ -96,7 +96,7 @@ grub_usb_hub_add_dev (grub_usb_controller_t controller,
i, 0, 0, NULL); i, 0, 0, NULL);
if (err) if (err)
{ {
for (i = 0; i < 8; i++) for (i = 0; i < GRUB_USB_MAX_CONF; i++)
grub_free (dev->config[i].descconf); grub_free (dev->config[i].descconf);
grub_free (dev); grub_free (dev);
return NULL; return NULL;
@@ -149,8 +149,8 @@ grub_usb_add_hub (grub_usb_device_t dev)
grub_usb_set_configuration (dev, 1); grub_usb_set_configuration (dev, 1);
dev->nports = hubdesc.portcnt; dev->nports = hubdesc.portcnt;
dev->children = grub_zalloc (hubdesc.portcnt * sizeof (dev->children[0])); dev->children = grub_calloc (hubdesc.portcnt, sizeof (dev->children[0]));
dev->ports = grub_zalloc (dev->nports * sizeof (dev->ports[0])); dev->ports = grub_calloc (dev->nports, sizeof (dev->ports[0]));
if (!dev->children || !dev->ports) if (!dev->children || !dev->ports)
{ {
grub_free (dev->children); grub_free (dev->children);
@@ -268,8 +268,8 @@ grub_usb_controller_dev_register_iter (grub_usb_controller_t controller, void *d
/* Query the number of ports the root Hub has. */ /* Query the number of ports the root Hub has. */
hub->nports = controller->dev->hubports (controller); hub->nports = controller->dev->hubports (controller);
hub->devices = grub_zalloc (sizeof (hub->devices[0]) * hub->nports); hub->devices = grub_calloc (hub->nports, sizeof (hub->devices[0]));
hub->ports = grub_zalloc (sizeof (hub->ports[0]) * hub->nports); hub->ports = grub_calloc (hub->nports, sizeof (hub->ports[0]));
if (!hub->devices || !hub->ports) if (!hub->devices || !hub->ports)
{ {
grub_free (hub->devices); grub_free (hub->devices);
+8 -7
View File
@@ -27,6 +27,7 @@
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/memory.h> #include <grub/memory.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/lockdown.h>
#ifdef GRUB_MACHINE_EFI #ifdef GRUB_MACHINE_EFI
#include <grub/efi/efi.h> #include <grub/efi/efi.h>
@@ -775,13 +776,13 @@ static grub_extcmd_t cmd;
GRUB_MOD_INIT(acpi) GRUB_MOD_INIT(acpi)
{ {
cmd = grub_register_extcmd ("acpi", grub_cmd_acpi, 0, cmd = grub_register_extcmd_lockdown ("acpi", grub_cmd_acpi, 0,
N_("[-1|-2] [--exclude=TABLE1,TABLE2|" N_("[-1|-2] [--exclude=TABLE1,TABLE2|"
"--load-only=TABLE1,TABLE2] FILE1" "--load-only=TABLE1,TABLE2] FILE1"
" [FILE2] [...]"), " [FILE2] [...]"),
N_("Load host ACPI tables and tables " N_("Load host ACPI tables and tables "
"specified by arguments."), "specified by arguments."),
options); options);
} }
GRUB_MOD_FINI(acpi) GRUB_MOD_FINI(acpi)
+2 -1
View File
@@ -59,7 +59,8 @@ grub_cmd_date (grub_command_t cmd __attribute__ ((unused)),
for (; argc; argc--, args++) for (; argc; argc--, args++)
{ {
char *p, c; const char *p;
char c;
int m1, ofs, n, cur_mask; int m1, ofs, n, cur_mask;
p = args[0]; p = args[0];
+4 -4
View File
@@ -38,8 +38,8 @@ grub_cmd_fwsetup (grub_command_t cmd __attribute__ ((unused)),
grub_size_t oi_size; grub_size_t oi_size;
grub_efi_guid_t global = GRUB_EFI_GLOBAL_VARIABLE_GUID; grub_efi_guid_t global = GRUB_EFI_GLOBAL_VARIABLE_GUID;
old_os_indications = grub_efi_get_variable ("OsIndications", &global, grub_efi_get_variable ("OsIndications", &global, &oi_size,
&oi_size); (void **) &old_os_indications);
if (old_os_indications != NULL && oi_size == sizeof (os_indications)) if (old_os_indications != NULL && oi_size == sizeof (os_indications))
os_indications |= *old_os_indications; os_indications |= *old_os_indications;
@@ -63,8 +63,8 @@ efifwsetup_is_supported (void)
grub_size_t oi_size = 0; grub_size_t oi_size = 0;
grub_efi_guid_t global = GRUB_EFI_GLOBAL_VARIABLE_GUID; grub_efi_guid_t global = GRUB_EFI_GLOBAL_VARIABLE_GUID;
os_indications_supported = grub_efi_get_variable ("OsIndicationsSupported", grub_efi_get_variable ("OsIndicationsSupported", &global, &oi_size,
&global, &oi_size); (void **) &os_indications_supported);
if (!os_indications_supported) if (!os_indications_supported)
return 0; return 0;
+7 -7
View File
@@ -205,14 +205,14 @@ static grub_command_t cmd_fakebios, cmd_loadbios;
GRUB_MOD_INIT(loadbios) GRUB_MOD_INIT(loadbios)
{ {
cmd_fakebios = grub_register_command ("fakebios", grub_cmd_fakebios, cmd_fakebios = grub_register_command_lockdown ("fakebios", grub_cmd_fakebios,
0, N_("Create BIOS-like structures for" 0, N_("Create BIOS-like structures for"
" backward compatibility with" " backward compatibility with"
" existing OS.")); " existing OS."));
cmd_loadbios = grub_register_command ("loadbios", grub_cmd_loadbios, cmd_loadbios = grub_register_command_lockdown ("loadbios", grub_cmd_loadbios,
N_("BIOS_DUMP [INT10_DUMP]"), N_("BIOS_DUMP [INT10_DUMP]"),
N_("Load BIOS dump.")); N_("Load BIOS dump."));
} }
GRUB_MOD_FINI(loadbios) GRUB_MOD_FINI(loadbios)
+5 -1
View File
@@ -40,14 +40,17 @@ static const struct guid_mapping guid_mappings[] =
{ GRUB_EFI_CRC32_GUIDED_SECTION_EXTRACTION_GUID, { GRUB_EFI_CRC32_GUIDED_SECTION_EXTRACTION_GUID,
"CRC32 GUIDED SECTION EXTRACTION"}, "CRC32 GUIDED SECTION EXTRACTION"},
{ GRUB_EFI_DEBUG_IMAGE_INFO_TABLE_GUID, "DEBUG IMAGE INFO"}, { GRUB_EFI_DEBUG_IMAGE_INFO_TABLE_GUID, "DEBUG IMAGE INFO"},
{ GRUB_EFI_DEVICE_TREE_GUID, "DEVICE TREE"},
{ GRUB_EFI_DXE_SERVICES_TABLE_GUID, "DXE SERVICES"}, { GRUB_EFI_DXE_SERVICES_TABLE_GUID, "DXE SERVICES"},
{ GRUB_EFI_HCDP_TABLE_GUID, "HCDP"}, { GRUB_EFI_HCDP_TABLE_GUID, "HCDP"},
{ GRUB_EFI_HOB_LIST_GUID, "HOB LIST"}, { GRUB_EFI_HOB_LIST_GUID, "HOB LIST"},
{ GRUB_EFI_LZMA_CUSTOM_DECOMPRESS_GUID, "LZMA CUSTOM DECOMPRESS"}, { GRUB_EFI_LZMA_CUSTOM_DECOMPRESS_GUID, "LZMA CUSTOM DECOMPRESS"},
{ 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_SAL_TABLE_GUID, "SAL"}, { GRUB_EFI_SAL_TABLE_GUID, "SAL"},
{ GRUB_EFI_SMBIOS_TABLE_GUID, "SMBIOS"}, { GRUB_EFI_SMBIOS_TABLE_GUID, "SMBIOS"},
{ 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_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"},
@@ -71,7 +74,8 @@ grub_cmd_lsefisystab (struct grub_command *cmd __attribute__ ((unused)),
grub_printf ("Vendor: "); grub_printf ("Vendor: ");
for (vendor_utf16 = st->firmware_vendor; *vendor_utf16; vendor_utf16++); for (vendor_utf16 = st->firmware_vendor; *vendor_utf16; vendor_utf16++);
vendor = grub_malloc (4 * (vendor_utf16 - st->firmware_vendor) + 1); /* Allocate extra 3 bytes to simplify math. */
vendor = grub_calloc (4, vendor_utf16 - st->firmware_vendor + 1);
if (!vendor) if (!vendor)
return grub_errno; return grub_errno;
*grub_utf16_to_utf8 ((grub_uint8_t *) vendor, st->firmware_vendor, *grub_utf16_to_utf8 ((grub_uint8_t *) vendor, st->firmware_vendor,
-142
View File
@@ -1,142 +0,0 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2017 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/>.
*
* EFI shim lock verifier.
*/
#include <grub/dl.h>
#include <grub/efi/efi.h>
#include <grub/err.h>
#include <grub/file.h>
#include <grub/misc.h>
#include <grub/verify.h>
GRUB_MOD_LICENSE ("GPLv3+");
#define GRUB_EFI_SHIM_LOCK_GUID \
{ 0x605dab50, 0xe046, 0x4300, \
{ 0xab, 0xb6, 0x3d, 0xd8, 0x10, 0xdd, 0x8b, 0x23 } \
}
struct grub_efi_shim_lock_protocol
{
grub_efi_status_t
(*verify) (void *buffer, grub_uint32_t size);
};
typedef struct grub_efi_shim_lock_protocol grub_efi_shim_lock_protocol_t;
static grub_efi_guid_t shim_lock_guid = GRUB_EFI_SHIM_LOCK_GUID;
static grub_efi_shim_lock_protocol_t *sl;
/* List of modules which cannot be loaded if UEFI secure boot mode is enabled. */
static const char * const disabled_mods[] = {"iorw", "memrw", "wrmsr", NULL};
static grub_err_t
shim_lock_init (grub_file_t io, enum grub_file_type type,
void **context __attribute__ ((unused)),
enum grub_verify_flags *flags)
{
const char *b, *e;
int i;
*flags = GRUB_VERIFY_FLAGS_SKIP_VERIFICATION;
if (!sl)
return GRUB_ERR_NONE;
switch (type & GRUB_FILE_TYPE_MASK)
{
case GRUB_FILE_TYPE_GRUB_MODULE:
/* Establish GRUB module name. */
b = grub_strrchr (io->name, '/');
e = grub_strrchr (io->name, '.');
b = b ? (b + 1) : io->name;
e = e ? e : io->name + grub_strlen (io->name);
e = (e > b) ? e : io->name + grub_strlen (io->name);
for (i = 0; disabled_mods[i]; i++)
if (!grub_strncmp (b, disabled_mods[i], grub_strlen (b) - grub_strlen (e)))
{
grub_error (GRUB_ERR_ACCESS_DENIED,
N_("module cannot be loaded in UEFI secure boot mode: %s"),
io->name);
return GRUB_ERR_ACCESS_DENIED;
}
/* Fall through. */
case GRUB_FILE_TYPE_ACPI_TABLE:
case GRUB_FILE_TYPE_DEVICE_TREE_IMAGE:
*flags = GRUB_VERIFY_FLAGS_DEFER_AUTH;
return GRUB_ERR_NONE;
case GRUB_FILE_TYPE_LINUX_KERNEL:
case GRUB_FILE_TYPE_MULTIBOOT_KERNEL:
case GRUB_FILE_TYPE_BSD_KERNEL:
case GRUB_FILE_TYPE_XNU_KERNEL:
case GRUB_FILE_TYPE_PLAN9_KERNEL:
for (i = 0; disabled_mods[i]; i++)
if (grub_dl_get (disabled_mods[i]))
{
grub_error (GRUB_ERR_ACCESS_DENIED,
N_("cannot boot due to dangerous module in memory: %s"),
disabled_mods[i]);
return GRUB_ERR_ACCESS_DENIED;
}
*flags = GRUB_VERIFY_FLAGS_SINGLE_CHUNK;
/* Fall through. */
default:
return GRUB_ERR_NONE;
}
}
static grub_err_t
shim_lock_write (void *context __attribute__ ((unused)), void *buf, grub_size_t size)
{
if (sl->verify (buf, size) != GRUB_EFI_SUCCESS)
return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("bad shim signature"));
return GRUB_ERR_NONE;
}
struct grub_file_verifier shim_lock =
{
.name = "shim_lock",
.init = shim_lock_init,
.write = shim_lock_write
};
GRUB_MOD_INIT(shim_lock)
{
sl = grub_efi_locate_protocol (&shim_lock_guid, 0);
grub_verifier_register (&shim_lock);
if (!sl)
return;
grub_dl_set_persistent (mod);
}
GRUB_MOD_FINI(shim_lock)
{
grub_verifier_unregister (&shim_lock);
}
+61
View File
@@ -0,0 +1,61 @@
/* smbios.c - get smbios tables. */
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2019 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/smbios.h>
#include <grub/misc.h>
#include <grub/efi/efi.h>
#include <grub/efi/api.h>
struct grub_smbios_eps *
grub_machine_smbios_get_eps (void)
{
unsigned i;
static grub_efi_packed_guid_t smbios_guid = GRUB_EFI_SMBIOS_TABLE_GUID;
for (i = 0; i < grub_efi_system_table->num_table_entries; i++)
{
grub_efi_packed_guid_t *guid =
&grub_efi_system_table->configuration_table[i].vendor_guid;
if (! grub_memcmp (guid, &smbios_guid, sizeof (grub_efi_packed_guid_t)))
return (struct grub_smbios_eps *)
grub_efi_system_table->configuration_table[i].vendor_table;
}
return 0;
}
struct grub_smbios_eps3 *
grub_machine_smbios_get_eps3 (void)
{
unsigned i;
static grub_efi_packed_guid_t smbios3_guid = GRUB_EFI_SMBIOS3_TABLE_GUID;
for (i = 0; i < grub_efi_system_table->num_table_entries; i++)
{
grub_efi_packed_guid_t *guid =
&grub_efi_system_table->configuration_table[i].vendor_guid;
if (! grub_memcmp (guid, &smbios3_guid, sizeof (grub_efi_packed_guid_t)))
return (struct grub_smbios_eps3 *)
grub_efi_system_table->configuration_table[i].vendor_table;
}
return 0;
}
+24 -116
View File
@@ -56,9 +56,13 @@ grub_tpm1_present (grub_efi_tpm_protocol_t *tpm)
if (status != GRUB_EFI_SUCCESS || caps.TPMDeactivatedFlag if (status != GRUB_EFI_SUCCESS || caps.TPMDeactivatedFlag
|| !caps.TPMPresentFlag) || !caps.TPMPresentFlag)
return tpm1_present = 0; tpm1_present = 0;
else
tpm1_present = 1;
return tpm1_present = 1; grub_dprintf ("tpm", "tpm1%s present\n", tpm1_present ? "" : " NOT");
return (grub_efi_boolean_t) tpm1_present;
} }
static grub_efi_boolean_t static grub_efi_boolean_t
@@ -75,9 +79,13 @@ grub_tpm2_present (grub_efi_tpm2_protocol_t *tpm)
status = efi_call_2 (tpm->get_capability, tpm, &caps); status = efi_call_2 (tpm->get_capability, tpm, &caps);
if (status != GRUB_EFI_SUCCESS || !caps.TPMPresentFlag) if (status != GRUB_EFI_SUCCESS || !caps.TPMPresentFlag)
return tpm2_present = 0; tpm2_present = 0;
else
tpm2_present = 1;
return tpm2_present = 1; grub_dprintf ("tpm", "tpm2%s present\n", tpm2_present ? "" : " NOT");
return (grub_efi_boolean_t) tpm2_present;
} }
static grub_efi_boolean_t static grub_efi_boolean_t
@@ -102,6 +110,7 @@ grub_tpm_handle_find (grub_efi_handle_t *tpm_handle,
*tpm_handle = handles[0]; *tpm_handle = handles[0];
grub_tpm_version = 1; grub_tpm_version = 1;
*protocol_version = 1; *protocol_version = 1;
grub_dprintf ("tpm", "TPM handle Found, version: 1\n");
return 1; return 1;
} }
@@ -113,6 +122,7 @@ grub_tpm_handle_find (grub_efi_handle_t *tpm_handle,
*tpm_handle = handles[0]; *tpm_handle = handles[0];
grub_tpm_version = 2; grub_tpm_version = 2;
*protocol_version = 2; *protocol_version = 2;
grub_dprintf ("tpm", "TPM handle Found, version: 2\n");
return 1; return 1;
} }
@@ -120,27 +130,8 @@ grub_tpm_handle_find (grub_efi_handle_t *tpm_handle,
} }
static grub_err_t static grub_err_t
grub_tpm1_execute (grub_efi_handle_t tpm_handle, grub_efi_log_event_status (grub_efi_status_t status)
PassThroughToTPM_InputParamBlock *inbuf,
PassThroughToTPM_OutputParamBlock *outbuf)
{ {
grub_efi_status_t status;
grub_efi_tpm_protocol_t *tpm;
grub_uint32_t inhdrsize = sizeof (*inbuf) - sizeof (inbuf->TPMOperandIn);
grub_uint32_t outhdrsize =
sizeof (*outbuf) - sizeof (outbuf->TPMOperandOut);
tpm = grub_efi_open_protocol (tpm_handle, &tpm_guid,
GRUB_EFI_OPEN_PROTOCOL_GET_PROTOCOL);
if (!grub_tpm1_present (tpm))
return 0;
/* UEFI TPM protocol takes the raw operand block, no param block header. */
status = efi_call_5 (tpm->pass_through_to_tpm, tpm,
inbuf->IPBLength - inhdrsize, inbuf->TPMOperandIn,
outbuf->OPBLength - outhdrsize, outbuf->TPMOperandOut);
switch (status) switch (status)
{ {
case GRUB_EFI_SUCCESS: case GRUB_EFI_SUCCESS:
@@ -150,8 +141,7 @@ grub_tpm1_execute (grub_efi_handle_t tpm_handle,
case GRUB_EFI_INVALID_PARAMETER: case GRUB_EFI_INVALID_PARAMETER:
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("Invalid parameter")); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("Invalid parameter"));
case GRUB_EFI_BUFFER_TOO_SMALL: case GRUB_EFI_BUFFER_TOO_SMALL:
return grub_error (GRUB_ERR_BAD_ARGUMENT, return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("Output buffer too small"));
N_("Output buffer too small"));
case GRUB_EFI_NOT_FOUND: case GRUB_EFI_NOT_FOUND:
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("TPM unavailable")); return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("TPM unavailable"));
default: default:
@@ -159,63 +149,6 @@ grub_tpm1_execute (grub_efi_handle_t tpm_handle,
} }
} }
static grub_err_t
grub_tpm2_execute (grub_efi_handle_t tpm_handle,
PassThroughToTPM_InputParamBlock *inbuf,
PassThroughToTPM_OutputParamBlock *outbuf)
{
grub_efi_status_t status;
grub_efi_tpm2_protocol_t *tpm;
grub_uint32_t inhdrsize = sizeof (*inbuf) - sizeof (inbuf->TPMOperandIn);
grub_uint32_t outhdrsize =
sizeof (*outbuf) - sizeof (outbuf->TPMOperandOut);
tpm = grub_efi_open_protocol (tpm_handle, &tpm2_guid,
GRUB_EFI_OPEN_PROTOCOL_GET_PROTOCOL);
if (!grub_tpm2_present (tpm))
return 0;
/* UEFI TPM protocol takes the raw operand block, no param block header. */
status = efi_call_5 (tpm->submit_command, tpm,
inbuf->IPBLength - inhdrsize, inbuf->TPMOperandIn,
outbuf->OPBLength - outhdrsize, outbuf->TPMOperandOut);
switch (status)
{
case GRUB_EFI_SUCCESS:
return 0;
case GRUB_EFI_DEVICE_ERROR:
return grub_error (GRUB_ERR_IO, N_("Command failed"));
case GRUB_EFI_INVALID_PARAMETER:
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("Invalid parameter"));
case GRUB_EFI_BUFFER_TOO_SMALL:
return grub_error (GRUB_ERR_BAD_ARGUMENT,
N_("Output buffer too small"));
case GRUB_EFI_NOT_FOUND:
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("TPM unavailable"));
default:
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("Unknown TPM error"));
}
}
grub_err_t
grub_tpm_execute (PassThroughToTPM_InputParamBlock *inbuf,
PassThroughToTPM_OutputParamBlock *outbuf)
{
grub_efi_handle_t tpm_handle;
grub_uint8_t protocol_version;
/* Absence of a TPM isn't a failure. */
if (!grub_tpm_handle_find (&tpm_handle, &protocol_version))
return 0;
if (protocol_version == 1)
return grub_tpm1_execute (tpm_handle, inbuf, outbuf);
else
return grub_tpm2_execute (tpm_handle, inbuf, outbuf);
}
static grub_err_t static grub_err_t
grub_tpm1_log_event (grub_efi_handle_t tpm_handle, unsigned char *buf, grub_tpm1_log_event (grub_efi_handle_t tpm_handle, unsigned char *buf,
grub_size_t size, grub_uint8_t pcr, grub_size_t size, grub_uint8_t pcr,
@@ -247,23 +180,9 @@ grub_tpm1_log_event (grub_efi_handle_t tpm_handle, unsigned char *buf,
algorithm = TCG_ALG_SHA; algorithm = TCG_ALG_SHA;
status = efi_call_7 (tpm->log_extend_event, tpm, (grub_addr_t) buf, (grub_uint64_t) size, status = efi_call_7 (tpm->log_extend_event, tpm, (grub_addr_t) buf, (grub_uint64_t) size,
algorithm, event, &eventnum, &lastevent); algorithm, event, &eventnum, &lastevent);
grub_free (event);
switch (status) return grub_efi_log_event_status (status);
{
case GRUB_EFI_SUCCESS:
return 0;
case GRUB_EFI_DEVICE_ERROR:
return grub_error (GRUB_ERR_IO, N_("Command failed"));
case GRUB_EFI_INVALID_PARAMETER:
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("Invalid parameter"));
case GRUB_EFI_BUFFER_TOO_SMALL:
return grub_error (GRUB_ERR_BAD_ARGUMENT,
N_("Output buffer too small"));
case GRUB_EFI_NOT_FOUND:
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("TPM unavailable"));
default:
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("Unknown TPM error"));
}
} }
static grub_err_t static grub_err_t
@@ -297,27 +216,13 @@ grub_tpm2_log_event (grub_efi_handle_t tpm_handle, unsigned char *buf,
status = efi_call_5 (tpm->hash_log_extend_event, tpm, 0, (grub_addr_t) buf, status = efi_call_5 (tpm->hash_log_extend_event, tpm, 0, (grub_addr_t) buf,
(grub_uint64_t) size, event); (grub_uint64_t) size, event);
grub_free (event);
switch (status) return grub_efi_log_event_status (status);
{
case GRUB_EFI_SUCCESS:
return 0;
case GRUB_EFI_DEVICE_ERROR:
return grub_error (GRUB_ERR_IO, N_("Command failed"));
case GRUB_EFI_INVALID_PARAMETER:
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("Invalid parameter"));
case GRUB_EFI_BUFFER_TOO_SMALL:
return grub_error (GRUB_ERR_BAD_ARGUMENT,
N_("Output buffer too small"));
case GRUB_EFI_NOT_FOUND:
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("TPM unavailable"));
default:
return grub_error (GRUB_ERR_UNKNOWN_DEVICE, N_("Unknown TPM error"));
}
} }
grub_err_t grub_err_t
grub_tpm_log_event (unsigned char *buf, grub_size_t size, grub_uint8_t pcr, grub_tpm_measure (unsigned char *buf, grub_size_t size, grub_uint8_t pcr,
const char *description) const char *description)
{ {
grub_efi_handle_t tpm_handle; grub_efi_handle_t tpm_handle;
@@ -326,6 +231,9 @@ grub_tpm_log_event (unsigned char *buf, grub_size_t size, grub_uint8_t pcr,
if (!grub_tpm_handle_find (&tpm_handle, &protocol_version)) if (!grub_tpm_handle_find (&tpm_handle, &protocol_version))
return 0; return 0;
grub_dprintf ("tpm", "log_event, pcr = %d, size = 0x%" PRIxGRUB_SIZE ", %s\n",
pcr, size, description);
if (protocol_version == 1) if (protocol_version == 1)
return grub_tpm1_log_event (tpm_handle, buf, size, pcr, description); return grub_tpm1_log_event (tpm_handle, buf, size, pcr, description);
else else
+23
View File
@@ -19,6 +19,7 @@
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/list.h> #include <grub/list.h>
#include <grub/lockdown.h>
#include <grub/misc.h> #include <grub/misc.h>
#include <grub/extcmd.h> #include <grub/extcmd.h>
#include <grub/script_sh.h> #include <grub/script_sh.h>
@@ -110,6 +111,28 @@ grub_register_extcmd (const char *name, grub_extcmd_func_t func,
summary, description, parser, 1); summary, description, parser, 1);
} }
static grub_err_t
grub_extcmd_lockdown (grub_extcmd_context_t ctxt __attribute__ ((unused)),
int argc __attribute__ ((unused)),
char **argv __attribute__ ((unused)))
{
return grub_error (GRUB_ERR_ACCESS_DENIED,
N_("%s: the command is not allowed when lockdown is enforced"),
ctxt->extcmd->cmd->name);
}
grub_extcmd_t
grub_register_extcmd_lockdown (const char *name, grub_extcmd_func_t func,
grub_command_flags_t flags, const char *summary,
const char *description,
const struct grub_arg_option *parser)
{
if (grub_is_lockdown () == GRUB_LOCKDOWN_ENABLED)
func = grub_extcmd_lockdown;
return grub_register_extcmd (name, func, flags, summary, description, parser);
}
void void
grub_unregister_extcmd (grub_extcmd_t ext) grub_unregister_extcmd (grub_extcmd_t ext)
{ {
+6 -4
View File
@@ -134,7 +134,8 @@ enum
IS_IA_EFI, IS_IA_EFI,
IS_ARM64_EFI, IS_ARM64_EFI,
IS_ARM_EFI, IS_ARM_EFI,
IS_RISCV_EFI, IS_RISCV32_EFI,
IS_RISCV64_EFI,
IS_HIBERNATED, IS_HIBERNATED,
IS_XNU64, IS_XNU64,
IS_XNU32, IS_XNU32,
@@ -576,7 +577,8 @@ grub_cmd_file (grub_extcmd_context_t ctxt, int argc, char **args)
case IS_IA_EFI: case IS_IA_EFI:
case IS_ARM64_EFI: case IS_ARM64_EFI:
case IS_ARM_EFI: case IS_ARM_EFI:
case IS_RISCV_EFI: case IS_RISCV32_EFI:
case IS_RISCV64_EFI:
{ {
char signature[4]; char signature[4];
grub_uint32_t pe_offset; grub_uint32_t pe_offset;
@@ -622,13 +624,13 @@ grub_cmd_file (grub_extcmd_context_t ctxt, int argc, char **args)
&& coff_head.machine != && coff_head.machine !=
grub_cpu_to_le16_compile_time (GRUB_PE32_MACHINE_ARMTHUMB_MIXED)) grub_cpu_to_le16_compile_time (GRUB_PE32_MACHINE_ARMTHUMB_MIXED))
break; break;
if (type == IS_RISCV_EFI if ((type == IS_RISCV32_EFI || type == IS_RISCV64_EFI)
&& coff_head.machine != && coff_head.machine !=
grub_cpu_to_le16_compile_time (GRUB_PE32_MACHINE_RISCV64)) grub_cpu_to_le16_compile_time (GRUB_PE32_MACHINE_RISCV64))
/* TODO: Determine bitness dynamically */ /* TODO: Determine bitness dynamically */
break; break;
if (type == IS_IA_EFI || type == IS_64_EFI || type == IS_ARM64_EFI || if (type == IS_IA_EFI || type == IS_64_EFI || type == IS_ARM64_EFI ||
type == IS_RISCV_EFI) type == IS_RISCV32_EFI || type == IS_RISCV64_EFI)
{ {
struct grub_pe64_optional_header o64; struct grub_pe64_optional_header o64;
if (grub_file_read (file, &o64, sizeof (o64)) != sizeof (o64)) if (grub_file_read (file, &o64, sizeof (o64)) != sizeof (o64))
+12 -3
View File
@@ -128,11 +128,17 @@ check_list (const gcry_md_spec_t *hash, const char *hashfilename,
high = hextoval (*p++); high = hextoval (*p++);
low = hextoval (*p++); low = hextoval (*p++);
if (high < 0 || low < 0) if (high < 0 || low < 0)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "invalid hash list"); {
grub_free (buf);
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "invalid hash list");
}
expected[i] = (high << 4) | low; expected[i] = (high << 4) | low;
} }
if ((p[0] != ' ' && p[0] != '\t') || (p[1] != ' ' && p[1] != '\t')) if ((p[0] != ' ' && p[0] != '\t') || (p[1] != ' ' && p[1] != '\t'))
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "invalid hash list"); {
grub_free (buf);
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "invalid hash list");
}
p += 2; p += 2;
if (prefix) if (prefix)
{ {
@@ -140,7 +146,10 @@ check_list (const gcry_md_spec_t *hash, const char *hashfilename,
filename = grub_xasprintf ("%s/%s", prefix, p); filename = grub_xasprintf ("%s/%s", prefix, p);
if (!filename) if (!filename)
return grub_errno; {
grub_free (buf);
return grub_errno;
}
file = grub_file_open (filename, GRUB_FILE_TYPE_TO_HASH file = grub_file_open (filename, GRUB_FILE_TYPE_TO_HASH
| (!uncompress ? GRUB_FILE_TYPE_NO_DECOMPRESS | (!uncompress ? GRUB_FILE_TYPE_NO_DECOMPRESS
: GRUB_FILE_TYPE_NONE)); : GRUB_FILE_TYPE_NONE));
+3 -3
View File
@@ -436,9 +436,9 @@ static grub_extcmd_t cmd;
GRUB_MOD_INIT(hdparm) GRUB_MOD_INIT(hdparm)
{ {
cmd = grub_register_extcmd ("hdparm", grub_cmd_hdparm, 0, cmd = grub_register_extcmd_lockdown ("hdparm", grub_cmd_hdparm, 0,
N_("[OPTIONS] DISK"), N_("[OPTIONS] DISK"),
N_("Get/set ATA disk parameters."), options); N_("Get/set ATA disk parameters."), options);
} }
GRUB_MOD_FINI(hdparm) GRUB_MOD_FINI(hdparm)
+1 -1
View File
@@ -27,7 +27,7 @@ GRUB_MOD_LICENSE ("GPLv3+");
static grub_err_t static grub_err_t
parse_args (int argc, char *argv[], int *byte, int *bit) parse_args (int argc, char *argv[], int *byte, int *bit)
{ {
char *rest; const char *rest;
if (argc != 1) if (argc != 1)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "address required"); return grub_error (GRUB_ERR_BAD_ARGUMENT, "address required");
+1 -1
View File
@@ -132,7 +132,7 @@ grub_cmd_play (grub_command_t cmd __attribute__ ((unused)),
} }
else else
{ {
char *end; const char *end;
unsigned tempo; unsigned tempo;
struct note note; struct note note;
int i; int i;
+52
View File
@@ -0,0 +1,52 @@
/* smbios.c - get smbios tables. */
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2019 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/acpi.h>
#include <grub/smbios.h>
#include <grub/misc.h>
struct grub_smbios_eps *
grub_machine_smbios_get_eps (void)
{
grub_uint8_t *ptr;
grub_dprintf ("smbios", "Looking for SMBIOS EPS. Scanning BIOS\n");
for (ptr = (grub_uint8_t *) 0xf0000; ptr < (grub_uint8_t *) 0x100000; ptr += 16)
if (grub_memcmp (ptr, "_SM_", 4) == 0
&& grub_byte_checksum (ptr, sizeof (struct grub_smbios_eps)) == 0)
return (struct grub_smbios_eps *) ptr;
return 0;
}
struct grub_smbios_eps3 *
grub_machine_smbios_get_eps3 (void)
{
grub_uint8_t *ptr;
grub_dprintf ("smbios", "Looking for SMBIOS3 EPS. Scanning BIOS\n");
for (ptr = (grub_uint8_t *) 0xf0000; ptr < (grub_uint8_t *) 0x100000; ptr += 16)
if (grub_memcmp (ptr, "_SM3_", 5) == 0
&& grub_byte_checksum (ptr, sizeof (struct grub_smbios_eps3)) == 0)
return (struct grub_smbios_eps3 *) ptr;
return 0;
}
+1 -1
View File
@@ -44,7 +44,7 @@ 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_uint32_t manufacturer[3], max_cpuid, a, b, c, features, addr;
grub_uint64_t value; grub_uint64_t value;
char *ptr; const char *ptr;
char buf[sizeof("1122334455667788")]; char buf[sizeof("1122334455667788")];
/* /*
+4 -3
View File
@@ -24,6 +24,7 @@
#include <grub/env.h> #include <grub/env.h>
#include <grub/command.h> #include <grub/command.h>
#include <grub/extcmd.h> #include <grub/extcmd.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/wrmsr.h>
@@ -37,7 +38,7 @@ grub_cmd_msr_write (grub_command_t cmd __attribute__ ((unused)), int argc, char
{ {
grub_uint32_t manufacturer[3], max_cpuid, a, b, c, features, addr; grub_uint32_t manufacturer[3], max_cpuid, a, b, c, features, addr;
grub_uint64_t value; grub_uint64_t value;
char *ptr; const char *ptr;
/* /*
* The CPUID instruction should be used to determine whether MSRs * The CPUID instruction should be used to determine whether MSRs
@@ -83,8 +84,8 @@ grub_cmd_msr_write (grub_command_t cmd __attribute__ ((unused)), int argc, char
GRUB_MOD_INIT(wrmsr) GRUB_MOD_INIT(wrmsr)
{ {
cmd_write = grub_register_command ("wrmsr", grub_cmd_msr_write, N_("ADDR VALUE"), cmd_write = grub_register_command_lockdown ("wrmsr", grub_cmd_msr_write, N_("ADDR VALUE"),
N_("Write a value to a CPU model specific register.")); N_("Write a value to a CPU model specific register."));
} }
GRUB_MOD_FINI(wrmsr) GRUB_MOD_FINI(wrmsr)
+10 -9
View File
@@ -23,6 +23,7 @@
#include <grub/env.h> #include <grub/env.h>
#include <grub/cpu/io.h> #include <grub/cpu/io.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/lockdown.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -131,17 +132,17 @@ GRUB_MOD_INIT(memrw)
N_("PORT"), N_("Read 32-bit value from PORT."), N_("PORT"), N_("Read 32-bit value from PORT."),
options); options);
cmd_write_byte = cmd_write_byte =
grub_register_command ("outb", grub_cmd_write, grub_register_command_lockdown ("outb", grub_cmd_write,
N_("PORT VALUE [MASK]"), N_("PORT VALUE [MASK]"),
N_("Write 8-bit VALUE to PORT.")); N_("Write 8-bit VALUE to PORT."));
cmd_write_word = cmd_write_word =
grub_register_command ("outw", grub_cmd_write, grub_register_command_lockdown ("outw", grub_cmd_write,
N_("PORT VALUE [MASK]"), N_("PORT VALUE [MASK]"),
N_("Write 16-bit VALUE to PORT.")); N_("Write 16-bit VALUE to PORT."));
cmd_write_dword = cmd_write_dword =
grub_register_command ("outl", grub_cmd_write, grub_register_command_lockdown ("outl", grub_cmd_write,
N_("ADDR VALUE [MASK]"), N_("ADDR VALUE [MASK]"),
N_("Write 32-bit VALUE to PORT.")); N_("Write 32-bit VALUE to PORT."));
} }
GRUB_MOD_FINI(memrw) GRUB_MOD_FINI(memrw)
-18
View File
@@ -35,24 +35,6 @@ static const struct grub_arg_option options[] =
{0, 0, 0, 0, 0, 0} {0, 0, 0, 0, 0, 0}
}; };
static int
grub_getkeystatus (void)
{
int status = 0;
grub_term_input_t term;
if (grub_term_poll_usb)
grub_term_poll_usb (0);
FOR_ACTIVE_TERM_INPUTS(term)
{
if (term->getkeystatus)
status |= term->getkeystatus (term);
}
return status;
}
static grub_err_t static grub_err_t
grub_cmd_keystatus (grub_extcmd_context_t ctxt, grub_cmd_keystatus (grub_extcmd_context_t ctxt,
int argc __attribute__ ((unused)), int argc __attribute__ ((unused)),
+26 -7
View File
@@ -32,6 +32,7 @@
#include <grub/auth.h> #include <grub/auth.h>
#include <grub/disk.h> #include <grub/disk.h>
#include <grub/partition.h> #include <grub/partition.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -104,13 +105,22 @@ legacy_file (const char *filename)
if (newsuffix) if (newsuffix)
{ {
char *t; char *t;
grub_size_t sz;
if (grub_add (grub_strlen (suffix), grub_strlen (newsuffix), &sz) ||
grub_add (sz, 1, &sz))
{
grub_errno = GRUB_ERR_OUT_OF_RANGE;
goto fail_0;
}
t = suffix; t = suffix;
suffix = grub_realloc (suffix, grub_strlen (suffix) suffix = grub_realloc (suffix, sz);
+ grub_strlen (newsuffix) + 1);
if (!suffix) if (!suffix)
{ {
grub_free (t); grub_free (t);
fail_0:
grub_free (entrysrc); grub_free (entrysrc);
grub_free (parsed); grub_free (parsed);
grub_free (newsuffix); grub_free (newsuffix);
@@ -154,13 +164,22 @@ legacy_file (const char *filename)
else else
{ {
char *t; char *t;
grub_size_t sz;
if (grub_add (grub_strlen (entrysrc), grub_strlen (parsed), &sz) ||
grub_add (sz, 1, &sz))
{
grub_errno = GRUB_ERR_OUT_OF_RANGE;
goto fail_1;
}
t = entrysrc; t = entrysrc;
entrysrc = grub_realloc (entrysrc, grub_strlen (entrysrc) entrysrc = grub_realloc (entrysrc, sz);
+ grub_strlen (parsed) + 1);
if (!entrysrc) if (!entrysrc)
{ {
grub_free (t); grub_free (t);
fail_1:
grub_free (parsed); grub_free (parsed);
grub_free (suffix); grub_free (suffix);
return grub_errno; return grub_errno;
@@ -314,7 +333,7 @@ grub_cmd_legacy_kernel (struct grub_command *mycmd __attribute__ ((unused)),
if (argc < 2) if (argc < 2)
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected")); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected"));
cutargs = grub_malloc (sizeof (cutargs[0]) * (argc - 1)); cutargs = grub_calloc (argc - 1, sizeof (cutargs[0]));
if (!cutargs) if (!cutargs)
return grub_errno; return grub_errno;
cutargc = argc - 1; cutargc = argc - 1;
@@ -436,7 +455,7 @@ grub_cmd_legacy_kernel (struct grub_command *mycmd __attribute__ ((unused)),
{ {
char rbuf[3] = "-r"; char rbuf[3] = "-r";
bsdargc = cutargc + 2; bsdargc = cutargc + 2;
bsdargs = grub_malloc (sizeof (bsdargs[0]) * bsdargc); bsdargs = grub_calloc (bsdargc, sizeof (bsdargs[0]));
if (!bsdargs) if (!bsdargs)
{ {
err = grub_errno; err = grub_errno;
@@ -559,7 +578,7 @@ grub_cmd_legacy_initrdnounzip (struct grub_command *mycmd __attribute__ ((unused
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("can't find command `%s'"), return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("can't find command `%s'"),
"module"); "module");
newargs = grub_malloc ((argc + 1) * sizeof (newargs[0])); newargs = grub_calloc (argc + 1, sizeof (newargs[0]));
if (!newargs) if (!newargs)
return grub_errno; return grub_errno;
grub_memcpy (newargs + 1, args, argc * sizeof (newargs[0])); grub_memcpy (newargs + 1, args, argc * sizeof (newargs[0]));
+2 -2
View File
@@ -70,7 +70,7 @@ grub_ls_list_devices (int longlist)
FOR_NET_APP_LEVEL (proto) FOR_NET_APP_LEVEL (proto)
{ {
if (first) if (first)
grub_puts_ (N_ ("Network protocols:")); grub_puts_ (N_("Network protocols:"));
first = 0; first = 0;
grub_printf ("%s ", proto->name); grub_printf ("%s ", proto->name);
} }
@@ -196,7 +196,7 @@ grub_ls_list_files (char *dirname, int longlist, int all, int human)
goto fail; goto fail;
} }
if (! *path) if (! *path && device_name)
{ {
if (grub_errno == GRUB_ERR_UNKNOWN_FS) if (grub_errno == GRUB_ERR_UNKNOWN_FS)
grub_errno = GRUB_ERR_NONE; grub_errno = GRUB_ERR_NONE;
+10 -9
View File
@@ -22,6 +22,7 @@
#include <grub/extcmd.h> #include <grub/extcmd.h>
#include <grub/env.h> #include <grub/env.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/lockdown.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -133,17 +134,17 @@ GRUB_MOD_INIT(memrw)
N_("ADDR"), N_("Read 32-bit value from ADDR."), N_("ADDR"), N_("Read 32-bit value from ADDR."),
options); options);
cmd_write_byte = cmd_write_byte =
grub_register_command ("write_byte", grub_cmd_write, grub_register_command_lockdown ("write_byte", grub_cmd_write,
N_("ADDR VALUE [MASK]"), N_("ADDR VALUE [MASK]"),
N_("Write 8-bit VALUE to ADDR.")); N_("Write 8-bit VALUE to ADDR."));
cmd_write_word = cmd_write_word =
grub_register_command ("write_word", grub_cmd_write, grub_register_command_lockdown ("write_word", grub_cmd_write,
N_("ADDR VALUE [MASK]"), N_("ADDR VALUE [MASK]"),
N_("Write 16-bit VALUE to ADDR.")); N_("Write 16-bit VALUE to ADDR."));
cmd_write_dword = cmd_write_dword =
grub_register_command ("write_dword", grub_cmd_write, grub_register_command_lockdown ("write_dword", grub_cmd_write,
N_("ADDR VALUE [MASK]"), N_("ADDR VALUE [MASK]"),
N_("Write 32-bit VALUE to ADDR.")); N_("Write 32-bit VALUE to ADDR."));
} }
GRUB_MOD_FINI(memrw) GRUB_MOD_FINI(memrw)
+2 -2
View File
@@ -154,7 +154,7 @@ grub_normal_add_menu_entry (int argc, const char **args,
goto fail; goto fail;
/* Save argc, args to pass as parameters to block arg later. */ /* Save argc, args to pass as parameters to block arg later. */
menu_args = grub_malloc (sizeof (char*) * (argc + 1)); menu_args = grub_calloc (argc + 1, sizeof (char *));
if (! menu_args) if (! menu_args)
goto fail; goto fail;
@@ -230,7 +230,7 @@ setparams_prefix (int argc, char **args)
len += 3; /* 3 = 1 space + 2 quotes */ len += 3; /* 3 = 1 space + 2 quotes */
p = args[i]; p = args[i];
while (*p) while (*p)
len += (*p++ == '\'' ? 3 : 1); len += (*p++ == '\'' ? 4 : 1);
} }
result = grub_malloc (len + 2); result = grub_malloc (len + 2);
+5 -2
View File
@@ -140,8 +140,11 @@ grub_mini_cmd_rmmod (struct grub_command *cmd __attribute__ ((unused)),
if (grub_dl_is_persistent (mod)) if (grub_dl_is_persistent (mod))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "cannot unload persistent module"); return grub_error (GRUB_ERR_BAD_ARGUMENT, "cannot unload persistent module");
if (grub_dl_unref (mod) <= 0) if (grub_dl_ref_count (mod) > 1)
grub_dl_unload (mod); return grub_error (GRUB_ERR_BAD_ARGUMENT, "cannot unload referenced module");
grub_dl_unref (mod);
grub_dl_unload (mod);
return 0; return 0;
} }
+1 -1
View File
@@ -195,7 +195,7 @@ grub_cmd_nativedisk (grub_command_t cmd __attribute__ ((unused)),
else else
path_prefix = prefix; path_prefix = prefix;
mods = grub_malloc (argc * sizeof (mods[0])); mods = grub_calloc (argc, sizeof (mods[0]));
if (!mods) if (!mods)
return grub_errno; return grub_errno;
+9 -3
View File
@@ -59,7 +59,13 @@ grub_parttool_register(const char *part_name,
for (nargs = 0; args[nargs].name != 0; nargs++); for (nargs = 0; args[nargs].name != 0; nargs++);
cur->nargs = nargs; cur->nargs = nargs;
cur->args = (struct grub_parttool_argdesc *) cur->args = (struct grub_parttool_argdesc *)
grub_malloc ((nargs + 1) * sizeof (struct grub_parttool_argdesc)); grub_calloc (nargs + 1, sizeof (struct grub_parttool_argdesc));
if (!cur->args)
{
grub_free (cur);
curhandle--;
return -1;
}
grub_memcpy (cur->args, args, grub_memcpy (cur->args, args,
(nargs + 1) * sizeof (struct grub_parttool_argdesc)); (nargs + 1) * sizeof (struct grub_parttool_argdesc));
@@ -257,7 +263,7 @@ grub_cmd_parttool (grub_command_t cmd __attribute__ ((unused)),
return err; return err;
} }
parsed = (int *) grub_zalloc (argc * sizeof (int)); parsed = (int *) grub_calloc (argc, sizeof (int));
for (i = 1; i < argc; i++) for (i = 1; i < argc; i++)
if (! parsed[i]) if (! parsed[i])
@@ -290,7 +296,7 @@ grub_cmd_parttool (grub_command_t cmd __attribute__ ((unused)),
} }
ptool = cur; ptool = cur;
pargs = (struct grub_parttool_args *) pargs = (struct grub_parttool_args *)
grub_zalloc (ptool->nargs * sizeof (struct grub_parttool_args)); grub_calloc (ptool->nargs, sizeof (struct grub_parttool_args));
for (j = i; j < argc; j++) for (j = i; j < argc; j++)
if (! parsed[j]) if (! parsed[j])
{ {
+1 -1
View File
@@ -86,7 +86,7 @@ grub_cmd_password (grub_command_t cmd __attribute__ ((unused)),
int argc, char **args) int argc, char **args)
{ {
grub_err_t err; grub_err_t err;
char *ptr, *ptr2; const char *ptr, *ptr2;
grub_uint8_t *ptro; grub_uint8_t *ptro;
struct pbkdf2_password *pass; struct pbkdf2_password *pass;
+5 -6
View File
@@ -95,7 +95,7 @@ grub_cmd_pcidump (grub_extcmd_context_t ctxt,
if (ctxt->state[0].set) if (ctxt->state[0].set)
{ {
ptr = ctxt->state[0].arg; ptr = ctxt->state[0].arg;
ctx.pciid_check_value |= (grub_strtoul (ptr, (char **) &ptr, 16) & 0xffff); ctx.pciid_check_value |= (grub_strtoul (ptr, &ptr, 16) & 0xffff);
if (grub_errno == GRUB_ERR_BAD_NUMBER) if (grub_errno == GRUB_ERR_BAD_NUMBER)
{ {
grub_errno = GRUB_ERR_NONE; grub_errno = GRUB_ERR_NONE;
@@ -108,8 +108,7 @@ grub_cmd_pcidump (grub_extcmd_context_t ctxt,
if (*ptr != ':') if (*ptr != ':')
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing `%c' symbol"), ':'); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing `%c' symbol"), ':');
ptr++; ptr++;
ctx.pciid_check_value |= (grub_strtoul (ptr, (char **) &ptr, 16) & 0xffff) ctx.pciid_check_value |= (grub_strtoul (ptr, &ptr, 16) & 0xffff) << 16;
<< 16;
if (grub_errno == GRUB_ERR_BAD_NUMBER) if (grub_errno == GRUB_ERR_BAD_NUMBER)
grub_errno = GRUB_ERR_NONE; grub_errno = GRUB_ERR_NONE;
else else
@@ -124,7 +123,7 @@ grub_cmd_pcidump (grub_extcmd_context_t ctxt,
ptr = ctxt->state[1].arg; ptr = ctxt->state[1].arg;
optr = ptr; optr = ptr;
ctx.bus = grub_strtoul (ptr, (char **) &ptr, 16); ctx.bus = grub_strtoul (ptr, &ptr, 16);
if (grub_errno == GRUB_ERR_BAD_NUMBER) if (grub_errno == GRUB_ERR_BAD_NUMBER)
{ {
grub_errno = GRUB_ERR_NONE; grub_errno = GRUB_ERR_NONE;
@@ -138,7 +137,7 @@ grub_cmd_pcidump (grub_extcmd_context_t ctxt,
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing `%c' symbol"), ':'); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing `%c' symbol"), ':');
ptr++; ptr++;
optr = ptr; optr = ptr;
ctx.device = grub_strtoul (ptr, (char **) &ptr, 16); ctx.device = grub_strtoul (ptr, &ptr, 16);
if (grub_errno == GRUB_ERR_BAD_NUMBER) if (grub_errno == GRUB_ERR_BAD_NUMBER)
{ {
grub_errno = GRUB_ERR_NONE; grub_errno = GRUB_ERR_NONE;
@@ -149,7 +148,7 @@ grub_cmd_pcidump (grub_extcmd_context_t ctxt,
if (*ptr == '.') if (*ptr == '.')
{ {
ptr++; ptr++;
ctx.function = grub_strtoul (ptr, (char **) &ptr, 16); ctx.function = grub_strtoul (ptr, &ptr, 16);
if (grub_errno) if (grub_errno)
return grub_errno; return grub_errno;
ctx.check_function = 1; ctx.check_function = 1;
+2 -2
View File
@@ -633,8 +633,8 @@ grub_verify_signature_real (struct grub_pubkey_context *ctxt,
if (!sk) if (!sk)
{ {
/* TRANSLATORS: %08x is 32-bit key id. */ /* TRANSLATORS: %08x is 32-bit key id. */
grub_error (GRUB_ERR_BAD_SIGNATURE, N_("public key %08x not found"), grub_error (GRUB_ERR_BAD_SIGNATURE,
keyid); N_("public key %08" PRIxGRUB_UINT64_T " not found"), keyid);
goto fail; goto fail;
} }
+53
View File
@@ -24,6 +24,7 @@
#include <grub/device.h> #include <grub/device.h>
#include <grub/disk.h> #include <grub/disk.h>
#include <grub/partition.h> #include <grub/partition.h>
#include <grub/gpt_partition.h>
#include <grub/net.h> #include <grub/net.h>
#include <grub/fs.h> #include <grub/fs.h>
#include <grub/file.h> #include <grub/file.h>
@@ -31,6 +32,7 @@
#include <grub/env.h> #include <grub/env.h>
#include <grub/extcmd.h> #include <grub/extcmd.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/i386/pc/boot.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -45,6 +47,7 @@ static const struct grub_arg_option options[] =
{"fs", 'f', 0, N_("Determine filesystem type."), 0, 0}, {"fs", 'f', 0, N_("Determine filesystem type."), 0, 0},
{"fs-uuid", 'u', 0, N_("Determine filesystem UUID."), 0, 0}, {"fs-uuid", 'u', 0, N_("Determine filesystem UUID."), 0, 0},
{"label", 'l', 0, N_("Determine filesystem label."), 0, 0}, {"label", 'l', 0, N_("Determine filesystem label."), 0, 0},
{"part-uuid", 0, 0, N_("Determine partition UUID."), 0, 0},
{0, 0, 0, 0, 0, 0} {0, 0, 0, 0, 0, 0}
}; };
@@ -98,6 +101,56 @@ grub_cmd_probe (grub_extcmd_context_t ctxt, int argc, char **args)
grub_device_close (dev); grub_device_close (dev);
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
} }
if (state[6].set)
{
/* AAAABBBB-CCCC-DDDD-EEEE-FFFFFFFFFFFF + null terminator */
char val[37] = "none";
if (dev->disk && dev->disk->partition)
{
struct grub_partition *p = dev->disk->partition;
grub_disk_t disk = grub_disk_open(dev->disk->name);
if (!disk)
{
grub_device_close (dev);
return grub_errno;
}
if (grub_strcmp(dev->disk->partition->partmap->name, "gpt") == 0)
{
struct grub_gpt_partentry entry;
grub_gpt_part_guid_t *guid;
if (grub_disk_read(disk, p->offset, p->index, sizeof(entry), &entry))
return grub_errno;
guid = &entry.guid;
grub_snprintf (val, sizeof(val),
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
grub_le_to_cpu32 (guid->data1),
grub_le_to_cpu16 (guid->data2),
grub_le_to_cpu16 (guid->data3),
guid->data4[0], guid->data4[1], guid->data4[2],
guid->data4[3], guid->data4[4], guid->data4[5],
guid->data4[6], guid->data4[7]);
}
else if (grub_strcmp(dev->disk->partition->partmap->name, "msdos") == 0)
{
grub_uint32_t nt_disk_sig;
if (grub_disk_read(disk, 0, GRUB_BOOT_MACHINE_WINDOWS_NT_MAGIC,
sizeof(nt_disk_sig), &nt_disk_sig) == 0)
grub_snprintf (val, sizeof(val), "%08x-%02x",
grub_le_to_cpu32(nt_disk_sig), 1 + p->number);
}
grub_disk_close(disk);
}
if (state[0].set)
grub_env_set (state[0].arg, val);
else
grub_printf ("%s", val);
grub_device_close (dev);
return GRUB_ERR_NONE;
}
fs = grub_fs_probe (dev); fs = grub_fs_probe (dev);
if (! fs) if (! fs)
return grub_errno; return grub_errno;
+2 -2
View File
@@ -64,7 +64,7 @@ set_matches (char **varnames, char *str, grub_size_t nmatches,
{ {
int i; int i;
char *p; char *p;
char *q; const char * q;
grub_err_t err; grub_err_t err;
unsigned long j; unsigned long j;
@@ -116,7 +116,7 @@ grub_cmd_regexp (grub_extcmd_context_t ctxt, int argc, char **args)
if (ret) if (ret)
goto fail; goto fail;
matches = grub_zalloc (sizeof (*matches) * (regex.re_nsub + 1)); matches = grub_calloc (regex.re_nsub + 1, sizeof (*matches));
if (! matches) if (! matches)
goto fail; goto fail;
+1 -1
View File
@@ -122,7 +122,7 @@ grub_cmd_search (grub_extcmd_context_t ctxt, int argc, char **args)
for (i = 0; state[SEARCH_HINT_BAREMETAL].args[i]; i++) for (i = 0; state[SEARCH_HINT_BAREMETAL].args[i]; i++)
nhints++; nhints++;
hints = grub_malloc (sizeof (hints[0]) * nhints); hints = grub_calloc (nhints, sizeof (hints[0]));
if (!hints) if (!hints)
return grub_errno; return grub_errno;
j = 0; j = 0;
+13 -14
View File
@@ -169,7 +169,7 @@ grub_cmd_setpci (grub_extcmd_context_t ctxt, int argc, char **argv)
if (ctxt->state[0].set) if (ctxt->state[0].set)
{ {
ptr = ctxt->state[0].arg; ptr = ctxt->state[0].arg;
pciid_check_value |= (grub_strtoul (ptr, (char **) &ptr, 16) & 0xffff); pciid_check_value |= (grub_strtoul (ptr, &ptr, 16) & 0xffff);
if (grub_errno == GRUB_ERR_BAD_NUMBER) if (grub_errno == GRUB_ERR_BAD_NUMBER)
{ {
grub_errno = GRUB_ERR_NONE; grub_errno = GRUB_ERR_NONE;
@@ -182,8 +182,7 @@ grub_cmd_setpci (grub_extcmd_context_t ctxt, int argc, char **argv)
if (*ptr != ':') if (*ptr != ':')
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing `%c' symbol"), ':'); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing `%c' symbol"), ':');
ptr++; ptr++;
pciid_check_value |= (grub_strtoul (ptr, (char **) &ptr, 16) & 0xffff) pciid_check_value |= (grub_strtoul (ptr, &ptr, 16) & 0xffff) << 16;
<< 16;
if (grub_errno == GRUB_ERR_BAD_NUMBER) if (grub_errno == GRUB_ERR_BAD_NUMBER)
grub_errno = GRUB_ERR_NONE; grub_errno = GRUB_ERR_NONE;
else else
@@ -200,7 +199,7 @@ grub_cmd_setpci (grub_extcmd_context_t ctxt, int argc, char **argv)
ptr = ctxt->state[1].arg; ptr = ctxt->state[1].arg;
optr = ptr; optr = ptr;
bus = grub_strtoul (ptr, (char **) &ptr, 16); bus = grub_strtoul (ptr, &ptr, 16);
if (grub_errno == GRUB_ERR_BAD_NUMBER) if (grub_errno == GRUB_ERR_BAD_NUMBER)
{ {
grub_errno = GRUB_ERR_NONE; grub_errno = GRUB_ERR_NONE;
@@ -214,7 +213,7 @@ grub_cmd_setpci (grub_extcmd_context_t ctxt, int argc, char **argv)
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing `%c' symbol"), ':'); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing `%c' symbol"), ':');
ptr++; ptr++;
optr = ptr; optr = ptr;
device = grub_strtoul (ptr, (char **) &ptr, 16); device = grub_strtoul (ptr, &ptr, 16);
if (grub_errno == GRUB_ERR_BAD_NUMBER) if (grub_errno == GRUB_ERR_BAD_NUMBER)
{ {
grub_errno = GRUB_ERR_NONE; grub_errno = GRUB_ERR_NONE;
@@ -225,7 +224,7 @@ grub_cmd_setpci (grub_extcmd_context_t ctxt, int argc, char **argv)
if (*ptr == '.') if (*ptr == '.')
{ {
ptr++; ptr++;
function = grub_strtoul (ptr, (char **) &ptr, 16); function = grub_strtoul (ptr, &ptr, 16);
if (grub_errno) if (grub_errno)
return grub_errno; return grub_errno;
check_function = 1; check_function = 1;
@@ -253,7 +252,7 @@ grub_cmd_setpci (grub_extcmd_context_t ctxt, int argc, char **argv)
if (i == ARRAY_SIZE (pci_registers)) if (i == ARRAY_SIZE (pci_registers))
{ {
regsize = 0; regsize = 0;
regaddr = grub_strtoul (ptr, (char **) &ptr, 16); regaddr = grub_strtoul (ptr, &ptr, 16);
if (grub_errno) if (grub_errno)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "unknown register"); return grub_error (GRUB_ERR_BAD_ARGUMENT, "unknown register");
} }
@@ -270,7 +269,7 @@ grub_cmd_setpci (grub_extcmd_context_t ctxt, int argc, char **argv)
if (*ptr == '+') if (*ptr == '+')
{ {
ptr++; ptr++;
regaddr += grub_strtoul (ptr, (char **) &ptr, 16); regaddr += grub_strtoul (ptr, &ptr, 16);
if (grub_errno) if (grub_errno)
return grub_errno; return grub_errno;
} }
@@ -302,14 +301,14 @@ grub_cmd_setpci (grub_extcmd_context_t ctxt, int argc, char **argv)
if (*ptr == '=') if (*ptr == '=')
{ {
ptr++; ptr++;
regwrite = grub_strtoul (ptr, (char **) &ptr, 16); regwrite = grub_strtoul (ptr, &ptr, 16);
if (grub_errno) if (grub_errno)
return grub_errno; return grub_errno;
write_mask = 0xffffffff; write_mask = 0xffffffff;
if (*ptr == ':') if (*ptr == ':')
{ {
ptr++; ptr++;
write_mask = grub_strtoul (ptr, (char **) &ptr, 16); write_mask = grub_strtoul (ptr, &ptr, 16);
if (grub_errno) if (grub_errno)
return grub_errno; return grub_errno;
write_mask = 0xffffffff; write_mask = 0xffffffff;
@@ -329,10 +328,10 @@ static grub_extcmd_t cmd;
GRUB_MOD_INIT(setpci) GRUB_MOD_INIT(setpci)
{ {
cmd = grub_register_extcmd ("setpci", grub_cmd_setpci, 0, cmd = grub_register_extcmd_lockdown ("setpci", grub_cmd_setpci, 0,
N_("[-s POSITION] [-d DEVICE] [-v VAR] " N_("[-s POSITION] [-d DEVICE] [-v VAR] "
"REGISTER[=VALUE[:MASK]]"), "REGISTER[=VALUE[:MASK]]"),
N_("Manipulate PCI devices."), options); N_("Manipulate PCI devices."), options);
} }
GRUB_MOD_FINI(setpci) GRUB_MOD_FINI(setpci)
+1 -1
View File
@@ -55,7 +55,7 @@ grub_interruptible_millisleep (grub_uint32_t ms)
start = grub_get_time_ms (); start = grub_get_time_ms ();
while (grub_get_time_ms () - start < ms) while (grub_get_time_ms () - start < ms)
if (grub_getkey_noblock () == GRUB_TERM_ESC) if (grub_key_is_interrupt (grub_getkey_noblock ()))
return 1; return 1;
return 0; return 0;
+398
View File
@@ -0,0 +1,398 @@
/* smbios.c - retrieve smbios information. */
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2019 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/env.h>
#include <grub/extcmd.h>
#include <grub/i18n.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/smbios.h>
GRUB_MOD_LICENSE ("GPLv3+");
/* Abstract useful values found in either the SMBIOS3 or SMBIOS EPS. */
static struct {
grub_addr_t start;
grub_addr_t end;
grub_uint16_t structures;
} table_desc;
static grub_extcmd_t cmd;
/* Locate the SMBIOS entry point structure depending on the hardware. */
struct grub_smbios_eps *
grub_smbios_get_eps (void)
{
static struct grub_smbios_eps *eps = NULL;
if (eps != NULL)
return eps;
eps = grub_machine_smbios_get_eps ();
return eps;
}
/* Locate the SMBIOS3 entry point structure depending on the hardware. */
static struct grub_smbios_eps3 *
grub_smbios_get_eps3 (void)
{
static struct grub_smbios_eps3 *eps = NULL;
if (eps != NULL)
return eps;
eps = grub_machine_smbios_get_eps3 ();
return eps;
}
static char *
linux_string (const char *value)
{
char *out = grub_malloc( grub_strlen (value) + 1);
const char *src = value;
char *dst = out;
for (; *src; src++)
if (*src > ' ' && *src < 127 && *src != ':')
*dst++ = *src;
*dst = 0;
return out;
}
/*
* These functions convert values from the various SMBIOS structure field types
* into a string formatted to be returned to the user. They expect that the
* structure and offset were already validated. When the requested data is
* successfully retrieved and formatted, the pointer to the string is returned;
* otherwise, NULL is returned on failure. Don't free the result.
*/
static const char *
grub_smbios_format_byte (const grub_uint8_t *structure, grub_uint8_t offset)
{
static char buffer[sizeof ("255")];
grub_snprintf (buffer, sizeof (buffer), "%u", structure[offset]);
return (const char *)buffer;
}
static const char *
grub_smbios_format_word (const grub_uint8_t *structure, grub_uint8_t offset)
{
static char buffer[sizeof ("65535")];
grub_uint16_t value = grub_get_unaligned16 (structure + offset);
grub_snprintf (buffer, sizeof (buffer), "%u", value);
return (const char *)buffer;
}
static const char *
grub_smbios_format_dword (const grub_uint8_t *structure, grub_uint8_t offset)
{
static char buffer[sizeof ("4294967295")];
grub_uint32_t value = grub_get_unaligned32 (structure + offset);
grub_snprintf (buffer, sizeof (buffer), "%" PRIuGRUB_UINT32_T, value);
return (const char *)buffer;
}
static const char *
grub_smbios_format_qword (const grub_uint8_t *structure, grub_uint8_t offset)
{
static char buffer[sizeof ("18446744073709551615")];
grub_uint64_t value = grub_get_unaligned64 (structure + offset);
grub_snprintf (buffer, sizeof (buffer), "%" PRIuGRUB_UINT64_T, value);
return (const char *)buffer;
}
static const char *
grub_smbios_get_string (const grub_uint8_t *structure, grub_uint8_t offset)
{
const grub_uint8_t *ptr = structure + structure[1];
const grub_uint8_t *table_end = (const grub_uint8_t *)table_desc.end;
const grub_uint8_t referenced_string_number = structure[offset];
grub_uint8_t i;
/* A string referenced with zero is interpreted as unset. */
if (referenced_string_number == 0)
return NULL;
/* Search the string set. */
for (i = 1; *ptr != 0 && ptr < table_end; i++)
if (i == referenced_string_number)
{
const char *str = (const char *)ptr;
while (*ptr++ != 0)
if (ptr >= table_end)
return NULL; /* The string isn't terminated. */
return str;
}
else
while (*ptr++ != 0 && ptr < table_end);
/* The string number is greater than the number of strings in the set. */
return NULL;
}
static const char *
grub_smbios_format_uuid (const grub_uint8_t *structure, grub_uint8_t offset)
{
static char buffer[sizeof ("ffffffff-ffff-ffff-ffff-ffffffffffff")];
const grub_uint8_t *f = structure + offset; /* little-endian fields */
const grub_uint8_t *g = f + 8; /* byte-by-byte fields */
grub_snprintf (buffer, sizeof (buffer),
"%02x%02x%02x%02x-%02x%02x-%02x%02x-"
"%02x%02x-%02x%02x%02x%02x%02x%02x",
f[3], f[2], f[1], f[0], f[5], f[4], f[7], f[6],
g[0], g[1], g[2], g[3], g[4], g[5], g[6], g[7]);
return (const char *)buffer;
}
/* List the field formatting functions and the number of bytes they need. */
static const struct {
const char *(*format) (const grub_uint8_t *structure, grub_uint8_t offset);
grub_uint8_t field_length;
} field_extractors[] = {
{grub_smbios_format_byte, 1},
{grub_smbios_format_word, 2},
{grub_smbios_format_dword, 4},
{grub_smbios_format_qword, 8},
{grub_smbios_get_string, 1},
{grub_smbios_format_uuid, 16}
};
/* List command options, with structure field getters ordered as above. */
#define FIRST_GETTER_OPT (3)
#define SETTER_OPT (FIRST_GETTER_OPT + ARRAY_SIZE(field_extractors))
#define LINUX_OPT (FIRST_GETTER_OPT + ARRAY_SIZE(field_extractors) + 1)
static const struct grub_arg_option options[] = {
{"type", 't', 0, N_("Match structures with the given type."),
N_("type"), ARG_TYPE_INT},
{"handle", 'h', 0, N_("Match structures with the given handle."),
N_("handle"), ARG_TYPE_INT},
{"match", 'm', 0, N_("Select a structure when several match."),
N_("match"), ARG_TYPE_INT},
{"get-byte", 'b', 0, N_("Get the byte's value at the given offset."),
N_("offset"), ARG_TYPE_INT},
{"get-word", 'w', 0, N_("Get two bytes' value at the given offset."),
N_("offset"), ARG_TYPE_INT},
{"get-dword", 'd', 0, N_("Get four bytes' value at the given offset."),
N_("offset"), ARG_TYPE_INT},
{"get-qword", 'q', 0, N_("Get eight bytes' value at the given offset."),
N_("offset"), ARG_TYPE_INT},
{"get-string", 's', 0, N_("Get the string specified at the given offset."),
N_("offset"), ARG_TYPE_INT},
{"get-uuid", 'u', 0, N_("Get the UUID's value at the given offset."),
N_("offset"), ARG_TYPE_INT},
{"set", '\0', 0, N_("Store the value in the given variable name."),
N_("variable"), ARG_TYPE_STRING},
{"linux", '\0', 0, N_("Filter the result like linux does."),
N_("variable"), ARG_TYPE_NONE},
{0, 0, 0, 0, 0, 0}
};
/*
* Return a matching SMBIOS structure.
*
* This method can use up to three criteria for selecting a structure:
* - The "type" field (use -1 to ignore)
* - The "handle" field (use -1 to ignore)
* - Which to return if several match (use 0 to ignore)
*
* The return value is a pointer to the first matching structure. If no
* structures match the given parameters, NULL is returned.
*/
static const grub_uint8_t *
grub_smbios_match_structure (const grub_int16_t type,
const grub_int32_t handle,
const grub_uint16_t match)
{
const grub_uint8_t *ptr = (const grub_uint8_t *)table_desc.start;
const grub_uint8_t *table_end = (const grub_uint8_t *)table_desc.end;
grub_uint16_t structures = table_desc.structures;
grub_uint16_t structure_count = 0;
grub_uint16_t matches = 0;
while (ptr < table_end
&& ptr[1] >= 4 /* Valid structures include the 4-byte header. */
&& (structure_count++ < structures || structures == 0))
{
grub_uint16_t structure_handle = grub_get_unaligned16 (ptr + 2);
grub_uint8_t structure_type = ptr[0];
if ((handle < 0 || handle == structure_handle)
&& (type < 0 || type == structure_type)
&& (match == 0 || match == ++matches))
return ptr;
else
{
ptr += ptr[1];
while ((*ptr++ != 0 || *ptr++ != 0) && ptr < table_end);
}
if (structure_type == GRUB_SMBIOS_TYPE_END_OF_TABLE)
break;
}
return NULL;
}
static grub_err_t
grub_cmd_smbios (grub_extcmd_context_t ctxt,
int argc __attribute__ ((unused)),
char **argv __attribute__ ((unused)))
{
struct grub_arg_list *state = ctxt->state;
grub_int16_t type = -1;
grub_int32_t handle = -1;
grub_uint16_t match = 0;
grub_uint8_t offset = 0;
const grub_uint8_t *structure;
const char *value;
char *modified_value = NULL;
grub_int32_t option;
grub_int8_t field_type = -1;
grub_uint8_t i;
if (table_desc.start == 0)
return grub_error (GRUB_ERR_IO,
N_("the SMBIOS entry point structure was not found"));
/* Read the given filtering options. */
if (state[0].set)
{
option = grub_strtol (state[0].arg, NULL, 0);
if (option < 0 || option > 255)
return grub_error (GRUB_ERR_BAD_ARGUMENT,
N_("the type must be between 0 and 255"));
type = (grub_int16_t)option;
}
if (state[1].set)
{
option = grub_strtol (state[1].arg, NULL, 0);
if (option < 0 || option > 65535)
return grub_error (GRUB_ERR_BAD_ARGUMENT,
N_("the handle must be between 0 and 65535"));
handle = (grub_int32_t)option;
}
if (state[2].set)
{
option = grub_strtol (state[2].arg, NULL, 0);
if (option <= 0 || option > 65535)
return grub_error (GRUB_ERR_BAD_ARGUMENT,
N_("the match must be a positive integer"));
match = (grub_uint16_t)option;
}
/* Determine the data type of the structure field to retrieve. */
for (i = 0; i < ARRAY_SIZE(field_extractors); i++)
if (state[FIRST_GETTER_OPT + i].set)
{
if (field_type >= 0)
return grub_error (GRUB_ERR_BAD_ARGUMENT,
N_("only one --get option is usable at a time"));
field_type = i;
}
/* Require a choice of a structure field to return. */
if (field_type < 0)
return grub_error (GRUB_ERR_BAD_ARGUMENT,
N_("one of the --get options is required"));
/* Locate a matching SMBIOS structure. */
structure = grub_smbios_match_structure (type, handle, match);
if (structure == NULL)
return grub_error (GRUB_ERR_IO,
N_("no structure matched the given options"));
/* Ensure the requested byte offset is inside the structure. */
option = grub_strtol (state[FIRST_GETTER_OPT + field_type].arg, NULL, 0);
if (option < 0 || option >= structure[1])
return grub_error (GRUB_ERR_OUT_OF_RANGE,
N_("the given offset is outside the structure"));
/* Ensure the requested data type at the offset is inside the structure. */
offset = (grub_uint8_t)option;
if (offset + field_extractors[field_type].field_length > structure[1])
return grub_error (GRUB_ERR_OUT_OF_RANGE,
N_("the field ends outside the structure"));
/* Format the requested structure field into a readable string. */
value = field_extractors[field_type].format (structure, offset);
if (value == NULL)
return grub_error (GRUB_ERR_IO,
N_("failed to retrieve the structure field"));
if (state[LINUX_OPT].set)
value = modified_value = linux_string (value);
/* Store or print the formatted value. */
if (state[SETTER_OPT].set)
grub_env_set (state[SETTER_OPT].arg, value);
else
grub_printf ("%s\n", value);
grub_free(modified_value);
return GRUB_ERR_NONE;
}
GRUB_MOD_INIT(smbios)
{
struct grub_smbios_eps3 *eps3;
struct grub_smbios_eps *eps;
if ((eps3 = grub_smbios_get_eps3 ()))
{
table_desc.start = (grub_addr_t)eps3->table_address;
table_desc.end = table_desc.start + eps3->maximum_table_length;
table_desc.structures = 0; /* SMBIOS3 drops the structure count. */
}
else if ((eps = grub_smbios_get_eps ()))
{
table_desc.start = (grub_addr_t)eps->intermediate.table_address;
table_desc.end = table_desc.start + eps->intermediate.table_length;
table_desc.structures = eps->intermediate.structures;
}
cmd = grub_register_extcmd ("smbios", grub_cmd_smbios, 0,
N_("[-t type] [-h handle] [-m match] "
"(-b|-w|-d|-q|-s|-u) offset "
"[--set variable]"),
N_("Retrieve SMBIOS information."), options);
}
GRUB_MOD_FINI(smbios)
{
grub_unregister_extcmd (cmd);
}
+5 -5
View File
@@ -87,7 +87,7 @@ handle_command (int argc, char **args, struct abstract_terminal **enabled,
i++; i++;
if (i == argc) if (i == argc)
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_ ("no terminal specified")); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("no terminal specified"));
for (; i < argc; i++) for (; i < argc; i++)
{ {
@@ -241,8 +241,8 @@ grub_cmd_terminal_input (grub_command_t cmd __attribute__ ((unused)),
(struct abstract_terminal **) (void *) &grub_term_inputs, (struct abstract_terminal **) (void *) &grub_term_inputs,
(struct abstract_terminal **) (void *) &grub_term_inputs_disabled, (struct abstract_terminal **) (void *) &grub_term_inputs_disabled,
grub_term_input_autoload, grub_term_input_autoload,
N_ ("Active input terminals:"), N_("Active input terminals:"),
N_ ("Available input terminals:")); N_("Available input terminals:"));
} }
static grub_err_t static grub_err_t
@@ -258,8 +258,8 @@ grub_cmd_terminal_output (grub_command_t cmd __attribute__ ((unused)),
(struct abstract_terminal **) (void *) &grub_term_outputs, (struct abstract_terminal **) (void *) &grub_term_outputs,
(struct abstract_terminal **) (void *) &grub_term_outputs_disabled, (struct abstract_terminal **) (void *) &grub_term_outputs_disabled,
grub_term_output_autoload, grub_term_output_autoload,
N_ ("Active output terminals:"), N_("Active output terminals:"),
N_ ("Available output terminals:")); N_("Available output terminals:"));
} }
static grub_command_t cmd_terminal_input, cmd_terminal_output; static grub_command_t cmd_terminal_input, cmd_terminal_output;
+1 -1
View File
@@ -31,7 +31,7 @@ GRUB_MOD_LICENSE ("GPLv3+");
/* A simple implementation for signed numbers. */ /* A simple implementation for signed numbers. */
static int static int
grub_strtosl (char *arg, char **end, int base) grub_strtosl (char *arg, const char ** const end, int base)
{ {
if (arg[0] == '-') if (arg[0] == '-')
return -grub_strtoul (arg + 1, end, base); return -grub_strtoul (arg + 1, end, base);
-7
View File
@@ -29,13 +29,6 @@
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
grub_err_t
grub_tpm_measure (unsigned char *buf, grub_size_t size, grub_uint8_t pcr,
const char *description)
{
return grub_tpm_log_event (buf, size, pcr, description);
}
static grub_err_t static grub_err_t
grub_tpm_verify_init (grub_file_t io, grub_tpm_verify_init (grub_file_t io,
enum grub_file_type type __attribute__ ((unused)), enum grub_file_type type __attribute__ ((unused)),
+9
View File
@@ -63,6 +63,11 @@ static const char *usb_devspeed[] =
"High" "High"
}; };
#if __GNUC__ >= 9
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
#endif
static grub_usb_err_t static grub_usb_err_t
grub_usb_get_string (grub_usb_device_t dev, grub_uint8_t index, int langid, grub_usb_get_string (grub_usb_device_t dev, grub_uint8_t index, int langid,
char **string) char **string)
@@ -108,6 +113,10 @@ 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;
} }
#if __GNUC__ >= 9
#pragma GCC diagnostic pop
#endif
static void static void
usb_print_str (const char *description, grub_usb_device_t dev, int idx) usb_print_str (const char *description, grub_usb_device_t dev, int idx)
{ {
+1 -1
View File
@@ -136,7 +136,7 @@ grub_cmd_videoinfo (grub_command_t cmd __attribute__ ((unused)),
ctx.height = ctx.width = ctx.depth = 0; ctx.height = ctx.width = ctx.depth = 0;
if (argc) if (argc)
{ {
char *ptr; const char *ptr;
ptr = args[0]; ptr = args[0];
ctx.width = grub_strtoul (ptr, &ptr, 0); ctx.width = grub_strtoul (ptr, &ptr, 0);
if (grub_errno) if (grub_errno)
+31 -5
View File
@@ -23,6 +23,7 @@
#include <grub/file.h> #include <grub/file.h>
#include <grub/device.h> #include <grub/device.h>
#include <grub/script_sh.h> #include <grub/script_sh.h>
#include <grub/safemath.h>
#include <regex.h> #include <regex.h>
@@ -48,6 +49,7 @@ merge (char **dest, char **ps)
int i; int i;
int j; int j;
char **p; char **p;
grub_size_t sz;
if (! dest) if (! dest)
return ps; return ps;
@@ -60,7 +62,12 @@ merge (char **dest, char **ps)
for (j = 0; ps[j]; j++) for (j = 0; ps[j]; j++)
; ;
p = grub_realloc (dest, sizeof (char*) * (i + j + 1)); if (grub_add (i, j, &sz) ||
grub_add (sz, 1, &sz) ||
grub_mul (sz, sizeof (char *), &sz))
return dest;
p = grub_realloc (dest, sz);
if (! p) if (! p)
{ {
grub_free (dest); grub_free (dest);
@@ -115,8 +122,15 @@ make_regex (const char *start, const char *end, regex_t *regexp)
char ch; char ch;
int i = 0; int i = 0;
unsigned len = end - start; unsigned len = end - start;
char *buffer = grub_malloc (len * 2 + 2 + 1); /* worst case size. */ char *buffer;
grub_size_t sz;
/* Worst case size is (len * 2 + 2 + 1). */
if (grub_mul (len, 2, &sz) ||
grub_add (sz, 3, &sz))
return 1;
buffer = grub_malloc (sz);
if (! buffer) if (! buffer)
return 1; return 1;
@@ -226,6 +240,7 @@ match_devices_iter (const char *name, void *data)
struct match_devices_ctx *ctx = data; struct match_devices_ctx *ctx = data;
char **t; char **t;
char *buffer; char *buffer;
grub_size_t sz;
/* skip partitions if asked to. */ /* skip partitions if asked to. */
if (ctx->noparts && grub_strchr (name, ',')) if (ctx->noparts && grub_strchr (name, ','))
@@ -239,11 +254,16 @@ match_devices_iter (const char *name, void *data)
if (regexec (ctx->regexp, buffer, 0, 0, 0)) if (regexec (ctx->regexp, buffer, 0, 0, 0))
{ {
grub_dprintf ("expand", "not matched\n"); grub_dprintf ("expand", "not matched\n");
fail:
grub_free (buffer); grub_free (buffer);
return 0; return 0;
} }
t = grub_realloc (ctx->devs, sizeof (char*) * (ctx->ndev + 2)); if (grub_add (ctx->ndev, 2, &sz) ||
grub_mul (sz, sizeof (char *), &sz))
goto fail;
t = grub_realloc (ctx->devs, sz);
if (! t) if (! t)
{ {
grub_free (buffer); grub_free (buffer);
@@ -300,6 +320,7 @@ match_files_iter (const char *name,
struct match_files_ctx *ctx = data; struct match_files_ctx *ctx = data;
char **t; char **t;
char *buffer; char *buffer;
grub_size_t sz;
/* skip . and .. names */ /* skip . and .. names */
if (grub_strcmp(".", name) == 0 || grub_strcmp("..", name) == 0) if (grub_strcmp(".", name) == 0 || grub_strcmp("..", name) == 0)
@@ -315,9 +336,14 @@ match_files_iter (const char *name,
if (! buffer) if (! buffer)
return 1; return 1;
t = grub_realloc (ctx->files, sizeof (char*) * (ctx->nfile + 2)); if (grub_add (ctx->nfile, 2, &sz) ||
if (! t) grub_mul (sz, sizeof (char *), &sz))
goto fail;
t = grub_realloc (ctx->files, sz);
if (!t)
{ {
fail:
grub_free (buffer); grub_free (buffer);
return 1; return 1;
} }
+3
View File
@@ -21,9 +21,12 @@
*/ */
#include <grub/crypto.h> #include <grub/crypto.h>
#include <grub/dl.h>
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/misc.h> #include <grub/misc.h>
GRUB_MOD_LICENSE ("GPLv2+");
gcry_err_code_t AF_merge (const gcry_md_spec_t * hash, grub_uint8_t * src, gcry_err_code_t AF_merge (const gcry_md_spec_t * hash, grub_uint8_t * src,
grub_uint8_t * dst, grub_size_t blocksize, grub_uint8_t * dst, grub_size_t blocksize,
grub_size_t blocknumbers); grub_size_t blocknumbers);
+6 -4
View File
@@ -219,8 +219,9 @@ grub_ata_setaddress (struct grub_ata *dev,
if (dev->sectors_per_track == 0 if (dev->sectors_per_track == 0
|| dev->heads == 0) || dev->heads == 0)
return grub_error (GRUB_ERR_OUT_OF_RANGE, return grub_error (GRUB_ERR_OUT_OF_RANGE,
"sector %d cannot be addressed " "sector %" PRIxGRUB_UINT64_T " cannot be "
"using CHS addressing", sector); "addressed using CHS addressing",
sector);
/* Calculate the sector, cylinder and head to use. */ /* Calculate the sector, cylinder and head to use. */
sect = ((grub_uint32_t) sector % dev->sectors_per_track) + 1; sect = ((grub_uint32_t) sector % dev->sectors_per_track) + 1;
@@ -232,8 +233,9 @@ grub_ata_setaddress (struct grub_ata *dev,
|| cylinder > dev->cylinders || cylinder > dev->cylinders
|| head > dev->heads) || head > dev->heads)
return grub_error (GRUB_ERR_OUT_OF_RANGE, return grub_error (GRUB_ERR_OUT_OF_RANGE,
"sector %d cannot be addressed " "sector %" PRIxGRUB_UINT64_T " cannot be "
"using CHS addressing", sector); "addressed using CHS addressing",
sector);
parms->taskfile.disk = 0xE0 | head; parms->taskfile.disk = 0xE0 | head;
parms->taskfile.sectnum = sect; parms->taskfile.sectnum = sect;
+214 -37
View File
@@ -1,6 +1,6 @@
/* /*
* GRUB -- GRand Unified Bootloader * GRUB -- GRand Unified Bootloader
* Copyright (C) 2003,2007,2010,2011 Free Software Foundation, Inc. * Copyright (C) 2003,2007,2010,2011,2019 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
@@ -224,7 +224,8 @@ lrw_xor (const struct lrw_sector *sec,
static gcry_err_code_t static gcry_err_code_t
grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev, grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
grub_uint8_t * data, grub_size_t len, grub_uint8_t * data, grub_size_t len,
grub_disk_addr_t sector, int do_encrypt) grub_disk_addr_t sector, grub_size_t log_sector_size,
int do_encrypt)
{ {
grub_size_t i; grub_size_t i;
gcry_err_code_t err; gcry_err_code_t err;
@@ -237,7 +238,7 @@ grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
return (do_encrypt ? grub_crypto_ecb_encrypt (dev->cipher, data, data, len) return (do_encrypt ? grub_crypto_ecb_encrypt (dev->cipher, data, data, len)
: grub_crypto_ecb_decrypt (dev->cipher, data, data, len)); : grub_crypto_ecb_decrypt (dev->cipher, data, data, len));
for (i = 0; i < len; i += (1U << dev->log_sector_size)) for (i = 0; i < len; i += (1U << log_sector_size))
{ {
grub_size_t sz = ((dev->cipher->cipher->blocksize grub_size_t sz = ((dev->cipher->cipher->blocksize
+ sizeof (grub_uint32_t) - 1) + sizeof (grub_uint32_t) - 1)
@@ -270,7 +271,7 @@ grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
if (!ctx) if (!ctx)
return GPG_ERR_OUT_OF_MEMORY; return GPG_ERR_OUT_OF_MEMORY;
tmp = grub_cpu_to_le64 (sector << dev->log_sector_size); tmp = grub_cpu_to_le64 (sector << log_sector_size);
dev->iv_hash->init (ctx); dev->iv_hash->init (ctx);
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));
@@ -281,25 +282,38 @@ grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
} }
break; break;
case GRUB_CRYPTODISK_MODE_IV_PLAIN64: case GRUB_CRYPTODISK_MODE_IV_PLAIN64:
iv[1] = grub_cpu_to_le32 (sector >> 32);
/* FALLTHROUGH */
case GRUB_CRYPTODISK_MODE_IV_PLAIN: case GRUB_CRYPTODISK_MODE_IV_PLAIN:
iv[0] = grub_cpu_to_le32 (sector & 0xFFFFFFFF); /*
* The IV is a 32 or 64 bit value of the dm-crypt native sector
* number. If using 32 bit IV mode, zero out the most significant
* 32 bits.
*/
{
grub_uint64_t iv64;
iv64 = grub_cpu_to_le64 (sector << (log_sector_size
- GRUB_CRYPTODISK_IV_LOG_SIZE));
grub_set_unaligned64 (iv, iv64);
if (dev->mode_iv == GRUB_CRYPTODISK_MODE_IV_PLAIN)
iv[1] = 0;
}
break; break;
case GRUB_CRYPTODISK_MODE_IV_BYTECOUNT64: case GRUB_CRYPTODISK_MODE_IV_BYTECOUNT64:
iv[1] = grub_cpu_to_le32 (sector >> (32 - dev->log_sector_size)); /* The IV is the 64 bit byte offset of the sector. */
iv[0] = grub_cpu_to_le32 ((sector << dev->log_sector_size) iv[1] = grub_cpu_to_le32 (sector >> (GRUB_TYPE_BITS (iv[1])
& 0xFFFFFFFF); - log_sector_size));
iv[0] = grub_cpu_to_le32 ((sector << log_sector_size)
& GRUB_TYPE_U_MAX (iv[0]));
break; break;
case GRUB_CRYPTODISK_MODE_IV_BENBI: case GRUB_CRYPTODISK_MODE_IV_BENBI:
{ {
grub_uint64_t num = (sector << dev->benbi_log) + 1; grub_uint64_t num = (sector << dev->benbi_log) + 1;
iv[sz - 2] = grub_cpu_to_be32 (num >> 32); iv[sz - 2] = grub_cpu_to_be32 (num >> GRUB_TYPE_BITS (iv[0]));
iv[sz - 1] = grub_cpu_to_be32 (num & 0xFFFFFFFF); iv[sz - 1] = grub_cpu_to_be32 (num & GRUB_TYPE_U_MAX (iv[0]));
} }
break; break;
case GRUB_CRYPTODISK_MODE_IV_ESSIV: case GRUB_CRYPTODISK_MODE_IV_ESSIV:
iv[0] = grub_cpu_to_le32 (sector & 0xFFFFFFFF); iv[0] = grub_cpu_to_le32 (sector & GRUB_TYPE_U_MAX (iv[0]));
err = grub_crypto_ecb_encrypt (dev->essiv_cipher, iv, iv, err = grub_crypto_ecb_encrypt (dev->essiv_cipher, iv, iv,
dev->cipher->cipher->blocksize); dev->cipher->cipher->blocksize);
if (err) if (err)
@@ -311,10 +325,10 @@ grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
case GRUB_CRYPTODISK_MODE_CBC: case GRUB_CRYPTODISK_MODE_CBC:
if (do_encrypt) if (do_encrypt)
err = grub_crypto_cbc_encrypt (dev->cipher, data + i, data + i, err = grub_crypto_cbc_encrypt (dev->cipher, data + i, data + i,
(1U << dev->log_sector_size), iv); ((grub_size_t) 1 << log_sector_size), iv);
else else
err = grub_crypto_cbc_decrypt (dev->cipher, data + i, data + i, err = grub_crypto_cbc_decrypt (dev->cipher, data + i, data + i,
(1U << dev->log_sector_size), iv); ((grub_size_t) 1 << log_sector_size), iv);
if (err) if (err)
return err; return err;
break; break;
@@ -322,10 +336,10 @@ grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
case GRUB_CRYPTODISK_MODE_PCBC: case GRUB_CRYPTODISK_MODE_PCBC:
if (do_encrypt) if (do_encrypt)
err = grub_crypto_pcbc_encrypt (dev->cipher, data + i, data + i, err = grub_crypto_pcbc_encrypt (dev->cipher, data + i, data + i,
(1U << dev->log_sector_size), iv); ((grub_size_t) 1 << log_sector_size), iv);
else else
err = grub_crypto_pcbc_decrypt (dev->cipher, data + i, data + i, err = grub_crypto_pcbc_decrypt (dev->cipher, data + i, data + i,
(1U << dev->log_sector_size), iv); ((grub_size_t) 1 << log_sector_size), iv);
if (err) if (err)
return err; return err;
break; break;
@@ -337,7 +351,7 @@ grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
if (err) if (err)
return err; return err;
for (j = 0; j < (1U << dev->log_sector_size); for (j = 0; j < (1U << log_sector_size);
j += dev->cipher->cipher->blocksize) j += dev->cipher->cipher->blocksize)
{ {
grub_crypto_xor (data + i + j, data + i + j, iv, grub_crypto_xor (data + i + j, data + i + j, iv,
@@ -368,11 +382,11 @@ grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
if (do_encrypt) if (do_encrypt)
err = grub_crypto_ecb_encrypt (dev->cipher, data + i, err = grub_crypto_ecb_encrypt (dev->cipher, data + i,
data + i, data + i,
(1U << dev->log_sector_size)); (1U << log_sector_size));
else else
err = grub_crypto_ecb_decrypt (dev->cipher, data + i, err = grub_crypto_ecb_decrypt (dev->cipher, data + i,
data + i, data + i,
(1U << dev->log_sector_size)); (1U << log_sector_size));
if (err) if (err)
return err; return err;
lrw_xor (&sec, dev, data + i); lrw_xor (&sec, dev, data + i);
@@ -381,10 +395,10 @@ grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
case GRUB_CRYPTODISK_MODE_ECB: case GRUB_CRYPTODISK_MODE_ECB:
if (do_encrypt) if (do_encrypt)
err = grub_crypto_ecb_encrypt (dev->cipher, data + i, data + i, err = grub_crypto_ecb_encrypt (dev->cipher, data + i, data + i,
(1U << dev->log_sector_size)); (1U << log_sector_size));
else else
err = grub_crypto_ecb_decrypt (dev->cipher, data + i, data + i, err = grub_crypto_ecb_decrypt (dev->cipher, data + i, data + i,
(1U << dev->log_sector_size)); (1U << log_sector_size));
if (err) if (err)
return err; return err;
break; break;
@@ -399,9 +413,174 @@ grub_cryptodisk_endecrypt (struct grub_cryptodisk *dev,
gcry_err_code_t gcry_err_code_t
grub_cryptodisk_decrypt (struct grub_cryptodisk *dev, grub_cryptodisk_decrypt (struct grub_cryptodisk *dev,
grub_uint8_t * data, grub_size_t len, grub_uint8_t * data, grub_size_t len,
grub_disk_addr_t sector) grub_disk_addr_t sector, grub_size_t log_sector_size)
{ {
return grub_cryptodisk_endecrypt (dev, data, len, sector, 0); return grub_cryptodisk_endecrypt (dev, data, len, sector, log_sector_size, 0);
}
grub_err_t
grub_cryptodisk_setcipher (grub_cryptodisk_t crypt, const char *ciphername, const char *ciphermode)
{
const char *cipheriv = NULL;
grub_crypto_cipher_handle_t cipher = NULL, secondary_cipher = NULL;
grub_crypto_cipher_handle_t essiv_cipher = NULL;
const gcry_md_spec_t *essiv_hash = NULL;
const struct gcry_cipher_spec *ciph;
grub_cryptodisk_mode_t mode;
grub_cryptodisk_mode_iv_t mode_iv = GRUB_CRYPTODISK_MODE_IV_PLAIN64;
int benbi_log = 0;
grub_err_t ret = GRUB_ERR_NONE;
ciph = grub_crypto_lookup_cipher_by_name (ciphername);
if (!ciph)
{
ret = grub_error (GRUB_ERR_FILE_NOT_FOUND, "Cipher %s isn't available",
ciphername);
goto err;
}
/* Configure the cipher used for the bulk data. */
cipher = grub_crypto_cipher_open (ciph);
if (!cipher)
{
ret = grub_error (GRUB_ERR_FILE_NOT_FOUND, "Cipher %s could not be initialized",
ciphername);
goto err;
}
/* Configure the cipher mode. */
if (grub_strcmp (ciphermode, "ecb") == 0)
{
mode = GRUB_CRYPTODISK_MODE_ECB;
mode_iv = GRUB_CRYPTODISK_MODE_IV_PLAIN;
cipheriv = NULL;
}
else if (grub_strcmp (ciphermode, "plain") == 0)
{
mode = GRUB_CRYPTODISK_MODE_CBC;
mode_iv = GRUB_CRYPTODISK_MODE_IV_PLAIN;
cipheriv = NULL;
}
else if (grub_memcmp (ciphermode, "cbc-", sizeof ("cbc-") - 1) == 0)
{
mode = GRUB_CRYPTODISK_MODE_CBC;
cipheriv = ciphermode + sizeof ("cbc-") - 1;
}
else if (grub_memcmp (ciphermode, "pcbc-", sizeof ("pcbc-") - 1) == 0)
{
mode = GRUB_CRYPTODISK_MODE_PCBC;
cipheriv = ciphermode + sizeof ("pcbc-") - 1;
}
else if (grub_memcmp (ciphermode, "xts-", sizeof ("xts-") - 1) == 0)
{
mode = GRUB_CRYPTODISK_MODE_XTS;
cipheriv = ciphermode + sizeof ("xts-") - 1;
secondary_cipher = grub_crypto_cipher_open (ciph);
if (!secondary_cipher)
{
ret = grub_error (GRUB_ERR_FILE_NOT_FOUND,
"Secondary cipher %s isn't available", ciphername);
goto err;
}
if (cipher->cipher->blocksize != GRUB_CRYPTODISK_GF_BYTES)
{
ret = grub_error (GRUB_ERR_BAD_ARGUMENT,
"Unsupported XTS block size: %" PRIuGRUB_SIZE,
cipher->cipher->blocksize);
goto err;
}
if (secondary_cipher->cipher->blocksize != GRUB_CRYPTODISK_GF_BYTES)
{
ret = grub_error (GRUB_ERR_BAD_ARGUMENT,
"Unsupported XTS block size: %" PRIuGRUB_SIZE,
secondary_cipher->cipher->blocksize);
goto err;
}
}
else if (grub_memcmp (ciphermode, "lrw-", sizeof ("lrw-") - 1) == 0)
{
mode = GRUB_CRYPTODISK_MODE_LRW;
cipheriv = ciphermode + sizeof ("lrw-") - 1;
if (cipher->cipher->blocksize != GRUB_CRYPTODISK_GF_BYTES)
{
ret = grub_error (GRUB_ERR_BAD_ARGUMENT,
"Unsupported LRW block size: %" PRIuGRUB_SIZE,
cipher->cipher->blocksize);
goto err;
}
}
else
{
ret = grub_error (GRUB_ERR_BAD_ARGUMENT, "Unknown cipher mode: %s",
ciphermode);
goto err;
}
if (cipheriv == NULL)
;
else if (grub_memcmp (cipheriv, "plain64", sizeof ("plain64") - 1) == 0)
mode_iv = GRUB_CRYPTODISK_MODE_IV_PLAIN64;
else if (grub_memcmp (cipheriv, "plain", sizeof ("plain") - 1) == 0)
mode_iv = GRUB_CRYPTODISK_MODE_IV_PLAIN;
else if (grub_memcmp (cipheriv, "benbi", sizeof ("benbi") - 1) == 0)
{
if (cipher->cipher->blocksize & (cipher->cipher->blocksize - 1)
|| cipher->cipher->blocksize == 0)
grub_error (GRUB_ERR_BAD_ARGUMENT,
"Unsupported benbi blocksize: %" PRIuGRUB_SIZE,
cipher->cipher->blocksize);
/* FIXME should we return an error here? */
for (benbi_log = 0;
(cipher->cipher->blocksize << benbi_log) < GRUB_DISK_SECTOR_SIZE;
benbi_log++);
mode_iv = GRUB_CRYPTODISK_MODE_IV_BENBI;
}
else if (grub_memcmp (cipheriv, "null", sizeof ("null") - 1) == 0)
mode_iv = GRUB_CRYPTODISK_MODE_IV_NULL;
else if (grub_memcmp (cipheriv, "essiv:", sizeof ("essiv:") - 1) == 0)
{
const char *hash_str = cipheriv + 6;
mode_iv = GRUB_CRYPTODISK_MODE_IV_ESSIV;
/* Configure the hash and cipher used for ESSIV. */
essiv_hash = grub_crypto_lookup_md_by_name (hash_str);
if (!essiv_hash)
{
ret = grub_error (GRUB_ERR_FILE_NOT_FOUND,
"Couldn't load %s hash", hash_str);
goto err;
}
essiv_cipher = grub_crypto_cipher_open (ciph);
if (!essiv_cipher)
{
ret = grub_error (GRUB_ERR_FILE_NOT_FOUND,
"Couldn't load %s cipher", ciphername);
goto err;
}
}
else
{
ret = grub_error (GRUB_ERR_BAD_ARGUMENT, "Unknown IV mode: %s",
cipheriv);
goto err;
}
crypt->cipher = cipher;
crypt->benbi_log = benbi_log;
crypt->mode = mode;
crypt->mode_iv = mode_iv;
crypt->secondary_cipher = secondary_cipher;
crypt->essiv_cipher = essiv_cipher;
crypt->essiv_hash = essiv_hash;
err:
if (ret)
{
grub_crypto_cipher_close (cipher);
grub_crypto_cipher_close (secondary_cipher);
}
return ret;
} }
gcry_err_code_t gcry_err_code_t
@@ -538,7 +717,7 @@ grub_cryptodisk_open (const char *name, grub_disk_t disk)
} }
disk->data = dev; disk->data = dev;
disk->total_sectors = dev->total_length; disk->total_sectors = dev->total_sectors;
disk->max_agglomerate = GRUB_DISK_MAX_MAX_AGGLOMERATE; disk->max_agglomerate = GRUB_DISK_MAX_MAX_AGGLOMERATE;
disk->id = dev->id; disk->id = dev->id;
dev->ref++; dev->ref++;
@@ -593,12 +772,11 @@ grub_cryptodisk_read (grub_disk_t disk, grub_disk_addr_t sector,
grub_dprintf ("cryptodisk", grub_dprintf ("cryptodisk",
"Reading %" PRIuGRUB_SIZE " sectors from sector 0x%" "Reading %" PRIuGRUB_SIZE " sectors from sector 0x%"
PRIxGRUB_UINT64_T " with offset of %" PRIuGRUB_UINT64_T "\n", PRIxGRUB_UINT64_T " with offset of %" PRIuGRUB_UINT64_T "\n",
size, sector, dev->offset); size, sector, dev->offset_sectors);
err = grub_disk_read (dev->source_disk, err = grub_disk_read (dev->source_disk,
(sector << (disk->log_sector_size grub_disk_from_native_sector (disk, sector + dev->offset_sectors),
- GRUB_DISK_SECTOR_BITS)) + dev->offset, 0, 0, size << disk->log_sector_size, buf);
size << disk->log_sector_size, buf);
if (err) if (err)
{ {
grub_dprintf ("cryptodisk", "grub_disk_read failed with error %d\n", err); grub_dprintf ("cryptodisk", "grub_disk_read failed with error %d\n", err);
@@ -606,7 +784,7 @@ grub_cryptodisk_read (grub_disk_t disk, grub_disk_addr_t sector,
} }
gcry_err = grub_cryptodisk_endecrypt (dev, (grub_uint8_t *) buf, gcry_err = grub_cryptodisk_endecrypt (dev, (grub_uint8_t *) buf,
size << disk->log_sector_size, size << disk->log_sector_size,
sector, 0); sector, dev->log_sector_size, 0);
return grub_crypto_gcry_error (gcry_err); return grub_crypto_gcry_error (gcry_err);
} }
@@ -643,11 +821,11 @@ grub_cryptodisk_write (grub_disk_t disk, grub_disk_addr_t sector,
grub_dprintf ("cryptodisk", grub_dprintf ("cryptodisk",
"Writing %" PRIuGRUB_SIZE " sectors to sector 0x%" "Writing %" PRIuGRUB_SIZE " sectors to sector 0x%"
PRIxGRUB_UINT64_T " with offset of %" PRIuGRUB_UINT64_T "\n", PRIxGRUB_UINT64_T " with offset of %" PRIuGRUB_UINT64_T "\n",
size, sector, dev->offset); size, sector, dev->offset_sectors);
gcry_err = grub_cryptodisk_endecrypt (dev, (grub_uint8_t *) tmp, gcry_err = grub_cryptodisk_endecrypt (dev, (grub_uint8_t *) tmp,
size << disk->log_sector_size, size << disk->log_sector_size,
sector, 1); sector, disk->log_sector_size, 1);
if (gcry_err) if (gcry_err)
{ {
grub_free (tmp); grub_free (tmp);
@@ -655,12 +833,10 @@ grub_cryptodisk_write (grub_disk_t disk, grub_disk_addr_t sector,
} }
/* Since ->write was called so disk.mod is loaded but be paranoid */ /* Since ->write was called so disk.mod is loaded but be paranoid */
sector = sector + dev->offset_sectors;
if (grub_disk_write_weak) if (grub_disk_write_weak)
err = grub_disk_write_weak (dev->source_disk, err = grub_disk_write_weak (dev->source_disk,
(sector << (disk->log_sector_size grub_disk_from_native_sector (disk, sector),
- GRUB_DISK_SECTOR_BITS))
+ dev->offset,
0, size << disk->log_sector_size, tmp); 0, size << disk->log_sector_size, tmp);
else else
err = grub_error (GRUB_ERR_BUG, "disk.mod not loaded"); err = grub_error (GRUB_ERR_BUG, "disk.mod not loaded");
@@ -1070,7 +1246,7 @@ luks_script_get (grub_size_t *sz)
ptr = grub_stpcpy (ptr, "luks_mount "); ptr = grub_stpcpy (ptr, "luks_mount ");
ptr = grub_stpcpy (ptr, i->uuid); ptr = grub_stpcpy (ptr, i->uuid);
*ptr++ = ' '; *ptr++ = ' ';
grub_snprintf (ptr, 21, "%" PRIuGRUB_UINT64_T " ", i->offset); grub_snprintf (ptr, 21, "%" PRIuGRUB_UINT64_T " ", i->offset_sectors);
while (*ptr) while (*ptr)
ptr++; ptr++;
for (iptr = i->cipher->cipher->name; *iptr; iptr++) for (iptr = i->cipher->cipher->name; *iptr; iptr++)
@@ -1150,5 +1326,6 @@ GRUB_MOD_FINI (cryptodisk)
{ {
grub_disk_dev_unregister (&grub_cryptodisk_dev); grub_disk_dev_unregister (&grub_cryptodisk_dev);
cryptodisk_cleanup (); cryptodisk_cleanup ();
grub_unregister_extcmd (cmd);
grub_procfs_unregister (&luks_script); grub_procfs_unregister (&luks_script);
} }
+10 -9
View File
@@ -148,7 +148,7 @@ scan_disk_partition_iter (grub_disk_t disk, grub_partition_t p, void *data)
if (m->disk && m->disk->id == disk->id if (m->disk && m->disk->id == disk->id
&& m->disk->dev->id == disk->dev->id && m->disk->dev->id == disk->dev->id
&& m->part_start == grub_partition_get_start (disk->partition) && m->part_start == grub_partition_get_start (disk->partition)
&& m->part_size == grub_disk_get_size (disk)) && m->part_size == grub_disk_native_sectors (disk))
return 0; return 0;
} }
@@ -969,7 +969,8 @@ grub_diskfilter_vg_register (struct grub_diskfilter_vg *vg)
for (p = vgp->lvs; p; p = p->next) for (p = vgp->lvs; p; p = p->next)
{ {
int cur_num; int cur_num;
char *num, *end; char *num;
const char *end;
if (!p->fullname) if (!p->fullname)
continue; continue;
if (grub_strncmp (p->fullname, lv->fullname, len) != 0) if (grub_strncmp (p->fullname, lv->fullname, len) != 0)
@@ -1134,7 +1135,7 @@ grub_diskfilter_make_raid (grub_size_t uuidlen, char *uuid, int nmemb,
array->lvs->segments->node_count = nmemb; array->lvs->segments->node_count = nmemb;
array->lvs->segments->raid_member_size = disk_size; array->lvs->segments->raid_member_size = disk_size;
array->lvs->segments->nodes array->lvs->segments->nodes
= grub_zalloc (nmemb * sizeof (array->lvs->segments->nodes[0])); = grub_calloc (nmemb, sizeof (array->lvs->segments->nodes[0]));
array->lvs->segments->stripe_size = stripe_size; array->lvs->segments->stripe_size = stripe_size;
for (i = 0; i < nmemb; i++) for (i = 0; i < nmemb; i++)
{ {
@@ -1189,13 +1190,13 @@ insert_array (grub_disk_t disk, const struct grub_diskfilter_pv_id *id,
grub_dprintf ("diskfilter", "Inserting %s (+%lld,%lld) into %s (%s)\n", disk->name, grub_dprintf ("diskfilter", "Inserting %s (+%lld,%lld) into %s (%s)\n", disk->name,
(unsigned long long) grub_partition_get_start (disk->partition), (unsigned long long) grub_partition_get_start (disk->partition),
(unsigned long long) grub_disk_get_size (disk), (unsigned long long) grub_disk_native_sectors (disk),
array->name, diskfilter->name); array->name, diskfilter->name);
#ifdef GRUB_UTIL #ifdef GRUB_UTIL
grub_util_info ("Inserting %s (+%" GRUB_HOST_PRIuLONG_LONG ",%" grub_util_info ("Inserting %s (+%" GRUB_HOST_PRIuLONG_LONG ",%"
GRUB_HOST_PRIuLONG_LONG ") into %s (%s)\n", disk->name, GRUB_HOST_PRIuLONG_LONG ") into %s (%s)\n", disk->name,
(unsigned long long) grub_partition_get_start (disk->partition), (unsigned long long) grub_partition_get_start (disk->partition),
(unsigned long long) grub_disk_get_size (disk), (unsigned long long) grub_disk_native_sectors (disk),
array->name, diskfilter->name); array->name, diskfilter->name);
array->driver = diskfilter; array->driver = diskfilter;
#endif #endif
@@ -1209,7 +1210,7 @@ insert_array (grub_disk_t disk, const struct grub_diskfilter_pv_id *id,
struct grub_diskfilter_lv *lv; struct grub_diskfilter_lv *lv;
/* FIXME: Check whether the update time of the superblocks are /* FIXME: Check whether the update time of the superblocks are
the same. */ the same. */
if (pv->disk && grub_disk_get_size (disk) >= pv->part_size) if (pv->disk && grub_disk_native_sectors (disk) >= pv->part_size)
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
pv->disk = grub_disk_open (disk->name); pv->disk = grub_disk_open (disk->name);
if (!pv->disk) if (!pv->disk)
@@ -1218,7 +1219,7 @@ insert_array (grub_disk_t disk, const struct grub_diskfilter_pv_id *id,
raid device, we shouldn't change it. */ raid device, we shouldn't change it. */
pv->start_sector -= pv->part_start; pv->start_sector -= pv->part_start;
pv->part_start = grub_partition_get_start (disk->partition); pv->part_start = grub_partition_get_start (disk->partition);
pv->part_size = grub_disk_get_size (disk); pv->part_size = grub_disk_native_sectors (disk);
#ifdef GRUB_UTIL #ifdef GRUB_UTIL
{ {
@@ -1226,7 +1227,7 @@ insert_array (grub_disk_t disk, const struct grub_diskfilter_pv_id *id,
grub_partition_t p; grub_partition_t p;
for (p = disk->partition; p; p = p->parent) for (p = disk->partition; p; p = p->parent)
s++; s++;
pv->partmaps = xmalloc (s * sizeof (pv->partmaps[0])); pv->partmaps = xcalloc (s, sizeof (pv->partmaps[0]));
s = 0; s = 0;
for (p = disk->partition; p; p = p->parent) for (p = disk->partition; p; p = p->parent)
pv->partmaps[s++] = xstrdup (p->partmap->name); pv->partmaps[s++] = xstrdup (p->partmap->name);
@@ -1310,7 +1311,7 @@ grub_diskfilter_get_pv_from_disk (grub_disk_t disk,
if (pv->disk && pv->disk->id == disk->id if (pv->disk && pv->disk->id == disk->id
&& pv->disk->dev->id == disk->dev->id && pv->disk->dev->id == disk->dev->id
&& pv->part_start == grub_partition_get_start (disk->partition) && pv->part_start == grub_partition_get_start (disk->partition)
&& pv->part_size == grub_disk_get_size (disk)) && pv->part_size == grub_disk_native_sectors (disk))
{ {
if (vg_out) if (vg_out)
*vg_out = vg; *vg_out = vg;
+2 -2
View File
@@ -107,7 +107,7 @@ grub_dmraid_nv_detect (grub_disk_t disk,
/* Skip partition. */ /* Skip partition. */
return NULL; return NULL;
sector = grub_disk_get_size (disk); sector = grub_disk_native_sectors (disk);
if (sector == GRUB_DISK_SIZE_UNKNOWN) if (sector == GRUB_DISK_SIZE_UNKNOWN)
/* Not raid. */ /* Not raid. */
return NULL; return NULL;
@@ -122,7 +122,7 @@ grub_dmraid_nv_detect (grub_disk_t disk,
if (sb.version != NV_VERSION) if (sb.version != NV_VERSION)
{ {
grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"unknown version: %d.%d", sb.version); "unknown version: %d.%d", sb.version >> 8, sb.version & 0xFF);
return NULL; return NULL;
} }
+1 -1
View File
@@ -867,7 +867,7 @@ grub_efidisk_get_device_name (grub_efi_handle_t *handle)
if (ctx.hd->partition_start == 0 if (ctx.hd->partition_start == 0
&& (ctx.hd->partition_size << (parent->log_sector_size && (ctx.hd->partition_size << (parent->log_sector_size
- GRUB_DISK_SECTOR_BITS)) - GRUB_DISK_SECTOR_BITS))
== grub_disk_get_size (parent)) == grub_disk_native_sectors (parent))
{ {
dev_name = grub_strdup (parent->name); dev_name = grub_strdup (parent->name);
} }
+4 -4
View File
@@ -258,7 +258,7 @@ configure_ciphers (grub_disk_t disk, const char *check_uuid,
if (2 * GRUB_MD_SHA256->mdlen + 1 > GRUB_CRYPTODISK_MAX_UUID_LENGTH) if (2 * GRUB_MD_SHA256->mdlen + 1 > GRUB_CRYPTODISK_MAX_UUID_LENGTH)
return NULL; return NULL;
sector = grub_disk_get_size (disk); sector = grub_disk_native_sectors (disk);
if (sector == GRUB_DISK_SIZE_UNKNOWN || sector == 0) if (sector == GRUB_DISK_SIZE_UNKNOWN || sector == 0)
return NULL; return NULL;
@@ -361,7 +361,7 @@ configure_ciphers (grub_disk_t disk, const char *check_uuid,
} }
newdev->cipher = cipher; newdev->cipher = cipher;
newdev->secondary_cipher = secondary_cipher; newdev->secondary_cipher = secondary_cipher;
newdev->offset = 0; newdev->offset_sectors = 0;
newdev->source_disk = NULL; newdev->source_disk = NULL;
newdev->benbi_log = 0; newdev->benbi_log = 0;
if (grub_le_to_cpu16 (header.alg) == 0x16) if (grub_le_to_cpu16 (header.alg) == 0x16)
@@ -391,7 +391,7 @@ configure_ciphers (grub_disk_t disk, const char *check_uuid,
newdev->modname = "geli"; newdev->modname = "geli";
newdev->total_length = grub_disk_get_size (disk) - 1; newdev->total_sectors = grub_disk_native_sectors (disk) - 1;
grub_memcpy (newdev->uuid, uuid, sizeof (newdev->uuid)); grub_memcpy (newdev->uuid, uuid, sizeof (newdev->uuid));
COMPILE_TIME_ASSERT (sizeof (newdev->uuid) >= 32 * 2 + 1); COMPILE_TIME_ASSERT (sizeof (newdev->uuid) >= 32 * 2 + 1);
return newdev; return newdev;
@@ -420,7 +420,7 @@ recover_key (grub_disk_t source, grub_cryptodisk_t dev)
if (dev->hash->mdlen > GRUB_CRYPTO_MAX_MDLEN) if (dev->hash->mdlen > GRUB_CRYPTO_MAX_MDLEN)
return grub_error (GRUB_ERR_BUG, "mdlen is too long"); return grub_error (GRUB_ERR_BUG, "mdlen is too long");
sector = grub_disk_get_size (source); sector = grub_disk_native_sectors (source);
if (sector == GRUB_DISK_SIZE_UNKNOWN || sector == 0) if (sector == GRUB_DISK_SIZE_UNKNOWN || sector == 0)
return grub_error (GRUB_ERR_BUG, "not a geli"); return grub_error (GRUB_ERR_BUG, "not a geli");
+1 -1
View File
@@ -297,7 +297,7 @@ dev_iterate (const struct grub_ieee1275_devalias *alias)
/* Power machines documentation specify 672 as maximum SAS disks in /* Power machines documentation specify 672 as maximum SAS disks in
one system. Using a slightly larger value to be safe. */ one system. Using a slightly larger value to be safe. */
table_size = 768; table_size = 768;
table = grub_malloc (table_size * sizeof (grub_uint64_t)); table = grub_calloc (table_size, sizeof (grub_uint64_t));
if (!table) if (!table)
{ {
+84 -26
View File
@@ -25,6 +25,7 @@
#include <grub/msdos_partition.h> #include <grub/msdos_partition.h>
#include <grub/gpt_partition.h> #include <grub/gpt_partition.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/safemath.h>
#ifdef GRUB_UTIL #ifdef GRUB_UTIL
#include <grub/emu/misc.h> #include <grub/emu/misc.h>
@@ -198,6 +199,7 @@ make_vg (grub_disk_t disk,
{ {
grub_free (vg->uuid); grub_free (vg->uuid);
grub_free (vg->name); grub_free (vg->name);
grub_free (vg);
return NULL; return NULL;
} }
grub_memcpy (vg->uuid, label->group_guid, LDM_GUID_STRLEN); grub_memcpy (vg->uuid, label->group_guid, LDM_GUID_STRLEN);
@@ -289,6 +291,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)
@@ -318,15 +321,21 @@ make_vg (grub_disk_t disk,
lv->visible = 1; lv->visible = 1;
lv->segments = grub_zalloc (sizeof (*lv->segments)); lv->segments = grub_zalloc (sizeof (*lv->segments));
if (!lv->segments) if (!lv->segments)
goto fail2; {
grub_free (lv);
goto fail2;
}
lv->segments->start_extent = 0; lv->segments->start_extent = 0;
lv->segments->type = GRUB_DISKFILTER_MIRROR; lv->segments->type = GRUB_DISKFILTER_MIRROR;
lv->segments->node_count = 0; lv->segments->node_count = 0;
lv->segments->node_alloc = 8; lv->segments->node_alloc = 8;
lv->segments->nodes = grub_zalloc (sizeof (*lv->segments->nodes) lv->segments->nodes = grub_calloc (lv->segments->node_alloc,
* lv->segments->node_alloc); sizeof (*lv->segments->nodes));
if (!lv->segments->nodes) if (!lv->segments->nodes)
goto fail2; {
grub_free (lv);
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))
@@ -350,7 +359,13 @@ make_vg (grub_disk_t disk,
grub_free (lv); grub_free (lv);
goto fail2; goto fail2;
} }
lv->name = grub_malloc (*ptr + 1); if (grub_add (*ptr, 1, &sz))
{
grub_free (lv->internal_id);
grub_free (lv);
goto fail2;
}
lv->name = grub_malloc (sz);
if (!lv->name) if (!lv->name)
{ {
grub_free (lv->internal_id); grub_free (lv->internal_id);
@@ -543,10 +558,14 @@ make_vg (grub_disk_t disk,
{ {
comp->segment_alloc = 8; comp->segment_alloc = 8;
comp->segment_count = 0; comp->segment_count = 0;
comp->segments = grub_malloc (sizeof (*comp->segments) comp->segments = grub_calloc (comp->segment_alloc,
* comp->segment_alloc); sizeof (*comp->segments));
if (!comp->segments) if (!comp->segments)
goto fail2; {
grub_free (comp->internal_id);
grub_free (comp);
goto fail2;
}
} }
else else
{ {
@@ -554,7 +573,11 @@ make_vg (grub_disk_t disk,
comp->segment_count = 1; comp->segment_count = 1;
comp->segments = grub_malloc (sizeof (*comp->segments)); comp->segments = grub_malloc (sizeof (*comp->segments));
if (!comp->segments) if (!comp->segments)
goto fail2; {
grub_free (comp->internal_id);
grub_free (comp);
goto fail2;
}
comp->segments->start_extent = 0; comp->segments->start_extent = 0;
comp->segments->extent_count = lv->size; comp->segments->extent_count = lv->size;
comp->segments->layout = 0; comp->segments->layout = 0;
@@ -566,15 +589,26 @@ make_vg (grub_disk_t disk,
comp->segments->layout = GRUB_RAID_LAYOUT_SYMMETRIC_MASK; comp->segments->layout = GRUB_RAID_LAYOUT_SYMMETRIC_MASK;
} }
else else
goto fail2; {
grub_free (comp->segments);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2;
}
ptr += *ptr + 1; ptr += *ptr + 1;
ptr++; ptr++;
if (!(vblk[i].flags & 0x10)) if (!(vblk[i].flags & 0x10))
goto fail2; {
grub_free (comp->segments);
grub_free (comp->internal_id);
grub_free (comp);
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);
grub_free (comp->internal_id); grub_free (comp->internal_id);
grub_free (comp); grub_free (comp);
goto fail2; goto fail2;
@@ -584,27 +618,48 @@ 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);
grub_free (comp->internal_id); grub_free (comp->internal_id);
grub_free (comp); 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_zalloc (sizeof (*comp->segments->nodes) comp->segments->nodes = grub_calloc (comp->segments->node_alloc,
* comp->segments->node_alloc); sizeof (*comp->segments->nodes));
if (!lv->segments->nodes) if (!lv->segments->nodes)
goto fail2; {
grub_free (comp->segments);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2;
}
} }
if (lv->segments->node_alloc == lv->segments->node_count) if (lv->segments->node_alloc == lv->segments->node_count)
{ {
void *t; void *t;
lv->segments->node_alloc *= 2; grub_size_t sz;
t = grub_realloc (lv->segments->nodes,
sizeof (*lv->segments->nodes) if (grub_mul (lv->segments->node_alloc, 2, &lv->segments->node_alloc) ||
* lv->segments->node_alloc); grub_mul (lv->segments->node_alloc, sizeof (*lv->segments->nodes), &sz))
{
grub_free (comp->segments->nodes);
grub_free (comp->segments);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2;
}
t = grub_realloc (lv->segments->nodes, sz);
if (!t) if (!t)
goto fail2; {
grub_free (comp->segments->nodes);
grub_free (comp->segments);
grub_free (comp->internal_id);
grub_free (comp);
goto fail2;
}
lv->segments->nodes = t; lv->segments->nodes = t;
} }
lv->segments->nodes[lv->segments->node_count].pv = 0; lv->segments->nodes[lv->segments->node_count].pv = 0;
@@ -723,10 +778,13 @@ make_vg (grub_disk_t disk,
if (comp->segment_alloc == comp->segment_count) if (comp->segment_alloc == comp->segment_count)
{ {
void *t; void *t;
comp->segment_alloc *= 2; grub_size_t sz;
t = grub_realloc (comp->segments,
comp->segment_alloc if (grub_mul (comp->segment_alloc, 2, &comp->segment_alloc) ||
* sizeof (*comp->segments)); grub_mul (comp->segment_alloc, sizeof (*comp->segments), &sz))
goto fail2;
t = grub_realloc (comp->segments, sz);
if (!t) if (!t)
goto fail2; goto fail2;
comp->segments = t; comp->segments = t;
@@ -807,7 +865,7 @@ grub_ldm_detect (grub_disk_t disk,
/* LDM is never inside a partition. */ /* LDM is never inside a partition. */
if (!has_ldm || disk->partition) if (!has_ldm || disk->partition)
continue; continue;
sector = grub_disk_get_size (disk); sector = grub_disk_native_sectors (disk);
if (sector == GRUB_DISK_SIZE_UNKNOWN) if (sector == GRUB_DISK_SIZE_UNKNOWN)
continue; continue;
sector--; sector--;
@@ -924,7 +982,7 @@ grub_util_is_ldm (grub_disk_t disk)
/* LDM is never inside a partition. */ /* LDM is never inside a partition. */
if (!has_ldm || disk->partition) if (!has_ldm || disk->partition)
continue; continue;
sector = grub_disk_get_size (disk); sector = grub_disk_native_sectors (disk);
if (sector == GRUB_DISK_SIZE_UNKNOWN) if (sector == GRUB_DISK_SIZE_UNKNOWN)
continue; continue;
sector--; sector--;
@@ -1017,7 +1075,7 @@ grub_util_ldm_embed (struct grub_disk *disk, unsigned int *nsectors,
*nsectors = lv->size; *nsectors = lv->size;
if (*nsectors > max_nsectors) if (*nsectors > max_nsectors)
*nsectors = max_nsectors; *nsectors = max_nsectors;
*sectors = grub_malloc (*nsectors * sizeof (**sectors)); *sectors = grub_calloc (*nsectors, sizeof (**sectors));
if (!*sectors) if (!*sectors)
return grub_errno; return grub_errno;
for (i = 0; i < *nsectors; i++) for (i = 0; i < *nsectors; i++)
+5 -13
View File
@@ -92,24 +92,16 @@ grub_cmd_loopback (grub_extcmd_context_t ctxt, int argc, char **args)
if (argc < 2) if (argc < 2)
return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected")); return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected"));
/* Check that a device with requested name does not already exist. */
for (newdev = loopback_list; newdev; newdev = newdev->next)
if (grub_strcmp (newdev->devname, args[0]) == 0)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "device name already exists");
file = grub_file_open (args[1], GRUB_FILE_TYPE_LOOPBACK file = grub_file_open (args[1], GRUB_FILE_TYPE_LOOPBACK
| GRUB_FILE_TYPE_NO_DECOMPRESS); | GRUB_FILE_TYPE_NO_DECOMPRESS);
if (! file) if (! file)
return grub_errno; return grub_errno;
/* First try to replace the old device. */
for (newdev = loopback_list; newdev; newdev = newdev->next)
if (grub_strcmp (newdev->devname, args[0]) == 0)
break;
if (newdev)
{
grub_file_close (newdev->file);
newdev->file = file;
return 0;
}
/* Unable to replace it, make a new entry. */ /* Unable to replace it, make a new entry. */
newdev = grub_malloc (sizeof (struct grub_loopback)); newdev = grub_malloc (sizeof (struct grub_loopback));
if (! newdev) if (! newdev)
+20 -176
View File
@@ -1,6 +1,6 @@
/* /*
* GRUB -- GRand Unified Bootloader * GRUB -- GRand Unified Bootloader
* Copyright (C) 2003,2007,2010,2011 Free Software Foundation, Inc. * Copyright (C) 2003,2007,2010,2011,2019 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
@@ -75,15 +75,7 @@ configure_ciphers (grub_disk_t disk, const char *check_uuid,
char uuid[sizeof (header.uuid) + 1]; char uuid[sizeof (header.uuid) + 1];
char ciphername[sizeof (header.cipherName) + 1]; char ciphername[sizeof (header.cipherName) + 1];
char ciphermode[sizeof (header.cipherMode) + 1]; char ciphermode[sizeof (header.cipherMode) + 1];
char *cipheriv = NULL;
char hashspec[sizeof (header.hashSpec) + 1]; char hashspec[sizeof (header.hashSpec) + 1];
grub_crypto_cipher_handle_t cipher = NULL, secondary_cipher = NULL;
grub_crypto_cipher_handle_t essiv_cipher = NULL;
const gcry_md_spec_t *hash = NULL, *essiv_hash = NULL;
const struct gcry_cipher_spec *ciph;
grub_cryptodisk_mode_t mode;
grub_cryptodisk_mode_iv_t mode_iv = GRUB_CRYPTODISK_MODE_IV_PLAIN64;
int benbi_log = 0;
grub_err_t err; grub_err_t err;
if (check_boot) if (check_boot)
@@ -103,6 +95,7 @@ configure_ciphers (grub_disk_t disk, const char *check_uuid,
|| grub_be_to_cpu16 (header.version) != 1) || grub_be_to_cpu16 (header.version) != 1)
return NULL; return NULL;
grub_memset (uuid, 0, sizeof (uuid));
optr = uuid; optr = uuid;
for (iptr = header.uuid; iptr < &header.uuid[ARRAY_SIZE (header.uuid)]; for (iptr = header.uuid; iptr < &header.uuid[ARRAY_SIZE (header.uuid)];
iptr++) iptr++)
@@ -126,183 +119,33 @@ configure_ciphers (grub_disk_t disk, const char *check_uuid,
grub_memcpy (hashspec, header.hashSpec, sizeof (header.hashSpec)); grub_memcpy (hashspec, header.hashSpec, sizeof (header.hashSpec));
hashspec[sizeof (header.hashSpec)] = 0; hashspec[sizeof (header.hashSpec)] = 0;
ciph = grub_crypto_lookup_cipher_by_name (ciphername); newdev = grub_zalloc (sizeof (struct grub_cryptodisk));
if (!ciph) if (!newdev)
{
grub_error (GRUB_ERR_FILE_NOT_FOUND, "Cipher %s isn't available",
ciphername);
return NULL; return NULL;
} newdev->offset_sectors = grub_be_to_cpu32 (header.payloadOffset);
newdev->source_disk = NULL;
/* Configure the cipher used for the bulk data. */ newdev->log_sector_size = GRUB_LUKS1_LOG_SECTOR_SIZE;
cipher = grub_crypto_cipher_open (ciph); newdev->total_sectors = grub_disk_native_sectors (disk) - newdev->offset_sectors;
if (!cipher) grub_memcpy (newdev->uuid, uuid, sizeof (uuid));
return NULL; newdev->modname = "luks";
if (grub_be_to_cpu32 (header.keyBytes) > 1024)
{
grub_error (GRUB_ERR_BAD_ARGUMENT, "invalid keysize %d",
grub_be_to_cpu32 (header.keyBytes));
grub_crypto_cipher_close (cipher);
return NULL;
}
/* Configure the cipher mode. */
if (grub_strcmp (ciphermode, "ecb") == 0)
{
mode = GRUB_CRYPTODISK_MODE_ECB;
mode_iv = GRUB_CRYPTODISK_MODE_IV_PLAIN;
cipheriv = NULL;
}
else if (grub_strcmp (ciphermode, "plain") == 0)
{
mode = GRUB_CRYPTODISK_MODE_CBC;
mode_iv = GRUB_CRYPTODISK_MODE_IV_PLAIN;
cipheriv = NULL;
}
else if (grub_memcmp (ciphermode, "cbc-", sizeof ("cbc-") - 1) == 0)
{
mode = GRUB_CRYPTODISK_MODE_CBC;
cipheriv = ciphermode + sizeof ("cbc-") - 1;
}
else if (grub_memcmp (ciphermode, "pcbc-", sizeof ("pcbc-") - 1) == 0)
{
mode = GRUB_CRYPTODISK_MODE_PCBC;
cipheriv = ciphermode + sizeof ("pcbc-") - 1;
}
else if (grub_memcmp (ciphermode, "xts-", sizeof ("xts-") - 1) == 0)
{
mode = GRUB_CRYPTODISK_MODE_XTS;
cipheriv = ciphermode + sizeof ("xts-") - 1;
secondary_cipher = grub_crypto_cipher_open (ciph);
if (!secondary_cipher)
{
grub_crypto_cipher_close (cipher);
return NULL;
}
if (cipher->cipher->blocksize != GRUB_CRYPTODISK_GF_BYTES)
{
grub_error (GRUB_ERR_BAD_ARGUMENT, "Unsupported XTS block size: %d",
cipher->cipher->blocksize);
grub_crypto_cipher_close (cipher);
grub_crypto_cipher_close (secondary_cipher);
return NULL;
}
if (secondary_cipher->cipher->blocksize != GRUB_CRYPTODISK_GF_BYTES)
{
grub_crypto_cipher_close (cipher);
grub_error (GRUB_ERR_BAD_ARGUMENT, "Unsupported XTS block size: %d",
secondary_cipher->cipher->blocksize);
grub_crypto_cipher_close (secondary_cipher);
return NULL;
}
}
else if (grub_memcmp (ciphermode, "lrw-", sizeof ("lrw-") - 1) == 0)
{
mode = GRUB_CRYPTODISK_MODE_LRW;
cipheriv = ciphermode + sizeof ("lrw-") - 1;
if (cipher->cipher->blocksize != GRUB_CRYPTODISK_GF_BYTES)
{
grub_error (GRUB_ERR_BAD_ARGUMENT, "Unsupported LRW block size: %d",
cipher->cipher->blocksize);
grub_crypto_cipher_close (cipher);
return NULL;
}
}
else
{
grub_crypto_cipher_close (cipher);
grub_error (GRUB_ERR_BAD_ARGUMENT, "Unknown cipher mode: %s",
ciphermode);
return NULL;
}
if (cipheriv == NULL);
else if (grub_memcmp (cipheriv, "plain", sizeof ("plain") - 1) == 0)
mode_iv = GRUB_CRYPTODISK_MODE_IV_PLAIN;
else if (grub_memcmp (cipheriv, "plain64", sizeof ("plain64") - 1) == 0)
mode_iv = GRUB_CRYPTODISK_MODE_IV_PLAIN64;
else if (grub_memcmp (cipheriv, "benbi", sizeof ("benbi") - 1) == 0)
{
if (cipher->cipher->blocksize & (cipher->cipher->blocksize - 1)
|| cipher->cipher->blocksize == 0)
grub_error (GRUB_ERR_BAD_ARGUMENT, "Unsupported benbi blocksize: %d",
cipher->cipher->blocksize);
/* FIXME should we return an error here? */
for (benbi_log = 0;
(cipher->cipher->blocksize << benbi_log) < GRUB_DISK_SECTOR_SIZE;
benbi_log++);
mode_iv = GRUB_CRYPTODISK_MODE_IV_BENBI;
}
else if (grub_memcmp (cipheriv, "null", sizeof ("null") - 1) == 0)
mode_iv = GRUB_CRYPTODISK_MODE_IV_NULL;
else if (grub_memcmp (cipheriv, "essiv:", sizeof ("essiv:") - 1) == 0)
{
char *hash_str = cipheriv + 6;
mode_iv = GRUB_CRYPTODISK_MODE_IV_ESSIV;
/* Configure the hash and cipher used for ESSIV. */
essiv_hash = grub_crypto_lookup_md_by_name (hash_str);
if (!essiv_hash)
{
grub_crypto_cipher_close (cipher);
grub_crypto_cipher_close (secondary_cipher);
grub_error (GRUB_ERR_FILE_NOT_FOUND,
"Couldn't load %s hash", hash_str);
return NULL;
}
essiv_cipher = grub_crypto_cipher_open (ciph);
if (!essiv_cipher)
{
grub_crypto_cipher_close (cipher);
grub_crypto_cipher_close (secondary_cipher);
return NULL;
}
}
else
{
grub_crypto_cipher_close (cipher);
grub_crypto_cipher_close (secondary_cipher);
grub_error (GRUB_ERR_BAD_ARGUMENT, "Unknown IV mode: %s",
cipheriv);
return NULL;
}
/* Configure the hash used for the AF splitter and HMAC. */ /* Configure the hash used for the AF splitter and HMAC. */
hash = grub_crypto_lookup_md_by_name (hashspec); newdev->hash = grub_crypto_lookup_md_by_name (hashspec);
if (!hash) if (!newdev->hash)
{ {
grub_crypto_cipher_close (cipher); grub_free (newdev);
grub_crypto_cipher_close (essiv_cipher);
grub_crypto_cipher_close (secondary_cipher);
grub_error (GRUB_ERR_FILE_NOT_FOUND, "Couldn't load %s hash", grub_error (GRUB_ERR_FILE_NOT_FOUND, "Couldn't load %s hash",
hashspec); hashspec);
return NULL; return NULL;
} }
newdev = grub_zalloc (sizeof (struct grub_cryptodisk)); err = grub_cryptodisk_setcipher (newdev, ciphername, ciphermode);
if (!newdev) if (err)
{ {
grub_crypto_cipher_close (cipher); grub_free (newdev);
grub_crypto_cipher_close (essiv_cipher);
grub_crypto_cipher_close (secondary_cipher);
return NULL; return NULL;
} }
newdev->cipher = cipher;
newdev->offset = grub_be_to_cpu32 (header.payloadOffset);
newdev->source_disk = NULL;
newdev->benbi_log = benbi_log;
newdev->mode = mode;
newdev->mode_iv = mode_iv;
newdev->secondary_cipher = secondary_cipher;
newdev->essiv_cipher = essiv_cipher;
newdev->essiv_hash = essiv_hash;
newdev->hash = hash;
newdev->log_sector_size = 9;
newdev->total_length = grub_disk_get_size (disk) - newdev->offset;
grub_memcpy (newdev->uuid, uuid, sizeof (newdev->uuid));
newdev->modname = "luks";
COMPILE_TIME_ASSERT (sizeof (newdev->uuid) >= sizeof (uuid)); COMPILE_TIME_ASSERT (sizeof (newdev->uuid) >= sizeof (uuid));
return newdev; return newdev;
} }
@@ -336,7 +179,7 @@ luks_recover_key (grub_disk_t source,
&& grub_be_to_cpu32 (header.keyblock[i].stripes) > max_stripes) && grub_be_to_cpu32 (header.keyblock[i].stripes) > max_stripes)
max_stripes = grub_be_to_cpu32 (header.keyblock[i].stripes); max_stripes = grub_be_to_cpu32 (header.keyblock[i].stripes);
split_key = grub_malloc (keysize * max_stripes); split_key = grub_calloc (keysize, max_stripes);
if (!split_key) if (!split_key)
return grub_errno; return grub_errno;
@@ -404,7 +247,8 @@ luks_recover_key (grub_disk_t source,
return err; return err;
} }
gcry_err = grub_cryptodisk_decrypt (dev, split_key, length, 0); gcry_err = grub_cryptodisk_decrypt (dev, split_key, length, 0,
GRUB_LUKS1_LOG_SECTOR_SIZE);
if (gcry_err) if (gcry_err)
{ {
grub_free (split_key); grub_free (split_key);
+791
View File
@@ -0,0 +1,791 @@
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2019 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/cryptodisk.h>
#include <grub/types.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/dl.h>
#include <grub/err.h>
#include <grub/disk.h>
#include <grub/crypto.h>
#include <grub/partition.h>
#include <grub/i18n.h>
#include <base64.h>
#include <json.h>
GRUB_MOD_LICENSE ("GPLv3+");
#define LUKS_MAGIC_1ST "LUKS\xBA\xBE"
#define LUKS_MAGIC_2ND "SKUL\xBA\xBE"
#define MAX_PASSPHRASE 256
enum grub_luks2_kdf_type
{
LUKS2_KDF_TYPE_ARGON2I,
LUKS2_KDF_TYPE_PBKDF2
};
typedef enum grub_luks2_kdf_type grub_luks2_kdf_type_t;
/* On disk LUKS header */
struct grub_luks2_header
{
char magic[6];
grub_uint16_t version;
grub_uint64_t hdr_size;
grub_uint64_t seqid;
char label[48];
char csum_alg[32];
grub_uint8_t salt[64];
char uuid[40];
char subsystem[48];
grub_uint64_t hdr_offset;
char _padding[184];
grub_uint8_t csum[64];
char _padding4096[7*512];
} GRUB_PACKED;
typedef struct grub_luks2_header grub_luks2_header_t;
struct grub_luks2_keyslot
{
/* The integer key to the associative array of keyslots. */
grub_uint64_t idx;
grub_int64_t key_size;
grub_int64_t priority;
struct
{
const char *encryption;
grub_uint64_t offset;
grub_uint64_t size;
grub_int64_t key_size;
} area;
struct
{
const char *hash;
grub_int64_t stripes;
} af;
struct
{
grub_luks2_kdf_type_t type;
const char *salt;
union
{
struct
{
grub_int64_t time;
grub_int64_t memory;
grub_int64_t cpus;
} argon2i;
struct
{
const char *hash;
grub_int64_t iterations;
} pbkdf2;
} u;
} kdf;
};
typedef struct grub_luks2_keyslot grub_luks2_keyslot_t;
struct grub_luks2_segment
{
grub_uint64_t idx;
grub_uint64_t offset;
const char *size;
const char *encryption;
grub_int64_t sector_size;
};
typedef struct grub_luks2_segment grub_luks2_segment_t;
struct grub_luks2_digest
{
grub_uint64_t idx;
/* Both keyslots and segments are interpreted as bitfields here */
grub_uint64_t keyslots;
grub_uint64_t segments;
const char *salt;
const char *digest;
const char *hash;
grub_int64_t iterations;
};
typedef struct grub_luks2_digest grub_luks2_digest_t;
gcry_err_code_t AF_merge (const gcry_md_spec_t * hash, grub_uint8_t * src,
grub_uint8_t * dst, grub_size_t blocksize,
grub_size_t blocknumbers);
static grub_err_t
luks2_parse_keyslot (grub_luks2_keyslot_t *out, const grub_json_t *keyslot)
{
grub_json_t area, af, kdf;
const char *type;
if (grub_json_getstring (&type, keyslot, "type"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing or invalid keyslot");
else if (grub_strcmp (type, "luks2"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Unsupported keyslot type %s", type);
else if (grub_json_getint64 (&out->key_size, keyslot, "key_size"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing keyslot information");
if (grub_json_getint64 (&out->priority, keyslot, "priority"))
out->priority = 1;
if (grub_json_getvalue (&area, keyslot, "area") ||
grub_json_getstring (&type, &area, "type"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing or invalid key area");
else if (grub_strcmp (type, "raw"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Unsupported key area type: %s", type);
else if (grub_json_getuint64 (&out->area.offset, &area, "offset") ||
grub_json_getuint64 (&out->area.size, &area, "size") ||
grub_json_getstring (&out->area.encryption, &area, "encryption") ||
grub_json_getint64 (&out->area.key_size, &area, "key_size"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing key area information");
if (grub_json_getvalue (&kdf, keyslot, "kdf") ||
grub_json_getstring (&type, &kdf, "type") ||
grub_json_getstring (&out->kdf.salt, &kdf, "salt"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing or invalid KDF");
else if (!grub_strcmp (type, "argon2i") || !grub_strcmp (type, "argon2id"))
{
out->kdf.type = LUKS2_KDF_TYPE_ARGON2I;
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 Argon2i parameters");
}
else if (!grub_strcmp (type, "pbkdf2"))
{
out->kdf.type = LUKS2_KDF_TYPE_PBKDF2;
if (grub_json_getstring (&out->kdf.u.pbkdf2.hash, &kdf, "hash") ||
grub_json_getint64 (&out->kdf.u.pbkdf2.iterations, &kdf, "iterations"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing PBKDF2 parameters");
}
else
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Unsupported KDF type %s", type);
if (grub_json_getvalue (&af, keyslot, "af") ||
grub_json_getstring (&type, &af, "type"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "missing or invalid area");
if (grub_strcmp (type, "luks1"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Unsupported AF type %s", type);
if (grub_json_getint64 (&out->af.stripes, &af, "stripes") ||
grub_json_getstring (&out->af.hash, &af, "hash"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing AF parameters");
return GRUB_ERR_NONE;
}
static grub_err_t
luks2_parse_segment (grub_luks2_segment_t *out, const grub_json_t *segment)
{
const char *type;
if (grub_json_getstring (&type, segment, "type"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid segment type");
else if (grub_strcmp (type, "crypt"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Unsupported segment type %s", type);
if (grub_json_getuint64 (&out->offset, segment, "offset") ||
grub_json_getstring (&out->size, segment, "size") ||
grub_json_getstring (&out->encryption, segment, "encryption") ||
grub_json_getint64 (&out->sector_size, segment, "sector_size"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing segment parameters");
return GRUB_ERR_NONE;
}
static grub_err_t
luks2_parse_digest (grub_luks2_digest_t *out, const grub_json_t *digest)
{
grub_json_t segments, keyslots, o;
grub_size_t i, size;
grub_uint64_t bit;
const char *type;
if (grub_json_getstring (&type, digest, "type"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid digest type");
else if (grub_strcmp (type, "pbkdf2"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Unsupported digest type %s", type);
if (grub_json_getvalue (&segments, digest, "segments") ||
grub_json_getvalue (&keyslots, digest, "keyslots") ||
grub_json_getstring (&out->salt, digest, "salt") ||
grub_json_getstring (&out->digest, digest, "digest") ||
grub_json_getstring (&out->hash, digest, "hash") ||
grub_json_getint64 (&out->iterations, digest, "iterations"))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Missing digest parameters");
if (grub_json_getsize (&size, &segments))
return grub_error (GRUB_ERR_BAD_ARGUMENT,
"Digest references no segments");
out->segments = 0;
for (i = 0; i < size; i++)
{
if (grub_json_getchild (&o, &segments, i) ||
grub_json_getuint64 (&bit, &o, NULL))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid segment");
out->segments |= (1 << bit);
}
if (grub_json_getsize (&size, &keyslots))
return grub_error (GRUB_ERR_BAD_ARGUMENT,
"Digest references no keyslots");
out->keyslots = 0;
for (i = 0; i < size; i++)
{
if (grub_json_getchild (&o, &keyslots, i) ||
grub_json_getuint64 (&bit, &o, NULL))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid keyslot");
out->keyslots |= (1 << bit);
}
return GRUB_ERR_NONE;
}
static grub_err_t
luks2_get_keyslot (grub_luks2_keyslot_t *k, grub_luks2_digest_t *d, grub_luks2_segment_t *s,
const grub_json_t *root, grub_size_t keyslot_json_idx)
{
grub_json_t keyslots, keyslot, digests, digest, segments, segment;
grub_size_t json_idx, size;
/* Get nth keyslot */
if (grub_json_getvalue (&keyslots, root, "keyslots") ||
grub_json_getchild (&keyslot, &keyslots, keyslot_json_idx) ||
grub_json_getuint64 (&k->idx, &keyslot, NULL) ||
grub_json_getchild (&keyslot, &keyslot, 0) ||
luks2_parse_keyslot (k, &keyslot))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Could not parse keyslot index %" PRIuGRUB_SIZE, keyslot_json_idx);
/* Get digest that matches the keyslot. */
if (grub_json_getvalue (&digests, root, "digests") ||
grub_json_getsize (&size, &digests))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Could not get digests");
for (json_idx = 0; json_idx < size; json_idx++)
{
if (grub_json_getchild (&digest, &digests, json_idx) ||
grub_json_getuint64 (&d->idx, &digest, NULL) ||
grub_json_getchild (&digest, &digest, 0) ||
luks2_parse_digest (d, &digest))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Could not parse digest index %" PRIuGRUB_SIZE, json_idx);
if ((d->keyslots & (1 << k->idx)))
break;
}
if (json_idx == size)
return grub_error (GRUB_ERR_FILE_NOT_FOUND, "No digest for keyslot \"%" PRIuGRUB_UINT64_T "\"", k->idx);
/* Get segment that matches the digest. */
if (grub_json_getvalue (&segments, root, "segments") ||
grub_json_getsize (&size, &segments))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Could not get segments");
for (json_idx = 0; json_idx < size; json_idx++)
{
if (grub_json_getchild (&segment, &segments, json_idx) ||
grub_json_getuint64 (&s->idx, &segment, NULL) ||
grub_json_getchild (&segment, &segment, 0) ||
luks2_parse_segment (s, &segment))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Could not parse segment index %" PRIuGRUB_SIZE, json_idx);
if ((d->segments & (1 << s->idx)))
break;
}
if (json_idx == size)
return grub_error (GRUB_ERR_FILE_NOT_FOUND, "No segment for digest \"%" PRIuGRUB_UINT64_T "\"", d->idx);
return GRUB_ERR_NONE;
}
/* Determine whether to use primary or secondary header */
static grub_err_t
luks2_read_header (grub_disk_t disk, grub_luks2_header_t *outhdr)
{
grub_luks2_header_t primary, secondary, *header = &primary;
grub_err_t ret;
/* Read the primary LUKS header. */
ret = grub_disk_read (disk, 0, 0, sizeof (primary), &primary);
if (ret)
return ret;
/* Look for LUKS magic sequence. */
if (grub_memcmp (primary.magic, LUKS_MAGIC_1ST, sizeof (primary.magic)) ||
grub_be_to_cpu16 (primary.version) != 2)
return GRUB_ERR_BAD_SIGNATURE;
/* Read the secondary header. */
ret = grub_disk_read (disk, 0, grub_be_to_cpu64 (primary.hdr_size), sizeof (secondary), &secondary);
if (ret)
return ret;
/* Look for LUKS magic sequence. */
if (grub_memcmp (secondary.magic, LUKS_MAGIC_2ND, sizeof (secondary.magic)) ||
grub_be_to_cpu16 (secondary.version) != 2)
return GRUB_ERR_BAD_SIGNATURE;
if (grub_be_to_cpu64 (primary.seqid) < grub_be_to_cpu64 (secondary.seqid))
header = &secondary;
grub_memcpy (outhdr, header, sizeof (*header));
return GRUB_ERR_NONE;
}
static grub_cryptodisk_t
luks2_scan (grub_disk_t disk, const char *check_uuid, int check_boot)
{
grub_cryptodisk_t cryptodisk;
grub_luks2_header_t header;
char uuid[sizeof (header.uuid) + 1];
grub_size_t i, j;
if (check_boot)
return NULL;
if (luks2_read_header (disk, &header))
{
grub_errno = GRUB_ERR_NONE;
return NULL;
}
for (i = 0, j = 0; i < sizeof (header.uuid); i++)
if (header.uuid[i] != '-')
uuid[j++] = header.uuid[i];
uuid[j] = '\0';
if (check_uuid && grub_strcasecmp (check_uuid, uuid) != 0)
return NULL;
cryptodisk = grub_zalloc (sizeof (*cryptodisk));
if (!cryptodisk)
return NULL;
COMPILE_TIME_ASSERT (sizeof (cryptodisk->uuid) >= sizeof (uuid));
grub_memcpy (cryptodisk->uuid, uuid, sizeof (uuid));
cryptodisk->modname = "luks2";
return cryptodisk;
}
static grub_err_t
luks2_verify_key (grub_luks2_digest_t *d, grub_uint8_t *candidate_key,
grub_size_t candidate_key_len)
{
grub_uint8_t candidate_digest[GRUB_CRYPTODISK_MAX_KEYLEN];
grub_uint8_t digest[GRUB_CRYPTODISK_MAX_KEYLEN], salt[GRUB_CRYPTODISK_MAX_KEYLEN];
grub_size_t saltlen = sizeof (salt), digestlen = sizeof (digest);
const gcry_md_spec_t *hash;
gcry_err_code_t gcry_ret;
/* Decode both digest and salt */
if (!base64_decode (d->digest, grub_strlen (d->digest), (char *)digest, &digestlen))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid digest");
if (!base64_decode (d->salt, grub_strlen (d->salt), (char *)salt, &saltlen))
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid digest salt");
/* Configure the hash used for the digest. */
hash = grub_crypto_lookup_md_by_name (d->hash);
if (!hash)
return grub_error (GRUB_ERR_FILE_NOT_FOUND, "Couldn't load %s hash", d->hash);
/* Calculate the candidate key's digest */
gcry_ret = grub_crypto_pbkdf2 (hash,
candidate_key, candidate_key_len,
salt, saltlen,
d->iterations,
candidate_digest, digestlen);
if (gcry_ret)
return grub_crypto_gcry_error (gcry_ret);
if (grub_memcmp (candidate_digest, digest, digestlen) != 0)
return grub_error (GRUB_ERR_ACCESS_DENIED, "Mismatching digests");
return GRUB_ERR_NONE;
}
static grub_err_t
luks2_decrypt_key (grub_uint8_t *out_key,
grub_disk_t source, grub_cryptodisk_t crypt,
grub_luks2_keyslot_t *k,
const grub_uint8_t *passphrase, grub_size_t passphraselen)
{
grub_uint8_t area_key[GRUB_CRYPTODISK_MAX_KEYLEN];
grub_uint8_t salt[GRUB_CRYPTODISK_MAX_KEYLEN];
grub_uint8_t *split_key = NULL;
grub_size_t saltlen = sizeof (salt);
char cipher[32], *p;
const gcry_md_spec_t *hash;
gcry_err_code_t gcry_ret;
grub_err_t ret;
if (!base64_decode (k->kdf.salt, grub_strlen (k->kdf.salt),
(char *)salt, &saltlen))
{
ret = grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid keyslot salt");
goto err;
}
/* Calculate the binary area key of the user supplied passphrase. */
switch (k->kdf.type)
{
case LUKS2_KDF_TYPE_ARGON2I:
ret = grub_error (GRUB_ERR_BAD_ARGUMENT, "Argon2 not supported");
goto err;
case LUKS2_KDF_TYPE_PBKDF2:
hash = grub_crypto_lookup_md_by_name (k->kdf.u.pbkdf2.hash);
if (!hash)
{
ret = grub_error (GRUB_ERR_FILE_NOT_FOUND, "Couldn't load %s hash",
k->kdf.u.pbkdf2.hash);
goto err;
}
gcry_ret = grub_crypto_pbkdf2 (hash, (grub_uint8_t *) passphrase,
passphraselen,
salt, saltlen,
k->kdf.u.pbkdf2.iterations,
area_key, k->area.key_size);
if (gcry_ret)
{
ret = grub_crypto_gcry_error (gcry_ret);
goto err;
}
break;
}
/* Set up disk encryption parameters for the key area */
grub_strncpy (cipher, k->area.encryption, sizeof (cipher));
p = grub_memchr (cipher, '-', grub_strlen (cipher));
if (!p)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid encryption");
*p = '\0';
ret = grub_cryptodisk_setcipher (crypt, cipher, p + 1);
if (ret)
return ret;
gcry_ret = grub_cryptodisk_setkey (crypt, area_key, k->area.key_size);
if (gcry_ret)
{
ret = grub_crypto_gcry_error (gcry_ret);
goto err;
}
/* Read and decrypt the binary key area with the area key. */
split_key = grub_malloc (k->area.size);
if (!split_key)
{
ret = grub_errno;
goto err;
}
grub_errno = GRUB_ERR_NONE;
ret = grub_disk_read (source, 0, k->area.offset, k->area.size, split_key);
if (ret)
{
grub_error (GRUB_ERR_IO, "Read error: %s\n", grub_errmsg);
goto err;
}
/*
* The key slots area is always encrypted in 512-byte sectors,
* regardless of encrypted data sector size.
*/
gcry_ret = grub_cryptodisk_decrypt (crypt, split_key, k->area.size, 0,
GRUB_LUKS1_LOG_SECTOR_SIZE);
if (gcry_ret)
{
ret = grub_crypto_gcry_error (gcry_ret);
goto err;
}
/* Configure the hash used for anti-forensic merging. */
hash = grub_crypto_lookup_md_by_name (k->af.hash);
if (!hash)
{
ret = grub_error (GRUB_ERR_FILE_NOT_FOUND, "Couldn't load %s hash",
k->af.hash);
goto err;
}
/* Merge the decrypted key material to get the candidate master key. */
gcry_ret = AF_merge (hash, split_key, out_key, k->key_size, k->af.stripes);
if (gcry_ret)
{
ret = grub_crypto_gcry_error (gcry_ret);
goto err;
}
grub_dprintf ("luks2", "Candidate key recovered\n");
err:
grub_free (split_key);
return ret;
}
static grub_err_t
luks2_recover_key (grub_disk_t source,
grub_cryptodisk_t crypt)
{
grub_uint8_t candidate_key[GRUB_CRYPTODISK_MAX_KEYLEN];
char passphrase[MAX_PASSPHRASE], cipher[32];
char *json_header = NULL, *part = NULL, *ptr;
grub_size_t candidate_key_len = 0, json_idx, size;
grub_luks2_header_t header;
grub_luks2_keyslot_t keyslot;
grub_luks2_digest_t digest;
grub_luks2_segment_t segment;
gcry_err_code_t gcry_ret;
grub_json_t *json = NULL, keyslots;
grub_err_t ret;
ret = luks2_read_header (source, &header);
if (ret)
return ret;
json_header = grub_zalloc (grub_be_to_cpu64 (header.hdr_size) - sizeof (header));
if (!json_header)
return GRUB_ERR_OUT_OF_MEMORY;
/* Read the JSON area. */
ret = grub_disk_read (source, 0, grub_be_to_cpu64 (header.hdr_offset) + sizeof (header),
grub_be_to_cpu64 (header.hdr_size) - sizeof (header), json_header);
if (ret)
goto err;
ptr = grub_memchr (json_header, 0, grub_be_to_cpu64 (header.hdr_size) - sizeof (header));
if (!ptr)
goto err;
ret = grub_json_parse (&json, json_header, grub_be_to_cpu64 (header.hdr_size));
if (ret)
{
ret = grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid LUKS2 JSON header");
goto err;
}
/* Get the passphrase from the user. */
if (source->partition)
part = grub_partition_get_name (source->partition);
grub_printf_ (N_("Enter passphrase for %s%s%s (%s): "), source->name,
source->partition ? "," : "", part ? : "",
crypt->uuid);
if (!grub_password_get (passphrase, MAX_PASSPHRASE))
{
ret = grub_error (GRUB_ERR_BAD_ARGUMENT, "Passphrase not supplied");
goto err;
}
if (grub_json_getvalue (&keyslots, json, "keyslots") ||
grub_json_getsize (&size, &keyslots))
{
ret = grub_error (GRUB_ERR_BAD_ARGUMENT, "Could not get keyslots");
goto err;
}
if (grub_disk_native_sectors (source) == GRUB_DISK_SIZE_UNKNOWN)
{
/* FIXME: Allow use of source disk, and maybe cause errors in read. */
grub_dprintf ("luks2", "Source disk %s has an unknown size, "
"conservatively returning error\n", source->name);
ret = grub_error (GRUB_ERR_BUG, "Unknown size of luks2 source device");
goto err;
}
/* Try all keyslot */
for (json_idx = 0; json_idx < size; json_idx++)
{
char indexstr[21]; /* log10(2^64) ~ 20, plus NUL character. */
typeof (source->total_sectors) max_crypt_sectors = 0;
grub_errno = GRUB_ERR_NONE;
ret = luks2_get_keyslot (&keyslot, &digest, &segment, json, json_idx);
if (ret)
goto err;
if (grub_errno != GRUB_ERR_NONE)
grub_dprintf ("luks2", "Ignoring unhandled error %d from luks2_get_keyslot\n", grub_errno);
if (keyslot.priority == 0)
{
grub_dprintf ("luks2", "Ignoring keyslot \"%" PRIuGRUB_UINT64_T "\" due to priority\n", keyslot.idx);
continue;
}
grub_dprintf ("luks2", "Trying keyslot \"%" PRIuGRUB_UINT64_T "\"\n", keyslot.idx);
/* Sector size should be one of 512, 1024, 2048, or 4096. */
if (!(segment.sector_size == 512 || segment.sector_size == 1024 ||
segment.sector_size == 2048 || segment.sector_size == 4096))
{
grub_dprintf ("luks2", "Segment \"%" PRIuGRUB_UINT64_T "\" sector"
" size %" PRIuGRUB_UINT64_T " is not one of"
" 512, 1024, 2048, or 4096\n",
segment.idx, segment.sector_size);
continue;
}
/* Set up disk according to keyslot's segment. */
crypt->offset_sectors = grub_divmod64 (segment.offset, segment.sector_size, NULL);
crypt->log_sector_size = grub_log2ull (segment.sector_size);
/* Set to the source disk/partition size, which is the maximum we allow. */
max_crypt_sectors = grub_disk_native_sectors (source);
max_crypt_sectors = grub_convert_sector (max_crypt_sectors, GRUB_DISK_SECTOR_BITS,
crypt->log_sector_size);
if (max_crypt_sectors < crypt->offset_sectors)
{
grub_dprintf ("luks2", "Segment \"%" PRIuGRUB_UINT64_T "\" has offset"
" %" PRIuGRUB_UINT64_T " which is greater than"
" source disk size %" PRIuGRUB_UINT64_T ","
" skipping\n", segment.idx, crypt->offset_sectors,
max_crypt_sectors);
continue;
}
if (grub_strcmp (segment.size, "dynamic") == 0)
crypt->total_sectors = max_crypt_sectors - crypt->offset_sectors;
else
{
grub_errno = GRUB_ERR_NONE;
/* Convert segment.size to sectors, rounding up to nearest sector */
crypt->total_sectors = grub_strtoull (segment.size, NULL, 10);
if (grub_errno == GRUB_ERR_NONE)
{
crypt->total_sectors = ALIGN_UP (crypt->total_sectors,
1 << crypt->log_sector_size);
crypt->total_sectors >>= crypt->log_sector_size;
}
else if (grub_errno == GRUB_ERR_BAD_NUMBER)
{
grub_dprintf ("luks2", "Segment \"%" PRIuGRUB_UINT64_T "\" size"
" \"%s\" is not a parsable number,"
" skipping keyslot\n",
segment.idx, segment.size);
continue;
}
else if (grub_errno == GRUB_ERR_OUT_OF_RANGE)
{
/*
* There was an overflow in parsing segment.size, so disk must
* be very large or the string is incorrect.
*
* TODO: Allow reading of at least up max_crypt_sectors. Really,
* its very unlikely one would be booting from such a large drive
* anyway. Use another smaller LUKS2 boot device.
*/
grub_dprintf ("luks2", "Segment \"%" PRIuGRUB_UINT64_T "\" size"
" %s overflowed 64-bit unsigned integer,"
" skipping keyslot\n", segment.idx, segment.size);
continue;
}
}
if (crypt->total_sectors == 0)
{
grub_dprintf ("luks2", "Segment \"%" PRIuGRUB_UINT64_T "\" has zero"
" sectors, skipping\n", segment.idx);
continue;
}
else if (max_crypt_sectors < (crypt->offset_sectors + crypt->total_sectors))
{
grub_dprintf ("luks2", "Segment \"%" PRIuGRUB_UINT64_T "\" has last"
" data position greater than source disk size,"
" the end of the crypto device will be"
" inaccessible\n", segment.idx);
/* Allow decryption up to the end of the source disk. */
crypt->total_sectors = max_crypt_sectors - crypt->offset_sectors;
}
ret = luks2_decrypt_key (candidate_key, source, crypt, &keyslot,
(const grub_uint8_t *) passphrase, grub_strlen (passphrase));
if (ret)
{
grub_dprintf ("luks2", "Decryption with keyslot \"%" PRIuGRUB_UINT64_T "\" failed: %s\n",
keyslot.idx, grub_errmsg);
continue;
}
ret = luks2_verify_key (&digest, candidate_key, keyslot.key_size);
if (ret)
{
grub_dprintf ("luks2", "Could not open keyslot \"%" PRIuGRUB_UINT64_T "\": %s\n",
keyslot.idx, grub_errmsg);
continue;
}
grub_snprintf (indexstr, sizeof (indexstr) - 1, "%" PRIuGRUB_UINT64_T, keyslot.idx);
/*
* TRANSLATORS: It's a cryptographic key slot: one element of an array
* where each element is either empty or holds a key.
*/
grub_printf_ (N_("Slot \"%s\" opened\n"), indexstr);
candidate_key_len = keyslot.key_size;
break;
}
if (candidate_key_len == 0)
{
ret = grub_error (GRUB_ERR_ACCESS_DENIED, "Invalid passphrase");
goto err;
}
/* Set up disk cipher. */
grub_strncpy (cipher, segment.encryption, sizeof (cipher));
ptr = grub_memchr (cipher, '-', grub_strlen (cipher));
if (!ptr)
return grub_error (GRUB_ERR_BAD_ARGUMENT, "Invalid encryption");
*ptr = '\0';
ret = grub_cryptodisk_setcipher (crypt, cipher, ptr + 1);
if (ret)
goto err;
/* Set the master key. */
gcry_ret = grub_cryptodisk_setkey (crypt, candidate_key, candidate_key_len);
if (gcry_ret)
{
ret = grub_crypto_gcry_error (gcry_ret);
goto err;
}
err:
grub_free (part);
grub_free (json_header);
grub_json_free (json);
return ret;
}
static struct grub_cryptodisk_dev luks2_crypto = {
.scan = luks2_scan,
.recover_key = luks2_recover_key
};
GRUB_MOD_INIT (luks2)
{
grub_cryptodisk_dev_register (&luks2_crypto);
}
GRUB_MOD_FINI (luks2)
{
grub_cryptodisk_dev_unregister (&luks2_crypto);
}
+325 -29
View File
@@ -25,6 +25,7 @@
#include <grub/lvm.h> #include <grub/lvm.h>
#include <grub/partition.h> #include <grub/partition.h>
#include <grub/i18n.h> #include <grub/i18n.h>
#include <grub/safemath.h>
#ifdef GRUB_UTIL #ifdef GRUB_UTIL
#include <grub/emu/misc.h> #include <grub/emu/misc.h>
@@ -33,12 +34,20 @@
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
struct cache_lv
{
struct grub_diskfilter_lv *lv;
char *cache_pool;
char *origin;
struct cache_lv *next;
};
/* Go the string STR and return the number after STR. *P will point /* Go the string STR and return the number after STR. *P will point
at the number. In case STR is not found, *P will be NULL and the at the number. In case STR is not found, *P will be NULL and the
return value will be 0. */ return value will be 0. */
static grub_uint64_t static grub_uint64_t
grub_lvm_getvalue (char **p, const char *str) grub_lvm_getvalue (const char ** const p, const char *str)
{ {
*p = grub_strstr (*p, str); *p = grub_strstr (*p, str);
if (! *p) if (! *p)
@@ -63,12 +72,12 @@ grub_lvm_checkvalue (char **p, char *str, char *tmpl)
#endif #endif
static int static int
grub_lvm_check_flag (char *p, const char *str, const char *flag) grub_lvm_check_flag (const char *p, const char *str, const char *flag)
{ {
grub_size_t len_str = grub_strlen (str), len_flag = grub_strlen (flag); grub_size_t len_str = grub_strlen (str), len_flag = grub_strlen (flag);
while (1) while (1)
{ {
char *q; const char *q;
p = grub_strstr (p, str); p = grub_strstr (p, str);
if (! p) if (! p)
return 0; return 0;
@@ -95,6 +104,34 @@ grub_lvm_check_flag (char *p, const char *str, const char *flag)
} }
} }
static void
grub_lvm_free_cache_lvs (struct cache_lv *cache_lvs)
{
struct cache_lv *cache;
while ((cache = cache_lvs))
{
cache_lvs = cache_lvs->next;
if (cache->lv)
{
unsigned int i;
for (i = 0; i < cache->lv->segment_count; ++i)
if (cache->lv->segments)
grub_free (cache->lv->segments[i].nodes);
grub_free (cache->lv->segments);
grub_free (cache->lv->fullname);
grub_free (cache->lv->idname);
grub_free (cache->lv->name);
}
grub_free (cache->lv);
grub_free (cache->origin);
grub_free (cache->cache_pool);
grub_free (cache);
}
}
static struct grub_diskfilter_vg * static struct grub_diskfilter_vg *
grub_lvm_detect (grub_disk_t disk, grub_lvm_detect (grub_disk_t disk,
struct grub_diskfilter_pv_id *id, struct grub_diskfilter_pv_id *id,
@@ -102,10 +139,12 @@ grub_lvm_detect (grub_disk_t disk,
{ {
grub_err_t err; grub_err_t err;
grub_uint64_t mda_offset, mda_size; grub_uint64_t mda_offset, mda_size;
grub_size_t ptr;
char buf[GRUB_LVM_LABEL_SIZE]; char buf[GRUB_LVM_LABEL_SIZE];
char vg_id[GRUB_LVM_ID_STRLEN+1]; char vg_id[GRUB_LVM_ID_STRLEN+1];
char pv_id[GRUB_LVM_ID_STRLEN+1]; char pv_id[GRUB_LVM_ID_STRLEN+1];
char *metadatabuf, *p, *q, *vgname; char *metadatabuf, *mda_end, *vgname;
const char *p, *q;
struct grub_lvm_label_header *lh = (struct grub_lvm_label_header *) buf; struct grub_lvm_label_header *lh = (struct grub_lvm_label_header *) buf;
struct grub_lvm_pv_header *pvh; struct grub_lvm_pv_header *pvh;
struct grub_lvm_disk_locn *dlocn; struct grub_lvm_disk_locn *dlocn;
@@ -139,6 +178,20 @@ grub_lvm_detect (grub_disk_t disk,
goto fail; goto fail;
} }
/*
* We read a grub_lvm_pv_header and then 2 grub_lvm_disk_locns that
* immediately follow the PV header. Make sure we have space for both.
*/
if (grub_le_to_cpu32 (lh->offset_xl) >=
GRUB_LVM_LABEL_SIZE - sizeof (struct grub_lvm_pv_header) -
2 * sizeof (struct grub_lvm_disk_locn))
{
#ifdef GRUB_UTIL
grub_util_info ("LVM PV header/disk locations are beyond the end of the block");
#endif
goto fail;
}
pvh = (struct grub_lvm_pv_header *) (buf + grub_le_to_cpu32(lh->offset_xl)); pvh = (struct grub_lvm_pv_header *) (buf + grub_le_to_cpu32(lh->offset_xl));
for (i = 0, j = 0; i < GRUB_LVM_ID_LEN; i++) for (i = 0, j = 0; i < GRUB_LVM_ID_LEN; i++)
@@ -173,7 +226,7 @@ grub_lvm_detect (grub_disk_t disk,
first one. */ first one. */
/* Allocate buffer space for the circular worst-case scenario. */ /* Allocate buffer space for the circular worst-case scenario. */
metadatabuf = grub_malloc (2 * mda_size); metadatabuf = grub_calloc (2, mda_size);
if (! metadatabuf) if (! metadatabuf)
goto fail; goto fail;
@@ -195,9 +248,27 @@ grub_lvm_detect (grub_disk_t disk,
} }
rlocn = mdah->raw_locns; rlocn = mdah->raw_locns;
if (grub_le_to_cpu64 (rlocn->offset) >= grub_le_to_cpu64 (mda_size))
{
#ifdef GRUB_UTIL
grub_util_info ("metadata offset is beyond end of metadata area");
#endif
goto fail2;
}
if (grub_le_to_cpu64 (rlocn->offset) + grub_le_to_cpu64 (rlocn->size) > if (grub_le_to_cpu64 (rlocn->offset) + grub_le_to_cpu64 (rlocn->size) >
grub_le_to_cpu64 (mdah->size)) grub_le_to_cpu64 (mdah->size))
{ {
if (2 * mda_size < GRUB_LVM_MDA_HEADER_SIZE ||
(grub_le_to_cpu64 (rlocn->offset) + grub_le_to_cpu64 (rlocn->size) -
grub_le_to_cpu64 (mdah->size) > mda_size - GRUB_LVM_MDA_HEADER_SIZE))
{
#ifdef GRUB_UTIL
grub_util_info ("cannot copy metadata wrap in circular buffer");
#endif
goto fail2;
}
/* Metadata is circular. Copy the wrap in place. */ /* Metadata is circular. Copy the wrap in place. */
grub_memcpy (metadatabuf + mda_size, grub_memcpy (metadatabuf + mda_size,
metadatabuf + GRUB_LVM_MDA_HEADER_SIZE, metadatabuf + GRUB_LVM_MDA_HEADER_SIZE,
@@ -205,19 +276,31 @@ grub_lvm_detect (grub_disk_t disk,
grub_le_to_cpu64 (rlocn->size) - grub_le_to_cpu64 (rlocn->size) -
grub_le_to_cpu64 (mdah->size)); grub_le_to_cpu64 (mdah->size));
} }
p = q = metadatabuf + grub_le_to_cpu64 (rlocn->offset);
while (*q != ' ' && q < metadatabuf + mda_size) if (grub_add ((grub_size_t)metadatabuf,
q++; (grub_size_t)grub_le_to_cpu64 (rlocn->offset),
&ptr))
if (q == metadatabuf + mda_size)
{ {
error_parsing_metadata:
#ifdef GRUB_UTIL #ifdef GRUB_UTIL
grub_util_info ("error parsing metadata"); grub_util_info ("error parsing metadata");
#endif #endif
goto fail2; goto fail2;
} }
p = q = (char *)ptr;
if (grub_add ((grub_size_t)metadatabuf, (grub_size_t)mda_size, &ptr))
goto error_parsing_metadata;
mda_end = (char *)ptr;
while (*q != ' ' && q < mda_end)
q++;
if (q == mda_end)
goto error_parsing_metadata;
vgname_len = q - p; vgname_len = q - p;
vgname = grub_malloc (vgname_len + 1); vgname = grub_malloc (vgname_len + 1);
if (!vgname) if (!vgname)
@@ -242,6 +325,8 @@ grub_lvm_detect (grub_disk_t disk,
if (! vg) if (! vg)
{ {
struct cache_lv *cache_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. */
vg = grub_malloc (sizeof (*vg)); vg = grub_malloc (sizeof (*vg));
@@ -275,17 +360,23 @@ grub_lvm_detect (grub_disk_t disk,
while (1) while (1)
{ {
grub_ssize_t s; grub_ssize_t s;
while (grub_isspace (*p)) while (grub_isspace (*p) && p < mda_end)
p++; p++;
if (p == mda_end)
goto fail4;
if (*p == '}') if (*p == '}')
break; break;
pv = grub_zalloc (sizeof (*pv)); pv = grub_zalloc (sizeof (*pv));
q = p; q = p;
while (*q != ' ') while (*q != ' ' && q < mda_end)
q++; q++;
if (q == mda_end)
goto pvs_fail_noname;
s = q - p; s = q - p;
pv->name = grub_malloc (s + 1); pv->name = grub_malloc (s + 1);
grub_memcpy (pv->name, p, s); grub_memcpy (pv->name, p, s);
@@ -328,10 +419,13 @@ grub_lvm_detect (grub_disk_t disk,
continue; continue;
pvs_fail: pvs_fail:
grub_free (pv->name); grub_free (pv->name);
pvs_fail_noname:
grub_free (pv); grub_free (pv);
goto fail4; goto fail4;
} }
} }
else
goto fail4;
p = grub_strstr (p, "logical_volumes {"); p = grub_strstr (p, "logical_volumes {");
if (p) if (p)
@@ -347,18 +441,24 @@ grub_lvm_detect (grub_disk_t disk,
struct grub_diskfilter_segment *seg; struct grub_diskfilter_segment *seg;
int is_pvmove; int is_pvmove;
while (grub_isspace (*p)) while (grub_isspace (*p) && p < mda_end)
p++; p++;
if (p == mda_end)
goto fail4;
if (*p == '}') if (*p == '}')
break; break;
lv = grub_zalloc (sizeof (*lv)); lv = grub_zalloc (sizeof (*lv));
q = p; q = p;
while (*q != ' ') while (*q != ' ' && q < mda_end)
q++; q++;
if (q == mda_end)
goto lvs_fail;
s = q - p; s = q - p;
lv->name = grub_strndup (p, s); lv->name = grub_strndup (p, s);
if (!lv->name) if (!lv->name)
@@ -367,8 +467,26 @@ grub_lvm_detect (grub_disk_t disk,
{ {
const char *iptr; const char *iptr;
char *optr; char *optr;
lv->fullname = grub_malloc (sizeof ("lvm/") - 1 + 2 * vgname_len
+ 1 + 2 * s + 1); /*
* This is kind of hard to read with our safe (but rather
* baroque) math primatives, but it boils down to:
*
* sz0 = vgname_len * 2 + 1 +
* s * 2 + 1 +
* sizeof ("lvm/") - 1;
*/
grub_size_t sz0 = vgname_len, sz1 = s;
if (grub_mul (sz0, 2, &sz0) ||
grub_add (sz0, 1, &sz0) ||
grub_mul (sz1, 2, &sz1) ||
grub_add (sz1, 1, &sz1) ||
grub_add (sz0, sz1, &sz0) ||
grub_add (sz0, sizeof ("lvm/") - 1, &sz0))
goto lvs_fail;
lv->fullname = grub_malloc (sz0);
if (!lv->fullname) if (!lv->fullname)
goto lvs_fail; goto lvs_fail;
@@ -426,7 +544,7 @@ grub_lvm_detect (grub_disk_t disk,
#endif #endif
goto lvs_fail; goto lvs_fail;
} }
lv->segments = grub_zalloc (sizeof (*seg) * lv->segment_count); lv->segments = grub_calloc (lv->segment_count, sizeof (*seg));
seg = lv->segments; seg = lv->segments;
for (i = 0; i < lv->segment_count; i++) for (i = 0; i < lv->segment_count; i++)
@@ -481,10 +599,19 @@ grub_lvm_detect (grub_disk_t disk,
} }
if (seg->node_count != 1) if (seg->node_count != 1)
seg->stripe_size = grub_lvm_getvalue (&p, "stripe_size = "); {
seg->stripe_size = grub_lvm_getvalue (&p, "stripe_size = ");
if (p == NULL)
{
#ifdef GRUB_UTIL
grub_util_info ("unknown stripe_size");
#endif
goto lvs_segment_fail;
}
}
seg->nodes = grub_zalloc (sizeof (*stripe) seg->nodes = grub_calloc (seg->node_count,
* seg->node_count); sizeof (*stripe));
stripe = seg->nodes; stripe = seg->nodes;
p = grub_strstr (p, "stripes = ["); p = grub_strstr (p, "stripes = [");
@@ -501,11 +628,14 @@ grub_lvm_detect (grub_disk_t disk,
{ {
p = grub_strchr (p, '"'); p = grub_strchr (p, '"');
if (p == NULL) if (p == NULL)
continue; goto lvs_segment_fail2;
q = ++p; q = ++p;
while (*q != '"') while (q < mda_end && *q != '"')
q++; q++;
if (q == mda_end)
goto lvs_segment_fail2;
s = q - p; s = q - p;
stripe->name = grub_malloc (s + 1); stripe->name = grub_malloc (s + 1);
@@ -520,7 +650,10 @@ grub_lvm_detect (grub_disk_t disk,
stripe->start = grub_lvm_getvalue (&p, ",") stripe->start = grub_lvm_getvalue (&p, ",")
* vg->extent_size; * vg->extent_size;
if (p == NULL) if (p == NULL)
continue; {
grub_free (stripe->name);
goto lvs_segment_fail2;
}
stripe++; stripe++;
} }
@@ -557,11 +690,14 @@ grub_lvm_detect (grub_disk_t disk,
p = grub_strchr (p, '"'); p = grub_strchr (p, '"');
if (p == NULL) if (p == NULL)
continue; goto lvs_segment_fail2;
q = ++p; q = ++p;
while (*q != '"') while (q < mda_end && *q != '"')
q++; q++;
if (q == mda_end)
goto lvs_segment_fail2;
s = q - p; s = q - p;
lvname = grub_malloc (s + 1); lvname = grub_malloc (s + 1);
@@ -645,7 +781,7 @@ grub_lvm_detect (grub_disk_t disk,
p = p ? grub_strchr (p + 1, '"') : 0; p = p ? grub_strchr (p + 1, '"') : 0;
p = p ? grub_strchr (p + 1, '"') : 0; p = p ? grub_strchr (p + 1, '"') : 0;
if (p == NULL) if (p == NULL)
continue; goto lvs_segment_fail2;
q = ++p; q = ++p;
while (*q != '"') while (*q != '"')
q++; q++;
@@ -671,6 +807,110 @@ 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)
{
struct cache_lv *cache = NULL;
char *p2, *p3;
grub_size_t sz;
cache = grub_zalloc (sizeof (*cache));
if (!cache)
goto cache_lv_fail;
cache->lv = grub_zalloc (sizeof (*cache->lv));
if (!cache->lv)
goto cache_lv_fail;
grub_memcpy (cache->lv, lv, sizeof (*cache->lv));
if (lv->fullname)
{
cache->lv->fullname = grub_strdup (lv->fullname);
if (!cache->lv->fullname)
goto cache_lv_fail;
}
if (lv->idname)
{
cache->lv->idname = grub_strdup (lv->idname);
if (!cache->lv->idname)
goto cache_lv_fail;
}
if (lv->name)
{
cache->lv->name = grub_strdup (lv->name);
if (!cache->lv->name)
goto cache_lv_fail;
}
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 = \"");
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->origin = grub_malloc (sz + 1);
if (!cache->origin)
goto cache_lv_fail;
grub_memcpy (cache->origin, p2, sz);
cache->origin[sz] = '\0';
cache->next = cache_lvs;
cache_lvs = cache;
break;
cache_lv_fail:
if (cache)
{
grub_free (cache->origin);
grub_free (cache->cache_pool);
if (cache->lv)
{
grub_free (cache->lv->fullname);
grub_free (cache->lv->idname);
grub_free (cache->lv->name);
}
grub_free (cache->lv);
grub_free (cache);
}
grub_lvm_free_cache_lvs (cache_lvs);
goto fail4;
}
else else
{ {
#ifdef GRUB_UTIL #ifdef GRUB_UTIL
@@ -741,12 +981,68 @@ grub_lvm_detect (grub_disk_t disk,
} }
if (lv1->segments[i].nodes[j].pv == NULL) if (lv1->segments[i].nodes[j].pv == NULL)
for (lv2 = vg->lvs; lv2; lv2 = lv2->next) for (lv2 = vg->lvs; lv2; lv2 = lv2->next)
if (grub_strcmp (lv2->name, {
lv1->segments[i].nodes[j].name) == 0) if (lv1 == lv2)
lv1->segments[i].nodes[j].lv = lv2; continue;
if (grub_strcmp (lv2->name,
lv1->segments[i].nodes[j].name) == 0)
lv1->segments[i].nodes[j].lv = lv2;
}
} }
} }
{
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;
} }
+2 -2
View File
@@ -111,7 +111,7 @@ grub_mdraid_detect (grub_disk_t disk,
grub_uint64_t size; grub_uint64_t size;
grub_uint8_t minor_version; grub_uint8_t minor_version;
size = grub_disk_get_size (disk); size = grub_disk_native_sectors (disk);
/* Check for an 1.x superblock. /* Check for an 1.x superblock.
* It's always aligned to a 4K boundary * It's always aligned to a 4K boundary
@@ -178,7 +178,7 @@ grub_mdraid_detect (grub_disk_t disk,
return NULL; return NULL;
if (grub_disk_read (disk, sector, if (grub_disk_read (disk, sector,
(char *) &sb.dev_roles[grub_le_to_cpu32 (sb.dev_number)] (char *) (sb.dev_roles + grub_le_to_cpu32 (sb.dev_number))
- (char *) &sb, - (char *) &sb,
sizeof (role), &role)) sizeof (role), &role))
return NULL; return NULL;
+1 -1
View File
@@ -190,7 +190,7 @@ grub_mdraid_detect (grub_disk_t disk,
struct grub_diskfilter_vg *ret; struct grub_diskfilter_vg *ret;
/* The sector where the mdraid 0.90 superblock is stored, if available. */ /* The sector where the mdraid 0.90 superblock is stored, if available. */
size = grub_disk_get_size (disk); size = grub_disk_native_sectors (disk);
if (size == GRUB_DISK_SIZE_UNKNOWN) if (size == GRUB_DISK_SIZE_UNKNOWN)
/* not 0.9x raid. */ /* not 0.9x raid. */
return NULL; return NULL;
+6
View File
@@ -331,6 +331,12 @@ grub_pata_device_initialize (int port, int device, int addr)
*devp = dev; *devp = dev;
err = check_device (dev); err = check_device (dev);
if (err == GRUB_ERR_UNKNOWN_DEVICE)
{
grub_dprintf ("pata", "%s\n", grub_errmsg);
grub_error_pop ();
}
if (err) if (err)
grub_print_error (); grub_print_error ();
+1 -1
View File
@@ -426,7 +426,7 @@ grub_xendisk_init (void)
if (!ctr) if (!ctr)
return; return;
virtdisks = grub_malloc (ctr * sizeof (virtdisks[0])); virtdisks = grub_calloc (ctr, sizeof (virtdisks[0]));
if (!virtdisks) if (!virtdisks)
return; return;
if (grub_xenstore_dir ("device/vbd", fill, &ctr)) if (grub_xenstore_dir ("device/vbd", fill, &ctr))
+8 -3
View File
@@ -121,9 +121,14 @@ grub_arch_efiemu_relocate_symbols64 (grub_efiemu_segment_t segs,
return err; return err;
break; break;
default: default:
return grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, {
N_("relocation 0x%x is not implemented yet"), char rel_info[17]; /* log16(2^64) = 16, plus NUL. */
ELF_R_TYPE (rel->r_info));
grub_snprintf (rel_info, sizeof (rel_info) - 1, "%" PRIxGRUB_UINT64_T,
ELF_R_TYPE (rel->r_info));
return grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
N_("relocation 0x%s is not implemented yet"), rel_info);
}
} }
} }
} }
+4 -11
View File
@@ -22,11 +22,11 @@
#include <grub/misc.h> #include <grub/misc.h>
#include <grub/mm.h> #include <grub/mm.h>
#include <grub/acpi.h> #include <grub/acpi.h>
#include <grub/smbios.h>
grub_err_t grub_err_t
grub_machine_efiemu_init_tables (void) grub_machine_efiemu_init_tables (void)
{ {
grub_uint8_t *ptr;
void *table; void *table;
grub_err_t err; grub_err_t err;
grub_efi_guid_t smbios = GRUB_EFI_SMBIOS_TABLE_GUID; grub_efi_guid_t smbios = GRUB_EFI_SMBIOS_TABLE_GUID;
@@ -57,17 +57,10 @@ grub_machine_efiemu_init_tables (void)
if (err) if (err)
return err; return err;
} }
table = grub_smbios_get_eps ();
for (ptr = (grub_uint8_t *) 0xf0000; ptr < (grub_uint8_t *) 0x100000; if (table)
ptr += 16)
if (grub_memcmp (ptr, "_SM_", 4) == 0
&& grub_byte_checksum (ptr, *(ptr + 5)) == 0)
break;
if (ptr < (grub_uint8_t *) 0x100000)
{ {
grub_dprintf ("efiemu", "Registering SMBIOS\n"); err = grub_efiemu_register_configuration_table (smbios, 0, 0, table);
err = grub_efiemu_register_configuration_table (smbios, 0, 0, ptr);
if (err) if (err)
return err; return err;
} }
+1 -1
View File
@@ -201,7 +201,7 @@ grub_efiemu_count_symbols (const Elf_Ehdr *e)
grub_efiemu_nelfsyms = (unsigned) s->sh_size / (unsigned) s->sh_entsize; grub_efiemu_nelfsyms = (unsigned) s->sh_size / (unsigned) s->sh_entsize;
grub_efiemu_elfsyms = (struct grub_efiemu_elf_sym *) grub_efiemu_elfsyms = (struct grub_efiemu_elf_sym *)
grub_malloc (sizeof (struct grub_efiemu_elf_sym) * grub_efiemu_nelfsyms); grub_calloc (grub_efiemu_nelfsyms, sizeof (struct grub_efiemu_elf_sym));
/* Relocators */ /* Relocators */
for (i = 0, s = (Elf_Shdr *) ((char *) e + e->e_shoff); for (i = 0, s = (Elf_Shdr *) ((char *) e + e->e_shoff);
+3 -3
View File
@@ -554,11 +554,11 @@ grub_efiemu_mmap_sort_and_uniq (void)
/* Initialize variables*/ /* Initialize variables*/
grub_memset (present, 0, sizeof (int) * GRUB_EFI_MAX_MEMORY_TYPE); grub_memset (present, 0, sizeof (int) * GRUB_EFI_MAX_MEMORY_TYPE);
scanline_events = (struct grub_efiemu_mmap_scan *) scanline_events = (struct grub_efiemu_mmap_scan *)
grub_malloc (sizeof (struct grub_efiemu_mmap_scan) * 2 * mmap_num); grub_calloc (mmap_num, sizeof (struct grub_efiemu_mmap_scan) * 2);
/* Number of chunks can't increase more than by factor of 2 */ /* Number of chunks can't increase more than by factor of 2 */
result = (grub_efi_memory_descriptor_t *) result = (grub_efi_memory_descriptor_t *)
grub_malloc (sizeof (grub_efi_memory_descriptor_t) * 2 * mmap_num); grub_calloc (mmap_num, sizeof (grub_efi_memory_descriptor_t) * 2);
if (!result || !scanline_events) if (!result || !scanline_events)
{ {
grub_free (result); grub_free (result);
@@ -660,7 +660,7 @@ grub_efiemu_mm_do_alloc (void)
/* Preallocate mmap */ /* Preallocate mmap */
efiemu_mmap = (grub_efi_memory_descriptor_t *) efiemu_mmap = (grub_efi_memory_descriptor_t *)
grub_malloc (mmap_reserved_size * sizeof (grub_efi_memory_descriptor_t)); grub_calloc (mmap_reserved_size, sizeof (grub_efi_memory_descriptor_t));
if (!efiemu_mmap) if (!efiemu_mmap)
{ {
grub_efiemu_unload (); grub_efiemu_unload ();
+3 -2
View File
@@ -39,7 +39,7 @@ static grub_size_t nvramsize;
/* Parse signed value */ /* Parse signed value */
static int static int
grub_strtosl (const char *arg, char **end, int base) grub_strtosl (const char *arg, const char ** const end, int base)
{ {
if (arg[0] == '-') if (arg[0] == '-')
return -grub_strtoul (arg + 1, end, base); return -grub_strtoul (arg + 1, end, base);
@@ -120,7 +120,8 @@ nvram_set (void * data __attribute__ ((unused)))
grub_memset (nvram, 0, nvramsize); grub_memset (nvram, 0, nvramsize);
FOR_SORTED_ENV (var) FOR_SORTED_ENV (var)
{ {
char *guid, *attr, *name, *varname; const char *guid;
char *attr, *name, *varname;
struct efi_variable *efivar; struct efi_variable *efivar;
int len = 0; int len = 0;
int i; int i;
+13 -3
View File
@@ -30,6 +30,7 @@
#include <grub/unicode.h> #include <grub/unicode.h>
#include <grub/fontformat.h> #include <grub/fontformat.h>
#include <grub/env.h> #include <grub/env.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -293,8 +294,7 @@ load_font_index (grub_file_t file, grub_uint32_t sect_length, struct
font->num_chars = sect_length / FONT_CHAR_INDEX_ENTRY_SIZE; font->num_chars = sect_length / FONT_CHAR_INDEX_ENTRY_SIZE;
/* Allocate the character index array. */ /* Allocate the character index array. */
font->char_index = grub_malloc (font->num_chars font->char_index = grub_calloc (font->num_chars, sizeof (struct char_index_entry));
* sizeof (struct char_index_entry));
if (!font->char_index) if (!font->char_index)
return 1; return 1;
font->bmp_idx = grub_malloc (0x10000 * sizeof (grub_uint16_t)); font->bmp_idx = grub_malloc (0x10000 * sizeof (grub_uint16_t));
@@ -361,9 +361,13 @@ static char *
read_section_as_string (struct font_file_section *section) read_section_as_string (struct font_file_section *section)
{ {
char *str; char *str;
grub_size_t sz;
grub_ssize_t ret; grub_ssize_t ret;
str = grub_malloc (section->length + 1); if (grub_add (section->length, 1, &sz))
return NULL;
str = grub_malloc (sz);
if (!str) if (!str)
return 0; return 0;
@@ -528,6 +532,12 @@ grub_font_load (const char *filename)
if (grub_memcmp (section.name, FONT_FORMAT_SECTION_NAMES_FONT_NAME, if (grub_memcmp (section.name, FONT_FORMAT_SECTION_NAMES_FONT_NAME,
sizeof (FONT_FORMAT_SECTION_NAMES_FONT_NAME) - 1) == 0) sizeof (FONT_FORMAT_SECTION_NAMES_FONT_NAME) - 1) == 0)
{ {
if (font->name != NULL)
{
grub_error (GRUB_ERR_BAD_FONT, "invalid font file: too many NAME sections");
goto fail;
}
font->name = read_section_as_string (&section); font->name = read_section_as_string (&section);
if (!font->name) if (!font->name)
goto fail; goto fail;
+11 -13
View File
@@ -301,7 +301,7 @@ grub_affs_read_symlink (grub_fshelp_node_t node)
return 0; return 0;
} }
latin1[symlink_size] = 0; latin1[symlink_size] = 0;
utf8 = grub_malloc (symlink_size * GRUB_MAX_UTF8_PER_LATIN1 + 1); utf8 = grub_calloc (GRUB_MAX_UTF8_PER_LATIN1 + 1, symlink_size);
if (!utf8) if (!utf8)
{ {
grub_free (latin1); grub_free (latin1);
@@ -400,12 +400,12 @@ grub_affs_iterate_dir (grub_fshelp_node_t dir,
{ {
unsigned int i; unsigned int i;
struct grub_affs_file file; struct grub_affs_file file;
struct grub_fshelp_node *node = 0; struct grub_fshelp_node *node, *orig_node;
struct grub_affs_data *data = dir->data; struct grub_affs_data *data = dir->data;
grub_uint32_t *hashtable; grub_uint32_t *hashtable;
/* Create the directory entries for `.' and `..'. */ /* Create the directory entries for `.' and `..'. */
node = grub_zalloc (sizeof (*node)); node = orig_node = grub_zalloc (sizeof (*node));
if (!node) if (!node)
return 1; return 1;
@@ -414,15 +414,12 @@ grub_affs_iterate_dir (grub_fshelp_node_t dir,
return 1; return 1;
if (dir->parent) if (dir->parent)
{ {
node = grub_zalloc (sizeof (*node));
if (!node)
return 1;
*node = *dir->parent; *node = *dir->parent;
if (hook ("..", GRUB_FSHELP_DIR, node, hook_data)) if (hook ("..", GRUB_FSHELP_DIR, node, hook_data))
return 1; return 1;
} }
hashtable = grub_zalloc (data->htsize * sizeof (*hashtable)); hashtable = grub_calloc (data->htsize, sizeof (*hashtable));
if (!hashtable) if (!hashtable)
return 1; return 1;
@@ -456,17 +453,18 @@ grub_affs_iterate_dir (grub_fshelp_node_t dir,
if (grub_affs_create_node (dir, hook, hook_data, &node, &hashtable, if (grub_affs_create_node (dir, hook, hook_data, &node, &hashtable,
next, &file)) next, &file))
return 1; {
/* Node has been replaced in function. */
grub_free (orig_node);
return 1;
}
next = grub_be_to_cpu32 (file.next); next = grub_be_to_cpu32 (file.next);
} }
} }
grub_free (hashtable);
return 0;
fail: fail:
grub_free (node); grub_free (orig_node);
grub_free (hashtable); grub_free (hashtable);
return 0; return 0;
} }
@@ -628,7 +626,7 @@ grub_affs_label (grub_device_t device, char **label)
len = file.namelen; len = file.namelen;
if (len > sizeof (file.name)) if (len > sizeof (file.name))
len = sizeof (file.name); len = sizeof (file.name);
*label = grub_malloc (len * GRUB_MAX_UTF8_PER_LATIN1 + 1); *label = grub_calloc (GRUB_MAX_UTF8_PER_LATIN1 + 1, len);
if (*label) if (*label)
*grub_latin1_to_utf8 ((grub_uint8_t *) *label, file.name, len) = '\0'; *grub_latin1_to_utf8 ((grub_uint8_t *) *label, file.name, len) = '\0';
} }
+36 -16
View File
@@ -40,6 +40,7 @@
#include <grub/btrfs.h> #include <grub/btrfs.h>
#include <grub/crypto.h> #include <grub/crypto.h>
#include <grub/diskfilter.h> #include <grub/diskfilter.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -136,6 +137,8 @@ struct grub_btrfs_chunk_item
#define GRUB_BTRFS_CHUNK_TYPE_RAID10 0x40 #define GRUB_BTRFS_CHUNK_TYPE_RAID10 0x40
#define GRUB_BTRFS_CHUNK_TYPE_RAID5 0x80 #define GRUB_BTRFS_CHUNK_TYPE_RAID5 0x80
#define GRUB_BTRFS_CHUNK_TYPE_RAID6 0x100 #define GRUB_BTRFS_CHUNK_TYPE_RAID6 0x100
#define GRUB_BTRFS_CHUNK_TYPE_RAID1C3 0x200
#define GRUB_BTRFS_CHUNK_TYPE_RAID1C4 0x400
grub_uint8_t dummy2[0xc]; grub_uint8_t dummy2[0xc];
grub_uint16_t nstripes; grub_uint16_t nstripes;
grub_uint16_t nsubstripes; grub_uint16_t nsubstripes;
@@ -329,9 +332,13 @@ save_ref (struct grub_btrfs_leaf_descriptor *desc,
if (desc->allocated < desc->depth) if (desc->allocated < desc->depth)
{ {
void *newdata; void *newdata;
desc->allocated *= 2; grub_size_t sz;
newdata = grub_realloc (desc->data, sizeof (desc->data[0])
* desc->allocated); if (grub_mul (desc->allocated, 2, &desc->allocated) ||
grub_mul (desc->allocated, sizeof (desc->data[0]), &sz))
return GRUB_ERR_OUT_OF_RANGE;
newdata = grub_realloc (desc->data, sz);
if (!newdata) if (!newdata)
return grub_errno; return grub_errno;
desc->data = newdata; desc->data = newdata;
@@ -376,9 +383,9 @@ next (struct grub_btrfs_data *data,
err = grub_btrfs_read_logical (data, grub_le_to_cpu64 (node.addr), err = grub_btrfs_read_logical (data, grub_le_to_cpu64 (node.addr),
&head, sizeof (head), 0); &head, sizeof (head), 0);
check_btrfs_header (data, &head, grub_le_to_cpu64 (node.addr));
if (err) if (err)
return -err; return -err;
check_btrfs_header (data, &head, grub_le_to_cpu64 (node.addr));
save_ref (desc, grub_le_to_cpu64 (node.addr), 0, save_ref (desc, grub_le_to_cpu64 (node.addr), 0,
grub_le_to_cpu32 (head.nitems), !head.level); grub_le_to_cpu32 (head.nitems), !head.level);
@@ -413,7 +420,7 @@ lower_bound (struct grub_btrfs_data *data,
{ {
desc->allocated = 16; desc->allocated = 16;
desc->depth = 0; desc->depth = 0;
desc->data = grub_malloc (sizeof (desc->data[0]) * desc->allocated); desc->data = grub_calloc (desc->allocated, sizeof (desc->data[0]));
if (!desc->data) if (!desc->data)
return grub_errno; return grub_errno;
} }
@@ -438,9 +445,9 @@ lower_bound (struct grub_btrfs_data *data,
/* FIXME: preread few nodes into buffer. */ /* FIXME: preread few nodes into buffer. */
err = grub_btrfs_read_logical (data, addr, &head, sizeof (head), err = grub_btrfs_read_logical (data, addr, &head, sizeof (head),
recursion_depth + 1); recursion_depth + 1);
check_btrfs_header (data, &head, addr);
if (err) if (err)
return err; return err;
check_btrfs_header (data, &head, addr);
addr += sizeof (head); addr += sizeof (head);
if (head.level) if (head.level)
{ {
@@ -622,16 +629,21 @@ find_device (struct grub_btrfs_data *data, grub_uint64_t id)
if (data->n_devices_attached > data->n_devices_allocated) if (data->n_devices_attached > data->n_devices_allocated)
{ {
void *tmp; void *tmp;
data->n_devices_allocated = 2 * data->n_devices_attached + 1; grub_size_t sz;
data->devices_attached
= grub_realloc (tmp = data->devices_attached, if (grub_mul (data->n_devices_attached, 2, &data->n_devices_allocated) ||
data->n_devices_allocated grub_add (data->n_devices_allocated, 1, &data->n_devices_allocated) ||
* sizeof (data->devices_attached[0])); grub_mul (data->n_devices_allocated, sizeof (data->devices_attached[0]), &sz))
goto fail;
data->devices_attached = grub_realloc (tmp = data->devices_attached, sz);
if (!data->devices_attached) if (!data->devices_attached)
{ {
data->devices_attached = tmp;
fail:
if (ctx.dev_found) if (ctx.dev_found)
grub_device_close (ctx.dev_found); grub_device_close (ctx.dev_found);
data->devices_attached = tmp;
return NULL; return NULL;
} }
} }
@@ -752,7 +764,7 @@ raid56_read_retry (struct grub_btrfs_data *data,
grub_err_t ret = GRUB_ERR_OUT_OF_MEMORY; grub_err_t ret = GRUB_ERR_OUT_OF_MEMORY;
grub_uint64_t i, failed_devices; grub_uint64_t i, failed_devices;
buffers = grub_zalloc (sizeof(*buffers) * nstripes); buffers = grub_calloc (nstripes, sizeof (*buffers));
if (!buffers) if (!buffers)
goto cleanup; goto cleanup;
@@ -964,14 +976,19 @@ grub_btrfs_read_logical (struct grub_btrfs_data *data, grub_disk_addr_t addr,
csize = (stripen + 1) * stripe_length - off; csize = (stripen + 1) * stripe_length - off;
break; break;
} }
case GRUB_BTRFS_CHUNK_TYPE_RAID1C4:
redundancy++;
/* fall through */
case GRUB_BTRFS_CHUNK_TYPE_RAID1C3:
redundancy++;
/* fall through */
case GRUB_BTRFS_CHUNK_TYPE_DUPLICATED: case GRUB_BTRFS_CHUNK_TYPE_DUPLICATED:
case GRUB_BTRFS_CHUNK_TYPE_RAID1: case GRUB_BTRFS_CHUNK_TYPE_RAID1:
{ {
grub_dprintf ("btrfs", "RAID1\n"); grub_dprintf ("btrfs", "RAID1 (copies: %d)\n", ++redundancy);
stripen = 0; stripen = 0;
stripe_offset = off; stripe_offset = off;
csize = grub_le_to_cpu64 (chunk->size) - off; csize = grub_le_to_cpu64 (chunk->size) - off;
redundancy = 2;
break; break;
} }
case GRUB_BTRFS_CHUNK_TYPE_RAID0: case GRUB_BTRFS_CHUNK_TYPE_RAID0:
@@ -1066,6 +1083,9 @@ grub_btrfs_read_logical (struct grub_btrfs_data *data, grub_disk_addr_t addr,
* stripen is computed without the parities * stripen is computed without the parities
* (0 for A0, A1, A2, 1 for B0, B1, B2, etc.). * (0 for A0, A1, A2, 1 for B0, B1, B2, etc.).
*/ */
if (nparities >= nstripes)
return grub_error (GRUB_ERR_BAD_FS,
"invalid RAID5/6: nparities >= nstripes");
high = grub_divmod64 (stripe_nr, nstripes - nparities, &stripen); high = grub_divmod64 (stripe_nr, nstripes - nparities, &stripen);
/* /*
@@ -2160,7 +2180,7 @@ grub_btrfs_embed (grub_device_t device __attribute__ ((unused)),
*nsectors = 64 * 2 - 1; *nsectors = 64 * 2 - 1;
if (*nsectors > max_nsectors) if (*nsectors > max_nsectors)
*nsectors = max_nsectors; *nsectors = max_nsectors;
*sectors = grub_malloc (*nsectors * sizeof (**sectors)); *sectors = grub_calloc (*nsectors, sizeof (**sectors));
if (!*sectors) if (!*sectors)
return grub_errno; return grub_errno;
for (i = 0; i < *nsectors; i++) for (i = 0; i < *nsectors; i++)
+8 -8
View File
@@ -148,16 +148,16 @@ grub_cbfs_mount (grub_disk_t disk)
grub_off_t header_off; grub_off_t header_off;
struct cbfs_header head; struct cbfs_header head;
if (grub_disk_get_size (disk) == GRUB_DISK_SIZE_UNKNOWN) if (grub_disk_native_sectors (disk) == GRUB_DISK_SIZE_UNKNOWN)
goto fail; goto fail;
if (grub_disk_read (disk, grub_disk_get_size (disk) - 1, if (grub_disk_read (disk, grub_disk_native_sectors (disk) - 1,
GRUB_DISK_SECTOR_SIZE - sizeof (ptr), GRUB_DISK_SECTOR_SIZE - sizeof (ptr),
sizeof (ptr), &ptr)) sizeof (ptr), &ptr))
goto fail; goto fail;
ptr = grub_cpu_to_le32 (ptr); ptr = grub_cpu_to_le32 (ptr);
header_off = (grub_disk_get_size (disk) << GRUB_DISK_SECTOR_BITS) header_off = (grub_disk_native_sectors (disk) << GRUB_DISK_SECTOR_BITS)
+ (grub_int32_t) ptr; + (grub_int32_t) ptr;
if (grub_disk_read (disk, 0, header_off, if (grub_disk_read (disk, 0, header_off,
@@ -171,16 +171,16 @@ grub_cbfs_mount (grub_disk_t disk)
if (!data) if (!data)
goto fail; goto fail;
data->cbfs_start = (grub_disk_get_size (disk) << GRUB_DISK_SECTOR_BITS) data->cbfs_start = (grub_disk_native_sectors (disk) << GRUB_DISK_SECTOR_BITS)
- (grub_be_to_cpu32 (head.romsize) - grub_be_to_cpu32 (head.offset)); - (grub_be_to_cpu32 (head.romsize) - grub_be_to_cpu32 (head.offset));
data->cbfs_end = (grub_disk_get_size (disk) << GRUB_DISK_SECTOR_BITS) data->cbfs_end = (grub_disk_native_sectors (disk) << GRUB_DISK_SECTOR_BITS)
- grub_be_to_cpu32 (head.bootblocksize); - grub_be_to_cpu32 (head.bootblocksize);
data->cbfs_align = grub_be_to_cpu32 (head.align); data->cbfs_align = grub_be_to_cpu32 (head.align);
if (data->cbfs_start >= (grub_disk_get_size (disk) << GRUB_DISK_SECTOR_BITS)) if (data->cbfs_start >= (grub_disk_native_sectors (disk) << GRUB_DISK_SECTOR_BITS))
goto fail; goto fail;
if (data->cbfs_end > (grub_disk_get_size (disk) << GRUB_DISK_SECTOR_BITS)) if (data->cbfs_end > (grub_disk_native_sectors (disk) << GRUB_DISK_SECTOR_BITS))
data->cbfs_end = (grub_disk_get_size (disk) << GRUB_DISK_SECTOR_BITS); data->cbfs_end = (grub_disk_native_sectors (disk) << GRUB_DISK_SECTOR_BITS);
data->next_hofs = data->cbfs_start; data->next_hofs = data->cbfs_start;
+9
View File
@@ -36,6 +36,11 @@ struct grub_archelp_data
grub_off_t size; grub_off_t size;
}; };
#if __GNUC__ >= 9
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
#endif
static grub_err_t static grub_err_t
grub_cpio_find_file (struct grub_archelp_data *data, char **name, grub_cpio_find_file (struct grub_archelp_data *data, char **name,
grub_int32_t *mtime, grub_uint32_t *mode) grub_int32_t *mtime, grub_uint32_t *mode)
@@ -96,6 +101,10 @@ grub_cpio_find_file (struct grub_archelp_data *data, char **name,
return GRUB_ERR_NONE; return GRUB_ERR_NONE;
} }
#if __GNUC__ >= 9
#pragma GCC diagnostic pop
#endif
static char * static char *
grub_cpio_get_link_target (struct grub_archelp_data *data) grub_cpio_get_link_target (struct grub_archelp_data *data)
{ {
+14 -5
View File
@@ -46,6 +46,7 @@
#include <grub/dl.h> #include <grub/dl.h>
#include <grub/types.h> #include <grub/types.h>
#include <grub/fshelp.h> #include <grub/fshelp.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -703,6 +704,7 @@ grub_ext2_read_symlink (grub_fshelp_node_t node)
{ {
char *symlink; char *symlink;
struct grub_fshelp_node *diro = node; struct grub_fshelp_node *diro = node;
grub_size_t sz;
if (! diro->inode_read) if (! diro->inode_read)
{ {
@@ -717,14 +719,21 @@ grub_ext2_read_symlink (grub_fshelp_node_t node)
} }
} }
symlink = grub_malloc (grub_le_to_cpu32 (diro->inode.size) + 1); if (grub_add (grub_le_to_cpu32 (diro->inode.size), 1, &sz))
{
grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow is detected"));
return NULL;
}
symlink = grub_malloc (sz);
if (! symlink) if (! symlink)
return 0; return 0;
/* If the filesize of the symlink is bigger than /*
60 the symlink is stored in a separate block, * If the filesize of the symlink is equal to or bigger than 60 the symlink
otherwise it is stored in the inode. */ * is stored in a separate block, otherwise it is stored in the inode.
if (grub_le_to_cpu32 (diro->inode.size) <= sizeof (diro->inode.symlink)) */
if (grub_le_to_cpu32 (diro->inode.size) < sizeof (diro->inode.symlink))
grub_memcpy (symlink, grub_memcpy (symlink,
diro->inode.symlink, diro->inode.symlink,
grub_le_to_cpu32 (diro->inode.size)); grub_le_to_cpu32 (diro->inode.size));
+15 -1
View File
@@ -702,7 +702,7 @@ grub_get_node_path (struct grub_f2fs_inode *inode, grub_uint32_t block,
grub_uint32_t dindirect_blks = indirect_blks * NIDS_PER_BLOCK; grub_uint32_t dindirect_blks = indirect_blks * NIDS_PER_BLOCK;
grub_uint32_t direct_index = DEF_ADDRS_PER_INODE; grub_uint32_t direct_index = DEF_ADDRS_PER_INODE;
int n = 0; int n = 0;
int level = 0; int level = -1;
if (inode->i_inline & F2FS_INLINE_XATTR) if (inode->i_inline & F2FS_INLINE_XATTR)
direct_index -= F2FS_INLINE_XATTR_ADDRS; direct_index -= F2FS_INLINE_XATTR_ADDRS;
@@ -712,6 +712,7 @@ grub_get_node_path (struct grub_f2fs_inode *inode, grub_uint32_t block,
if (block < direct_index) if (block < direct_index)
{ {
offset[n] = block; offset[n] = block;
level = 0;
goto got; goto got;
} }
@@ -860,6 +861,10 @@ grub_f2fs_get_block (grub_fshelp_node_t node, grub_disk_addr_t block_ofs)
int level, i; int level, i;
level = grub_get_node_path (inode, block_ofs, offset, noffset); level = grub_get_node_path (inode, block_ofs, offset, noffset);
if (level < 0)
return -1;
if (level == 0) if (level == 0)
return grub_le_to_cpu32 (inode->i_addr[offset[0]]); return grub_le_to_cpu32 (inode->i_addr[offset[0]]);
@@ -1235,6 +1240,11 @@ grub_f2fs_utf16_to_utf8 (grub_uint16_t *in_buf_le)
return out_buf; return out_buf;
} }
#if __GNUC__ >= 9
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
#endif
static grub_err_t static grub_err_t
grub_f2fs_label (grub_device_t device, char **label) grub_f2fs_label (grub_device_t device, char **label)
{ {
@@ -1255,6 +1265,10 @@ grub_f2fs_label (grub_device_t device, char **label)
return grub_errno; return grub_errno;
} }
#if __GNUC__ >= 9
#pragma GCC diagnostic pop
#endif
static grub_err_t static grub_err_t
grub_f2fs_uuid (grub_device_t device, char **uuid) grub_f2fs_uuid (grub_device_t device, char **uuid)
{ {
+76 -15
View File
@@ -26,6 +26,7 @@
#include <grub/err.h> #include <grub/err.h>
#include <grub/dl.h> #include <grub/dl.h>
#include <grub/charset.h> #include <grub/charset.h>
#include <grub/datetime.h>
#ifndef MODE_EXFAT #ifndef MODE_EXFAT
#include <grub/fat.h> #include <grub/fat.h>
#else #else
@@ -596,6 +597,7 @@ struct grub_fat_iterate_context
{ {
#ifdef MODE_EXFAT #ifdef MODE_EXFAT
struct grub_fat_dir_node dir; struct grub_fat_dir_node dir;
struct grub_fat_dir_entry entry;
#else #else
struct grub_fat_dir_entry dir; struct grub_fat_dir_entry dir;
#endif #endif
@@ -642,27 +644,27 @@ grub_fat_iterate_dir_next (grub_fshelp_node_t node,
grub_memset (&ctxt->dir, 0, sizeof (ctxt->dir)); grub_memset (&ctxt->dir, 0, sizeof (ctxt->dir));
while (1) while (1)
{ {
struct grub_fat_dir_entry dir; struct grub_fat_dir_entry *dir = &ctxt->entry;
ctxt->offset += sizeof (dir); ctxt->offset += sizeof (*dir);
if (grub_fat_read_data (node->disk, node, 0, 0, ctxt->offset, sizeof (dir), if (grub_fat_read_data (node->disk, node, 0, 0, ctxt->offset, sizeof (*dir),
(char *) &dir) (char *) dir)
!= sizeof (dir)) != sizeof (*dir))
break; break;
if (dir.entry_type == 0) if (dir->entry_type == 0)
break; break;
if (!(dir.entry_type & 0x80)) if (!(dir->entry_type & 0x80))
continue; continue;
if (dir.entry_type == 0x85) if (dir->entry_type == 0x85)
{ {
unsigned i, nsec, slots = 0; unsigned i, nsec, slots = 0;
nsec = dir.type_specific.file.secondary_count; nsec = dir->type_specific.file.secondary_count;
ctxt->dir.attr = grub_cpu_to_le16 (dir.type_specific.file.attr); ctxt->dir.attr = grub_cpu_to_le16 (dir->type_specific.file.attr);
ctxt->dir.have_stream = 0; ctxt->dir.have_stream = 0;
for (i = 0; i < nsec; i++) for (i = 0; i < nsec; i++)
{ {
@@ -705,7 +707,7 @@ grub_fat_iterate_dir_next (grub_fshelp_node_t node,
if (i != nsec) if (i != nsec)
{ {
ctxt->offset -= sizeof (dir); ctxt->offset -= sizeof (*dir);
continue; continue;
} }
@@ -715,20 +717,47 @@ grub_fat_iterate_dir_next (grub_fshelp_node_t node,
return 0; return 0;
} }
/* Allocation bitmap. */ /* Allocation bitmap. */
if (dir.entry_type == 0x81) if (dir->entry_type == 0x81)
continue; continue;
/* Upcase table. */ /* Upcase table. */
if (dir.entry_type == 0x82) if (dir->entry_type == 0x82)
continue; continue;
/* Volume label. */ /* Volume label. */
if (dir.entry_type == 0x83) if (dir->entry_type == 0x83)
continue; continue;
grub_dprintf ("exfat", "unknown primary type 0x%02x\n", grub_dprintf ("exfat", "unknown primary type 0x%02x\n",
dir.entry_type); dir->entry_type);
} }
return grub_errno ? : GRUB_ERR_EOF; return grub_errno ? : GRUB_ERR_EOF;
} }
/*
* Convert a timestamp in exFAT format to seconds since the UNIX epoch
* according to sections 7.4.8 and 7.4.9 in the exFAT specification.
* https://docs.microsoft.com/en-us/windows/win32/fileio/exfat-specification
*/
static int
grub_exfat_timestamp (grub_uint32_t field, grub_uint8_t msec, grub_int32_t *nix) {
struct grub_datetime datetime = {
.year = (field >> 25) + 1980,
.month = (field & 0x01E00000) >> 21,
.day = (field & 0x001F0000) >> 16,
.hour = (field & 0x0000F800) >> 11,
.minute = (field & 0x000007E0) >> 5,
.second = (field & 0x0000001F) * 2 + (msec >= 100 ? 1 : 0),
};
/* The conversion below allows seconds=60, so don't trust its validation. */
if ((field & 0x1F) > 29)
return 0;
/* Validate the 10-msec field even though it is rounded down to seconds. */
if (msec > 199)
return 0;
return grub_datetime2unixtime (&datetime, nix);
}
#else #else
static grub_err_t static grub_err_t
@@ -856,6 +885,29 @@ grub_fat_iterate_dir_next (grub_fshelp_node_t node,
return grub_errno ? : GRUB_ERR_EOF; return grub_errno ? : GRUB_ERR_EOF;
} }
/*
* Convert a date and time in FAT format to seconds since the UNIX epoch
* according to sections 11.3.5 and 11.3.6 in ECMA-107.
* https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-107.pdf
*/
static int
grub_fat_timestamp (grub_uint16_t time, grub_uint16_t date, grub_int32_t *nix) {
struct grub_datetime datetime = {
.year = (date >> 9) + 1980,
.month = (date & 0x01E0) >> 5,
.day = (date & 0x001F),
.hour = (time >> 11),
.minute = (time & 0x07E0) >> 5,
.second = (time & 0x001F) * 2,
};
/* The conversion below allows seconds=60, so don't trust its validation. */
if ((time & 0x1F) > 29)
return 0;
return grub_datetime2unixtime (&datetime, nix);
}
#endif #endif
static grub_err_t lookup_file (grub_fshelp_node_t node, static grub_err_t lookup_file (grub_fshelp_node_t node,
@@ -965,10 +1017,19 @@ grub_fat_dir (grub_device_t device, const char *path, grub_fs_dir_hook_t hook,
#ifdef MODE_EXFAT #ifdef MODE_EXFAT
if (!ctxt.dir.have_stream) if (!ctxt.dir.have_stream)
continue; continue;
info.mtimeset = grub_exfat_timestamp (grub_le_to_cpu32 (ctxt.entry.type_specific.file.m_time),
ctxt.entry.type_specific.file.m_time_tenth,
&info.mtime);
#else #else
if (ctxt.dir.attr & GRUB_FAT_ATTR_VOLUME_ID) if (ctxt.dir.attr & GRUB_FAT_ATTR_VOLUME_ID)
continue; continue;
info.mtimeset = grub_fat_timestamp (grub_le_to_cpu16 (ctxt.dir.w_time),
grub_le_to_cpu16 (ctxt.dir.w_date),
&info.mtime);
#endif #endif
if (info.mtimeset == 0)
grub_error (GRUB_ERR_OUT_OF_RANGE,
"invalid modification timestamp for %s", path);
if (hook (ctxt.filename, &info, hook_data)) if (hook (ctxt.filename, &info, hook_data))
break; break;
+12
View File
@@ -362,6 +362,18 @@ grub_fshelp_read_file (grub_disk_t disk, grub_fshelp_node_t node,
grub_disk_addr_t i, blockcnt; grub_disk_addr_t i, blockcnt;
int blocksize = 1 << (log2blocksize + GRUB_DISK_SECTOR_BITS); int blocksize = 1 << (log2blocksize + GRUB_DISK_SECTOR_BITS);
/*
* Catch blatantly invalid log2blocksize. We could be a lot stricter, but
* this is the most permissive we can be before we start to see integer
* overflow/underflow issues.
*/
if (log2blocksize + GRUB_DISK_SECTOR_BITS >= 31)
{
grub_error (GRUB_ERR_OUT_OF_RANGE,
N_("blocksize too large"));
return -1;
}
if (pos > filesize) if (pos > filesize)
{ {
grub_error (GRUB_ERR_OUT_OF_RANGE, grub_error (GRUB_ERR_OUT_OF_RANGE,
+6 -3
View File
@@ -30,6 +30,7 @@
#include <grub/hfs.h> #include <grub/hfs.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+");
@@ -1360,7 +1361,7 @@ grub_hfs_label (grub_device_t device, char **label)
grub_size_t len = data->sblock.volname[0]; grub_size_t len = data->sblock.volname[0];
if (len > sizeof (data->sblock.volname) - 1) if (len > sizeof (data->sblock.volname) - 1)
len = sizeof (data->sblock.volname) - 1; len = sizeof (data->sblock.volname) - 1;
*label = grub_malloc (len * MAX_UTF8_PER_MAC_ROMAN + 1); *label = grub_calloc (MAX_UTF8_PER_MAC_ROMAN + 1, len);
if (*label) if (*label)
macroman_to_utf8 (*label, data->sblock.volname + 1, macroman_to_utf8 (*label, data->sblock.volname + 1,
len + 1, 0); len + 1, 0);
@@ -1433,11 +1434,13 @@ static struct grub_fs grub_hfs_fs =
GRUB_MOD_INIT(hfs) GRUB_MOD_INIT(hfs)
{ {
grub_fs_register (&grub_hfs_fs); if (!grub_is_lockdown ())
grub_fs_register (&grub_hfs_fs);
my_mod = mod; my_mod = mod;
} }
GRUB_MOD_FINI(hfs) GRUB_MOD_FINI(hfs)
{ {
grub_fs_unregister (&grub_hfs_fs); if (!grub_is_lockdown())
grub_fs_unregister (&grub_hfs_fs);
} }
+82 -26
View File
@@ -31,6 +31,7 @@
#include <grub/hfs.h> #include <grub/hfs.h>
#include <grub/charset.h> #include <grub/charset.h>
#include <grub/hfsplus.h> #include <grub/hfsplus.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -176,6 +177,17 @@ grub_hfsplus_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
break; break;
} }
/*
* If the extent overflow tree isn't ready yet, we can't look
* in it. This can happen where the catalog file is corrupted.
*/
if (!node->data->extoverflow_tree_ready)
{
grub_error (GRUB_ERR_BAD_FS,
"attempted to read extent overflow tree before loading");
break;
}
/* Set up the key to look for in the extent overflow file. */ /* Set up the key to look for in the extent overflow file. */
extoverflow.extkey.fileid = node->fileid; extoverflow.extkey.fileid = node->fileid;
extoverflow.extkey.type = 0; extoverflow.extkey.type = 0;
@@ -187,7 +199,8 @@ grub_hfsplus_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
|| !nnode) || !nnode)
{ {
grub_error (GRUB_ERR_READ_ERROR, grub_error (GRUB_ERR_READ_ERROR,
"no block found for the file id 0x%x and the block offset 0x%x", "no block found for the file id 0x%x and the block"
" offset 0x%" PRIuGRUB_UINT64_T,
node->fileid, fileblock); node->fileid, fileblock);
break; break;
} }
@@ -240,6 +253,7 @@ grub_hfsplus_mount (grub_disk_t disk)
return 0; return 0;
data->disk = disk; data->disk = disk;
data->extoverflow_tree_ready = 0;
/* Read the bootblock. */ /* Read the bootblock. */
grub_disk_read (disk, GRUB_HFSPLUS_SBLOCK, 0, sizeof (volheader), grub_disk_read (disk, GRUB_HFSPLUS_SBLOCK, 0, sizeof (volheader),
@@ -356,6 +370,8 @@ grub_hfsplus_mount (grub_disk_t disk)
if (data->extoverflow_tree.nodesize < 2) if (data->extoverflow_tree.nodesize < 2)
goto fail; goto fail;
data->extoverflow_tree_ready = 1;
if (grub_hfsplus_read_file (&data->attr_tree.file, 0, 0, if (grub_hfsplus_read_file (&data->attr_tree.file, 0, 0,
sizeof (struct grub_hfsplus_btnode), sizeof (struct grub_hfsplus_btnode),
sizeof (header), (char *) &header) <= 0) sizeof (header), (char *) &header) <= 0)
@@ -475,8 +491,12 @@ grub_hfsplus_read_symlink (grub_fshelp_node_t node)
{ {
char *symlink; char *symlink;
grub_ssize_t numread; grub_ssize_t numread;
grub_size_t sz = node->size;
symlink = grub_malloc (node->size + 1); if (grub_add (sz, 1, &sz))
return NULL;
symlink = grub_malloc (sz);
if (!symlink) if (!symlink)
return 0; return 0;
@@ -630,6 +650,10 @@ grub_hfsplus_btree_search (struct grub_hfsplus_btree *btree,
pointer = ((char *) currkey pointer = ((char *) currkey
+ grub_be_to_cpu16 (currkey->keylen) + grub_be_to_cpu16 (currkey->keylen)
+ 2); + 2);
if ((char *) pointer > node + btree->nodesize - 2)
return grub_error (GRUB_ERR_BAD_FS, "HFS+ key beyond end of node");
currnode = grub_be_to_cpu32 (grub_get_unaligned32 (pointer)); currnode = grub_be_to_cpu32 (grub_get_unaligned32 (pointer));
match = 1; match = 1;
} }
@@ -661,6 +685,7 @@ list_nodes (void *record, void *hook_arg)
char *filename; char *filename;
int i; int i;
struct grub_fshelp_node *node; struct grub_fshelp_node *node;
grub_uint16_t *keyname;
struct grub_hfsplus_catfile *fileinfo; struct grub_hfsplus_catfile *fileinfo;
enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN; enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN;
struct list_nodes_ctx *ctx = hook_arg; struct list_nodes_ctx *ctx = hook_arg;
@@ -714,37 +739,39 @@ list_nodes (void *record, void *hook_arg)
if (type == GRUB_FSHELP_UNKNOWN) if (type == GRUB_FSHELP_UNKNOWN)
return 0; return 0;
filename = grub_malloc (grub_be_to_cpu16 (catkey->namelen) filename = grub_calloc (grub_be_to_cpu16 (catkey->namelen),
* GRUB_MAX_UTF8_PER_UTF16 + 1); GRUB_MAX_UTF8_PER_UTF16 + 1);
if (! filename) if (! filename)
return 0; return 0;
keyname = grub_calloc (grub_be_to_cpu16 (catkey->namelen), sizeof (*keyname));
if (!keyname)
{
grub_free (filename);
return 0;
}
/* Make sure the byte order of the UTF16 string is correct. */ /* Make sure the byte order of the UTF16 string is correct. */
for (i = 0; i < grub_be_to_cpu16 (catkey->namelen); i++) for (i = 0; i < grub_be_to_cpu16 (catkey->namelen); i++)
{ {
catkey->name[i] = grub_be_to_cpu16 (catkey->name[i]); keyname[i] = grub_be_to_cpu16 (catkey->name[i]);
if (catkey->name[i] == '/') if (keyname[i] == '/')
catkey->name[i] = ':'; keyname[i] = ':';
/* If the name is obviously invalid, skip this node. */ /* If the name is obviously invalid, skip this node. */
if (catkey->name[i] == 0) if (keyname[i] == 0)
{ {
grub_free (keyname);
grub_free (filename); grub_free (filename);
return 0; return 0;
} }
} }
*grub_utf16_to_utf8 ((grub_uint8_t *) filename, catkey->name, *grub_utf16_to_utf8 ((grub_uint8_t *) filename, keyname,
grub_be_to_cpu16 (catkey->namelen)) = '\0'; grub_be_to_cpu16 (catkey->namelen)) = '\0';
/* Restore the byte order to what it was previously. */ grub_free (keyname);
for (i = 0; i < grub_be_to_cpu16 (catkey->namelen); i++)
{
if (catkey->name[i] == ':')
catkey->name[i] = '/';
catkey->name[i] = grub_be_to_cpu16 (catkey->name[i]);
}
/* hfs+ is case insensitive. */ /* hfs+ is case insensitive. */
if (! ctx->dir->data->case_sensitive) if (! ctx->dir->data->case_sensitive)
@@ -975,6 +1002,7 @@ grub_hfsplus_label (grub_device_t device, char **label)
grub_disk_t disk = device->disk; grub_disk_t disk = device->disk;
struct grub_hfsplus_catkey *catkey; struct grub_hfsplus_catkey *catkey;
int i, label_len; int i, label_len;
grub_uint16_t *label_name;
struct grub_hfsplus_key_internal intern; struct grub_hfsplus_key_internal intern;
struct grub_hfsplus_btnode *node = NULL; struct grub_hfsplus_btnode *node = NULL;
grub_disk_addr_t ptr = 0; grub_disk_addr_t ptr = 0;
@@ -1003,22 +1031,50 @@ grub_hfsplus_label (grub_device_t device, char **label)
grub_hfsplus_btree_recptr (&data->catalog_tree, node, ptr); grub_hfsplus_btree_recptr (&data->catalog_tree, node, ptr);
label_len = grub_be_to_cpu16 (catkey->namelen); label_len = grub_be_to_cpu16 (catkey->namelen);
for (i = 0; i < label_len; i++)
{
catkey->name[i] = grub_be_to_cpu16 (catkey->name[i]);
/* If the name is obviously invalid, skip this node. */ /* Ensure that the length is >= 0. */
if (catkey->name[i] == 0) if (label_len < 0)
return 0; label_len = 0;
/* Ensure label length is at most 255 Unicode characters. */
if (label_len > 255)
label_len = 255;
label_name = grub_calloc (label_len, sizeof (*label_name));
if (!label_name)
{
grub_free (node);
grub_free (data);
return grub_errno;
} }
*label = grub_malloc (label_len * GRUB_MAX_UTF8_PER_UTF16 + 1); for (i = 0; i < label_len; i++)
if (! *label) {
return grub_errno; label_name[i] = grub_be_to_cpu16 (catkey->name[i]);
*grub_utf16_to_utf8 ((grub_uint8_t *) (*label), catkey->name, /* If the name is obviously invalid, skip this node. */
if (label_name[i] == 0)
{
grub_free (label_name);
grub_free (node);
grub_free (data);
return 0;
}
}
*label = grub_calloc (label_len, GRUB_MAX_UTF8_PER_UTF16 + 1);
if (! *label)
{
grub_free (label_name);
grub_free (node);
grub_free (data);
return grub_errno;
}
*grub_utf16_to_utf8 ((grub_uint8_t *) (*label), label_name,
label_len) = '\0'; label_len) = '\0';
grub_free (label_name);
grub_free (node); grub_free (node);
grub_free (data); grub_free (data);
+55 -18
View File
@@ -28,6 +28,7 @@
#include <grub/fshelp.h> #include <grub/fshelp.h>
#include <grub/charset.h> #include <grub/charset.h>
#include <grub/datetime.h> #include <grub/datetime.h>
#include <grub/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -331,7 +332,7 @@ grub_iso9660_convert_string (grub_uint8_t *us, int len)
int i; int i;
grub_uint16_t t[MAX_NAMELEN / 2 + 1]; grub_uint16_t t[MAX_NAMELEN / 2 + 1];
p = grub_malloc (len * GRUB_MAX_UTF8_PER_UTF16 + 1); p = grub_calloc (len, GRUB_MAX_UTF8_PER_UTF16 + 1);
if (! p) if (! p)
return NULL; return NULL;
@@ -531,11 +532,22 @@ add_part (struct iterate_dir_ctx *ctx,
int len2) int len2)
{ {
int size = ctx->symlink ? grub_strlen (ctx->symlink) : 0; int size = ctx->symlink ? grub_strlen (ctx->symlink) : 0;
grub_size_t sz;
char *new;
ctx->symlink = grub_realloc (ctx->symlink, size + len2 + 1); if (grub_add (size, len2, &sz) ||
if (! ctx->symlink) grub_add (sz, 1, &sz))
return; return;
new = grub_realloc (ctx->symlink, sz);
if (!new)
{
grub_free (ctx->symlink);
ctx->symlink = NULL;
return;
}
ctx->symlink = new;
grub_memcpy (ctx->symlink + size, part, len2); grub_memcpy (ctx->symlink + size, part, len2);
ctx->symlink[size + len2] = 0; ctx->symlink[size + len2] = 0;
} }
@@ -560,17 +572,24 @@ susp_iterate_dir (struct grub_iso9660_susp_entry *entry,
{ {
grub_size_t off = 0, csize = 1; grub_size_t off = 0, csize = 1;
char *old; char *old;
grub_size_t sz;
csize = entry->len - 5; csize = entry->len - 5;
old = ctx->filename; old = ctx->filename;
if (ctx->filename_alloc) if (ctx->filename_alloc)
{ {
off = grub_strlen (ctx->filename); off = grub_strlen (ctx->filename);
ctx->filename = grub_realloc (ctx->filename, csize + off + 1); if (grub_add (csize, off, &sz) ||
grub_add (sz, 1, &sz))
return GRUB_ERR_OUT_OF_RANGE;
ctx->filename = grub_realloc (ctx->filename, sz);
} }
else else
{ {
off = 0; off = 0;
ctx->filename = grub_zalloc (csize + 1); if (grub_add (csize, 1, &sz))
return GRUB_ERR_OUT_OF_RANGE;
ctx->filename = grub_zalloc (sz);
} }
if (!ctx->filename) if (!ctx->filename)
{ {
@@ -621,7 +640,12 @@ susp_iterate_dir (struct grub_iso9660_susp_entry *entry,
is the length. Both are part of the `Component is the length. Both are part of the `Component
Record'. */ Record'. */
if (ctx->symlink && !ctx->was_continue) if (ctx->symlink && !ctx->was_continue)
add_part (ctx, "/", 1); {
add_part (ctx, "/", 1);
if (grub_errno)
return grub_errno;
}
add_part (ctx, (char *) &entry->data[pos + 2], add_part (ctx, (char *) &entry->data[pos + 2],
entry->data[pos + 1]); entry->data[pos + 1]);
ctx->was_continue = (entry->data[pos] & 1); ctx->was_continue = (entry->data[pos] & 1);
@@ -640,6 +664,11 @@ susp_iterate_dir (struct grub_iso9660_susp_entry *entry,
add_part (ctx, "/", 1); add_part (ctx, "/", 1);
break; break;
} }
/* Check if grub_realloc() failed in add_part(). */
if (grub_errno)
return grub_errno;
/* In pos + 1 the length of the `Component Record' is /* In pos + 1 the length of the `Component Record' is
stored. */ stored. */
pos += entry->data[pos + 1] + 2; pos += entry->data[pos + 1] + 2;
@@ -776,14 +805,18 @@ grub_iso9660_iterate_dir (grub_fshelp_node_t dir,
if (node->have_dirents >= node->alloc_dirents) if (node->have_dirents >= node->alloc_dirents)
{ {
struct grub_fshelp_node *new_node; struct grub_fshelp_node *new_node;
node->alloc_dirents *= 2; grub_size_t sz;
new_node = grub_realloc (node,
sizeof (struct grub_fshelp_node) if (grub_mul (node->alloc_dirents, 2, &node->alloc_dirents) ||
+ ((node->alloc_dirents grub_sub (node->alloc_dirents, ARRAY_SIZE (node->dirents), &sz) ||
- ARRAY_SIZE (node->dirents)) grub_mul (sz, sizeof (node->dirents[0]), &sz) ||
* sizeof (node->dirents[0]))); grub_add (sz, sizeof (struct grub_fshelp_node), &sz))
goto fail_0;
new_node = grub_realloc (node, sz);
if (!new_node) if (!new_node)
{ {
fail_0:
if (ctx.filename_alloc) if (ctx.filename_alloc)
grub_free (ctx.filename); grub_free (ctx.filename);
grub_free (node); grub_free (node);
@@ -799,14 +832,18 @@ grub_iso9660_iterate_dir (grub_fshelp_node_t dir,
* sizeof (node->dirents[0]) < grub_strlen (ctx.symlink) + 1) * sizeof (node->dirents[0]) < grub_strlen (ctx.symlink) + 1)
{ {
struct grub_fshelp_node *new_node; struct grub_fshelp_node *new_node;
new_node = grub_realloc (node, grub_size_t sz;
sizeof (struct grub_fshelp_node)
+ ((node->alloc_dirents if (grub_sub (node->alloc_dirents, ARRAY_SIZE (node->dirents), &sz) ||
- ARRAY_SIZE (node->dirents)) grub_mul (sz, sizeof (node->dirents[0]), &sz) ||
* sizeof (node->dirents[0])) grub_add (sz, sizeof (struct grub_fshelp_node) + 1, &sz) ||
+ grub_strlen (ctx.symlink) + 1); grub_add (sz, grub_strlen (ctx.symlink), &sz))
goto fail_1;
new_node = grub_realloc (node, sz);
if (!new_node) if (!new_node)
{ {
fail_1:
if (ctx.filename_alloc) if (ctx.filename_alloc)
grub_free (ctx.filename); grub_free (ctx.filename);
grub_free (node); grub_free (node);
+22 -4
View File
@@ -261,13 +261,15 @@ static grub_err_t grub_jfs_lookup_symlink (struct grub_jfs_data *data, grub_uint
static grub_int64_t static grub_int64_t
getblk (struct grub_jfs_treehead *treehead, getblk (struct grub_jfs_treehead *treehead,
struct grub_jfs_tree_extent *extents, struct grub_jfs_tree_extent *extents,
int max_extents,
struct grub_jfs_data *data, struct grub_jfs_data *data,
grub_uint64_t blk) grub_uint64_t blk)
{ {
int found = -1; int found = -1;
int i; int i;
for (i = 0; i < grub_le_to_cpu16 (treehead->count) - 2; i++) for (i = 0; i < grub_le_to_cpu16 (treehead->count) - 2 &&
i < max_extents; i++)
{ {
if (treehead->flags & GRUB_JFS_TREE_LEAF) if (treehead->flags & GRUB_JFS_TREE_LEAF)
{ {
@@ -302,7 +304,16 @@ getblk (struct grub_jfs_treehead *treehead,
<< (grub_le_to_cpu16 (data->sblock.log2_blksz) << (grub_le_to_cpu16 (data->sblock.log2_blksz)
- GRUB_DISK_SECTOR_BITS), 0, - GRUB_DISK_SECTOR_BITS), 0,
sizeof (*tree), (char *) tree)) sizeof (*tree), (char *) tree))
ret = getblk (&tree->treehead, &tree->extents[0], data, blk); {
if (grub_memcmp (&tree->treehead, treehead, sizeof (struct grub_jfs_treehead)) ||
grub_memcmp (&tree->extents, extents, 254 * sizeof (struct grub_jfs_tree_extent)))
ret = getblk (&tree->treehead, &tree->extents[0], 254, data, blk);
else
{
grub_error (GRUB_ERR_BAD_FS, "jfs: infinite recursion detected");
ret = -1;
}
}
grub_free (tree); grub_free (tree);
return ret; return ret;
} }
@@ -316,7 +327,7 @@ static grub_int64_t
grub_jfs_blkno (struct grub_jfs_data *data, struct grub_jfs_inode *inode, grub_jfs_blkno (struct grub_jfs_data *data, struct grub_jfs_inode *inode,
grub_uint64_t blk) grub_uint64_t blk)
{ {
return getblk (&inode->file.tree, &inode->file.extents[0], data, blk); return getblk (&inode->file.tree, &inode->file.extents[0], 16, data, blk);
} }
@@ -505,6 +516,10 @@ le_to_cpu16_copy (grub_uint16_t *out, grub_uint16_t *in, grub_size_t len)
*out++ = grub_le_to_cpu16 (*in++); *out++ = grub_le_to_cpu16 (*in++);
} }
#if __GNUC__ >= 9
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
#endif
/* Read in the next dirent from the directory described by DIRO. */ /* Read in the next dirent from the directory described by DIRO. */
static grub_err_t static grub_err_t
@@ -563,7 +578,7 @@ grub_jfs_getent (struct grub_jfs_diropen *diro)
/* Move down to the leaf level. */ /* Move down to the leaf level. */
nextent = leaf->next; nextent = leaf->next;
if (leaf->next != 255) if (leaf->next != 255 && len > 0)
do do
{ {
next_leaf = &diro->next_leaf[nextent]; next_leaf = &diro->next_leaf[nextent];
@@ -582,6 +597,9 @@ grub_jfs_getent (struct grub_jfs_diropen *diro)
return 0; return 0;
} }
#if __GNUC__ >= 9
#pragma GCC diagnostic pop
#endif
/* Read LEN bytes from the file described by DATA starting with byte /* Read LEN bytes from the file described by DATA starting with byte
POS. Return the amount of read bytes in READ. */ POS. Return the amount of read bytes in READ. */
+17 -1
View File
@@ -38,6 +38,8 @@ GRUB_MOD_LICENSE ("GPLv3+");
#define GRUB_MINIX_MAGIC_30 0x138F #define GRUB_MINIX_MAGIC_30 0x138F
#endif #endif
#define EXT2_MAGIC 0xEF53
#define GRUB_MINIX_INODE_DIR_BLOCKS 7 #define GRUB_MINIX_INODE_DIR_BLOCKS 7
#define GRUB_MINIX_LOG2_BSIZE 1 #define GRUB_MINIX_LOG2_BSIZE 1
#define GRUB_MINIX_ROOT_INODE 1 #define GRUB_MINIX_ROOT_INODE 1
@@ -466,7 +468,21 @@ grub_minix_find_file (struct grub_minix_data *data, const char *path)
static struct grub_minix_data * static struct grub_minix_data *
grub_minix_mount (grub_disk_t disk) grub_minix_mount (grub_disk_t disk)
{ {
struct grub_minix_data *data; struct grub_minix_data *data = NULL;
grub_uint16_t ext2_marker;
grub_disk_read (disk, 2, 56, sizeof (ext2_marker), &ext2_marker);
if (grub_errno != GRUB_ERR_NONE)
goto fail;
/*
* The ext2 filesystems can sometimes be mistakenly identified as MINIX, e.g.
* due to the number of free ext2 inodes being written to the same location
* where the MINIX superblock magic is found. Avoid such situations by
* skipping any filesystems that have the ext2 superblock magic.
*/
if (ext2_marker == grub_cpu_to_le16_compile_time (EXT2_MAGIC))
goto fail;
data = grub_malloc (sizeof (struct grub_minix_data)); data = grub_malloc (sizeof (struct grub_minix_data));
if (!data) if (!data)
+38 -20
View File
@@ -416,15 +416,35 @@ grub_nilfs2_btree_node_get_key (struct grub_nilfs2_btree_node *node,
} }
static inline int static inline int
grub_nilfs2_btree_node_lookup (struct grub_nilfs2_btree_node *node, grub_nilfs2_btree_node_nchildren_max (struct grub_nilfs2_data *data,
struct grub_nilfs2_btree_node *node)
{
int node_children_max = ((NILFS2_BLOCK_SIZE (data) -
sizeof (struct grub_nilfs2_btree_node) -
NILFS_BTREE_NODE_EXTRA_PAD_SIZE) /
(sizeof (grub_uint64_t) + sizeof (grub_uint64_t)));
return (node->bn_flags & NILFS_BTREE_NODE_ROOT) ? 3 : node_children_max;
}
static inline int
grub_nilfs2_btree_node_lookup (struct grub_nilfs2_data *data,
struct grub_nilfs2_btree_node *node,
grub_uint64_t key, int *indexp) grub_uint64_t key, int *indexp)
{ {
grub_uint64_t nkey; grub_uint64_t nkey;
int index, low, high, s; int index = 0, low, high, s;
low = 0; low = 0;
high = grub_le_to_cpu16 (node->bn_nchildren) - 1; high = grub_le_to_cpu16 (node->bn_nchildren) - 1;
index = 0; if (high >= grub_nilfs2_btree_node_nchildren_max (data, node))
{
grub_error (GRUB_ERR_BAD_FS, "too many children");
*indexp = index;
return 0;
}
s = 0; s = 0;
while (low <= high) while (low <= high)
{ {
@@ -459,18 +479,6 @@ grub_nilfs2_btree_node_lookup (struct grub_nilfs2_btree_node *node,
return s == 0; return s == 0;
} }
static inline int
grub_nilfs2_btree_node_nchildren_max (struct grub_nilfs2_data *data,
struct grub_nilfs2_btree_node *node)
{
int node_children_max = ((NILFS2_BLOCK_SIZE (data) -
sizeof (struct grub_nilfs2_btree_node) -
NILFS_BTREE_NODE_EXTRA_PAD_SIZE) /
(sizeof (grub_uint64_t) + sizeof (grub_uint64_t)));
return (node->bn_flags & NILFS_BTREE_NODE_ROOT) ? 3 : node_children_max;
}
static inline grub_uint64_t * static inline grub_uint64_t *
grub_nilfs2_btree_node_dptrs (struct grub_nilfs2_data *data, grub_nilfs2_btree_node_dptrs (struct grub_nilfs2_data *data,
struct grub_nilfs2_btree_node *node) struct grub_nilfs2_btree_node *node)
@@ -517,7 +525,11 @@ grub_nilfs2_btree_lookup (struct grub_nilfs2_data *data,
node = grub_nilfs2_btree_get_root (inode); node = grub_nilfs2_btree_get_root (inode);
level = grub_nilfs2_btree_get_level (node); level = grub_nilfs2_btree_get_level (node);
found = grub_nilfs2_btree_node_lookup (node, key, &index); found = grub_nilfs2_btree_node_lookup (data, node, key, &index);
if (grub_errno != GRUB_ERR_NONE)
goto fail;
ptr = grub_nilfs2_btree_node_get_ptr (data, node, index); ptr = grub_nilfs2_btree_node_get_ptr (data, node, index);
if (need_translate) if (need_translate)
ptr = grub_nilfs2_dat_translate (data, ptr); ptr = grub_nilfs2_dat_translate (data, ptr);
@@ -538,11 +550,12 @@ grub_nilfs2_btree_lookup (struct grub_nilfs2_data *data,
} }
if (!found) if (!found)
found = grub_nilfs2_btree_node_lookup (node, key, &index); found = grub_nilfs2_btree_node_lookup (data, node, key, &index);
else else
index = 0; index = 0;
if (index < grub_nilfs2_btree_node_nchildren_max (data, node)) if (index < grub_nilfs2_btree_node_nchildren_max (data, node) &&
grub_errno == GRUB_ERR_NONE)
{ {
ptr = grub_nilfs2_btree_node_get_ptr (data, node, index); ptr = grub_nilfs2_btree_node_get_ptr (data, node, index);
if (need_translate) if (need_translate)
@@ -569,6 +582,11 @@ grub_nilfs2_btree_lookup (struct grub_nilfs2_data *data,
static inline grub_uint64_t static inline grub_uint64_t
grub_nilfs2_direct_lookup (struct grub_nilfs2_inode *inode, grub_uint64_t key) grub_nilfs2_direct_lookup (struct grub_nilfs2_inode *inode, grub_uint64_t key)
{ {
if (1 + key > 6)
{
grub_error (GRUB_ERR_BAD_FS, "key is too large");
return 0xffffffffffffffff;
}
return grub_le_to_cpu64 (inode->i_bmap[1 + key]); return grub_le_to_cpu64 (inode->i_bmap[1 + key]);
} }
@@ -584,7 +602,7 @@ grub_nilfs2_bmap_lookup (struct grub_nilfs2_data *data,
{ {
grub_uint64_t ptr; grub_uint64_t ptr;
ptr = grub_nilfs2_direct_lookup (inode, key); ptr = grub_nilfs2_direct_lookup (inode, key);
if (need_translate) if (ptr != ((grub_uint64_t) 0xffffffffffffffff) && need_translate)
ptr = grub_nilfs2_dat_translate (data, ptr); ptr = grub_nilfs2_dat_translate (data, ptr);
return ptr; return ptr;
} }
@@ -753,7 +771,7 @@ grub_nilfs2_load_sb (struct grub_nilfs2_data *data)
partition_size = (grub_le_to_cpu64 (data->sblock.s_dev_size) partition_size = (grub_le_to_cpu64 (data->sblock.s_dev_size)
>> GRUB_DISK_SECTOR_BITS); >> GRUB_DISK_SECTOR_BITS);
else else
partition_size = grub_disk_get_size (disk); partition_size = grub_disk_native_sectors (disk);
if (partition_size != GRUB_DISK_SIZE_UNKNOWN) if (partition_size != GRUB_DISK_SIZE_UNKNOWN)
{ {
/* Read second super block. */ /* Read second super block. */
+2 -2
View File
@@ -556,8 +556,8 @@ get_utf8 (grub_uint8_t *in, grub_size_t len)
grub_uint16_t *tmp; grub_uint16_t *tmp;
grub_size_t i; grub_size_t i;
buf = grub_malloc (len * GRUB_MAX_UTF8_PER_UTF16 + 1); buf = grub_calloc (len, GRUB_MAX_UTF8_PER_UTF16 + 1);
tmp = grub_malloc (len * sizeof (tmp[0])); tmp = grub_calloc (len, sizeof (tmp[0]));
if (!buf || !tmp) if (!buf || !tmp)
{ {
grub_free (buf); grub_free (buf);
+31 -7
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/safemath.h>
GRUB_MOD_LICENSE ("GPLv3+"); GRUB_MOD_LICENSE ("GPLv3+");
@@ -266,7 +267,7 @@ grub_sfs_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
node->next_extent = node->block; node->next_extent = node->block;
node->cache_size = 0; node->cache_size = 0;
node->cache = grub_malloc (sizeof (node->cache[0]) * cache_size); node->cache = grub_calloc (cache_size, sizeof (node->cache[0]));
if (!node->cache) if (!node->cache)
{ {
grub_errno = 0; grub_errno = 0;
@@ -307,10 +308,15 @@ grub_sfs_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
if (node->cache && node->cache_size >= node->cache_allocated) if (node->cache && node->cache_size >= node->cache_allocated)
{ {
struct cache_entry *e = node->cache; struct cache_entry *e = node->cache;
e = grub_realloc (node->cache,node->cache_allocated * 2 grub_size_t sz;
* sizeof (e[0]));
if (grub_mul (node->cache_allocated, 2 * sizeof (e[0]), &sz))
goto fail;
e = grub_realloc (node->cache, sz);
if (!e) if (!e)
{ {
fail:
grub_errno = 0; grub_errno = 0;
grub_free (node->cache); grub_free (node->cache);
node->cache = 0; node->cache = 0;
@@ -367,6 +373,7 @@ grub_sfs_mount (grub_disk_t disk)
struct grub_sfs_objc *rootobjc; struct grub_sfs_objc *rootobjc;
char *rootobjc_data = 0; char *rootobjc_data = 0;
grub_uint32_t blk; grub_uint32_t blk;
unsigned int max_len;
data = grub_malloc (sizeof (*data)); data = grub_malloc (sizeof (*data));
if (!data) if (!data)
@@ -415,7 +422,13 @@ grub_sfs_mount (grub_disk_t disk)
data->diropen.data = data; data->diropen.data = data;
data->diropen.cache = 0; data->diropen.cache = 0;
data->disk = disk; data->disk = disk;
data->label = grub_strdup ((char *) (rootobjc->objects[0].filename));
/* We only read 1 block of data, so truncate the name if needed. */
max_len = ((GRUB_DISK_SECTOR_SIZE << data->log_blocksize)
- 24 /* offsetof (struct grub_sfs_objc, objects) */
- 25); /* offsetof (struct grub_sfs_obj, filename) */
data->label = grub_zalloc (max_len + 1);
grub_strncpy (data->label, (char *) rootobjc->objects[0].filename, max_len);
grub_free (rootobjc_data); grub_free (rootobjc_data);
return data; return data;
@@ -477,10 +490,16 @@ grub_sfs_create_node (struct grub_fshelp_node **node,
grub_size_t len = grub_strlen (name); grub_size_t len = grub_strlen (name);
grub_uint8_t *name_u8; grub_uint8_t *name_u8;
int ret; int ret;
grub_size_t sz;
if (grub_mul (len, GRUB_MAX_UTF8_PER_LATIN1, &sz) ||
grub_add (sz, 1, &sz))
return 1;
*node = grub_malloc (sizeof (**node)); *node = grub_malloc (sizeof (**node));
if (!*node) if (!*node)
return 1; return 1;
name_u8 = grub_malloc (len * GRUB_MAX_UTF8_PER_LATIN1 + 1); name_u8 = grub_malloc (sz);
if (!name_u8) if (!name_u8)
{ {
grub_free (*node); grub_free (*node);
@@ -724,8 +743,13 @@ grub_sfs_label (grub_device_t device, char **label)
data = grub_sfs_mount (disk); data = grub_sfs_mount (disk);
if (data) if (data)
{ {
grub_size_t len = grub_strlen (data->label); grub_size_t sz, len = grub_strlen (data->label);
*label = grub_malloc (len * GRUB_MAX_UTF8_PER_LATIN1 + 1);
if (grub_mul (len, GRUB_MAX_UTF8_PER_LATIN1, &sz) ||
grub_add (sz, 1, &sz))
return GRUB_ERR_OUT_OF_RANGE;
*label = grub_malloc (sz);
if (*label) if (*label)
*grub_latin1_to_utf8 ((grub_uint8_t *) *label, *grub_latin1_to_utf8 ((grub_uint8_t *) *label,
(const grub_uint8_t *) data->label, (const grub_uint8_t *) data->label,
Loaded 100 of 358 files, more files were not shown because too many files have changed in this diff. Show more