#!/bin/sh
#
# Allow the remctl remote address to ssh into the host.
#
# remctl backend to add the source IP address to the allowed list of IP
# addresses for connecting to the ssh port.  This is my version of port
# knocking, assuming availability of remctl and Kerberos on the remote
# side.
#
# Written by Russ Allbery <eagle@eyrie.org>
#
# The authors hereby relinquish any claim to any copyright that they may have
# in this work, whether granted under contract or by operation of law or
# international treaty, and hereby commit to the public, at large, that they
# shall not, at any time in the future, seek to enforce any copyright in this
# work against any person or entity, or prevent any person or entity from
# copying, publishing, distributing or creating derivative works of this
# work.

set -e

# Ensure a sane PATH with iptables in it.
PATH=/sbin:/usr/sbin:/bin:/usr/bin

# Ensure we're being run under remctl.
if [ -z "$REMOTE_ADDR" ]; then
    echo 'No REMOTE_ADDR set (must be run via remctl)' >&2
    exit 1
fi

# Process the (one) command.
case $1 in
    allow)
        if echo "$REMOTE_ADDR" | grep -q ':'; then
            command=ip6tables
        else
            command=iptables
        fi
        "$command" -I INPUT 1 -m comment --comment 'added by knock' \
            -s "$REMOTE_ADDR" -p tcp --dport 22 --syn -j ACCEPT
        ;;
    *)
        echo "Unknown command $1" >&2
        exit 1
        ;;
esac
exit 0

# Documentation.  Use a hack to hide this from the shell.  Because of the
# above exit line, this should never be executed.
DOCS=<<__END_OF_DOCS__

=for stopwords
Allbery remctl remctld subcommand

=head1 NAME

knock-backend - Allow the remctl remote address to ssh into the host

=head1 SYNOPSIS

B<knock-backend> allow

=head1 DESCRIPTION

A B<remctl> backend to allow the source IP originating the remctl call to SSH
into the host.  The only supported subcommand is C<allow>, and the IP address
is taken from the C<REMOTE_ADDR> environment variable set by B<remctld>.

Use a B<remctld> configuration like:

    knock allow /usr/sbin/knock-backend princ:eagle@EYRIE.ORG

(replacing the principal with whatever Kerberos principal should have access
to do this).

=head1 SEE ALSO

iptables(8), remctl(1), remctld(8)

=head1 AUTHOR

Russ Allbery <eagle@eyrie.org>

=cut
__END_OF_DOCS__
