Blame SOURCES/ovmf-vars-generator

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