Blame SOURCES/ovmf-vars-generator

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