#!/bin/sh
# run as a systemd service to start up the ssh daemon

ODIR=/opt/natp-ssh

if [ ! -f ${ODIR}/etc/conf ] ;then
  echo "ERROR: ${ODIR}/etc/conf must exist and contain configuration." 1>&2
  exit 1
fi

. ${ODIR}/etc/conf

if [ "${MINPORT}" = "" -o "${MAXPORT}" = "" ] ;then
  echo "ERROR: MINPORT=${MINPORT} or MAXPORT=${MAXPORT} not defined" \
   "in ${ODIR}/etc/conf." 1>&2
  exit 1
fi

# First, set up iptables to limit who can connect to reverse ssh

if [ "${ALLOWNETS}" = "" ] ;then
  # if ALLOWNETS not defined in etc/conf, set it to localhost only
  ALLOWNETS="127.0.0.0/8 ::1/128"
fi

TABLE=NATPSSH
for IPTABLES in iptables ip6tables ;do
  ${IPTABLES} --new ${TABLE} >> /dev/null 2>&1 || true
  ${IPTABLES} --flush ${TABLE}
done

LOG="LOG --log-tcp-sequence --log-tcp-options --log-ip-options"
for NET in ${ALLOWNETS} ;do
  OPTS="--append ${TABLE} --source ${NET} --jump"
  ISIPV6=$(echo ${NET} | grep :)
  if [ "${ISIPV6}" = "" ] ;then # IPv4
    iptables ${OPTS} ${LOG}
    iptables ${OPTS} ACCEPT
  else # IPv6
    ip6tables ${OPTS} ${LOG}
    ip6tables ${OPTS} ACCEPT
  fi
done

for IPTABLES in iptables ip6tables ;do
  ${IPTABLES} --append ${TABLE} --jump ${LOG} --log-prefix "DENY "
  ${IPTABLES} --append ${TABLE} --proto tcp --jump REJECT \
    --reject-with tcp-reset
  ${IPTABLES} --append ${TABLE} --jump REJECT
done

for IPTABLES in iptables ip6tables ;do
  ${IPTABLES} --delete INPUT --jump ${TABLE} --proto tcp \
    --dport ${MINPORT}:${MAXPORT} --tcp-flags SYN,RST,ACK SYN \
    >>/dev/null 2>&1 || true
  ${IPTABLES} --insert INPUT --jump ${TABLE} --proto tcp \
    --dport ${MINPORT}:${MAXPORT} --tcp-flags SYN,RST,ACK SYN
done

# /run/sshd needs to exist for privilege separation to work. This is
# hard-compiled into the binary and cannot be overridden. If systemd has
# already created /run/sshd for ssh.service, great! If not, create it.
umask 022
mkdir -p /run/ssh 2>>/dev/mull

# Finally, run sshd
exec ${ODIR}/bin/natp-sshd -D ${SSHD_OPTS} -f ${ODIR}/etc/sshd_config
