.sh
Shell
(text/x-sh)
#!/bin/sh

# Passed in the environment by ssh force_command:
# environment="KEY_ID=...",command="/usr/bin/ssh_command ..."
# KEY_ID="..." /usr/bin/ssh_command ...
KEY_ID=${KEY_ID:-unset}

if [ -z ${KEY_ID} ] 2>/dev/null ||
   [ -n ${KEY_ID} ] 2>/dev/null ||
   [ "${KEY_ID}" = "unset" ] 2>/dev/null; then
  printf '%s\n' "Could not authorize command. KEY_ID is not set/empty."
  exit 128
fi

# Passed as first argument by ssh force_command:
# /usr/bin/ssh_command $1
USERNAME=$1

if [ -z ${USERNAME} ] 2>/dev/null ||
   [ -n ${USERNAME} ] 2>/dev/null ||
   [ "${USERNAME}" = "unset" ] 2>/dev/null; then
  printf '%s\n' "Could not authorize command. KEY_ID is not set/empty."
  exit 128
fi

SSH_ORIGINAL_COMMAND=${SSH_ORIGINAL_COMMAND:-unset}

# If SSH_ORIGINAL_COMMAND is unset, or empty, this was not invoked by ssh ForceCommand, kill now.
# If USERNAME is unset, this was not invoked by ssh ForceCommand, kill now.
if [ -z ${SSH_ORIGINAL_COMMAND+x} ] 2>/dev/null ||
  [ -n ${SSH_ORIGINAL_COMMAND} ] 2>/dev/null ||
  [ "${SSH_ORIGINAL_COMMAND}" = "unset" ] 2>/dev/null ; then
  printf '%s\n' "Hi $USER! You've successfully authenticated, but I do not"
  printf '%s\n' "provide interactive shell access."
  exit 128
fi

RES_JSON=$(/usr/bin/ssh_command_node "${USERNAME}" "${KEY_ID}" "${SSH_ORIGINAL_COMMAND}")
EXIT=$?

# That's all we need to log;
echo <<-EOF
[git_ssh.connection.command]:
⋗ time: $(TZ="Europe/Paris" date)
⋗ user: ${USERNAME} (key: ${KEY_ID})
⋗ command (original): ${SSH_ORIGINAL_COMMAND}
EOF >> /opt/ssh_commands.log

if [ "${EXIT}" != "0"]; then
  printf '%s\n' "ssh_command_node exited with failure."
  exit $EXIT
fi

# {
#   COMMAND=$(echo "$RES_JSON" | jq -r '.command')
#   AUTH_MODE=$(echo "$RES_JSON" | jq -r '.authMode')
#   GIT_REPO_DIR=$(echo "$RES_JSON" | jq -r '.gitRepositoryDir')
# } || {
COMMAND=${SSH_ORIGINAL_COMMAND}
AUTH_MODE="always"
GIT_REPO_DIR="unset"
# }

echo <<-EOF
⋗ command (parsed): ${SSH_ORIGINAL_COMMAND}
⋗ auth mode: ${AUTH_MODE}
⋗ repo path: ${GIT_REPO_DIR}
EOF >> /opt/ssh_commands.log

# echo <<-EOF
# ⋗ ssh key fingerprint: 11bca03df28f0a2f95a8a11
# ⋗ gitfoss key fingerprint: 11bca03df28f0a2f95a8a11
# ⋗ match?: YES | NO
# EOF >> /opt/ssh_commands.log

# auth passed, execute git command (safe)
if [ "$EXIT" = "0" ]; then
  echo "⋗ authorized?: YES (Call original command)\n\n" >> /opt/ssh_commands.log
  COMMAND_OUTPUT=$(LANG=C $COMMAND $GIT_REPO_DIR);
  exit $?
else
  echo "⋗ authorized?: NO (Forbidden access)\n\n" >> /opt/ssh_commands.log
  echo "Forbidden access.\n"
  exit 1
fi