/*
 * SSH DAEMON WRAPPER
 * running on debian/gnu linux, maybe on many other !
 *
 * how to use:
 * 1/ create /etc/sshwrap.conf, put your bpf filter (with which you'll open
 *    the sshd daemon while recieving the packet)
 * 2/ compile sshwrap:
 *    $ gcc -Wall -lpcap -o sshwrap sshwrap.c
 * 3/ launch sshwrap
 *
 *
 * YES IT IS A LAME PROD, BUT WE DON'T CARE, WE'ARE LAME #~{@^[~
 *
 * check out http://www.minithins.net/releases , cns@minithins.net
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pcap.h>

int main (int argc, char **argv)
{
  pcap_t *desc;
  u_char *packet;
  char *device;
  char cmd[512];
  struct pcap_pkthdr usefull;

  struct bpf_program fcode;
  bpf_u_int32 localnet, netmask;

  int snap = 1518;
  int promisc_mode = 1;

  char errbuf[PCAP_ERRBUF_SIZE];

  int fd = open ("/etc/sshwrap.conf", O_RDONLY);
  memset (cmd, 0, 512);
  cmd[read (fd, cmd, 512) - 1] = 0;
  close (fd);

  printf("regle: [%s]\n", cmd);

  if (getuid ())
  {
    printf("root priviledges are required ...\n");
    exit (1);
  }
  device = pcap_lookupdev(errbuf);

  desc = pcap_open_live(device, snap, promisc_mode, 1000, errbuf);

  if (pcap_lookupnet(device, &localnet, &netmask, errbuf)<0)
          perror("pcap_lookupnet");
  if (pcap_compile(desc, &fcode, cmd, 1, localnet)<0)
          perror("pcap_compile");
  if (pcap_setfilter(desc, &fcode) < 0)
          perror("pcap_setfilter");

  while (1)
  {
    packet = (u_char *) pcap_next (desc, &usefull);
    if (packet)
    {
      if (!fork ())
      {
        if (access("/var/run/sshd.pid", F_OK))
        {
          if (!fork ())
            execlp("/etc/init.d/ssh", "/etc/init.d/sshd", "start", NULL);
          else
          {
            sleep (30);
            execlp("/etc/init.d/ssh", "/etc/init.d/sshd", "stop", NULL);
          }
        }
        else
          printf("/var/run/sshd.pid already is existing.\n");
      }
    }
  }

  pcap_close (desc);

  return 0;
}
