#!/bin/bash -e
#
# Copyright (c) 2015 Alon Swartz <alon@turnkeylinux.org>
# 
# This file is part of InitHooks.
# 
# InitHooks 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.
# 
set -e

SUDOADMIN_STATE=/etc/sudoadmin/state

fatal() { echo "FATAL [$(basename $0)]: $@" 1>&2; exit 1; }
warn() { echo "WARN [$(basename $0)]: $@"; }
info() { echo "INFO [$(basename $0)]: $@"; }

usage() {
cat<<EOF
Syntax: $(basename $0) on|off|status [--disable-setpass [--enable-disabled-samba-account]]
Configure system to use admin user with sudo, or root

On:
    - installs sudo package
    - creates admin user and sets random password
    - configures passwordless sudo for admin user
    - configures inithooks and init-fence for admin user
    - updates confconsole services for admin user
    - merges root .ssh/authorized_keys with admin
    - locks the root user
    - disables root ssh access
    - sets root ssh login banner
    - restarts ssh daemon, if it is running
    - sets admin password interactively (unless --disable-setpass)

Off:
    - configures inithooks and init-fence for root
    - updates confconsole services for root
    - merges admin .ssh/authorized_keys with root
    - enables root ssh access
    - locks admin user
    - unsets root ssh login banner
    - restarts ssh daemon, if it is running
    - sets root password interactively (unless --disable-setpass)

For a server with Samba, a disabled target account requires confirmation.
For a password-preserving noninteractive switch, pass
--enable-disabled-samba-account to explicitly enable that target account.

Status:
    - checks turnkey-sudoadmin status, returns one of the following:
        - unconfigured
        - on
        - off

EOF
exit 1
}

install_sudo() {
    info $FUNCNAME $@
    which sudo >/dev/null && return
    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get -y install sudo
}

create_user() {
    info $FUNCNAME $@
    username=$1
    grep -q ^${username}: /etc/passwd && return
    useradd --create-home --skel /etc/skel --shell /bin/bash ${username}
    echo ${username}:$(mcookie) | chpasswd
}

# PVE sets the root password outside the guest and disables 30rootpass. If
# firstboot creates a sudo administrator, let it inherit that password without
# exposing the hash in arguments or trace output. The marker contains no hash;
# it permits a failed copy to be retried before root is locked.
pve_admin_password_prepare() {
    [ "${_TURNKEY_SUDOADMIN_FIRSTBOOT:-0}" = 1 ] || return 0
    [ -e /var/lib/turnkey-info/inithooks.service/lxc ] || return 0
    if ! grep -q '^admin:' /etc/passwd; then
        install -d -m 0700 /var/lib/inithooks/pve-admin-password
        : > /var/lib/inithooks/pve-admin-password/pending
        chmod 0600 /var/lib/inithooks/pve-admin-password/pending
    fi
}

