#!/bin/sh set -e die() { echo >&2 "novaboot-shell: $*" exit 1 } print_help() { cat < $tmp mv $tmp ~/.ssh/authorized_keys } exec_shell() { [ "$NB_ADMIN" ] || die "Permission denied" exec /bin/bash || exec /bin/sh } lock_queue() { lslocks | awk '{ if ($9 == "'"$RUN_DIR"'") { print $2 } }' } print_queue() { local queue queue=$( for pid in $(lock_queue); do echo $pid $(sed --null-data -ne '/^NOVABOOT_ID=/ s///p' /proc/$pid/environ) done | sort) if [ "$queue" ]; then echo "Target is occupied by:" ( echo "PID USER LOGIN_TIME FROM"; echo "$queue" ) | column -t fi } locked() { print_queue tmp=$(mktemp) no_fork= flock -h 2>&1 | grep -q -e "--no-fork" && no_fork=--no-fork rm -f "$tmp" exec flock $no_fork "$RUN_DIR" "$@" } unlocked() { exec "$@" } check_var() { if eval [ "\"\$$1\"" ]; then return 0 else die "$1 variable not defined in $CFG" fi } # run_subcommand should be called only after permission checks and/or locking run_subcommand() { case "$*" in "console") trap "rm -f $RUN_DIR/ppid" EXIT echo $NOVABOOT_PPID > $RUN_DIR/ppid echo 'novaboot-shell: Connected' # TODO: $reset_begin_cmd check_var console_cmd && eval exec $console_cmd;; "reset") check_var reset_cmd && eval exec $reset_cmd;; "rsync --server "*" . .") if ! [ $# -eq 5 -o \( $# -eq 6 -a "$4" = '--log-format=X' \) ]; then die "Unexpected rsync invocation: $*" fi mkdir -p "$HOME/tftproot" cd "$HOME/tftproot" exec "$@";; "on") check_var on_cmd && eval exec $on_cmd;; "off") check_var off_cmd && eval exec $off_cmd;; esac } main() { if [ "$1" = "-c" ]; then shift else die "Permission denied"; fi NB_ADMIN= if [ "${1%% *}" = "user" ]; then # Get user name encoded in ~/.ssh/authorized_keys set -- $1 NB_USER="$2"; [ "$3" = "admin" ] && NB_ADMIN=1 set -- $SSH_ORIGINAL_COMMAND fi if [ $# -eq 0 ]; then print_help; fi IP=${SSH_CONNECTION%% *} HOST=$(getent hosts $IP) || HOST=$IP REMOTE=${HOST##* } DATE=$(LANG=C date +'%F_%T') export NOVABOOT_ID="${NB_USER:-?} $DATE ${REMOTE}" export NOVABOOT_PPID=$PPID mkdir -p "$RUN_DIR" case "$1" in # Commands allowed at any time "console") locked $0 console;; "get-config") target_config; exit;; "add-key") shift; add_key "$@"; exit;; "shell") exec_shell; exit;; "help") print_help;; # Commands allowed only when nobody or the same user is connected # to the console. "The same user" means that we were executed by # the same sshd process that has the lock. This is ensured by # using SSH connection sharing on cline side. reset | rsync | on | off) ALLOWED_PPID=$(cat $RUN_DIR/ppid 2>/dev/null || :) if [ "$PPID" -eq "${ALLOWED_PPID:-0}" ]; then run=unlocked; else run=locked; fi $run $0 "$@";; *) echo >&2 "novaboot-shell: Command not allowed: $*" logger -p error "novaboot-shell: Command not allowed: $*" exit 1;; esac } RUN_DIR="$HOME" if [ "$NOVABOOT_SHELL_CONFIG" ]; then CFG="$NOVABOOT_SHELL_CONFIG" else CFG="$HOME/.novaboot-shell" fi . "$CFG" if [ -z "$NOVABOOT_ID" ]; then main "$@" else run_subcommand "$@" fi