#!/bin/bash
# Row 234 (#1740, #436a row a), design r6 E3: the installer key's forced command.
#
# Installed as /usr/local/sbin/mosaic-keys, root, 0755, and named by mosaic-installer's own line in
# /etc/ssh/mosaic-keys/mosaic-installer:
#   restrict,command="/usr/local/sbin/mosaic-keys",from="<from>" ssh-ed25519 <base64> mosaic-installer-<tag>
#
# It matches SSH_ORIGINAL_COMMAND against three fixed patterns and hands the words to
# mosaic-keys-write through sudo. Nothing else runs. sudo's env_reset drops SSH_CONNECTION, so the
# connection and the request go to syslog here, before sudo. The writer checks everything again.
set -u
export PATH=/usr/bin:/bin LC_ALL=C

request=${SSH_ORIGINAL_COMMAND-}
/usr/bin/logger -t mosaic-keys -- "connection=${SSH_CONNECTION-} request=${request:0:1024}"

user='[a-z_][a-z0-9_-]{0,31}'
tag='mosaic-[0-9a-f]{32}'
key='(ssh-ed25519|ecdsa-sha2-nistp256|ssh-rsa) [A-Za-z0-9+/]+={0,2}'
list_re="^list $user\$"
add_re="^add $user $key $tag\$"
remove_re="^remove $user $tag\$"

if [[ $request =~ $list_re || $request =~ $add_re || $request =~ $remove_re ]]; then
  # The patterns hold no space, glob or quote characters, so a split on spaces gives the words back.
  read -r -a words <<<"$request"
  exec /usr/bin/sudo -n /usr/local/sbin/mosaic-keys-write "${words[@]}"
fi
echo 'mosaic-keys: refused' >&2
exit 1
