예제 #1
0
파일: p0f.c 프로젝트: kernevil/p0f
static void open_log(void) {

  struct stat st;
  s32 log_fd;

  log_fd = open((char*)log_file, O_WRONLY | O_APPEND | O_NOFOLLOW | O_LARGEFILE);

  if (log_fd >= 0) {

    if (fstat(log_fd, &st)) PFATAL("fstat() on '%s' failed.", log_file);

    if (!S_ISREG(st.st_mode)) FATAL("'%s' is not a regular file.", log_file);

  } else {

    if (errno != ENOENT) PFATAL("Cannot open '%s'.", log_file);

    log_fd = open((char*)log_file, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW,
                  LOG_MODE);

    if (log_fd < 0) PFATAL("Cannot open '%s'.", log_file);

  }

  if (flock(log_fd, LOCK_EX | LOCK_NB))
    FATAL("'%s' is being used by another process.", log_file);

  lf = fdopen(log_fd, "a");

  if (!lf) FATAL("fdopen() on '%s' failed.", log_file);

  SAYF("[+] Log file '%s' opened for writing.\n", log_file);

}
예제 #2
0
/* Pin current process and its children to a single CPU. Man
 * sched_setaffinity(2) says:
 *
 * > A child created via fork(2) inherits its parent's CPU affinity
 * > mask.  The affinity mask is preserved across an execve(2).
 */
