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