Blame SOURCES/ovmf-vars-generator

7439a5
#!/bin/python3
7439a5
# Copyright (C) 2017 Red Hat
7439a5
# Authors:
7439a5
# - Patrick Uiterwijk <puiterwijk@redhat.com>
7439a5
# - Kashyap Chamarthy <kchamart@redhat.com>
7439a5
#
7439a5
# Licensed under MIT License, for full text see LICENSE
7439a5
#
7439a5
# Purpose: Launch a QEMU guest and enroll ithe UEFI keys into an OVMF
7439a5
#          variables ("VARS") file.  Then boot a Linux kernel with QEMU.
7439a5
#          Finally, perform a check to verify if Secure Boot
7439a5
#          is enabled.
7439a5
7439a5
from __future__ import print_function
7439a5
7439a5
import argparse
7439a5
import os
7439a5
import logging
7439a5
import tempfile
7439a5
import shutil
7439a5
import string
7439a5
import subprocess
7439a5
7439a5
7439a5
def strip_special(line):
7439a5
    return ''.join([c for c in str(line) if c in string.printable])
7439a5
7439a5
7439a5
def generate_qemu_cmd(args, readonly, *extra_args):
7439a5
    if args.disable_smm:
7439a5
        machinetype = 'pc'
7439a5
    else:
7439a5
        machinetype = 'q35,smm=on'
7439a5
    machinetype += ',accel=%s' % ('kvm' if args.enable_kvm else 'tcg')
7439a5
7439a5
    if args.oem_string is None:
7439a5
        oemstrings = []
7439a5
    else:
7439a5
        oemstring_values = [
7439a5
            ",value=" + s.replace(",", ",,") for s in args.oem_string ]
7439a5
        oemstrings = [
7439a5
            '-smbios',
7439a5
            "type=11" + ''.join(oemstring_values) ]
7439a5
7439a5
    return [
7439a5
        args.qemu_binary,
7439a5
        '-machine', machinetype,
7439a5
        '-display', 'none',
be6997
        '-cpu', 'max',
7439a5
        '-no-user-config',
7439a5
        '-nodefaults',
7439a5
        '-m', '768',
7439a5
        '-smp', '2,sockets=2,cores=1,threads=1',
7439a5
        '-chardev', 'pty,id=charserial1',
7439a5
        '-device', 'isa-serial,chardev=charserial1,id=serial1',
7439a5
        '-global', 'driver=cfi.pflash01,property=secure,value=%s' % (
7439a5
            'off' if args.disable_smm else 'on'),
7439a5
        '-drive',
7439a5
        'file=%s,if=pflash,format=raw,unit=0,readonly=on' % (
7439a5
            args.ovmf_binary),
7439a5
        '-drive',
7439a5
        'file=%s,if=pflash,format=raw,unit=1,readonly=%s' % (
7439a5
            args.out_temp, 'on' if readonly else 'off'),
7439a5
        '-serial', 'stdio'] + oemstrings + list(extra_args)
7439a5
7439a5
7439a5
def download(url, target, suffix, no_download):
7439a5
    istemp = False
7439a5
    if target and os.path.exists(target):
7439a5
        return target, istemp
7439a5
    if not target:
7439a5
        temped = tempfile.mkstemp(prefix='qosb.', suffix='.%s' % suffix)
7439a5
        os.close(temped[0])
7439a5
        target = temped[1]
7439a5
        istemp = True
7439a5
    if no_download:
7439a5
        raise Exception('%s did not exist, but downloading was disabled' %
7439a5
                        target)
7439a5
    import requests
7439a5
    logging.debug('Downloading %s to %s', url, target)
7439a5
    r = requests.get(url, stream=True)
7439a5
    with open(target, 'wb') as f:
7439a5
        for chunk in r.iter_content(chunk_size=1024):
7439a5
            if chunk:
7439a5
                f.write(chunk)
7439a5
    return target, istemp
7439a5
7439a5
7439a5
def enroll_keys(args):
7439a5
    shutil.copy(args.ovmf_template_vars, args.out_temp)
7439a5
7439a5
    logging.info('Starting enrollment')
7439a5
7439a5
    cmd = generate_qemu_cmd(
7439a5
        args,
7439a5
        False,
7439a5
        '-drive',
7439a5
        'file=%s,format=raw,if=none,media=cdrom,id=drive-cd1,'
7439a5
        'readonly=on' % args.uefi_shell_iso,
7439a5
        '-device',
7439a5
        'ide-cd,drive=drive-cd1,id=cd1,'
7439a5
        'bootindex=1')
7439a5
    p = subprocess.Popen(cmd,
7439a5
        stdin=subprocess.PIPE,
7439a5
        stdout=subprocess.PIPE,
7439a5
        stderr=subprocess.STDOUT)