void pin_cpu() {
	int cpu = sched_getcpu();
	if (cpu == -1)
		PFATAL("sched_getcpu()");

	cpu_set_t mask;
	CPU_ZERO(&mask);
	CPU_SET(cpu, &mask);
	int r = sched_setaffinity(0, sizeof(cpu_set_t), &mask);
	if (r == -1)
		PFATAL("sched_setaffinity()");
}
예제 #3
0
파일: p0f.c 프로젝트: kernevil/p0f
static void open_api(void) {

  s32 old_umask;
  u32 i;

  struct sockaddr_un u;
  struct stat st;

  api_fd = socket(PF_UNIX, SOCK_STREAM, 0);

  if (api_fd < 0) PFATAL("socket(PF_UNIX) failed.");

  memset(&u, 0, sizeof(u));
  u.sun_family = AF_UNIX;

  if (strlen((char*)api_sock) >= sizeof(u.sun_path))
    FATAL("API socket filename is too long for sockaddr_un (blame Unix).");

  strcpy(u.sun_path, (char*)api_sock);

  /* This is bad, but you can't do any better with standard unix socket
     semantics today :-( */

  if (!stat((char*)api_sock, &st) && !S_ISSOCK(st.st_mode))
    FATAL("'%s' exists but is not a socket.", api_sock);

  if (unlink((char*)api_sock) && errno != ENOENT)
    PFATAL("unlink('%s') failed.", api_sock);

  old_umask = umask(0777 ^ API_MODE);

  if (bind(api_fd, (struct sockaddr*)&u, sizeof(u)))
    PFATAL("bind() on '%s' failed.", api_sock);
  
  umask(old_umask);

  if (listen(api_fd, api_max_conn))
    PFATAL("listen() on '%s' failed.", api_sock);

  if (fcntl(api_fd, F_SETFL, O_NONBLOCK))
    PFATAL("fcntl() to set O_NONBLOCK on API listen socket fails.");

  api_cl = DFL_ck_alloc(api_max_conn * sizeof(struct api_client));

  for (i = 0; i < api_max_conn; i++) api_cl[i].fd = -1;

  SAYF("[+] Listening on API socket '%s' (max %u clients).\n",
       api_sock, api_max_conn);

}
예제 #4
0
파일: p0f.c 프로젝트: kernevil/p0f
static void fork_off(void) {

  s32 npid;

  fflush(0);

  npid = fork();

  if (npid < 0) PFATAL("fork() failed.");

  if (!npid) {

    /* Let's assume all this is fairly unlikely to fail, so we can live
       with the parent possibly proclaiming success prematurely. */

    if (dup2(null_fd, 0) < 0) PFATAL("dup2() failed.");

    /* If stderr is redirected to a file, keep that fd and use it for
       normal output. */

    if (isatty(2)) {

      if (dup2(null_fd, 1) < 0 || dup2(null_fd, 2) < 0)
        PFATAL("dup2() failed.");

    } else {

      if (dup2(2, 1) < 0) PFATAL("dup2() failed.");

    }

    close(null_fd);
    null_fd = -1;

    if (chdir("/")) PFATAL("chdir('/') failed.");

    setsid();

  } else {

    SAYF("[+] Daemon process created, PID %u (stderr %s).\n", npid,
      isatty(2) ? "not kept" : "kept as-is");

    SAYF("\nGood luck, you're on your own now!\n");

    exit(0);

  }

}
예제 #5
0
파일: afl-as.c 프로젝트: TylerOderkirk/afl
int main(int argc, char** argv) {

  s32 pid;
  int status;

  struct timeval tv;
  struct timezone tz;

  SAYF(cCYA "afl-as " cBRI VERSION cNOR " (" __DATE__ " " __TIME__ 
       ") by <*****@*****.**>\n");

  if (argc < 2) {

    SAYF("\n"
         "This is a helper application for afl-fuzz. It is a wrapper around GNU 'as',\n"
         "executed by the toolchain whenever using afl-gcc. You probably don't want to\n"
         "run this program directly.\n\n");

    exit(1);

  }

  gettimeofday(&tv, &tz);

  rand_seed = tv.tv_sec ^ tv.tv_usec ^ getpid();

  srandom(rand_seed);

  edit_params(argc, argv);

  add_instrumentation();

  if (!(pid = fork())) {

    execvp(as_params[0], (char**)as_params);
    FATAL("Oops, failed to execute '%s' - check your PATH", as_params[0]);

  }

  if (pid < 0) PFATAL("fork() failed");

  if (waitpid(pid, &status, 0) <= 0) PFATAL("waitpid() failed");

//  unlink(modified_file);

  exit(WEXITSTATUS(status));

}
예제 #6
0
/* Make sure options.libpath is actually working. */
void ensure_libpath(const char *argv_0) {
	if (!options.libpath) {
		char *path = NULL;
		do {
			// 1. Relative to executable, useful for development
			char tmp[PATH_MAX];
			if (!realpath(argv_0, tmp)) {
				PFATAL("realpath(argv[0])");
			}
			char *path = dirname(tmp);
			if (dl_checkpath(path, TEST_LIBNAME)) break;

			// 2. Linker resolution (ie: no slash in name)
			path = "";
			if (dl_checkpath(path, TEST_LIBNAME)) break;

			// 3. Give up.
			path = NULL;			
		} while(0);
		
		if (!path) {
			FATAL("Unable to load library \"" PRELOAD_LIBNAME "\", "
			      "most likely I tried a wrong path. "
			      "Consider specifying --libpath option.");
		}
		options.libpath = strdup(path);
	} else {
		if (!dl_checkpath(options.libpath, TEST_LIBNAME)) {
			FATAL("Unable to load " PRELOAD_LIBNAME " from directory \"%s\".\n"
			      "\tAre files \"" PRELOAD_LIBNAME "\" and \"" TEST_LIBNAME "\" available there?", options.libpath);
		}
	}
}
예제 #7
0
파일: afl-showmap.c 프로젝트: slox3r/afl
static u32 write_results(void) {

  s32 fd;
  FILE* f;
  u32 i, ret = 0;
  u8  cco = !!getenv("AFL_CMIN_CRASHES_ONLY"),
      caa = !!getenv("AFL_CMIN_ALLOW_ANY");

  if (!strncmp(out_file,"/dev/", 5)) {

    fd = open(out_file, O_WRONLY, 0600);
    if (fd < 0) PFATAL("Unable to open '%s'", out_file);

  } else {

    unlink(out_file); /* Ignore errors */
    fd = open(out_file, O_WRONLY | O_CREAT | O_EXCL, 0600);
    if (fd < 0) PFATAL("Unable to create '%s'", out_file);

  }

  f = fdopen(fd, "w");

  if (!f) PFATAL("fdopen() failed");

  for (i = 0; i < MAP_SIZE; i++) {

    if (!trace_bits[i]) continue;
    ret++;

    if (cmin_mode) {

      if (child_timed_out) break;
      if (!caa && child_crashed != cco) break;

      fprintf(f, "%u%u\n", trace_bits[i], i);

    } else fprintf(f, "%06u:%u\n", i, trace_bits[i]);

  }
  
  fclose(f);

  return ret;

}
예제 #8
0
파일: recvmmsg-loop.c 프로젝트: majek/dump
int main()
{
	struct sigaction sa = {0};
	sa.sa_handler = &timer_handler;
	sigaction(SIGALRM, &sa, NULL);

	struct itimerval timer = {0};
	timer.it_value.tv_sec = 1;
	timer.it_interval.tv_sec = 1;
	setitimer(ITIMER_REAL, &timer, NULL);

	struct sockaddr_storage listen_addr;
	net_gethostbyname(&listen_addr, "::", 1234);
	int fd = net_bind_udp(&listen_addr);

	struct mmsghdr messages[MAX_MSG] = {0};
	char buffers[MAX_MSG][MTU_SIZE];
	struct iovec iovecs[MAX_MSG] = {0};

	/* Setup recvmmsg data structures. */
	int i;
	for (i = 0; i < MAX_MSG; i++) {
		char *buf = &buffers[i][0];
		struct iovec *iovec = &iovecs[i];
		struct mmsghdr *msg = &messages[i];

		msg->msg_hdr.msg_iov = iovec;
		msg->msg_hdr.msg_iovlen = 1;

		iovec->iov_base = &buf[0];
		iovec->iov_len = MTU_SIZE;
	}

	while (1) {
		int r = recvmmsg(fd, messages, MAX_MSG, MSG_WAITFORONE, NULL);
		if (r == 0) {
			return 0;
		}

		if (r < 0) {
			if (errno == EINTR) {
				continue;
			}
			PFATAL("recv()");
		} else {
			for (i = 0; i < MAX_MSG; i++) {
				struct mmsghdr *msg = &messages[i];
				bytes += msg->msg_len;
				msg->msg_len = 0;
			}
			packets += r;
		}
	}
	close(fd);

	return 0;
}
예제 #9
0
파일: recv.c 프로젝트: majek/idea
int net_connect_udp(struct net_addr *shost)
{
	int sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (sd < 0) {
		PFATAL("socket()");
	}

	int one = 1;
	int r = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&one,
			   sizeof(one));
	if (r < 0) {
		PFATAL("setsockopt(SO_REUSEADDR)");
	}

	/* one =  1; */
	/* r = setsockopt(sd, IPPROTO_IP, IP_RECVERR, &one, sizeof(one)); */
	/* if (r != 0) { */
	/* 	perror("setsockopt(SOL_IP, IP_RECVERR)"); */
	/* } */

	/* socklen_t l = sizeof(one); */
	/* r = getsockopt(sd, IPPROTO_IP, IP_RECVERR, &one, &l); */
	/* if (r != 0) { */
	/* 	perror("setsockopt(SOL_IP, IP_RECVERR)"); */
	/* } */

	/* struct net_addr *bb = net_parse_addr("0.0.0.0:0"); */

        /* r = bind(sd, bb->sockaddr, bb->sockaddr_len); */
	/* if (r != 0) { */
	/* 	perror("bind()"); */
	/* } */

	if (-1 == connect(sd, shost->sockaddr, shost->sockaddr_len)) {
		/* is non-blocking, so we don't get error at that point yet */
		if (EINPROGRESS != errno) {
			PFATAL("connect()");
			return -1;
		}
	}

	return sd;
}
예제 #10
0
파일: afl-showmap.c 프로젝트: slox3r/afl
static void setup_shm(void) {

  u8* shm_str;

  shm_id = shmget(IPC_PRIVATE, MAP_SIZE, IPC_CREAT | IPC_EXCL | 0600);

  if (shm_id < 0) PFATAL("shmget() failed");

  atexit(remove_shm);

  shm_str = alloc_printf("%d", shm_id);

  setenv(SHM_ENV_VAR, shm_str, 1);

  ck_free(shm_str);

  trace_bits = shmat(shm_id, NULL, 0);
  
  if (!trace_bits) PFATAL("shmat() failed");

}
예제 #11
0
파일: bpf-drop.c 프로젝트: majek/dump
int main()
{
	struct sigaction sa = {0};
	sa.sa_handler = &timer_handler;
	sigaction(SIGALRM, &sa, NULL);

	struct itimerval timer = {0};
	timer.it_value.tv_sec = 1;
	timer.it_interval.tv_sec = 1;
	setitimer(ITIMER_REAL, &timer, NULL);

	struct sockaddr_storage listen_addr;
	net_gethostbyname(&listen_addr, "::", 1234);
	int fd = net_bind_udp(&listen_addr);

	net_setup_bpf(fd);

	char buf[MTU_SIZE];

	while (1) {
		int r = read(fd, buf, MTU_SIZE);
		if (r == 0) {
			int err = 0;
			socklen_t err_len = sizeof(err);
			getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &err_len);
			if (err == 0) {
				packets += 1;
				continue;
			}
			return 0;
		}

		if (r < 0) {
			if (errno == EINTR) {
				continue;
			}
			PFATAL("recv()");
		} else {
			packets += 1;
			bytes += r;
		}
	}
	close(fd);

	return 0;
}
예제 #12
0
파일: p0f.c 프로젝트: kernevil/p0f
static void get_hash_seed(void) {

  s32 f = open("/dev/urandom", O_RDONLY);

  if (f < 0) PFATAL("Cannot open /dev/urandom for reading.");

#ifndef DEBUG_BUILD

  /* In debug versions, use a constant seed. */

  if (read(f, &hash_seed, sizeof(hash_seed)) != sizeof(hash_seed))
    FATAL("Cannot read data from /dev/urandom.");

#endif /* !DEBUG_BUILD */

  close(f);

}
예제 #13
0
파일: udpsender.c 프로젝트: LucasSiba/dump
void thread_loop(void *userdata) {
	struct state *state = userdata;

	struct mmsghdr *messages = calloc(state->packets_in_buf, sizeof(struct mmsghdr));
	struct iovec *iovecs = calloc(state->packets_in_buf, sizeof(struct iovec));

	int fd = net_connect_udp(state->target_addr, state->src_port);

	int i;
	for (i = 0; i < state->packets_in_buf; i++) {
		struct iovec *iovec = &iovecs[i];
		struct mmsghdr *msg = &messages[i];

		msg->msg_hdr.msg_iov = iovec;
		msg->msg_hdr.msg_iovlen = 1;

		iovec->iov_base = (void*)state->payload;
		iovec->iov_len = state->payload_sz;
	}
	
	while (1) {
		int r = sendmmsg(fd, messages, state->packets_in_buf, 0);
		if (r <= 0) {
			if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
				continue;
			}

			if (errno == ECONNREFUSED) {
				continue;
			}
			PFATAL("sendmmsg()");
		}
		int i, bytes = 0;
		for (i = 0; i < r; i++) {
			struct mmsghdr *msg = &messages[i];
			/* char *buf = msg->msg_hdr.msg_iov->iov_base; */
			int len = msg->msg_len;
			msg->msg_hdr.msg_flags = 0;
			msg->msg_len = 0;
			bytes += len;
		}
	}
}
예제 #14
0
파일: bpf-drop.c 프로젝트: majek/dump
static int net_setup_bpf(int sd)
{
	struct sock_filter code[] = {
		// ret #0
		{0x06, 0, 0, 0x00000000},
	};

	struct sock_fprog bpf = {
		.len = ARRAY_SIZE(code),
		.filter = code,
	};

	int r = setsockopt(sd, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
	if (r < 0) {
		PFATAL("setsockopt(SO_ATTACH_FILTER)");
	}

	return sd;
}
예제 #15
0
// just dummy open 
static int gfx_inf_open(struct inode *inode, struct file *file)
{
    BYTE *pHandleAttrs;

    PDEBUG("filep=0x%8.8x\n", (unsigned int)file);

    pHandleAttrs = (BYTE *) MALLOC(GFX_DEFAULT_SURFACES*sizeof(BYTE));

    if(!pHandleAttrs)
    {
        PFATAL("Failed to allocate private file handle data !\n");
        return -EIO;
    }
    memset(pHandleAttrs, 0, GFX_DEFAULT_SURFACES*sizeof(BYTE));
    file->private_data = pHandleAttrs;

    MOD_INC_USE_COUNT;  // MODULE

    return 0;
}
예제 #16
0
파일: afl-showmap.c 프로젝트: slox3r/afl
static void detect_file_args(char** argv) {

  u32 i = 0;
  u8* cwd = getcwd(NULL, 0);

  if (!cwd) PFATAL("getcwd() failed");

  while (argv[i]) {

    u8* aa_loc = strstr(argv[i], "@@");

    if (aa_loc) {

      u8 *aa_subst, *n_arg;

      if (!at_file) FATAL("@@ syntax is not supported by this tool.");

      /* Be sure that we're always using fully-qualified paths. */

      if (at_file[0] == '/') aa_subst = at_file;
      else aa_subst = alloc_printf("%s/%s", cwd, at_file);

      /* Construct a replacement argv value. */

      *aa_loc = 0;
      n_arg = alloc_printf("%s%s%s", argv[i], aa_subst, aa_loc + 2);
      argv[i] = n_arg;
      *aa_loc = '@';

      if (at_file[0] != '/') ck_free(aa_subst);

    }

    i++;

  }

  free(cwd); /* not tracked */

}
예제 #17
0
파일: p0f.c 프로젝트: kernevil/p0f
static void drop_privs(void) {

  struct passwd* pw;

  pw = getpwnam((char*)switch_user);

  if (!pw) FATAL("User '%s' not found.", switch_user);

  if (!strcmp(pw->pw_dir, "/"))
    FATAL("User '%s' must have a dedicated home directory.", switch_user);

  if (!pw->pw_uid || !pw->pw_gid)
    FATAL("User '%s' must be non-root.", switch_user);

  if (initgroups(pw->pw_name, pw->pw_gid))
    PFATAL("initgroups() for '%s' failed.", switch_user);

  if (chdir(pw->pw_dir))
    PFATAL("chdir('%s') failed.", pw->pw_dir);

  if (chroot(pw->pw_dir))
    PFATAL("chroot('%s') failed.", pw->pw_dir);

  if (chdir("/"))
    PFATAL("chdir('/') after chroot('%s') failed.", pw->pw_dir);

  if (!access("/proc/", F_OK) || !access("/sys/", F_OK))
    FATAL("User '%s' must have a dedicated home directory.", switch_user);

  if (setgid(pw->pw_gid))
    PFATAL("setgid(%u) failed.", pw->pw_gid);

  if (setuid(pw->pw_uid))
    PFATAL("setuid(%u) failed.", pw->pw_uid);

  if (getegid() != pw->pw_gid || geteuid() != pw->pw_uid)
    FATAL("Inconsistent euid / egid after dropping privs.");

  SAYF("[+] Privileges dropped: uid %u, gid %u, root '%s'.\n",
       pw->pw_uid, pw->pw_gid, pw->pw_dir);

}
예제 #18
0
파일: p0f.c 프로젝트: kernevil/p0f
static void live_event_loop(void) {

#ifndef __CYGWIN__

  /* The huge problem with winpcap on cygwin is that you can't get a file
     descriptor suitable for poll() / select() out of it:

     http://www.winpcap.org/pipermail/winpcap-users/2009-April/003179.html

     The only alternatives seem to be additional processes / threads, a
     nasty busy loop, or a ton of Windows-specific code. If you need APi
     queries on Windows, you are welcome to fix this :-) */

  struct pollfd *pfds;
  struct api_client** ctable;
  u32 pfd_count;

  /* We need room for pcap, and possibly api_fd + api_clients. */

  pfds = ck_alloc((1 + (api_sock ? (1 + api_max_conn) : 0)) *
                  sizeof(struct pollfd));

  ctable = ck_alloc((1 + (api_sock ? (1 + api_max_conn) : 0)) *
                    sizeof(struct api_client*));

  pfd_count = regen_pfds(pfds, ctable);

  if (!daemon_mode) 
    SAYF("[+] Entered main event loop.\n\n");

  while (!stop_soon) {

    s32 pret, i;
    u32 cur;

    /* We use a 250 ms timeout to keep Ctrl-C responsive without resortng to
       silly sigaction hackery or unsafe signal handler code. */

poll_again:

    pret = poll(pfds, pfd_count, 250);

    if (pret < 0) {
      if (errno == EINTR) break;
      PFATAL("poll() failed.");
    }

    if (!pret) { if (log_file) fflush(lf); continue; }

    /* Examine pfds... */

    for (cur = 0; cur < pfd_count; cur++) {

      if (pfds[cur].revents & POLLOUT) switch (cur) {

        case 0: case 1:

          FATAL("Unexpected POLLOUT on fd %d.\n", cur);

        default:

          /* Write API response, restart state when complete. */

          if (ctable[cur]->in_off < sizeof(struct p0f_api_query))
            FATAL("Inconsistent p0f_api_response state.\n");

          i = write(pfds[cur].fd, 
                   ((char*)ctable[cur]->out_data) + ctable[cur]->out_off,
                   ctable[cur]->out_data_len - ctable[cur]->out_off);

          if (i <= 0) PFATAL("write() on API socket fails despite POLLOUT.");

          ctable[cur]->out_off += i;

          /* All done? Back to square zero then! */

          if (ctable[cur]->out_off == ctable[cur]->out_data_len) {

             ctable[cur]->in_off = ctable[cur]->out_off = ctable[cur]->out_data_len = 0;
             pfds[cur].events   = (POLLIN | POLLERR | POLLHUP);
             ck_free(ctable[cur]->out_data);

          }

      }

      if (pfds[cur].revents & POLLIN) switch (cur) {
 
        case 0:

          /* Process traffic on the capture interface. */

          if (pcap_dispatch(pt, -1, (pcap_handler)parse_packet, 0) < 0)
            FATAL("Packet capture interface is down.");

          break;

        case 1:

          /* Accept new API connection, limits permitting. */

          if (!api_sock) FATAL("Unexpected API connection.");

          if (pfd_count - 2 < api_max_conn) {

            for (i = 0; i < api_max_conn && api_cl[i].fd >= 0; i++);

            if (i == api_max_conn) FATAL("Inconsistent API connection data.");

            api_cl[i].fd = accept(api_fd, NULL, NULL);

            if (api_cl[i].fd < 0) {

              WARN("Unable to handle API connection: accept() fails.");

            } else {

              if (fcntl(api_cl[i].fd, F_SETFL, O_NONBLOCK))
                PFATAL("fcntl() to set O_NONBLOCK on API connection fails.");

              api_cl[i].in_off = api_cl[i].out_off = 0;
              pfd_count = regen_pfds(pfds, ctable);

              DEBUG("[#] Accepted new API connection, fd %d.\n", api_cl[i].fd);

              goto poll_again;

            }

          } else WARN("Too many API connections (use -S to adjust).\n");

          break;

        default:

          /* Receive API query, dispatch when complete. */

          if (ctable[cur]->in_off >= sizeof(struct p0f_api_query))
            FATAL("Inconsistent p0f_api_query state.\n");

          i = read(pfds[cur].fd, 
                   ((char*)&ctable[cur]->in_data) + ctable[cur]->in_off,
                   sizeof(struct p0f_api_query) - ctable[cur]->in_off);

          if (i < 0) PFATAL("read() on API socket fails despite POLLIN.");

          ctable[cur]->in_off += i;

          /* Query in place? Compute response and prepare to send it back. */

          if (ctable[cur]->in_off == sizeof(struct p0f_api_query)) {

            handle_query(&ctable[cur]->in_data, &ctable[cur]->out_data, &ctable[cur]->out_data_len);
            pfds[cur].events = (POLLOUT | POLLERR | POLLHUP);

          }

      }

      if (pfds[cur].revents & (POLLERR | POLLHUP)) switch (cur) {

        case 0:

          FATAL("Packet capture interface is down.");

        case 1:

          FATAL("API socket is down.");

        default:

          /* Shut down API connection and free its state. */

          DEBUG("[#] API connection on fd %d closed.\n", pfds[cur].fd);

          close(pfds[cur].fd);
          ctable[cur]->fd = -1;
 
          pfd_count = regen_pfds(pfds, ctable);
          goto poll_again;

      }

      /* Processed all reported updates already? If so, bail out early. */

      if (pfds[cur].revents && !--pret) break;

    }

  }

  ck_free(ctable);
  ck_free(pfds);

#else

  if (!daemon_mode) 
    SAYF("[+] Entered main event loop.\n\n");

  /* Ugh. The only way to keep SIGINT and other signals working is to have this
     funny loop with dummy I/O every 250 ms. Signal handlers don't get called
     in pcap_dispatch() or pcap_loop() unless there's I/O. */

  while (!stop_soon) {

    s32 ret = pcap_dispatch(pt, -1, (pcap_handler)parse_packet, 0);

    if (ret < 0) return;

    if (log_file && !ret) fflush(lf);

    write(2, NULL, 0);

  }

#endif /* ^!__CYGWIN__ */

  WARN("User-initiated shutdown.");

}
예제 #19
0
파일: options.c 프로젝트: 0x0mar/skipfish
int read_config_file(const char *filename, int *_argc, char ***_argv) {

  FILE *fh;
  char line[MAX_LINE_LEN + 1];
  char *val, *ptr;
  u8 *tmp;
  u32 idx, i;

  APPEND_STRING(fargv, fargc, ck_strdup((u8*)*_argv[0]));

  fh = fopen(filename, "r");
  if (!fh) PFATAL("Unable to read config from: %s", filename);

  while (!feof(fh) && fargc < MAX_ARGS && fgets(line, MAX_LINE_LEN, fh)) {

    /* Skip comments and empty lines */
    if (line[0] == '\n' || line[0] == '\r' || line[0] == '#')
      continue;

    /* NULL terminate the key */
    idx = strcspn(line, " \t=");
    if (idx == strlen(line))
      FATAL("Config key error at line: %s", line);
    line[idx] = '\0';

    /* Find the beginning of the value. */
    val = line + (idx + 1);
    idx = strspn(val, " \t=");
    if (idx == strlen(val))
      FATAL("Config value error at line: %s", line);
    val = val + idx;

    /* Trim the unwanted characters from the value */
    ptr = val + (strlen(val) - 1);
    while(*ptr && *ptr < 0x21) {
      *ptr = 0;
      ptr--;
    }

    /* Done! Now we have a key/value pair. If the flag is set to 'false'
       we will disregard this line. If the value is 'true', we will set
       the flag without a value. In any other case, we will set the flag
       and value */

    if (val[0] == '\0')
      FATAL("Empty value in config line: %s", line);

    if (strcasecmp("false", val) == 0)
      continue;

    tmp = ck_alloc(strlen(line) + 3);
    sprintf((char*)tmp, "--%s", line);

    APPEND_STRING(fargv, fargc, tmp);
    if (strncasecmp("true", val, 3) != 0)
      APPEND_STRING(fargv, fargc, ck_strdup((u8*)val));

  }

  /* Copy arguments from command line into our array */
  for (i=1; i<*_argc && fargc < MAX_ARGS; ++i)
    APPEND_STRING(fargv, fargc, ck_strdup((u8*)(*_argv)[i]));

  /* Replace original flags */
  *_argc = fargc;
  *_argv = (char **)fargv;

  fclose(fh);
  return 0;
}
예제 #20
0
파일: p0f.c 프로젝트: kernevil/p0f
static void prepare_pcap(void) {

  char pcap_err[PCAP_ERRBUF_SIZE];
  u8* orig_iface = use_iface;

  if (read_file) {

    if (set_promisc)
      FATAL("Dude, how am I supposed to make a file promiscuous?");

    if (use_iface)
      FATAL("Options -i and -r are mutually exclusive.");

    if (access((char*)read_file, R_OK))
      PFATAL("Can't access file '%s'.", read_file);

    pt = pcap_open_offline((char*)read_file, pcap_err);

    if (!pt) FATAL("pcap_open_offline: %s", pcap_err);

    SAYF("[+] Will read pcap data from file '%s'.\n", read_file);

  } else {

    if (!use_iface) {

      /* See the earlier note on libpcap SEGV - same problem here.
         Also, this retusns something stupid on Windows, but hey... */
     
      if (!access("/sys/class/net", R_OK | X_OK) || errno == ENOENT)
        use_iface = (u8*)pcap_lookupdev(pcap_err);

      if (!use_iface)
        FATAL("libpcap is out of ideas; use -i to specify interface.");

    }

#ifdef __CYGWIN__

    /* On Windows, interface names are unwieldy, and people prefer to use
       numerical IDs. */

    else {

      int iface_id;

      if (sscanf((char*)use_iface, "%u", &iface_id) == 1) {
        use_iface = find_interface(iface_id);
      }
  
    }

    pt = pcap_open_live((char*)use_iface, SNAPLEN, set_promisc, 250, pcap_err);

#else 

    /* PCAP timeouts tend to be broken, so we'll use a minimum value
       and rely on select() instead. */

    pt = pcap_open_live((char*)use_iface, SNAPLEN, set_promisc, 1, pcap_err);

#endif /* ^__CYGWIN__ */

    if (!orig_iface)
      SAYF("[+] Intercepting traffic on default interface '%s'.\n", use_iface);
    else
      SAYF("[+] Intercepting traffic on interface '%s'.\n", use_iface);

    if (!pt) FATAL("pcap_open_live: %s", pcap_err);

  }

  link_type = pcap_datalink(pt);

}
예제 #21
0
파일: readfp.c 프로젝트: markyosti/p0f
void read_config(u8* fname) {

  s32 f;
  struct stat st;
  u8  *data, *cur;

  f = open((char*)fname, O_RDONLY);
  if (f < 0) PFATAL("Cannot open '%s' for reading.", fname);

  if (fstat(f, &st)) PFATAL("fstat() on '%s' failed.", fname);

  if (!st.st_size) { 
    close(f);
    goto end_fp_read;
  }

  cur = data = ck_alloc(st.st_size + 1);

  if (read(f, data, st.st_size) != st.st_size)
    FATAL("Short read from '%s'.", fname);

  data[st.st_size] = 0;

  close(f);

  /* If you put NUL in your p0f.fp... Well, sucks to be you. */

  while (1) {

    u8 *eol;

    line_no++;

    while (isblank(*cur)) cur++;

    eol = cur;
    while (*eol && *eol != '\n') eol++;

    if (*cur != ';' && cur != eol) {

      u8* line = ck_memdup_str(cur, eol - cur);

      config_parse_line(line);

      ck_free(line);

    }

    if (!*eol) break;

    cur = eol + 1;

  }

  ck_free(data);

end_fp_read:  

  if (!sig_cnt)
    SAYF("[!] No signatures found in '%s'.\n", fname);
  else 
    SAYF("[+] Loaded %u signature%s from '%s'.\n", sig_cnt,
         sig_cnt == 1 ? "" : "s", fname);

}
예제 #22
0
파일: afl-as.c 프로젝트: TylerOderkirk/afl
static void add_instrumentation(void) {

  static u8 line[MAX_AS_LINE];

  FILE* inf;
  FILE* outf;
  s32 outfd;
  u32 ins_lines = 0;
  u8  now_instr = 0;
  u8  output_next = 0;

  if (input_file) {

    inf = fopen(input_file, "r");
    if (!inf) PFATAL("Unable to read '%s'", input_file);

  } else inf = stdin;

  outfd = open(modified_file, O_WRONLY | O_EXCL | O_CREAT, 0600);

  if (outfd < 0) PFATAL("Unable to write to '%s'", modified_file);

  outf = fdopen(outfd, "w");

  if (!outf) PFATAL("fdopen() failed");

  while (fgets(line, MAX_AS_LINE, inf)) {

    u8* label;

    /* Oh boy. The ARM version is extremely messy compared to Intel,
       because of the very limited range of immediate pointers within
       opcodes. When we inject the instrumentation, it's possible to
       push some labels / literal pools outside the range they were
       in when GCC first generated the code. This means several things:

       - We need to rewrite instructions such as ldr to movw + movt +
         ldr.

       - We need to do a similar but different hack for fld* / fst*.

       - We need to inject additional .ltorg sections and jump over
         them to ensure sufficient density of literal pools.

       - We need to be careful to not accidentally instrument .word
         literals that appear in the code segment.

       Whoever complains that x86 assembly is counterintuitive and ARM
       is user-friendly is probably at least a bit high.

     */

    /* Output instrumentation unless we're hitting a block of .word
       literals. */

    if (output_next) {

      if (strncmp(line, "\t.word", 6)) {
        fprintf(outf, trampoline_fmt, R(MAP_SIZE));
        ins_lines++;
      }

      output_next = 0;

    }

    /* Rewrite label-referencing ldr instructions. */

    if (now_instr && !strncmp(line, "\tldr", 4) && 
        (label = strstr(line, ", .L"))) {

      u8* reg = strchr(line + 4, '\t');

      label[0] = 0;

      fprintf(outf, "%s, =%s\n", line, label + 2);
      fprintf(outf, "%s, [%s]\n", line, reg);

      continue;

    }

    /* Do not-exactly-the-same for fld* and fst*. */

    if (now_instr &&
        (!strncmp(line, "\tfld", 4) || !strncmp(line, "\tfst", 4)) &&
        (label = strstr(line, ", .L"))) {

      label[0] = 0;

      fprintf(outf, "push {r12}\n");
      fprintf(outf, "ldr r12, =%s\n", label + 2);
      fprintf(outf, "%s, [r12]\n", line);
      fprintf(outf, "pop {r12}\n");

      continue;

    }

    fputs(line, outf);

    /* We only want to instrument the .text section. So, let's keep track
       of that in processed files. */

    if (line[0] == '\t' && line[1] == '.') {

      if (!strncmp(line + 2, "text\n", 5)) {
        now_instr = 1; 
        continue; 
      }

      if (!strncmp(line + 2, "section\t", 8) ||
          !strncmp(line + 2, "bss\n", 4) ||
          !strncmp(line + 2, "data\n", 5)) {
        now_instr = 0;
        continue;
      }

    }

    /* If we're in the right mood for instrumenting, check for function
       names or conditional labels, decide what to do next. */

    if (now_instr && (
        (strstr(line, ":\n") && (line[0] == '.' ? isdigit(line[2]) : 1)) ||
        (line[0] == '\t' && line[1] == 'b' && line[2] == 'e'))) {

      output_next = 1;

    }


  }

  fputs(main_payload, outf);

  if (input_file) fclose(inf);
  fclose(outf);

  if (!ins_lines) WARNF("No instrumentation targets found.");
  else OKF("Successfully instrumented %u locations (seed = 0x%08x).",
           ins_lines, rand_seed);

}
예제 #23
0
int main(int argc, char** argv) {

#ifdef HAVE_AFFINITY

    u32 cpu_cnt = sysconf(_SC_NPROCESSORS_ONLN),
        idle_cpus = 0, maybe_cpus = 0, i;

    SAYF(cCYA "afl-gotcpu " cBRI VERSION cRST " by <*****@*****.**>\n");

    ACTF("Measuring per-core preemption rate (this will take %0.02f sec)...",
         ((double)CTEST_CORE_TRG_MS) * cpu_cnt / 1000);

    for (i = 0; i < cpu_cnt; i++) {

        cpu_set_t c;
        u32 util_perc;

        CPU_ZERO(&c);
        CPU_SET(i, &c);

        if (sched_setaffinity(0, sizeof(c), &c))
            PFATAL("sched_setaffinity failed");

        util_perc = measure_preemption(CTEST_CORE_TRG_MS);

        if (util_perc < 105) {

            SAYF("    Core #%u: " cLGN "AVAILABLE\n" cRST, i);
            maybe_cpus++;
            idle_cpus++;

        } else if (util_perc < 130) {

            SAYF("    Core #%u: " cYEL "CAUTION " cRST "(%u%%)\n", i, util_perc);
            maybe_cpus++;

        } else {

            SAYF("    Core #%u: " cLRD "OVERBOOKED " cRST "(%u%%)\n" cRST, i,
                 util_perc);

        }

    }

    SAYF(cGRA "\n>>> ");

    if (idle_cpus) {

        if (maybe_cpus == idle_cpus) {

            SAYF(cLGN "PASS: "******"You can run more processes on %u core%s.",
                 idle_cpus, idle_cpus > 1 ? "s" : "");

        } else {

            SAYF(cLGN "PASS: "******"You can run more processes on %u to %u core%s.",
                 idle_cpus, maybe_cpus, maybe_cpus > 1 ? "s" : "");

        }

        SAYF(cGRA " <<<" cRST "\n\n");
        return 0;

    }

    if (maybe_cpus) {

        SAYF(cYEL "CAUTION: " cRST "You may still have %u core%s available.",
             maybe_cpus, maybe_cpus > 1 ? "s" : "");
        SAYF(cGRA " <<<" cRST "\n\n");
        return 1;

    }

    SAYF(cLRD "FAIL: " cRST "All cores are overbooked.");
    SAYF(cGRA " <<<" cRST "\n\n");
    return 2;

#else

    u32 util_perc;

    SAYF(cCYA "afl-gotcpu " cBRI VERSION cRST " by <*****@*****.**>\n");

    /* Run a busy loop for CTEST_TARGET_MS. */

    ACTF("Measuring gross preemption rate (this will take %0.02f sec)...",
         ((double)CTEST_TARGET_MS) / 1000);

    util_perc = measure_preemption(CTEST_TARGET_MS);

    /* Deliver the final verdict. */

    SAYF(cGRA "\n>>> ");

    if (util_perc < 105) {

        SAYF(cLGN "PASS: "******"You can probably run additional processes.");

    } else if (util_perc < 130) {

        SAYF(cYEL "CAUTION: " cRST "Your CPU may be somewhat overbooked (%u%%).",
             util_perc);

    } else {

        SAYF(cLRD "FAIL: " cRST "Your CPU is overbooked (%u%%).", util_perc);

    }

    SAYF(cGRA " <<<" cRST "\n\n");

    return (util_perc > 105) + (util_perc > 130);

#endif /* ^HAVE_AFFINITY */

}
예제 #24
0
파일: p0f.c 프로젝트: kernevil/p0f
int main(int argc, char** argv) {

  s32 r;

  setlinebuf(stdout);

  SAYF("--- p0f " VERSION " by Michal Zalewski <*****@*****.**> ---\n\n");

  if (getuid() != geteuid())
    FATAL("Please don't make me setuid. See README for more.\n");

  while ((r = getopt(argc, argv, "+LS:df:i:m:o:pr:s:t:u:")) != -1) switch (r) {

    case 'L':

      list_interfaces();
      exit(0);

    case 'S':

#ifdef __CYGWIN__

      FATAL("API mode not supported on Windows (see README).");

#else

      if (api_max_conn != API_MAX_CONN)
        FATAL("Multiple -S options not supported.");

      api_max_conn = atol(optarg);

      if (!api_max_conn || api_max_conn > 100)
        FATAL("Outlandish value specified for -S.");

      break;

#endif /* ^__CYGWIN__ */


    case 'd':

      if (daemon_mode)
        FATAL("Double werewolf mode not supported yet.");

      daemon_mode = 1;
      break;

    case 'f':

      if (fp_file)
        FATAL("Multiple -f options not supported.");

      fp_file = (u8*)optarg;
      break;

    case 'i':

      if (use_iface)
        FATAL("Multiple -i options not supported (try '-i any').");

      use_iface = (u8*)optarg;

      break;

    case 'm':

      if (max_conn != MAX_CONN || max_hosts != MAX_HOSTS)
        FATAL("Multiple -m options not supported.");

      if (sscanf(optarg, "%u,%u", &max_conn, &max_hosts) != 2 ||
          !max_conn || max_conn > 100000 ||
          !max_hosts || max_hosts > 500000)
        FATAL("Outlandish value specified for -m.");

      break;

    case 'o':

      if (log_file)
        FATAL("Multiple -o options not supported.");

      log_file = (u8*)optarg;

      break;

    case 'p':
    
      if (set_promisc)
        FATAL("Even more promiscuous? People will call me slutty!");

      set_promisc = 1;
      break;

    case 'r':

      if (read_file)
        FATAL("Multiple -r options not supported.");

      read_file = (u8*)optarg;

      break;

    case 's':

#ifdef __CYGWIN__

      FATAL("API mode not supported on Windows (see README).");

#else

      if (api_sock) 
        FATAL("Multiple -s options not supported.");

      api_sock = (u8*)optarg;

      break;

#endif /* ^__CYGWIN__ */

    case 't':

      if (conn_max_age != CONN_MAX_AGE || host_idle_limit != HOST_IDLE_LIMIT)
        FATAL("Multiple -t options not supported.");

      if (sscanf(optarg, "%u,%u", &conn_max_age, &host_idle_limit) != 2 ||
          !conn_max_age || conn_max_age > 1000000 ||
          !host_idle_limit || host_idle_limit > 1000000)
        FATAL("Outlandish value specified for -t.");

      break;

    case 'u':

      if (switch_user)
        FATAL("Split personality mode not supported.");

      switch_user = (u8*)optarg;

      break;

    default: usage();

  }

  if (optind < argc) {

    if (optind + 1 == argc) orig_rule = (u8*)argv[optind];
    else FATAL("Filter rule must be a single parameter (use quotes).");

  }

  if (read_file && api_sock)
    FATAL("API mode looks down on ofline captures.");

  if (!api_sock && api_max_conn != API_MAX_CONN)
    FATAL("Option -S makes sense only with -s.");

  if (daemon_mode) {

    if (read_file)
      FATAL("Daemon mode and offline captures don't mix.");

    if (!log_file && !api_sock)
      FATAL("Daemon mode requires -o or -s.");

#ifdef __CYGWIN__

    if (switch_user) 
      SAYF("[!] Note: under cygwin, -u is largely useless.\n");

#else

    if (!switch_user) 
      SAYF("[!] Consider specifying -u in daemon mode (see README).\n");

#endif /* ^__CYGWIN__ */

  }

  tzset();
  setlocale(LC_TIME, "C");

  close_spare_fds();

  get_hash_seed();

  http_init();

  read_config(fp_file ? fp_file : (u8*)FP_FILE);

  prepare_pcap();
  prepare_bpf();

  if (log_file) open_log();
  if (api_sock) open_api();
  
  if (daemon_mode) {
    null_fd = open("/dev/null", O_RDONLY);
    if (null_fd < 0) PFATAL("Cannot open '/dev/null'.");
  }
  
  if (switch_user) drop_privs();

  if (daemon_mode) fork_off();

  signal(SIGHUP, daemon_mode ? SIG_IGN : abort_handler);
  signal(SIGINT, abort_handler);
  signal(SIGTERM, abort_handler);

  if (read_file) offline_event_loop(); else live_event_loop();

  if (!daemon_mode)
    SAYF("\nAll done. Processed %llu packets.\n", packet_cnt);

#ifdef DEBUG_BUILD
  destroy_all_hosts();
  TRK_report();
#endif /* DEBUG_BUILD */

  return 0;

}
예제 #25
0
static void add_instrumentation(void) {

  static u8 line[MAX_AS_LINE];

  FILE* inf;
  FILE* outf;
  s32 outfd;
  u32 ins_lines = 0;

  u8  instr_ok = 0, skip_csect = 0, skip_next_label = 0,
      skip_intel = 0, skip_app = 0;

#ifdef __APPLE__

  u8* colon_pos;

#endif /* __APPLE__ */

  if (input_file) {

    inf = fopen(input_file, "r");
    if (!inf) PFATAL("Unable to read '%s'", input_file);

  } else inf = stdin;

  outfd = open(modified_file, O_WRONLY | O_EXCL | O_CREAT, 0600);

  if (outfd < 0) PFATAL("Unable to write to '%s'", modified_file);

  outf = fdopen(outfd, "w");

  if (!outf) PFATAL("fdopen() failed");  

  while (fgets(line, MAX_AS_LINE, inf)) {

    fputs(line, outf);

    if (pass_thru) continue;

    /* We only want to instrument the .text section. So, let's keep track
       of that in processed files. */

    if (line[0] == '\t' && line[1] == '.') {

      /* OpenBSD puts jump tables directly inline with the code, which is
         a bit annoying. They use a specific format of p2align directives
         around them, so we use that as a signal. */

      if (!clang_mode && instr_ok && !strncmp(line + 2, "p2align ", 8) &&
          isdigit(line[10]) && line[11] == '\n') skip_next_label = 1;

      if (!strncmp(line + 2, "text\n", 5) ||
          !strncmp(line + 2, "section\t.text", 13) ||
          !strncmp(line + 2, "section\t__TEXT,__text", 21) ||
          !strncmp(line + 2, "section __TEXT,__text", 21)) {
        instr_ok = 1;
        continue; 
      }

      if (!strncmp(line + 2, "section\t", 8) ||
          !strncmp(line + 2, "section ", 8) ||
          !strncmp(line + 2, "bss\n", 4) ||
          !strncmp(line + 2, "data\n", 5)) {
        instr_ok = 0;
        continue;
      }

    }

    /* Detect off-flavor assembly (rare, happens in gdb). */

    if (strstr(line, ".code")) {

      if (strstr(line, ".code32")) skip_csect = use_64bit;
      if (strstr(line, ".code64")) skip_csect = !use_64bit;

    }

    /* Detect syntax changes. */

    if (strstr(line, ".intel_syntax")) skip_intel = 1;
    if (strstr(line, ".att_syntax")) skip_intel = 0;

    /* Detect and skip ad-hoc __asm__ blocks. */

    if (line[0] == '#' || line[1] == '#') {

      if (strstr(line, "#APP")) skip_app = 1;
      if (strstr(line, "#NO_APP")) skip_app = 0;

    }

    /* If we're in the right mood for instrumenting, check for function
       names or conditional labels. This is a bit messy, but in essence,
       we want to catch:

         ^main:      - function entry point (always instrumented)
         ^.L0:       - GCC branch label
         ^.LBB0_0:   - clang branch label (but only in clang mode)
         ^\tjnz foo  - conditional branches

       ...but not:

         ^# BB#0:    - clang comments
         ^ # BB#0:   - ditto
         ^.Ltmp0:    - clang non-branch labels
         ^.LC0       - GCC non-branch labels
         ^.LBB0_0:   - ditto (when in GCC mode)
         ^\tjmp foo  - non-conditional jumps

       Additionally, clang and GCC on MacOS X follow a different convention
       with no leading dots on labels, hence the weird maze of #ifdefs
       later on.

     */

    if (skip_intel || skip_app || skip_csect || !instr_ok ||
        line[0] == '#' || line[0] == ' ') continue;

    /* Conditional branch instruction (jnz, etc). */

    if (line[0] == '\t') {

      if (line[1] == 'j' && line[2] != 'm' && R(100) < inst_ratio) {

        fprintf(outf, use_64bit ? trampoline_fmt_64 : trampoline_fmt_32,
                R(MAP_SIZE));

        ins_lines++;

      }

      continue;

    }

    /* Label of some sort. */

#ifdef __APPLE__

    /* Apple: L<whatever><digit>: */

    if ((colon_pos = strstr(line, ":"))) {

      if (line[0] == 'L' && isdigit(*(colon_pos - 1))) {

#else

    /* Everybody else: .L<whatever>: */

    if (strstr(line, ":")) {

      if (line[0] == '.') {

#endif /* __APPLE__ */

        /* .L0: or LBB0_0: style jump destination */

#ifdef __APPLE__

        /* Apple: L<num> / LBB<num> */

        if ((isdigit(line[1]) || (clang_mode && !strncmp(line, "LBB", 3)))
            && R(100) < inst_ratio) {

#else

        /* Apple: .L<num> / .LBB<num> */

        if ((isdigit(line[2]) || (clang_mode && !strncmp(line + 1, "LBB", 3)))
            && R(100) < inst_ratio) {

#endif /* __APPLE__ */

          /* An optimization is possible here by adding the code only if the
             label is mentioned in the code in contexts other than call / jmp.
             That said, this complicates the code by requiring two-pass
             processing (messy with stdin), and results in a speed gain
             typically under 10%. */

          if (!skip_next_label) {

            fprintf(outf, use_64bit ? trampoline_fmt_64 : trampoline_fmt_32,
                    R(MAP_SIZE));

            ins_lines++;

          } else skip_next_label = 0;

        }

      } else {

        /* Function label (always instrumented) */

        fprintf(outf, use_64bit ? trampoline_fmt_64 : trampoline_fmt_32,
                R(MAP_SIZE));

        ins_lines++;
    
      }

    }

  }

  if (ins_lines)
    fputs(use_64bit ? main_payload_64 : main_payload_32, outf);

  if (input_file) fclose(inf);
  fclose(outf);

  if (!be_quiet) {

    if (!ins_lines) WARNF("No instrumentation targets found.");
    else OKF("Instrumented %u locations (%s-bit, %s mode, ratio %u%%).",
             ins_lines, use_64bit ? "64" : "32",
             getenv("AFL_HARDEN") ? "hardened" : "non-hardened",
             inst_ratio);
 
  }

}


/* Main entry point */

int main(int argc, char** argv) {

  s32 pid;
  u32 rand_seed;
  int status;
  u8* inst_ratio_str = getenv("AFL_INST_RATIO");

  struct timeval tv;
  struct timezone tz;

  clang_mode = !!getenv(CLANG_ENV_VAR);

  if (isatty(2) && !getenv("AFL_QUIET")) {

    SAYF(cCYA "afl-as " cBRI VERSION cRST " (" __DATE__ " " __TIME__ 
         ") by <*****@*****.**>\n");
 
  } else be_quiet = 1;

  if (argc < 2) {

    SAYF("\n"
         "This is a helper application for afl-fuzz. It is a wrapper around GNU 'as',\n"
         "executed by the toolchain whenever using afl-gcc or afl-clang. You probably\n"
         "don't want to run this program directly.\n\n"

         "Rarely, when dealing with extremely complex projects, it may be advisable to\n"
         "set AFL_INST_RATIO to a value less than 100 in order to reduce the odds of\n"
         "instrumenting every discovered branch.\n\n");

    exit(1);

  }

  gettimeofday(&tv, &tz);

  rand_seed = tv.tv_sec ^ tv.tv_usec ^ getpid();

  srandom(rand_seed);

  edit_params(argc, argv);

  if (inst_ratio_str) {

    if (sscanf(inst_ratio_str, "%u", &inst_ratio) != 1 || inst_ratio > 100) 
      FATAL("Bad value of AFL_INST_RATIO (must be between 0 and 100)");

  }

  if (getenv(AS_LOOP_ENV_VAR))
    FATAL("Endless loop when calling 'as' (remove '.' from your PATH)");

  setenv(AS_LOOP_ENV_VAR, "1", 1);

  /* When compiling with ASAN, we don't have a particularly elegant way to skip
     ASAN-specific branches. But we can probabilistically compensate for
     that... */

  if (getenv("AFL_USE_ASAN") || getenv("AFL_USE_MSAN")) inst_ratio /= 3;

  if (!just_version) add_instrumentation();

  if (!(pid = fork())) {

    execvp(as_params[0], (char**)as_params);
    FATAL("Oops, failed to execute '%s' - check your PATH", as_params[0]);

  }

  if (pid < 0) PFATAL("fork() failed");

  if (waitpid(pid, &status, 0) <= 0) PFATAL("waitpid() failed");

  if (!getenv("AFL_KEEP_ASSEMBLY")) unlink(modified_file);

  exit(WEXITSTATUS(status));

}
예제 #26
0
파일: p0f-sendsyn6.c 프로젝트: ATpiu/tpotce
int main(int argc, char** argv) {

  static struct sockaddr_in6 sin;
  char one = 1;
  s32  sock;
  u32  i;

  static u8 work_buf[MIN_TCP6 + 24];

  struct ipv6_hdr* ip6 = (struct ipv6_hdr*)work_buf;
  struct tcp_hdr*  tcp = (struct tcp_hdr*)(ip6 + 1);
  u8 *opts = work_buf + MIN_TCP6;


  if (argc != 4) {
    ERRORF("Usage: p0f-sendsyn your_ip dst_ip port\n");
    exit(1);
  }

  parse_addr(argv[1], ip6->src);
  parse_addr(argv[2], ip6->dst);

  sock = socket(AF_INET, SOCK_RAW, IPPROTO_IPV6);

  if (sock < 0) PFATAL("Can't open raw socket (you need to be root).");

  if (setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (char*)&one, sizeof(char)))
    PFATAL("setsockopt() on raw socket failed.");

  sin.sin6_family = PF_INET6;
  
  memcpy(&sin.sin6_addr, ip6->dst, 16);

  ip6->ver_tos = ntohl(6 << 24);
  ip6->pay_len = ntohs(sizeof(struct tcp_hdr) + 24);
  ip6->proto   = PROTO_TCP;
  ip6->ttl     = 192;

  tcp->dport     = htons(atoi(argv[3]));
  tcp->seq       = htonl(0x12345678);
  tcp->doff_rsvd = ((sizeof(struct tcp_hdr) + 24) / 4) << 4;
  tcp->flags     = TCP_SYN;
  tcp->win       = htons(SPECIAL_WIN);

  for (i = 0; i < 8; i++) {

    tcp->sport = htons(65535 - i);

    memcpy(opts, opt_combos[i], 24);
    tcp_cksum(ip6->src, ip6->dst, tcp, 24);

    if (sendto(sock, work_buf, sizeof(work_buf), 0, (struct sockaddr*)&sin,
        sizeof(struct sockaddr_in6)) < 0) PFATAL("sendto() fails.");

    usleep(100000);

  }

  SAYF("Eight packets sent! Check p0f output to examine responses, if any.\n");

  return 0;

}
예제 #27
0
파일: afl-showmap.c 프로젝트: slox3r/afl
static void run_target(char** argv) {

  static struct itimerval it;
  int status = 0;

  if (!quiet_mode)
    SAYF("-- Program output begins --\n" cRST);

  MEM_BARRIER();

  child_pid = fork();

  if (child_pid < 0) PFATAL("fork() failed");

  if (!child_pid) {

    struct rlimit r;

    if (quiet_mode) {

      s32 fd = open("/dev/null", O_RDWR);

      if (fd < 0 || dup2(fd, 1) < 0 || dup2(fd, 2) < 0) {
        *(u32*)trace_bits = EXEC_FAIL_SIG;
        PFATAL("Descriptor initialization failed");
      }

      close(fd);

    }

    if (mem_limit) {

      r.rlim_max = r.rlim_cur = ((rlim_t)mem_limit) << 20;

#ifdef RLIMIT_AS

      setrlimit(RLIMIT_AS, &r); /* Ignore errors */

#else

      setrlimit(RLIMIT_DATA, &r); /* Ignore errors */

#endif /* ^RLIMIT_AS */

    }

    r.rlim_max = r.rlim_cur = 0;
    setrlimit(RLIMIT_CORE, &r); /* Ignore errors */

    execv(target_path, argv);

    *(u32*)trace_bits = EXEC_FAIL_SIG;
    exit(0);

  }

  /* Configure timeout, wait for child, cancel timeout. */

  if (exec_tmout) {

    child_timed_out = 0;
    it.it_value.tv_sec = (exec_tmout / 1000);
    it.it_value.tv_usec = (exec_tmout % 1000) * 1000;

  }

  setitimer(ITIMER_REAL, &it, NULL);

  if (waitpid(child_pid, &status, 0) <= 0) FATAL("waitpid() failed");

  child_pid = 0;
  it.it_value.tv_sec = 0;
  it.it_value.tv_usec = 0;
  setitimer(ITIMER_REAL, &it, NULL);

  MEM_BARRIER();

  /* Clean up bitmap, analyze exit condition, etc. */

  if (*(u32*)trace_bits == EXEC_FAIL_SIG)
    FATAL("Unable to execute '%s'", argv[0]);

  classify_counts(trace_bits);

  if (!quiet_mode)
    SAYF(cRST "-- Program output ends --\n");

  if (!child_timed_out && !stop_soon && WIFSIGNALED(status))
    child_crashed = 1;

  if (!quiet_mode) {

    if (child_timed_out)
      SAYF(cLRD "\n+++ Program timed off +++\n" cRST);
    else if (stop_soon)
      SAYF(cLRD "\n+++ Program aborted by user +++\n" cRST);
    else if (child_crashed)
      SAYF(cLRD "\n+++ Program killed by signal %u +++\n" cRST, WTERMSIG(status));

  }


}
예제 #28
0
파일: skipfish.c 프로젝트: kyx114/rapid
int main(int argc, char** argv) {
  s32 opt;
  u32 loop_cnt = 0, purge_age = 0, seed;
  u8 sig_loaded = 0, show_once = 0, no_statistics = 0,
     display_mode = 0, has_fake = 0;
  s32 oindex = 0;
  u8 *wordlist = NULL, *output_dir = NULL;
  u8 *sig_list_strg = NULL;
  u8 *gtimeout_str = NULL;
  u32 gtimeout = 0;

  struct termios term;
  struct timeval tv;
  u64 st_time, en_time;

  signal(SIGINT, ctrlc_handler);
  signal(SIGWINCH, resize_handler);
  signal(SIGPIPE, SIG_IGN);
  SSL_library_init();

/* Options, options, and options */

  static struct option long_options[] = {
    {"auth", required_argument, 0, 'A' },
    {"host", required_argument, 0, 'F' },
    {"cookie", required_argument, 0, 'C' },
    {"reject-cookies", required_argument, 0, 'N' },
    {"header", required_argument, 0, 'H' },
    {"user-agent", required_argument, 0, 'b' },
#ifdef PROXY_SUPPORT
    {"proxy", required_argument, 0, 'J' },
#endif /* PROXY_SUPPORT */
    {"max-depth", required_argument, 0, 'd' },
    {"max-child", required_argument, 0, 'c' },
    {"max-descendants", required_argument, 0, 'x' },
    {"max-requests", required_argument, 0, 'r' },
    {"max-rate", required_argument, 0, 'l'},
    {"probability", required_argument, 0, 'p' },
    {"seed", required_argument, 0, 'q' },
    {"include", required_argument, 0, 'I' },
    {"exclude", required_argument, 0, 'X' },
    {"skip-param", required_argument, 0, 'K' },
    {"skip-forms", no_argument, 0, 'O' },
    {"include-domain", required_argument, 0, 'D' },
    {"ignore-links", no_argument, 0, 'P' },
    {"no-ext-fuzzing", no_argument, 0, 'Y' },
    {"log-mixed-content", no_argument, 0, 'M' },
    {"skip-error-pages", no_argument, 0, 'Z' },
    {"log-external-urls", no_argument, 0, 'U' },
    {"log-cache-mismatches", no_argument, 0, 'E' },
    {"form-value", no_argument, 0, 'T' },
    {"rw-wordlist", required_argument, 0, 'W' },
    {"no-keyword-learning", no_argument, 0, 'L' },
    {"mode", required_argument, 0, 'J' },
    {"wordlist", required_argument, 0, 'S'},
    {"trust-domain", required_argument, 0, 'B' },
    {"max-connections", required_argument, 0, 'g' },
    {"max-host-connections", required_argument, 0, 'm' },
    {"max-fail", required_argument, 0, 'f' },
    {"request-timeout", required_argument, 0, 't' },
    {"network-timeout", required_argument, 0, 'w' },
    {"idle-timeout", required_argument, 0, 'i' },
    {"response-size", required_argument, 0, 's' },
    {"discard-binary", required_argument, 0, 'e' },
    {"output", required_argument, 0, 'o' },
    {"help", no_argument, 0, 'h' },
    {"quiet", no_argument, 0, 'u' },
    {"verbose", no_argument, 0, 'v' },
    {"scan-timeout", required_argument, 0, 'k'},
    {"signatures", required_argument, 0, 'z'},
    {"checks", no_argument, 0, 0},
    {"checks-toggle", required_argument, 0, 0},
    {"no-checks", no_argument, 0, 0},
    {"fast", no_argument, 0, 0},
    {"auth-form", required_argument, 0, 0},
    {"auth-form-target", required_argument, 0, 0},
    {"auth-user", required_argument, 0, 0},
    {"auth-user-field", required_argument, 0, 0},
    {"auth-pass", required_argument, 0, 0},
    {"auth-pass-field", required_argument, 0, 0},
    {"auth-verify-url", required_argument, 0, 0},
    {0, 0, 0, 0 }

  };
  /* Come up with a quasi-decent random seed. */

  gettimeofday(&tv, NULL);
  seed = tv.tv_usec ^ (tv.tv_sec << 16) ^ getpid();

  SAY("skipfish version " VERSION " by <*****@*****.**>\n");

  while ((opt = getopt_long(argc, argv,
          "+A:B:C:D:EF:G:H:I:J:K:LMNOPQR:S:T:UW:X:YZ"
          "b:c:d:ef:g:hi:k:l:m:o:p:q:r:s:t:uvw:x:z:",
          long_options, &oindex)) >= 0)

    switch (opt) {

      case 'A': {
          u8* x = (u8*)strchr(optarg, ':');
          if (!x) FATAL("Credentials must be in 'user:pass' form.");
          *(x++) = 0;
          auth_user = (u8*)optarg;
          auth_pass = x;
          auth_type = AUTH_BASIC;
          break;
        }

#ifdef PROXY_SUPPORT
      case 'J':  {
          u8* x = (u8*)strchr(optarg, ':');
          if (!x) FATAL("Proxy data must be in 'host:port' form.");
          *(x++) = 0;
          use_proxy = (u8*)optarg;
          use_proxy_port = atoi((char*)x);
          if (!use_proxy_port) FATAL("Incorrect proxy port number.");
          break;
        }
#endif /* PROXY_SUPPORT */

      case 'F': {
          u8* x = (u8*)strchr(optarg, '=');
          u32 fake_addr;
          if (!x) FATAL("Fake mappings must be in 'host=IP' form.");
          *x = 0;
          fake_addr = inet_addr((char*)x + 1);
          if (fake_addr == (u32)-1)
            FATAL("Could not parse IP address '%s'.", x + 1);
          fake_host((u8*)optarg, fake_addr);
          has_fake = 1;
          break;
        }

      case 'H': {
          u8* x = (u8*)strchr(optarg, '=');
          if (!x) FATAL("Extra headers must be in 'name=value' form.");
          *x = 0;
          if (!strcasecmp(optarg, "Cookie"))
            FATAL("Do not use -H to set cookies (try -C instead).");
          SET_HDR((u8*)optarg, x + 1, &global_http_par);
          break;
        }

      case 'C': {
          u8* x = (u8*)strchr(optarg, '=');
          if (!x) FATAL("Cookies must be in 'name=value' form.");
          if (strchr(optarg, ';'))
            FATAL("Split multiple cookies into separate -C options.");
          *x = 0;
          SET_CK((u8*)optarg, x + 1, &global_http_par);
          break;
        }

      case 'D':
        if (*optarg == '*') optarg++;
        APPEND_FILTER(allow_domains, num_allow_domains, optarg);
        break;

      case 'K':
        APPEND_FILTER(skip_params, num_skip_params, optarg);
        break;

      case 'B':
        if (*optarg == '*') optarg++;
        APPEND_FILTER(trust_domains, num_trust_domains, optarg);
        break;

      case 'I':
        if (*optarg == '*') optarg++;
        APPEND_FILTER(allow_urls, num_allow_urls, optarg);
        break;

      case 'X':
        if (*optarg == '*') optarg++;
        APPEND_FILTER(deny_urls, num_deny_urls, optarg);
        break;

      case 'T': {
          u8* x = (u8*)strchr(optarg, '=');
          if (!x) FATAL("Rules must be in 'name=value' form.");
          *x = 0;
          add_form_hint((u8*)optarg, x + 1);
          break;
        }

      case 'N':
        ignore_cookies = 1;
        break;

      case 'Y':
        no_fuzz_ext = 1;
        break;

      case 'q':
        if (sscanf(optarg, "0x%08x", &seed) != 1)
          FATAL("Invalid seed format.");
        srandom(seed);
        break;

      case 'Q':
        suppress_dupes = 1;
        break;

      case 'P':
        no_parse = 1;
        break;

      case 'M':
        warn_mixed = 1;
        break;

      case 'U':
        log_ext_urls = 1;
        break;

      case 'L':
        dont_add_words = 1;
        break;

      case 'E':
        pedantic_cache = 1;
        break;

      case 'O':
        no_forms = 1;
        break;

      case 'R':
        purge_age = atoi(optarg);
        if (purge_age < 3) FATAL("Purge age invalid or too low (min 3).");
        break;

      case 'd':
        max_depth = atoi(optarg);
        if (max_depth < 2) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'c':
        max_children = atoi(optarg);
        if (!max_children) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'x':
        max_descendants = atoi(optarg);
        if (!max_descendants) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'p':
        crawl_prob = atoi(optarg);
        if (!crawl_prob) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'W':
        if (wordlist)
          FATAL("Only one -W parameter permitted (use -S to load supplemental dictionaries).");

        if (!strcmp(optarg, "-")) wordlist = (u8*)"/dev/null";
        else wordlist = (u8*)optarg;

        break;

      case 'S':
        load_keywords((u8*)optarg, 1, 0);
        break;

      case 'z':
        load_signatures((u8*)optarg);
        sig_loaded = 1;
        break;

      case 'b':
        if (optarg[0] == 'i') browser_type = BROWSER_MSIE; else
        if (optarg[0] == 'f') browser_type = BROWSER_FFOX; else
        if (optarg[0] == 'p') browser_type = BROWSER_PHONE; else
          usage(argv[0]);
        break;

      case 'g':
        max_connections = atoi(optarg);
        if (!max_connections) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'm':
        max_conn_host = atoi(optarg);
        if (!max_conn_host) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'G':
        max_guesses = atoi(optarg);
        if (!max_guesses) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'r':
        max_requests = atoi(optarg);
        if (!max_requests) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'l':
        max_requests_sec = atof(optarg);
        if (!max_requests_sec) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'f':
        max_fail = atoi(optarg);
        if (!max_fail) FATAL("Invalid value '%s'.", optarg);
        break;

      case 't':
        resp_tmout = atoi(optarg);
        if (!resp_tmout) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'w':
        rw_tmout = atoi(optarg);
        if (!rw_tmout) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'i':
        idle_tmout = atoi(optarg);
        if (!idle_tmout) FATAL("Invalid value '%s'.", optarg);
        break;

      case 's':
        size_limit = atoi(optarg);
        if (!size_limit) FATAL("Invalid value '%s'.", optarg);
        break;

      case 'o':
        if (output_dir) FATAL("Multiple -o options not allowed.");
        output_dir = (u8*)optarg;

        rmdir(optarg);

        if (mkdir(optarg, 0755))
          PFATAL("Unable to create '%s'.", output_dir);

        break;

      case 'u':
        no_statistics = 1;
        break;

      case 'v':
        verbosity++;
        break;


      case 'e':
        delete_bin = 1;
        break;

      case 'k':
        if (gtimeout_str) FATAL("Multiple -k options not allowed.");
        gtimeout_str = (u8*)optarg;
        break;

      case 'Z':
        no_500_dir = 1;
        break;

      case 0:
        if (!strcmp("checks", long_options[oindex].name ))
          display_injection_checks();
        if (!strcmp("checks-toggle", long_options[oindex].name ))
          toggle_injection_checks((u8*)optarg, 1, 1);
        if (!strcmp("no-checks", long_options[oindex].name ))
          no_checks = 1;
        if (!strcmp("signatures", long_options[oindex].name ))
          load_signatures((u8*)optarg);
        if(!strcmp("fast", long_options[oindex].name ))
          toggle_injection_checks((u8*)"2,4,5,13,14,15,16", 0, 0);
        if (!strcmp("auth-form", long_options[oindex].name ))
          auth_form = (u8*)optarg;
        if (!strcmp("auth-user", long_options[oindex].name ))
          auth_user = (u8*)optarg;
        if (!strcmp("auth-pass", long_options[oindex].name ))
          auth_pass = (u8*)optarg;
        if (!strcmp("auth-pass-field", long_options[oindex].name ))
          auth_pass_field = (u8*)optarg;
        if (!strcmp("auth-user-field", long_options[oindex].name ))
          auth_user_field = (u8*)optarg;
        if (!strcmp("auth-form-target", long_options[oindex].name ))
          auth_form_target = (u8*)optarg;
        if (!strcmp("auth-verify-url", long_options[oindex].name ))
          auth_verify_url = (u8*)optarg;

        break;

      default:
        usage(argv[0]);

  }

#ifdef PROXY_SUPPORT
  if (has_fake && use_proxy)
    FATAL("-F and -J should not be used together.");
#endif /* PROXY_SUPPORT */

  if (access(ASSETS_DIR "/index.html", R_OK))
    PFATAL("Unable to access '%s/index.html' - wrong directory?", ASSETS_DIR);

  srandom(seed);

  if (optind == argc)
    FATAL("Scan target not specified (try -h for help).");

  if (!output_dir)
    FATAL("Output directory not specified (try -h for help).");

  if(verbosity && !no_statistics && isatty(2))
    FATAL("Please use -v in combination with the -u flag or, "
          "run skipfish while redirecting stderr to a file. ");


  if (resp_tmout < rw_tmout)
    resp_tmout = rw_tmout;

  if (max_connections < max_conn_host)
    max_connections = max_conn_host;

  /* Parse the timeout string - format h:m:s */
  if (gtimeout_str) {
    int i = 0;
    int m[3] = { 1, 60, 3600 };

    u8* tok = (u8*)strtok((char*)gtimeout_str, ":");

    while(tok && i <= 2) {
      gtimeout += atoi((char*)tok) * m[i];
      tok = (u8*)strtok(NULL, ":");
      i++;
    }

    if(!gtimeout)
      FATAL("Wrong timeout format, please use h:m:s (hours, minutes, seconds)");
    DEBUG("* Scan timeout is set to %d seconds\n", gtimeout);
  }


  if (!wordlist) {
    wordlist = (u8*)"/dev/null";
    DEBUG("* No wordlist specified with -W: defaulting to /dev/null\n");
  }

  /* If no signature files have been specified via command-line: load
     the default file */
  if (!sig_loaded)
    load_signatures((u8*)SIG_FILE);

  load_keywords(wordlist, 0, purge_age);

  /* Load the signatures list for the matching */
  if (sig_list_strg) load_signatures(sig_list_strg);

  /* Try to authenticate when the auth_user and auth_pass fields are set. */
  if (auth_user && auth_pass) {
    authenticate();

    while (next_from_queue()) {
      usleep(1000);
    }

    switch (auth_state) {
      case ASTATE_DONE:
        DEBUGC(L1, "*- Authentication succeeded!\n");
        break;

      default:
        DEBUG("Auth state: %d\n", auth_state);
        FATAL("Authentication failed (use -uv for more info)\n");
        break;
    }
  }

  /* Schedule all URLs in the command line for scanning. */

  while (optind < argc) {
    struct http_request *req;

    /* Support @ notation for reading URL lists from files. */

    if (argv[optind][0] == '@') {
      read_urls((u8*)argv[optind++] + 1);
      continue;
    }

    req = ck_alloc(sizeof(struct http_request));

    if (parse_url((u8*)argv[optind], req, NULL))
      FATAL("Scan target '%s' is not a valid absolute URL.", argv[optind]);

    if (!url_allowed_host(req))
      APPEND_FILTER(allow_domains, num_allow_domains,
                    __DFL_ck_strdup(req->host));

    if (!url_allowed(req))
      FATAL("URL '%s' explicitly excluded by -I / -X rules.", argv[optind]);

    maybe_add_pivot(req, NULL, 2);
    destroy_request(req);

    optind++;
  }

  /* Char-by char stdin. */

  tcgetattr(0, &term);
  term.c_lflag &= ~ICANON;
  tcsetattr(0, TCSANOW, &term);
  fcntl(0, F_SETFL, O_NONBLOCK);

  gettimeofday(&tv, NULL);
  st_time = tv.tv_sec * 1000LL + tv.tv_usec / 1000;

#ifdef SHOW_SPLASH
  if (!no_statistics) splash_screen();
#endif /* SHOW_SPLASH */

  if (!no_statistics) SAY("\x1b[H\x1b[J");
  else SAY(cLGN "[*] " cBRI "Scan in progress, please stay tuned...\n");

  u64 refresh_time = 0;

  /* Enter the crawler loop */
  while ((next_from_queue() && !stop_soon) || (!show_once++)) {

    u8 keybuf[8];

    u64 end_time;
    u64 run_time;
    struct timeval tv_tmp;

    gettimeofday(&tv_tmp, NULL);
    end_time = tv_tmp.tv_sec * 1000LL + tv_tmp.tv_usec / 1000;

    run_time = end_time - st_time;
    if (gtimeout > 0 && run_time && run_time/1000 > gtimeout) {
      DEBUG("* Stopping scan due to timeout\n");
      stop_soon = 1;
    }

    req_sec = (req_count - queue_cur / 1.15) * 1000 / (run_time + 1);

    if (no_statistics || ((loop_cnt++ % 100) && !show_once && idle == 0))
      continue;

    if (end_time > refresh_time) {
      refresh_time = (end_time + 10);

      if (clear_screen) {
        SAY("\x1b[H\x1b[2J");
        clear_screen = 0;
      }

      SAY(cYEL "\x1b[H"
          "skipfish version " VERSION " by [email protected]\n\n"
           cBRI "  -" cPIN " %s " cBRI "-\n\n" cNOR,
           allow_domains[0]);


      if (!display_mode) {
        http_stats(st_time);
        SAY("\n");
        database_stats();
      } else {
        http_req_list();
      }

      SAY("        \r");
    }

    if (fread(keybuf, 1, sizeof(keybuf), stdin) > 0) {
      display_mode ^= 1;
      clear_screen = 1;
    }
  }

  gettimeofday(&tv, NULL);
  en_time = tv.tv_sec * 1000LL + tv.tv_usec / 1000;

  SAY("\n");

  if (stop_soon)
    SAY(cYEL "[!] " cBRI "Scan aborted by user, bailing out!" cNOR "\n");

  term.c_lflag |= ICANON;
  tcsetattr(0, TCSANOW, &term);
  fcntl(0, F_SETFL, O_SYNC);

  save_keywords((u8*)wordlist);

  write_report(output_dir, en_time - st_time, seed);

#ifdef LOG_STDERR
  SAY("\n== PIVOT DEBUG ==\n");
  dump_pivots(0, 0);
  SAY("\n== END OF DUMP ==\n\n");
#endif /* LOG_STDERR */

  SAY(cLGN "[+] " cBRI "This was a great day for science!" cRST "\n\n");

#ifdef DEBUG_ALLOCATOR
  if (!stop_soon) {
    destroy_database();
    destroy_signature_lists();
    destroy_http();
    destroy_signatures();
    __TRK_report();
  }
#endif /* DEBUG_ALLOCATOR */

  fflush(0);

  EVP_cleanup();
  CRYPTO_cleanup_all_ex_data();

  return 0;

}
예제 #29
0
파일: p0f-client.c 프로젝트: ATpiu/tpotce
int main(int argc, char** argv) {

  u8 tmp[128];
  struct tm* t;

  static struct p0f_api_query q;
  static struct p0f_api_response r;

  static struct sockaddr_un sun;

  s32  sock;
  time_t ut;

  if (argc != 3) {
    ERRORF("Usage: p0f-client /path/to/socket host_ip\n");
    exit(1);
  }

  q.magic = P0F_QUERY_MAGIC;

  if (strchr(argv[2], ':')) {

    parse_addr6(argv[2], q.addr);
    q.addr_type = P0F_ADDR_IPV6;

  } else {

    parse_addr4(argv[2], q.addr);
    q.addr_type = P0F_ADDR_IPV4;

  }

  sock = socket(PF_UNIX, SOCK_STREAM, 0);

  if (sock < 0) PFATAL("Call to socket() failed.");

  sun.sun_family = AF_UNIX;

  if (strlen(argv[1]) >= sizeof(sun.sun_path))
    FATAL("API socket filename is too long for sockaddr_un (blame Unix).");

  strcpy(sun.sun_path, argv[1]);

  if (connect(sock, (struct sockaddr*)&sun, sizeof(sun)))
    PFATAL("Can't connect to API socket.");

  if (write(sock, &q, sizeof(struct p0f_api_query)) !=
      sizeof(struct p0f_api_query)) FATAL("Short write to API socket.");

  if (read(sock, &r, sizeof(struct p0f_api_response)) !=
      sizeof(struct p0f_api_response)) FATAL("Short read from API socket.");
  
  close(sock);

  if (r.magic != P0F_RESP_MAGIC)
    FATAL("Bad response magic (0x%08x).\n", r.magic);

  if (r.status == P0F_STATUS_BADQUERY)
    FATAL("P0f did not understand the query.\n");

  if (r.status == P0F_STATUS_NOMATCH) {
    SAYF("No matching host in p0f cache. That's all we know.\n");
    return 0;
  }

  ut = r.first_seen;
  t = localtime(&ut);
  strftime((char*)tmp, 128, "%Y/%m/%d %H:%M:%S", t);

  SAYF("First seen    = %s\n", tmp);

  ut = r.last_seen;
  t = localtime(&ut);
  strftime((char*)tmp, 128, "%Y/%m/%d %H:%M:%S", t);

  SAYF("Last update   = %s\n", tmp);

  SAYF("Total flows   = %u\n", r.total_conn);

  if (!r.os_name[0])
    SAYF("Detected OS   = ???\n");
  else
    SAYF("Detected OS   = %s %s%s%s\n", r.os_name, r.os_flavor,
         (r.os_match_q & P0F_MATCH_GENERIC) ? " [generic]" : "",
         (r.os_match_q & P0F_MATCH_FUZZY) ? " [fuzzy]" : "");

  if (!r.http_name[0])
    SAYF("HTTP software = ???\n");
  else
    SAYF("HTTP software = %s %s (ID %s)\n", r.http_name, r.http_flavor,
         (r.bad_sw == 2) ? "is fake" : (r.bad_sw ? "OS mismatch" : "seems legit"));

  if (!r.link_type[0])
    SAYF("Network link  = ???\n");
  else
    SAYF("Network link  = %s\n", r.link_type);

  if (!r.language[0])
    SAYF("Language      = ???\n");
  else
    SAYF("Language      = %s\n", r.language);


  if (r.distance == -1)
    SAYF("Distance      = ???\n");
  else
    SAYF("Distance      = %u\n", r.distance);

  if (r.last_nat) {
    ut = r.last_nat;
    t = localtime(&ut);
    strftime((char*)tmp, 128, "%Y/%m/%d %H:%M:%S", t);
    SAYF("IP sharing    = %s\n", tmp);
  }

  if (r.last_chg) {
    ut = r.last_chg;
    t = localtime(&ut);
    strftime((char*)tmp, 128, "%Y/%m/%d %H:%M:%S", t);
    SAYF("Sys change    = %s\n", tmp);
  }

  if (r.uptime_min) {
    SAYF("Uptime        = %u days %u hrs %u min (modulo %u days)\n", 
         r.uptime_min / 60 / 24, (r.uptime_min / 60) % 24, r.uptime_min % 60,
         r.up_mod_days);
  }

  return 0;

}
예제 #30
0
파일: udpclient.c 프로젝트: LucasSiba/dump
void thread_loop(void *userdata)
{
	struct state *state = userdata;

	pthread_spin_init(&state->lock, PTHREAD_PROCESS_PRIVATE);

	char send_buf[PKT_SIZE], recv_buf[PKT_SIZE];
	struct msghdr *msg = calloc(2, sizeof(struct msghdr));
	struct iovec *iovec = calloc(2, sizeof(struct iovec));
	int i;
	for (i = 0; i < 2; i++) {
		msg[i].msg_iov = &iovec[i];
		msg[i].msg_iovlen = 1;
		iovec[i].iov_len = sizeof(send_buf);
	}

	iovec[0].iov_base = send_buf;
	iovec[1].iov_base = recv_buf;

	char pktinfo[4096];
	msg[1].msg_control = pktinfo;
	msg[1].msg_controllen = sizeof(pktinfo);

	uint64_t packet_no = 0;
	while (1) {
		int fd = net_connect_udp(state->target_addr, state->src_port,
					 state->busy_poll);

		struct timeval tv = {1, 0}; // 1 second
		int r = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv,
				   sizeof(tv));
		if (r < 0) {
			PFATAL("setsockopt(SO_RCVTIMEO)");
		}

		for (;; packet_no++) {
			memset(send_buf, 0, sizeof(send_buf));
			snprintf(send_buf, sizeof(send_buf), "%i-%li-%lu",
				 getpid(), gettid(), packet_no);

			uint64_t t0 = realtime_now(), t1 = 0, tp = 0;
			int r = sendmsg(fd, &msg[0], 0);
			if (r <= 0) {
				if (errno == EAGAIN || errno == EWOULDBLOCK ||
				    errno == ECONNREFUSED) {
					break;
				}
				if (errno == EINTR) {
					continue;
				}
				PFATAL("sendmmsg()");
			}

			msg[1].msg_controllen = sizeof(pktinfo);
			while (1) {
				int flags = state->polling ? MSG_DONTWAIT : 0;
				r = recvmsg(fd, &msg[1], flags);
				t1 = realtime_now();
				if (t1 - t0 >= 1000000000) {
					/* No msg for 1s */
					errno = ECONNREFUSED;
					break;
				}

				if (r <= 0 &&
				    (errno == EINTR || errno == EAGAIN ||
				     errno == EWOULDBLOCK)) {
					continue;
				}

				if (r == 0 && state->polling) {
					continue;
				}
				break;
			}

			if (r <= 0 && errno == ECONNREFUSED) {
				sleep(1);
				break;
			}

			if (r <= 0) {
				PFATAL("recvmmsg()");
			}

			if (memcmp(send_buf, recv_buf, sizeof(recv_buf)) != 0) {
				fprintf(stderr, "[!] bad message\n");
				sleep(1);
				break;
			}

			struct cmsghdr *cmsg;
			for (cmsg = CMSG_FIRSTHDR(&msg[1]); cmsg;
			     cmsg = CMSG_NXTHDR(&msg[1], cmsg)) {
				switch (cmsg->cmsg_level) {
				case SOL_SOCKET:
					switch (cmsg->cmsg_type) {
					case SO_TIMESTAMPNS: {
						struct timespec *ts =
							(struct timespec *)
							CMSG_DATA(cmsg);
						tp = TIMESPEC_NSEC(ts);
						break;
					}
					}
					break;
				}
			}

			pthread_spin_lock(&state->lock);
			stddev_add(&state->stddev, t1 - t0);
			if (tp != 0) {
				stddev_add(&state->stddev_packet, t1 - tp);
			}
			pthread_spin_unlock(&state->lock);
		}
		close(fd);
	}
}