pve_admin_password_apply() (
    set -eo pipefail
    local marker=/var/lib/inithooks/pve-admin-password/pending
    local applied=/var/lib/inithooks/pve-admin-password/applied
    local had_xtrace=false root_record= root_hash= password_last= password_min= password_max=
    local password_warn= password_inactive= account_expiry= today= field=
    if [ "${_TURNKEY_SUDOADMIN_FIRSTBOOT:-0}" != 1 ] || [ ! -e /var/lib/turnkey-info/inithooks.service/lxc ]; then
        echo none
        return 0
    fi
    if [ ! -e "$marker" ]; then
        if [ -e "$applied" ]; then echo copied; else echo none; fi
        return 0
    fi
    if [[ $- == *x* ]]; then
        had_xtrace=true
        set +x
    fi
    trap 'unset root_record root_hash; if [[ "$had_xtrace" == true ]]; then set -x; fi' EXIT
    root_record=$(getent shadow root) || { echo "Unable to read the provisioned administrator state." >&2; exit 1; }
    IFS=: read -r _ root_hash password_last password_min password_max password_warn password_inactive account_expiry _ <<< "$root_record"
    case "$root_hash" in ''|'!'*|'*'*) root_hash= ;; esac
    if [[ -n "$root_hash" ]]; then
        for field in "$password_last" "$password_min" "$password_max" "$password_warn" "$password_inactive" "$account_expiry"; do
            if [[ -n "$field" && ! "$field" =~ ^[0-9]+$ ]]; then root_hash=; fi
        done
        today=$(( $(date +%s) / 86400 ))
        if [[ -n "$account_expiry" ]]; then
            if [[ ! "$account_expiry" =~ ^[0-9]+$ ]] || (( 10#$account_expiry <= today )); then
                root_hash=
            fi
        fi
        if [[ -n "$password_last" ]]; then
            if [[ ! "$password_last" =~ ^[0-9]+$ ]] || (( 10#$password_last == 0 )); then
                root_hash=
            elif [[ -n "$password_max" ]]; then
                if [[ ! "$password_max" =~ ^[0-9]+$ ]] || (( 10#$password_last + 10#$password_max <= today )); then
                    root_hash=
                fi
            fi
        fi
    fi
    if [[ -n "$root_hash" ]]; then
        # Keep the new account unavailable while chpasswd resets its password
        # age. Restore all source aging fields before allowing an admin login.
        chage -E 1 admin
        printf 'admin:%s\n' "$root_hash" | chpasswd -e
        chage -d "${password_last:--1}" -m "${password_min:--1}" -M "${password_max:--1}" \
            -W "${password_warn:--1}" -I "${password_inactive:--1}" -E "${account_expiry:--1}" admin
        : > "$applied"
        chmod 0600 "$applied"
        echo copied
    else
        rm -f "$applied"
        echo none
    fi
    rm -f "$marker"
)

passwordless_sudo() {
    info $FUNCNAME $@
    username=$1
    cfg="/etc/sudoers.d/99_${username}"
    str="${username} ALL=(ALL) NOPASSWD:ALL"
    touch $cfg
    grep -q "^${str}$" $cfg && return
    echo "$str" >> $cfg
    chmod 0440 $cfg
}

inithooks_sudoadmin() {
    info $FUNCNAME $@
    val=$1
    key="SUDOADMIN"
    cfg="/etc/default/inithooks"
    [ -e $cfg ] || return 0
    grep -q ^${key}= $cfg || (echo "$key=$val" >> $cfg; return)
    sed -i "s/^${key}=.*/$key=$val/" $cfg
}

setup_initfence() {
    info $FUNCNAME $@
    username=$1
    root_profiled=/root/.profile.d/turnkey-init-fence
    user_profiled=/home/${username}/.profile.d/turnkey-init-fence
    if [ -e $root_profiled ]; then
        if [ $username != "root" ]; then
            mkdir -p $(dirname $user_profiled)
            cp $root_profiled $user_profiled
            sed -i "s|^|sudo |" $user_profiled
            sed -i "s|/root|/home\/${username}|g" $user_profiled
            chown -R $username:$username $(dirname $user_profiled)
        fi
    fi
    return 0
}

update_confconsole_services() {
    info $FUNCNAME $@
    new_uname=$1
    old_uname=$2
    cfg="/etc/confconsole/services.txt"
    [ -e $cfg ] || return 0
    sed -i "s|${old_uname}@|${new_uname}@|g" $cfg
}

ssh_authorizedkeys_inithook() {
    info $FUNCNAME $@
    username=$1
    sshkeys_inithook=/usr/lib/inithooks/firstboot.d/40ec2-sshkeys
    [ -e $sshkeys_inithook ] || return 0
    sed -i "s|^USERNAME.*|USERNAME = \'${username}\'|" $sshkeys_inithook
}

ssh_authorizedkeys_merge() {
    info $FUNCNAME $@
    user1=$1
    user2=$2

    grep -q ^${user1}: /etc/passwd || return 0
    grep -q ^${user2}: /etc/passwd || return 0

    auth1="$(eval printf ~$user1)/.ssh/authorized_keys"
    mkdir -p $(dirname $auth1)
    chmod 0700 $(dirname $auth1)
    touch $auth1

    auth2="$(eval printf ~$user2)/.ssh/authorized_keys"
    mkdir -p $(dirname $auth2)
    chmod 0700 $(dirname $auth2)
    touch $auth2

    cat $auth1 $auth2 | sort | uniq > $auth1.new
    echo $auth1 $auth2 | xargs -n 1 cp $auth1.new
    rm $auth1.new

    chown -R $user1:$user1 $(dirname $auth1)
    chown -R $user2:$user2 $(dirname $auth2)
}

permitrootlogin_ssh() {
    info $FUNCNAME $@
    val=$1
    key="PermitRootLogin"
    cfg="/etc/ssh/sshd_config"
    grep -q ^${key} $cfg || (echo "$key $val" >> $cfg; return)
    sed -i "s/^${key} .*/$key $val/" $cfg
}

set_sshrootbanner() {
    info $FUNCNAME $@
    content=$1
    banner_path="/root/.ssh/banner"
    mkdir -p $(dirname $banner_path)
    echo $content > $banner_path
}

user_state() {
    info $FUNCNAME $@
    username=$1
    action=$2
    grep -q ^${username}: /etc/passwd || return 0
    passwd --${action} $username
    if [ $username != "root" ]; then
        [ $action == "lock" ] && usermod --expiredate "1" $username
        if [ "$action" == "unlock" ] && [ "${pve_admin_password_result:-none}" != copied ]; then
            usermod --expiredate "" "$username"
        fi
    fi
    return 0
}

restart_sshd() {
    info $FUNCNAME $@
    if [ -e /var/run/sshd.pid ]; then
        /etc/init.d/ssh restart
    fi
}

clear_prompt_secret() {
    unset target_password
    if [ "${sudoadmin_restore_xtrace:-0}" = 1 ]; then
        sudoadmin_restore_xtrace=0
        set -x
    fi
}

prompt_target_password() {
    local username=$1
    local script=/usr/lib/inithooks/bin/setpass.py
    [ -x "$script" ] || fatal "Password setup is unavailable; administrator mode was not changed."
    # A caller may have enabled xtrace with bash -x or exported SHELLOPTS.
    # Suspend it before the secret enters shell state, and clear that state
    # before restoring it on every normal/error exit from this script.
    if [[ $- == *x* ]]; then
        set +x
        sudoadmin_restore_xtrace=1
    else
        sudoadmin_restore_xtrace=0
    fi
    trap clear_prompt_secret EXIT
    # Dialogs stay on the controlling terminal; only fd 3 is captured.
    if target_password=$("$script" "$username" --prompt-fd=3 3>&1 >/dev/tty); then
        return 0
    else
        local result=$?
        clear_prompt_secret
        trap - EXIT
        return "$result"
    fi
}

set_prompted_password() {
    local username=$1 result
    # The password stays out of command arguments and is not written to disk.
    if printf '%s\n' "$target_password" | /usr/lib/inithooks/bin/setpass.py "$username" --pass-stdin; then
        result=0
    else
        result=$?
    fi
    clear_prompt_secret
    if [ "${admin_service_transition:-0}" != 1 ]; then
        trap - EXIT
    fi
    return "$result"
}

# A service integration can fence its own access while the system account,
# password and SSH settings change. Firstboot services have separate hooks.
admin_transition_cleanup() {
    local result=$?
    clear_prompt_secret
    if [ "$result" -ne 0 ] && [ "${admin_service_transition:-0}" = 1 ]; then
        /usr/lib/inithooks/bin/sudoadmin-service-transition failed "$admin_transition_direction" "$admin_transition_password_option" "$admin_transition_approval" || true
    fi
}

admin_transition_begin() {
    local direction=$1 password_option=${2:-} approval=${3:-}
    [[ -z "$password_option" || "$password_option" == --disable-setpass ]] || fatal "Unknown option: $password_option"
    [[ -z "$approval" || ( "$password_option" == --disable-setpass && "$approval" == --enable-disabled-samba-account ) ]] || fatal "Unknown or incompatible option: $approval"
    [ "${_TURNKEY_SUDOADMIN_FIRSTBOOT:-0}" != 1 ] || return 0
    if [ ! -x /usr/lib/inithooks/bin/sudoadmin-service-transition ]; then
        [ -z "$approval" ] || fatal "This server does not support enabling a disabled Samba account."
        return 0
    fi
    # Hold the lock through finish/cleanup so a second switch cannot unmask a
    # service while the first switch is still changing accounts.
    exec {admin_transition_lock}>/run/lock/turnkey-sudoadmin.lock
    flock -n "$admin_transition_lock" || fatal "Another administrator switch is running."
    admin_transition_direction=$direction
    admin_transition_password_option=$password_option
    admin_transition_approval=$approval
    admin_service_transition=1
    trap admin_transition_cleanup EXIT
    /usr/lib/inithooks/bin/sudoadmin-service-transition prepare "$direction" "$password_option" "$approval"
}

admin_transition_finish() {
    [ "${admin_service_transition:-0}" = 1 ] || return 0
    /usr/lib/inithooks/bin/sudoadmin-service-transition finish "$admin_transition_direction"
    admin_service_transition=0
    trap - EXIT
}

admin_transition_set_password() {
    local username=$1 password_option=${2:-}
    [ "${admin_service_transition:-0}" = 1 ] || return 0
    [ "$password_option" != --disable-setpass ] || return 0
    # Apply the selected password before explicitly unlocking the destination
    # account or restarting SSH. chpasswd may itself unlock the account, but
    # it cannot make the old password usable as a result of this switch.
    set_prompted_password "$username"
    admin_transition_password_applied=1
}

set_status() {
    if [ ! -d $(dirname $SUDOADMIN_STATE) ]; then
        mkdir $(dirname $SUDOADMIN_STATE)
    fi
    cat > $SUDOADMIN_STATE <<EOF
# This is an automatically generated file, do not edit manually
state=$1
EOF
}
check_status() {
    if [ ! -f $SUDOADMIN_STATE ]; then
        echo 'unconfigured'
    else
        sed -rn 's/state=(.*)/\1/p' "$SUDOADMIN_STATE"
    fi
}

case $1 in
    --supports-service-transition)
        [ "$#" -eq 1 ] || usage
        exit 0
        ;;
    on)
        [ "$(id -u)" != "0" ] && fatal "must be run with root permissions"
        [ "$2" == "--disable-setpass" ] || prompt_target_password "admin"
        admin_transition_begin on "${2:-}" "${3:-}"
        install_sudo;
        pve_admin_password_prepare;
        create_user "admin";
        pve_admin_password_result=$(pve_admin_password_apply);
        passwordless_sudo "admin";
        inithooks_sudoadmin "true";
        admin_transition_set_password "admin" "${2:-}"
        setup_initfence "admin";
        update_confconsole_services "admin" "root";
        ssh_authorizedkeys_inithook "admin";
        ssh_authorizedkeys_merge "admin" "root";
        user_state "admin" "unlock";
        user_state "root" "lock";
        permitrootlogin_ssh "no";
        set_sshrootbanner 'Please login as user "admin" rather than user "root".';
        restart_sshd;
        set_status "on"
        [ "$2" == "--disable-setpass" ] || [ "${admin_transition_password_applied:-0}" = 1 ] || set_prompted_password "admin";
        admin_transition_finish
        ;;

    off)
        [ "$(id -u)" != "0" ] && fatal "must be run with root permissions"
        [ "$2" == "--disable-setpass" ] || prompt_target_password "root"
        admin_transition_begin off "${2:-}" "${3:-}"
        inithooks_sudoadmin "false";
        admin_transition_set_password "root" "${2:-}"
        setup_initfence "root";
        update_confconsole_services "root" "admin";
        ssh_authorizedkeys_inithook "root";
        ssh_authorizedkeys_merge "root" "admin";
        permitrootlogin_ssh "yes";
        user_state "root" "unlock";
        user_state "admin" "lock";
        set_sshrootbanner "";
        restart_sshd;
        set_status "off"
        [ "$2" == "--disable-setpass" ] || [ "${admin_transition_password_applied:-0}" = 1 ] || set_prompted_password "root";
        admin_transition_finish
        ;;

    status)
        check_status;
        ;;

    *)  
        usage;;
esac