7439a5
    logging.info('Performing enrollment')
7439a5
    # Wait until the UEFI shell starts (first line is printed)
7439a5
    read = p.stdout.readline()
7439a5
    if b'char device redirected' in read:
7439a5
        read = p.stdout.readline()
7439a5
    # Skip passed QEMU warnings, like the following one we see in Ubuntu:
7439a5
    # qemu-system-x86_64: warning: TCG doesn't support requested feature: CPUID.01H:ECX.vmx [bit 5]
7439a5
    while b'qemu-system-x86_64: warning:' in read:
7439a5
        read = p.stdout.readline()
7439a5
    if args.print_output:
7439a5
        print(strip_special(read), end='')
7439a5
        print()
7439a5
    # Send the escape char to enter the UEFI shell early
7439a5
    p.stdin.write(b'\x1b')
7439a5
    p.stdin.flush()
7439a5
    # And then run the following three commands from the UEFI shell:
7439a5
    # change into the first file system device; install the default
7439a5
    # keys and certificates, and reboot
7439a5
    p.stdin.write(b'fs0:\r\n')
7439a5
    p.stdin.write(b'EnrollDefaultKeys.efi\r\n')
7439a5
    p.stdin.write(b'reset -s\r\n')
7439a5
    p.stdin.flush()
7439a5
    while True:
7439a5
        read = p.stdout.readline()
7439a5
        if args.print_output:
7439a5
            print('OUT: %s' % strip_special(read), end='')
7439a5
            print()
7439a5
        if b'info: success' in read:
7439a5
            break
7439a5
    p.wait()
7439a5
    if args.print_output:
7439a5
        print(strip_special(p.stdout.read()), end='')
7439a5
    logging.info('Finished enrollment')
7439a5
7439a5
7439a5
def test_keys(args):
7439a5
    logging.info('Grabbing test kernel')
7439a5
    kernel, kerneltemp = download(args.kernel_url, args.kernel_path,
7439a5
                                  'kernel', args.no_download)
7439a5
7439a5
    logging.info('Starting verification')
7439a5
    try:
7439a5
        cmd = generate_qemu_cmd(
7439a5
            args,
7439a5
            True,
7439a5
            '-append', 'console=tty0 console=ttyS0,115200n8',
7439a5
            '-kernel', kernel)
7439a5
        p = subprocess.Popen(cmd,
7439a5
            stdin=subprocess.PIPE,
7439a5
            stdout=subprocess.PIPE,
7439a5
            stderr=subprocess.STDOUT)
7439a5
        logging.info('Performing verification')
7439a5
        while True:
7439a5
            read = p.stdout.readline()
7439a5
            if args.print_output:
7439a5
                print('OUT: %s' % strip_special(read), end='')
7439a5
                print()
7439a5
            if b'Secure boot disabled' in read:
7439a5
                raise Exception('Secure Boot was disabled')
7439a5
            elif b'Secure boot enabled' in read:
7439a5
                logging.info('Confirmed: Secure Boot is enabled')
7439a5
                break
7439a5
            elif b'Kernel is locked down from EFI secure boot' in read:
7439a5
                logging.info('Confirmed: Secure Boot is enabled')
7439a5
                break
7439a5
        p.kill()
7439a5
        if args.print_output:
7439a5
            print(strip_special(p.stdout.read()), end='')
7439a5
        logging.info('Finished verification')
7439a5
    finally:
7439a5
        if kerneltemp:
7439a5
            os.remove(kernel)
7439a5
7439a5
7439a5
def parse_args():
7439a5
    parser = argparse.ArgumentParser()
7439a5
    parser.add_argument('output', help='Filename for output vars file')
7439a5
    parser.add_argument('--out-temp', help=argparse.SUPPRESS)
7439a5
    parser.add_argument('--force', help='Overwrite existing output file',
7439a5
                        action='store_true')
7439a5
    parser.add_argument('--print-output', help='Print the QEMU guest output',
7439a5
                        action='store_true')
7439a5
    parser.add_argument('--verbose', '-v', help='Increase verbosity',
7439a5
                        action='count')
7439a5
    parser.add_argument('--quiet', '-q', help='Decrease verbosity',
7439a5
                        action='count')
7439a5
    parser.add_argument('--qemu-binary', help='QEMU binary path',
7439a5
                        default='/usr/bin/qemu-system-x86_64')
7439a5
    parser.add_argument('--enable-kvm', help='Enable KVM acceleration',
7439a5
                        action='store_true')
7439a5
    parser.add_argument('--ovmf-binary', help='OVMF secureboot code file',
7439a5
                        default='/usr/share/edk2/ovmf/OVMF_CODE.secboot.fd')
