#!/bin/bash
set -euo pipefail
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
umask 077
ulimit -c 0

state=/var/lib/t2-touchid-recovery
transfer_file=t2-touchid-keybag.p7m
uid_pattern='^[1-9][0-9]{0,8}$'
uuid_pattern='^[0-9A-Fa-f]{8}(-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$'
temp=
recipient_copy=

fail() {
    printf '%s\n' "$*" >&2
    exit 1
}

usage() {
    printf '%s\n' 'Usage: t2-touchid-keybag init' \
        '       t2-touchid-keybag export [TRANSFER_DIR]' \
        '       t2-touchid-keybag export KEYBAG RECIPIENT_CERT [TRANSFER_DIR]' \
        '       t2-touchid-keybag seal MACOS_UID ACCOUNT_UUID RECIPIENT_CERT < user.kb' \
        '       t2-touchid-keybag import MACOS_UID SHA256 [ENCRYPTED_FILE]' \
        '       t2-touchid-keybag migrate MACOS_UID ACCOUNT_UUID'
}

invalid_args() {
    usage >&2
    exit 2
}

seal_keybag() {
    local uid=$1 account=$2 recipient=$3
    [[ $uid =~ $uid_pattern && $account =~ $uuid_pattern ]] ||
        fail 'Use the UID and GeneratedUID of the selected macOS account.'
    [[ -f $recipient && -r $recipient ]] || fail 'Choose the recipient.pem file from Fedora.'
    [[ $recipient == /* ]] || recipient=./$recipient
    # Include one extra byte so the importer rejects oversized keybags.
    { printf 'T2-TOUCHID-KEYBAG-1\n%s\n%s\n' "$uid" "$account"; head -c 16001; } |
        openssl smime -encrypt -binary -aes256 -outform DER "$recipient"
}

choose_keybag() {
    local file selected
    local -a candidates=('Enter a different keybag path')
    shopt -s nullglob
    for file in "$HOME"/Library/Keychains/*/user.kb; do
        if [[ -f $file && ! -L $file && -r $file && -s $file ]]; then
            candidates+=("$file")
        fi
    done
    if [[ ${#candidates[@]} == 2 ]]; then
        keybag=${candidates[1]}
        return
    fi
    printf '%s\n' 'Choose the user.kb for the macOS account that owns the fingerprint.'
    PS3='Choose a keybag: '
    select selected in "${candidates[@]}"; do
        if [[ $REPLY == 1 ]]; then
            IFS= read -er -p 'Full path to user.kb: ' keybag || exit 1
            return
        elif [[ -n $selected ]]; then
            keybag=$selected
            return
        fi
        printf '%s\n' 'Enter one of the listed numbers.' >&2
    done
    exit 1
}

decrypt_keybag() {
    openssl smime -decrypt -binary -inform DER -in "$1" \
        -recip "$state/recipient/recipient.pem" -inkey "$state/recipient/key.pem"
}

validate_keybag() {
    decrypt_keybag "$1" | /usr/libexec/t2-touchid-recovery/keybag-uuid "$2" >/dev/null
}

cleanup() {
    if [[ -n $recipient_copy ]]; then rm -f -- "$recipient_copy"; fi
    [[ -n $temp ]] || return 0
    if [[ -d $temp ]]; then
        rm -f -- "$temp"/{key.pem,recipient.pem,keybag.p7m,macos-uid}
        rmdir -- "$temp"
    else
        rm -f -- "$temp"
    fi
}

trap cleanup EXIT
trap 'exit 130' HUP INT TERM

case ${1:-} in
    -h|--help)
        [[ $# == 1 ]] || invalid_args
        usage
        ;;
    init)
        [[ $# == 1 ]] || invalid_args
        [[ $EUID == 0 ]] || fail 'Run init through pkexec on Fedora.'
        if [[ ! -d $state/recipient ]]; then
            temp=$(mktemp -d "$state/.recipient.XXXXXXXX")
            openssl req -quiet -x509 -newkey rsa:3072 -noenc -days 3650 \
                -subj '/CN=Fedora Touch ID transfer/' \
                -keyout "$temp/key.pem" -out "$temp/recipient.pem"
            mv -nT -- "$temp" "$state/recipient"
        fi
        [[ -s $state/recipient/key.pem && -s $state/recipient/recipient.pem ]] ||
            fail 'No complete transfer key in the Fedora state directory.'
        openssl x509 -in "$state/recipient/recipient.pem" -noout -fingerprint -sha256 >&2
        cat -- "$state/recipient/recipient.pem"
        ;;
    export)
        [[ $# -le 4 ]] || invalid_args
        [[ $(uname -s) == Darwin ]] || fail 'Export from the selected macOS account.'
        macos_uid=$(id -u)
        [[ $macos_uid =~ $uid_pattern ]] || fail 'Export as the selected macOS user, without sudo.'
        [[ -t 0 && -t 1 ]] || fail 'Run export from Terminal so you can verify the recipient certificate.'
        if [[ $# -le 2 ]]; then
            transfer_dir=${2:-$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P)}
            recipient=$transfer_dir/recipient.pem
        else
            keybag=$2
            recipient=$3
            transfer_dir=${4:-/Volumes/EFI}
        fi
        [[ -f $recipient && -r $recipient ]] || fail 'Choose the recipient.pem file from Fedora.'
        [[ $recipient == /* ]] || recipient=./$recipient
        [[ $transfer_dir == /* && -d $transfer_dir && -w $transfer_dir ]] ||
            fail 'Choose a mounted transfer folder that your macOS account can write to. Use a USB drive if EFI needs administrator access.'
        output=$transfer_dir/$transfer_file
        [[ ! -e $output && ! -L $output ]] || fail "Already exists: $output"
        # Encrypt to the same certificate that the user checks below.
        recipient_copy=$(mktemp "${TMPDIR:-/tmp}/t2-touchid-recipient.XXXXXXXX")
        cp -- "$recipient" "$recipient_copy"
        recipient=$recipient_copy
        openssl x509 -in "$recipient" -noout -fingerprint -sha256 >&2
        printf '%s\n' 'Compare the certificate fingerprint above with the one you saved on Fedora.'
        read -r -p 'Do the fingerprints match? [y/N] ' answer || exit 1
        [[ $answer == [yY] || $answer == [yY][eE][sS] ]] || fail 'Export canceled.'
        if [[ $# -le 2 ]]; then
            choose_keybag
            printf 'Using %s\n' "$keybag"
        fi
        [[ -f $keybag && ! -L $keybag && -r $keybag && -s $keybag ]] ||
            fail 'Choose a readable, nonempty keybag file.'
        account=$(dscl . -read "/Users/$(id -un)" UniqueID GeneratedUID)
        account_uid=$(awk '$1 == "UniqueID:" {print $2}' <<<"$account")
        account_uuid=$(awk '$1 == "GeneratedUID:" {print $2}' <<<"$account")
        [[ $account_uid == "$macos_uid" && $account_uuid =~ $uuid_pattern ]] ||
            fail 'Could not identify the selected local macOS account.'
        temp=$(mktemp "$transfer_dir/.t2-touchid-keybag.XXXXXXXX")
        seal_keybag "$macos_uid" "$account_uuid" "$recipient" <"$keybag" >"$temp"
        digest=$(openssl dgst -sha256 -r <"$temp")
        mv -n -- "$temp" "$output"
        [[ ! -e $temp ]] || fail "Already exists: $output"
        temp=
        printf 'Encrypted keybag: %s\n' "$output"
        printf 'macOS UID: %s\n' "$macos_uid"
        printf 'Encrypted keybag SHA-256: %s\n' "${digest%% *}"
        if [[ $# -le 2 ]]; then
            printf '%s\n' 'Keep the UID and SHA-256 separately from the drive. Eject the drive and shut down.' \
                'Start Fedora and run t2-touchid-setup import.'
        fi
        ;;
    seal)
        [[ $# == 4 ]] || invalid_args
        [[ $(uname -s) == Linux ]] || fail 'Use export on macOS to verify the recipient certificate.'
        [[ ! -t 0 ]] || fail 'Read the existing keybag from a file or pipe.'
        seal_keybag "$2" "$3" "$4"
        ;;
    import)
        [[ $# == 3 || $# == 4 ]] || invalid_args
        [[ $EUID == 0 ]] || fail 'Run import through pkexec on Fedora.'
        [[ $2 =~ $uid_pattern ]] || fail 'Expected the numeric UID of the selected macOS account.'
        [[ $3 =~ ^[0-9A-Fa-f]{64}$ ]] || fail 'Enter the SHA-256 printed by the macOS export.'
        input=${4:-/boot/efi/$transfer_file}
        [[ -s $state/recipient/key.pem && -s $state/recipient/recipient.pem ]] || fail 'Run init on Fedora first.'
        [[ ! -e $state/keybag && ! -L $state/keybag ]] ||
            fail "A keybag is already configured. To replace it, back up $state/keybag first."

        temp=$(mktemp -d "$state/.keybag.XXXXXXXX")
        python3 -I - "$input" "$3" >"$temp/keybag.p7m" <<'PY'
import hashlib
import os
import stat
import sys

try:
    fd = os.open(sys.argv[1], os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
    with os.fdopen(fd, "rb") as source:
        if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):
            sys.exit("Choose a regular encrypted keybag file.")
        encrypted = source.read(65537)
except OSError as exc:
    sys.exit(f"Could not read the encrypted keybag: {exc.strerror}")
if not 0 < len(encrypted) <= 65536:
    sys.exit("The encrypted keybag is empty or too large.")
if hashlib.sha256(encrypted).hexdigest() != sys.argv[2].lower():
    sys.exit("The encrypted keybag does not match the macOS export hash.")
sys.stdout.buffer.write(encrypted)
PY
        validate_keybag "$temp/keybag.p7m" "$2"
        printf '%s\n' "$2" >"$temp/macos-uid"
        mv -nT -- "$temp" "$state/keybag"
        [[ ! -e $temp ]] || fail 'A keybag is already configured.'
        temp=
        printf 'Keybag imported. Unlock Touch ID will use this keybag.\n'
        ;;
    migrate)
        [[ $# == 3 ]] || invalid_args
        [[ $EUID == 0 ]] || fail 'Run migrate through pkexec on Fedora.'
        [[ $2 =~ $uid_pattern && $3 =~ $uuid_pattern ]] ||
            fail 'Use the UID and GeneratedUID of the selected macOS account.'
        exec 9>/run/t2-keybag-trial.lock
        flock -n 9 || fail 'Another Touch ID recovery operation is running.'
        input=$state/keybag/keybag.p7m
        [[ -s $input && -s $state/keybag/macos-uid ]] || fail 'No installed trial keybag to migrate.'
        [[ $(<"$state/keybag/macos-uid") == "$2" ]] || fail 'The installed trial keybag uses a different macOS UID.'
        if validate_keybag "$input" "$2" 2>/dev/null; then
            printf 'The installed keybag is already in the current format.\n'
            exit 0
        fi
        temp=$(mktemp -d "$state/.keybag.XXXXXXXX")
        decrypt_keybag "$input" | seal_keybag "$2" "$3" "$state/recipient/recipient.pem" >"$temp/keybag.p7m"
        validate_keybag "$temp/keybag.p7m" "$2"
        mv -fT -- "$temp/keybag.p7m" "$input"
        printf 'The installed trial keybag was migrated. Unlock Touch ID will use this keybag.\n'
        ;;
    *) invalid_args ;;
esac
