Blame SOURCES/ovmf-vars-generator

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