7439a5
    parser.add_argument('--ovmf-template-vars', help='OVMF empty vars file',
7439a5
                        default='/usr/share/edk2/ovmf/OVMF_VARS.fd')
7439a5
    parser.add_argument('--uefi-shell-iso', help='Path to uefi shell iso',
7439a5
                        default='/usr/share/edk2/ovmf/UefiShell.iso')
7439a5
    parser.add_argument('--skip-enrollment',
7439a5
                        help='Skip enrollment, only test', action='store_true')
7439a5
    parser.add_argument('--skip-testing',
7439a5
                        help='Skip testing generated "VARS" file',
7439a5
                        action='store_true')
7439a5
    parser.add_argument('--kernel-path',
7439a5
                        help='Specify a consistent path for kernel')
7439a5
    parser.add_argument('--no-download', action='store_true',
7439a5
                        help='Never download a kernel')
7439a5
    parser.add_argument('--fedora-version',
7439a5
                        help='Fedora version to get kernel for checking',
7439a5
                        default='27')
7439a5
    parser.add_argument('--kernel-url', help='Kernel URL',
7439a5
                        default='https://download.fedoraproject.org/pub/fedora'
7439a5
                                '/linux/releases/%(version)s/Everything/x86_64'
7439a5
                                '/os/images/pxeboot/vmlinuz')
7439a5
    parser.add_argument('--disable-smm',
7439a5
                        help=('Don\'t restrict varstore pflash writes to '
7439a5
                              'guest code that executes in SMM. Use this '
7439a5
                              'option only if your OVMF binary doesn\'t have '
7439a5
                              'the edk2 SMM driver stack built into it '
7439a5
                              '(possibly because your QEMU binary lacks SMM '
7439a5
                              'emulation). Note that without restricting '
7439a5
                              'varstore pflash writes to guest code that '
7439a5
                              'executes in SMM, a malicious guest kernel, '
7439a5
                              'used for testing, could undermine Secure '
7439a5
                              'Boot.'),
7439a5
                        action='store_true')
7439a5
    parser.add_argument('--oem-string',
7439a5
                        help=('Pass the argument to the guest as a string in '
7439a5
                              'the SMBIOS Type 11 (OEM Strings) table. '
7439a5
                              'Multiple occurrences of this option are '
7439a5
                              'collected into a single SMBIOS Type 11 table. '
7439a5
                              'A pure ASCII string argument is strongly '
7439a5
                              'suggested.'),
7439a5
                        action='append')
7439a5
    args = parser.parse_args()
7439a5
    args.kernel_url = args.kernel_url % {'version': args.fedora_version}
7439a5
7439a5
    validate_args(args)
7439a5
    return args
7439a5
7439a5
7439a5
def validate_args(args):
7439a5
    if (os.path.exists(args.output)
7439a5
            and not args.force
7439a5
            and not args.skip_enrollment):
7439a5
        raise Exception('%s already exists' % args.output)
7439a5
7439a5
    if args.skip_enrollment and not os.path.exists(args.output):
7439a5
        raise Exception('%s does not yet exist' % args.output)
7439a5
7439a5
    verbosity = (args.verbose or 1) - (args.quiet or 0)
7439a5
    if verbosity >= 2:
7439a5
        logging.basicConfig(level=logging.DEBUG)
7439a5
    elif verbosity == 1:
7439a5
        logging.basicConfig(level=logging.INFO)
7439a5
    elif verbosity < 0:
7439a5
        logging.basicConfig(level=logging.ERROR)
7439a5
    else:
7439a5
        logging.basicConfig(level=logging.WARN)
7439a5
7439a5
    if args.skip_enrollment:
7439a5
        args.out_temp = args.output
7439a5
    else:
7439a5
        temped = tempfile.mkstemp(prefix='qosb.', suffix='.vars')
7439a5
        os.close(temped[0])
7439a5
        args.out_temp = temped[1]
7439a5
        logging.debug('Temp output: %s', args.out_temp)
7439a5
7439a5
7439a5
def move_to_dest(args):
7439a5
    shutil.copy(args.out_temp, args.output)
7439a5
    os.remove(args.out_temp)
7439a5
7439a5
7439a5
def main():
7439a5
    args = parse_args()
7439a5
    if not args.skip_enrollment:
7439a5
        enroll_keys(args)
7439a5
    if not args.skip_testing:
7439a5
        test_keys(args)
7439a5
    if not args.skip_enrollment:
7439a5
        move_to_dest(args)
7439a5
        if args.skip_testing:
7439a5
            logging.info('Created %s' % args.output)
7439a5
        else:
7439a5
            logging.info('Created and verified %s' % args.output)
7439a5
    else:
7439a5
        logging.info('Verified %s', args.output)
7439a5
7439a5
7439a5
if __name__ == '__main__':
7439a5
    main()