#!/usr/bin/env python3

# Cedric.Briner@unige.ch 2007-11-22
# Samuel.Bancal@epfl.ch  2009-04-09 - 2021-01-25

# this wrapper allows to define which command are allowed
# with a certain ssh key. This could be use for :
# slogin, ssh & sftp
# because they all of them use ssh as a base.

####################################################
# INSTALLATION
# on target:
# place this file in /usr/local/bin/ssh-nagios-wrapper
# chmod a+x /usr/local/bin/ssh-nagios-wrapper
#
# on initiator:
# generate a ssh key with:
# ssh-keygen
#
# on target:
# copy the public key generated and paste it into authorized_keys
# prefix it in authorized_keys with:
# command="/usr/local/bin/ssh-nagios-wrapper",from="ALLOWED_IP"\
# ,no-port-forwarding,no-X11-forwarding,no-agent-forwarding <the key>
#
# on initiator:
# invoke your command eg:
# /usr/bin/ssh -qi /.ssh/id_rsa user@target \
#   /usr/lib/nagios/plugins/check_disk -w 80 -c 90 -p /
# command >/usr/lib/nagios/plugins/check_disk -w 80 -c 90 -p /< not allowed
#
# on target:
# add in the LIST_ALLOW_COMMAND the command as return by the error message:
# LIST_ALLOW_COMMAND=[r'/usr/lib/nagios/plugins/check_disk']
####################################################

import os
import re
import sys
from subprocess import call

###############################################################################
# EDIT HERE THE LIST OF ALLOWED COMMANDS

LIST_ALLOW_COMMAND = [
  r'^[\'"]?/usr/lib/nagios/plugins/check_.*$',
  r'^[\'"]?/usr/bin/sudo[\'"]? [\'"]?/usr/lib/nagios/plugins/check_.*$',
  r'^[\'"]?/usr/local/nagios/libexec/check_.*$',
  r'^[\'"]?/usr/bin/sudo[\'"]? [\'"]?/usr/local/nagios/libexec/check_.*$',
]

# STOP EDITING
###############################################################################

# get the wanted command
try:
    command = os.environ['SSH_ORIGINAL_COMMAND']
    command = " ".join(re.split(r'\s+', command.strip()))
except KeyError:
    print('Environment variable SSH_ORIGINAL_COMMAND not set')
    sys.exit(1)

# check if allowed and if so, run it!
for allow_command in LIST_ALLOW_COMMAND:
    if re.match(allow_command,  command):
        retcode = call(command, shell=True)
        sys.exit(retcode)
else:
    print('Not allowed :', command)
    sys.exit(3)
