Provide Secure Boot support
[grml2usb.git] / grml2usb
index 05067e4..5108b9f 100755 (executable)
--- a/grml2usb
+++ b/grml2usb
@@ -502,8 +502,6 @@ def install_grub(device):
         device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
         register_tmpfile(device_mountpoint)
         try:
-            mount(device, device_mountpoint, "")
-
             # If using --grub-mbr then make sure we install grub in MBR instead of PBR
             if options.grubmbr:
                 logging.debug("Using option --grub-mbr ...")
@@ -512,15 +510,18 @@ def install_grub(device):
                 grub_device = device
 
             set_rw(device)
-            set_rw(grub_device)
+            mount(device, device_mountpoint, "")
 
             logging.info("Installing grub as bootloader")
-            for opt in ["", "--force"]:
-                logging.debug("grub-install --recheck %s --no-floppy --root-directory=%s %s",
-                              opt, device_mountpoint, grub_device)
-                proc = subprocess.Popen([GRUB_INSTALL, "--recheck", opt,
+            for opt in ["--", "--force"]:
+                set_rw(device)
+                set_rw(grub_device)
+                logging.debug("%s --recheck --no-floppy --target=i386-pc --root-directory=%s %s %s",
+                              GRUB_INSTALL, device_mountpoint, opt, grub_device)
+                proc = subprocess.Popen([GRUB_INSTALL, "--recheck",
                                          "--no-floppy", "--target=i386-pc",
-                                         "--root-directory=%s" % device_mountpoint, grub_device],
+                                         "--root-directory=%s" % device_mountpoint,
+                                         opt, grub_device],
                                         stdout=file(os.devnull, "r+"))
                 proc.wait()
                 if proc.returncode == 0:
@@ -715,8 +716,6 @@ def mount(source, target, mount_options):
         logging.debug("Source %s is not a device, therefore not mounting.", source)
         return 0
 
-    set_rw(source)
-
     logging.debug("mount %s %s %s", mount_options, source, target)
     proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
     proc.wait()
@@ -1030,6 +1029,9 @@ def copy_addons(iso_mount, target):
     # ipxe.lkrn
     handle_addon_copy('ipxe.lkrn', addons, iso_mount)
 
+    # netboot.xyz
+    handle_addon_copy('netboot.xyz.lkrn', addons, iso_mount)
+
 
 def build_loopbackcfg(target):
     """Generate GRUB's loopback.cfg based on existing config files.
@@ -1117,6 +1119,7 @@ def copy_bootloader_files(iso_mount, target, grml_flavour):
     if efi_img:
         mkdir(target + '/boot/')
         exec_rsync(efi_img, target + '/boot/efi.img')
+        handle_secure_boot(target, efi_img)
 
     for ffile in ['f%d' % number for number in range(1, 11)]:
         search_and_copy(ffile, iso_mount, syslinux_target + ffile)
@@ -1273,6 +1276,7 @@ def handle_grub_config(grml_flavour, device, target):
     logging.debug("Updating grub configuration")
 
     grub_target = target + '/boot/grub/'
+    secureboot_target = target + '/EFI/ubuntu/'
 
     bootid_re = re.compile("bootid=[\w_-]+")
     live_media_path_re = re.compile("live-media-path=[\w_/-]+")
@@ -1287,7 +1291,7 @@ def handle_grub_config(grml_flavour, device, target):
             remove_regexes.append(re.compile(regex))
 
     shortname = get_shortname(grml_flavour)
-    for filename in glob.glob(grub_target + '*.cfg'):
+    for filename in glob.glob(grub_target + '*.cfg') + glob.glob(secureboot_target + '*.cfg'):
         for line in fileinput.input(filename, inplace=1):
             line = line.rstrip("\r\n")
             if option_re.search(line):
@@ -1507,6 +1511,51 @@ def handle_syslinux_config(grml_flavour, target):
     add_syslinux_entry("%s/additional.cfg" % syslinux_target, flavour_filename)
 
 
+def handle_secure_boot(target, efi_img):
+    """Provide secure boot support by extracting files from /boot/efi.img
+
+    @target: path where grml's main files should be copied to
+    @efi_img: path to the efi.img file that includes the files for secure boot
+    """
+
+    mkdir(target + '/efi/boot/')
+    efi_mountpoint = tempfile.mkdtemp(prefix="grml2usb", dir=os.path.abspath(options.tmpdir))
+    logging.debug("efi_mountpoint = %s" % efi_mountpoint)
+    register_tmpfile(efi_mountpoint)
+
+    try:
+        logging.debug("mount(%s, %s, ['-o', 'ro', '-t', 'vfat']" % (efi_img, efi_mountpoint))
+        mount(efi_img, efi_mountpoint, ['-o', 'ro', '-t', 'vfat'])
+    except CriticalException as error:
+        logging.critical("Fatal: %s", error)
+        sys.exit(1)
+
+    ubuntu_cfg = search_file('grub.cfg', efi_mountpoint + '/EFI/ubuntu')
+    logging.debug("ubuntu_cfg = %s" % ubuntu_cfg)
+    if not ubuntu_cfg:
+        logging.info("No /EFI/ubuntu/grub.cfg found inside EFI image, looks like Secure Boot support is missing.")
+    else:
+        mkdir(target + '/efi/ubuntu')
+        logging.debug("exec_rsync(%s, %s + '/efi/ubuntu/grub.cfg')" % (ubuntu_cfg, target))
+        exec_rsync(ubuntu_cfg, target + '/efi/ubuntu/grub.cfg')
+
+        logging.debug("exec_rsync(%s + '/EFI/BOOT/grubx64.efi', %s + '/efi/boot/grubx64.efi')'" % (efi_mountpoint, target))
+        exec_rsync(efi_mountpoint + '/EFI/BOOT/grubx64.efi', target + '/efi/boot/grubx64.efi')
+
+        # NOTE - we're overwriting /efi/boot/bootx64.efi from copy_bootloader_files here
+        logging.debug("exec_rsync(%s + '/EFI/BOOT/bootx64.efi', %s + '/efi/boot/bootx64.efi')'" % (efi_mountpoint, target))
+        exec_rsync(efi_mountpoint + '/EFI/BOOT/bootx64.efi', target + '/efi/boot/bootx64.efi')
+
+    try:
+        unmount(efi_mountpoint, "")
+        logging.debug('Unmounted %s' % efi_mountpoint)
+        os.rmdir(efi_mountpoint)
+        logging.debug('Removed directory %s' % efi_mountpoint)
+    except StandardError:
+        logging.critical('RuntimeError while umount %s' % efi_mountpoint)
+        sys.exit(1)
+
+
 def handle_bootloader_config(grml_flavour, device, target):
     """Main handler for generating bootloader's configuration
 
@@ -1593,6 +1642,8 @@ def install_grml(mountpoint, device):
             check_for_fat(device)
             if not options.skipbootflag:
                 check_boot_flag(device)
+
+            set_rw(device)
             mount(device, device_mountpoint, ['-o', 'utf8,iocharset=iso8859-1'])
         except CriticalException as error:
             mount(device, device_mountpoint, "")
@@ -1840,8 +1891,7 @@ def main():
         if not os.path.isdir(device):
             if device[-1:].isdigit():
                 if int(device[-1:]) > 4 or device[-2:].isdigit():
-                    logging.critical("Fatal: installation on partition number >4 not supported. (BIOS won't support it.)")
-                    sys.exit(1)
+                    logging.warn("Warning: installing on partition number >4, booting *might* fail depending on your system.")
 
         # provide upgrade path
         handle_compat_warning(device)