#!/bin/bash
#
# Copyright (c) 2017 Red Hat, Inc.
# Copyright (c) 2017 Shawn Rose
# Copyright (c) 2017 Guilhem Moulin
#
# Author: Harald Hoyer <harald@redhat.com>
# Author: Nathaniel McCallum <npmccallum@redhat.com>
# Author: Shawn Rose <shawnandrewrose@gmail.com>
# Author: Guilhem Moulin <guilhem@guilhem.org>
# Based-on: src/initramfs-tools/scripts/local-top/clevis.in
# Author: Oldřich Jedlička <oldium.pro@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

. /lib/dracut-lib.sh
. /lib/dracut-crypt-lib.sh

. clevis-luks-common-functions

# Return fifo path or nothing if not found
get_device_fifo_path() {
    local device="$1"
    local tmp

    [ -z "${device}" ] && return 0

    if tmp=$(getkey /tmp/luks.keys "$device"); then
        keydev="${tmp%%:*}"
        keypath="${tmp#*:}"

        [ "${keydev}" != "/" ] && return 1
        [ "${keypath#run/cryptroot-ask-pipes/}" = "${keypath}" ] && return 1

        echo "/${keypath}"
        return 0
    fi
    return 1
}

# Gets the luks device to be unlocked and used pins
get_pid_device_pins() {
    local pid="$1"
    local CRYPTTAB_SOURCE

    CRYPTTAB_SOURCE=$(tr '\0' '\n' 2>/dev/null </proc/${pid}/cmdline | \
        awk 'NR==2 { if (index($0, "cryptroot-ask")) found=1 } NR==3 && found { print; exit } NR>3 { exit }')

    # Wrong process, no CRYPTTAB_SOURCE, return error
    [ -n "$CRYPTTAB_SOURCE" ] || return 1

    [ -b "$CRYPTTAB_SOURCE" ] || return 0

    local cache="/var/cache/clevis-disks/${CRYPTTAB_SOURCE//\//_}"
    if [ ! -f "$cache" ]; then
        local pins
        if ! pins=$(clevis_luks_read_used_pins "$CRYPTTAB_SOURCE"); then
            return 1
        fi
        echo "${CRYPTTAB_SOURCE}:${pins}" > "$cache"
    fi

    cat "$cache"
    return 0
}

# Print colon-separated password-asking info like device, pins and fifo
# path for unlocking with password
get_askpass_info() {
    local psinfo pf dev_pins
    psinfo=$(ps -A 2>/dev/null || ps) # Doing this so I don't end up matching myself
    echo "$psinfo" | awk '/cryptroot-ask/ { print $1 }' | {
        while read -r pid; do
            if dev_pins=$(get_pid_device_pins "${pid}") && pf=$(get_device_fifo_path "${dev_pins%%:*}"); then
                if [[ $pf != "" && $dev_pins != "" ]]; then
                    # Output only in case of clevis device
                    echo "${dev_pins}:${pf}"
                fi
                # Return that we found valid process
                return 0
            fi
        done
        return 1
    }
}

# Try to decrypt the password to fifo file
luks_decrypt() {
    local CRYPTTAB_SOURCE=$1
    local PASSFIFO=$2
    local pt

    if pt=$(clevis_luks_unlock_device "${CRYPTTAB_SOURCE}"); then
        echo -n "${pt}" >"${PASSFIFO}"
        return 0
    else
        return 1
    fi
}

# Wait for askpass, and then try and decrypt immediately. Just in case
# there are multiple devices that need decrypting, this will loop
# infinitely (The local-bottom script will kill this after decryption)
clevisloop() {
    local askpass_info
    local sleep_time
    local OLD_CRYPTTAB_SOURCE=""
    local tpm1cfg_attempted=0

    while true; do
        # Re-get the askpass PID in case there are multiple encrypted devices
        CRYPTTAB_SOURCE=""
        sleep_time=.1
        until [ -n "$CRYPTTAB_SOURCE" ] && [ -p "$PASSFIFO" ]; do
            sleep $sleep_time
            if askpass_info=$(get_askpass_info); then
                IFS=':' read -r CRYPTTAB_SOURCE pins PASSFIFO <<EOM
${askpass_info}
EOM
                # Ask process is running, variables might be empty for non-clevis device
                sleep_time=.5
            else
                # No valid process found
                sleep_time=.1
            fi
        done

        # Make the source has changed if needed
        [ "$CRYPTTAB_SOURCE" = "$OLD_CRYPTTAB_SOURCE" ] && continue
        OLD_CRYPTTAB_SOURCE="$CRYPTTAB_SOURCE"

        if [[ " $pins " == *" tpm1 "* ]] && [ $tpm1cfg_attempted -eq 0 ]; then
            tpm1cfg_attempted=1
            do_configure_tpm1
        fi

        if luks_decrypt "${CRYPTTAB_SOURCE}" "${PASSFIFO}"; then
            info "Unlocked ${CRYPTTAB_SOURCE} with clevis"

            # Now that the current device has its password, let's sleep a
            # bit. This gives cryptsetup time to actually decrypt the
            # device and prompt for the next password if needed.
            sleep .5
        else
            warn "Unable to unlock ${CRYPTTAB_SOURCE} with clevis, supplying empty password"
            : > "${PASSFIFO}"
            sleep 5
        fi
    done
}

do_configure_tpm1() {
    local tcsd_output=

    [ -x /usr/bin/clevis-decrypt-tpm1 ] && [ -f /usr/libexec/clevis-luks-tpm1-functions ] || return

    . /usr/libexec/clevis-luks-tpm1-functions

    info "Starting TCSD daemon"

    if ! tcsd_output=$(TCSD_NO_PRIVILEGE_DROP=0 start_tcsd 2>&1); then
        if [ -n "$tcsd_output" ]; then
            echo "Unable to start TCSD: $tcsd_output" | vwarn
        else
            warn "Unable to start TCSD"
        fi
    fi
}

mkdir -p /var/cache/clevis-disks
chmod 0700 /var/cache/clevis-disks

clevisloop &
echo $! >/run/clevis.pid
