Blame SOURCES/ovmf-vars-generator

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