/* This software was derived from SATAN 1.1.1 by Dan Farmer and Wietse Venema
  (http://www.porcupine.org/satan).
*/
 /*
  * tcp_scan - determine available tcp services, optionally collect banners
  * and detect telnet options
  * 
  * Author: Wietse Venema.
  * Converted to SARA environment:  Advanced Research Corporation
  */
 
#include <sys/types.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h> 
#ifdef FAVOR_BSD
#define __FAVOR_BSD
#endif
#include <netinet/tcp.h>

#include <arpa/telnet.h>

#include <stdio.h>
#include <signal.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>

extern int errno;
extern char *optarg;
extern int optind;

#ifndef __STDC__
extern char *strerror();
#endif

#define offsetof(t,m)	(size_t)(&(((t *)0)->m))

#ifndef IPPORT_TELNET
#define IPPORT_TELNET	23
#endif

#ifndef ICMP_MINLEN
#define ICMP_MINLEN 8 
#endif

#ifndef ICMP_UNREACH
#define ICMP_UNREACH 3
#endif

#ifndef ICMP_UNREACH_PROTOCOL
#define ICMP_UNREACH_PROTOCOL 2
#endif

#ifndef ICMP_UNREACH_NET
#define ICMP_UNREACH_NET 0
#endif

#ifndef ICMP_UNREACH_PORT
#define ICMP_UNREACH_PORT 3
#endif

#ifndef ICMP_UNREACH_HOST
#define ICMP_UNREACH_HOST 1
#endif

#ifndef ICMP_UNREACH_FILTER_PROHIB
#define ICMP_UNREACH_FILTER_PROHIB 13	
#endif
 
#ifndef FD_SET
#include <sys/select.h>
#endif

#include "lib.h"

#define BANNER_LENGTH	2048		/* upper bound on banner info */
#define BANNER_TIME	10		/* time for host to send banner */
#define BANNER_IDLE	1		/* delay after last banner info */

#define YES     1
#define NO      0

#define WAIT	1
#define NOWAIT	0

int     verbose;			/* default silent mode */
int     banner_time = BANNER_TIME;	/* banner timeout */
int     open_file_limit;		/* max nr of open files */
int     load_limit;			/* max nr of open sockets */
int     banner_length;                  /* override default banner buf length */

struct timeval now;			/* banner_info last update time */
fd_set  write_socket_mask;		/* sockets with connect() in progress */
fd_set  read_socket_mask;		/* sockets with connect() finished */
fd_set  read_mask;                      /* globalize for fw support */
fd_set  write_mask;                     /* globalize for fw support */
int     ports_busy;			/* number of open sockets */
int     ports_done;			/* number of finished sockets */
int     max_sock;			/* max socket file descriptor */
int     want_err;			/* want good/bad news */
int     show_all;			/* report all ports */

int    *socket_to_port;			/* socket to port number */

typedef struct {
    unsigned char *buf;			/* banner information or null */
    int     count;			/* amount of banner received sofar */
    int     flags;			/* see below */
    struct timeval connect_time;	/* when connect() finished */
    struct timeval read_time;		/* time of last banner update */
} BANNER_INFO;

BANNER_INFO *banner_info = 0;

#define F_TELNET	(1<<0)		/* telnet options seen */

int     icmp_sock;			/* for unreachable reports */
static struct sockaddr_in sin;		/* remote endpoint info */

static char *send_string;		/* string to send */
int response_time;			/* need some response */

#define NEW(type, count) (type *) mymalloc((count) * sizeof(type))

#define time_since(t) (now.tv_sec - t.tv_sec + 1e-6 * (now.tv_usec - t.tv_usec))

time_t *s_ttl;
static struct timeval fw_wait = {0,0};
static struct timeval go_wait = {1,1};
static struct timeval no_wait = {0,0};


/* usage - explain command syntax */

void usage(why)
char   *why;
{
    if (why)
        remark(why);
    error("usage: %s [-abuUv] [-l load] [-f fw timeout] [-s send string] [-B banner length] [-w banner time] host ports...", progname);
}

/* add_socket - say this socket is being connected */

void add_socket(sock, port)
int     sock;
int     port;
{
    BANNER_INFO *bp;

    socket_to_port[sock] = port;
    if (banner_info) {
	bp = banner_info + sock;
	bp->count = 0;
	bp->buf = 0;
	bp->flags = 0;
    }
    FD_SET(sock, &write_socket_mask);
    if (sock > max_sock)
	max_sock = sock;
    ports_busy++;
}

/* drop_socket - release socket resources */

void drop_socket(sock)
int     sock;
{
    BANNER_INFO *bp;

    if (banner_info && (bp = banner_info + sock)->buf)
	free((char *) bp->buf);
    close(sock);
    FD_CLR(sock, &read_socket_mask);
    FD_CLR(sock, &write_socket_mask);
    ports_busy--;
    ports_done++;
    s_ttl[sock]=0;
    FD_CLR(sock, &write_mask);
}


void report_and_drop_socket(sock, err)
int     sock;
int     err;
{
    alarm(0);

    if (show_all || want_err == err || (want_err < 0 && want_err != ~err) || err == ECONNRESET) {
	struct servent *sp;
	int     port = socket_to_port[sock];

	printf("%d:%s:", port, (sp = getservbyport(htons(port), "tcp")) != 0 ?
	       sp->s_name : "UNKNOWN");
	if (banner_info) {
	    BANNER_INFO *bp = banner_info + sock;

	    if (bp->flags & F_TELNET)
		putchar('t');
	    putchar(':');
	    if (bp->count > 0)
		print_data(stdout, bp->buf, bp->count);
	}
	if (err && show_all)
	    printf("%s", strerror(err));
            printf("\n");
            fflush(stdout);
        }
        drop_socket(sock);
}

/* receive_icmp - receive and decode ICMP message */

void receive_icmp(sock)
int     sock;
{
    union {
	char    chars[BUFSIZ];
	struct ip ip;
    }       buf;
    int     data_len;
    int     hdr_len;
    struct ip *ip;
    struct icmp *icmp;
    struct tcphdr *tcp;
    int     port;

    if ((data_len = recv(sock, (char *) &buf, sizeof(buf), 0)) < 0) {
	error("error: recv: %m");
	return;
    }

    /*
     * Extract the IP header.
     */
    ip = &buf.ip;
    if (ip->ip_p != IPPROTO_ICMP) {
	error("error: not ICMP proto (%d)", ip->ip_p);
	return;
    }

    /*
     * Extract the IP payload.
     */
    hdr_len = ip->ip_hl << 2;
    if (data_len - hdr_len < ICMP_MINLEN) {
	remark("short ICMP packet (%d bytes)", data_len);
	return;
    }
    icmp = (struct icmp *) ((char *) ip + hdr_len);
    data_len -= hdr_len;

    if (icmp->icmp_type != ICMP_UNREACH)
	return;

    /*
     * Extract the offending IP packet header.
     */
    if (data_len < offsetof(struct icmp, icmp_ip) + sizeof(icmp->icmp_ip)) {
	remark("short IP header in ICMP");
	return;
    }
    ip = &(icmp->icmp_ip);
    if (ip->ip_p != IPPROTO_TCP)
	return;
    if (ip->ip_dst.s_addr != sin.sin_addr.s_addr)
	return;

    /*
     * Extract the offending TCP packet header.
     */
    hdr_len = ip->ip_hl << 2;
    tcp = (struct tcphdr *) ((char *) ip + hdr_len);
    data_len -= hdr_len;
    if (data_len < offsetof(struct tcphdr, th_dport) + sizeof(tcp->th_dport)) {
	remark("short TCP header in ICMP");
	return;
    }

    /*
     * Process ICMP subcodes.  Added ICMP_UNREACH_FILTER_PROHIB (RET).
     */
    switch (icmp->icmp_code) {
    case ICMP_UNREACH_FILTER_PROHIB:
    case ICMP_UNREACH_NET:
    case ICMP_UNREACH_PROTOCOL:
	/* error("error: network or protocol unreachable"); */
	/* NOTREACHED */
    case ICMP_UNREACH_PORT:
    case ICMP_UNREACH_HOST:
	port = ntohs(tcp->th_dport);
	for (sock = 0; sock < open_file_limit; sock++)
	    if (socket_to_port[sock] == port) {
		report_and_drop_socket(sock, EHOSTUNREACH);
		return;
	    }
	break;
    }
}

/* do_send_string - send the send string */

void do_send_string(sock)
int     sock;
{
    char    buf[BUFSIZ];
    char   *cp = buf;
    char    ch;
    int     c;
    int     i;
    char   *s = send_string;

    while (*s && cp < buf + sizeof(buf) - 1) {	/* don't overflow the buffer */

	if (*s != '\\') {			/* ordinary character */
	    *cp++ = *s++;

	} else if (isdigit(*++s) && *s < '8') {	/* \nnn octal code */
	    sscanf(s, "%3o", &c);
	    *cp++ = c;
	    for (i = 0; i < 3 && isdigit(*s) && *s < '8'; i++)
		s++;
	} else if ((ch = *s++) == 0) {		/* at string terminator */
	    break;
	} else if (ch == 'b') {			/* \b becomes backspace */
	    *cp++ = '\b';
	} else if (ch == 'f') {			/* \f becomes formfeed */
	    *cp++ = '\f';
	} else if (ch == 'n') {			/* \n becomes newline */
	    *cp++ = '\n';
	} else if (ch == 'r') {			/* \r becomes carriage ret */
	    *cp++ = '\r';
	} else if (ch == 's') {			/* \s becomes blank */
	    *cp++ = ' ';
	} else if (ch == 't') {			/* \t becomes tab */
	    *cp++ = '\t';
	} else {				/* \any becomes any */
	    *cp++ = '\\';	
	    *cp++ = ch; 
	}
    }
    if (write(sock, buf, cp - buf) <0) {
      report_and_drop_socket(sock, errno);
    }
}
/* monitor_ports - watch for socket activity */

void monitor_ports(wait)
int     wait;
{
    static struct timeval arc_fw_wait;
    static struct timeval arc_go_wait;
    static struct timeval arc_no_wait;
    static time_t arc_t;
    int     sock;
    char    ch;
    int     sel_err;

    arc_fw_wait = fw_wait;
    arc_go_wait = go_wait;
    arc_no_wait = no_wait;

    if (banner_info == 0) {
	/*
	 * When a connect() completes, report the socket and get rid of it.
	 */
	write_mask = write_socket_mask;
	read_mask = read_socket_mask;

       if (fw_wait.tv_sec > 0) {
	 if (sel_err=select(max_sock + 1, &read_mask, &write_mask, (fd_set *) 0,
                   wait ? &arc_fw_wait : &arc_no_wait) < 0)
	    error("select: %m");
         arc_t=time(NULL);
       }
       else
	if (sel_err=select(max_sock + 1, &read_mask, &write_mask, (fd_set *) 0,
		   wait ? (struct timeval *) 0 : &arc_no_wait) < 0)
	    error("select: %m");
	if (FD_ISSET(icmp_sock, &read_mask))
        {
	    receive_icmp(icmp_sock);
        }
	for (sock = 0; ports_busy > 0 && sock <= max_sock; sock++) {
	    if (FD_ISSET(sock, &write_mask)) {
		if (read(sock, &ch, 1) < 0 && errno != EWOULDBLOCK && errno != EAGAIN) {
		    report_and_drop_socket(sock, errno);
		} else {
		    report_and_drop_socket(sock, 0);
		}
	    }
           if (fw_wait.tv_sec > 0) {
              if (s_ttl[sock] > 0) {
                 if ((arc_t - s_ttl[sock]) > fw_wait.tv_sec) {
                    report_and_drop_socket(sock, ETIMEDOUT);
                 }
              }
           }
	}
    } else {

	/*
	 * When a connect() completes, try to receive some data within
	 * banner_time seconds. Assume we have received all banner data when
	 * a socket stops sending for BANNER_IDLE seconds.
	 */
	write_mask = write_socket_mask;
	read_mask = read_socket_mask;
	if (sel_err=select(max_sock + 1, &read_mask, &write_mask, (fd_set *) 0,
		   wait ? &arc_go_wait : &arc_no_wait) < 0)
	    error("select: %m");
	if (FD_ISSET(icmp_sock, &read_mask))
	    receive_icmp(icmp_sock);
	gettimeofday(&now, (struct timezone *) 0);
        arc_t = time(NULL);
	for (sock = 0; ports_busy > 0 && sock <= max_sock; sock++) {
	    if (sock == icmp_sock)
		continue;
	    if (FD_ISSET(sock, &write_mask)) {
		FD_CLR(sock, &write_socket_mask);
		FD_SET(sock, &read_socket_mask);
		banner_info[sock].connect_time = now;
                s_ttl[sock]=0;
		if (send_string)
		    do_send_string(sock);
	    } else if (FD_ISSET(sock, &read_mask)) {
		switch (read_socket(sock)) {
		case -1:
		    if (errno != EWOULDBLOCK && errno != EAGAIN)
			report_and_drop_socket(sock, errno);
		    break;
		case 0:
		    report_and_drop_socket(sock, 0);
		    break;
		}
	    } else if (FD_ISSET(sock, &read_socket_mask)) {
		if (time_since_connect(sock) > banner_time
		    || time_since_read(sock) > BANNER_IDLE)
		    report_and_drop_socket(sock, 0);
	    }
            if (fw_wait.tv_sec > 0)
               if (s_ttl[sock] > 0)
               {
                 if ((arc_t - s_ttl[sock]) > fw_wait.tv_sec)
                    report_and_drop_socket(sock, ETIMEDOUT);
               }
	}
    }
}

/* scan_ports - scan ranges of ports */

void scan_ports(service)
char   *service;
{
    char   *cp;
    int     min_port;
    int     max_port;
    int     port;
    int     sock;

    /*
     * Translate service argument to range of port numbers.
     */
    if ((cp = strchr(service, '-')) != 0) {
	*cp++ = 0;
	min_port = (service[0] ? ntohs(find_port(service, "tcp")) : 1);
	max_port = (cp[0] ? ntohs(find_port(cp, "tcp")) : 65535);
    } else {
	min_port = max_port = ntohs(find_port(service, "tcp"));
    }

    /*
     * Iterate over each port in the given range. Try to keep as many sockets
     * open at the same time as possible. Gradually increase the number of
     * probes so that they will be spread in time.
     */
    for (port = min_port; port <= max_port; port++) {
	if (verbose)
	    remark("connecting to port %d", port);
	sin.sin_port = htons(port);
	while ((sock = socket(sin.sin_family, SOCK_STREAM, 0)) < 0) {
               remark("socket: %m");
            monitor_ports(WAIT);
        }
 
	add_socket(sock, port);
	non_blocking(sock, YES);
	if (connect(sock, (struct sockaddr *) & sin, sizeof(sin)) < 0
	    && errno != EINPROGRESS) {
	    report_and_drop_socket(sock, errno);
	    continue;
	}
        if (fw_wait.tv_sec > 0) {
           s_ttl[sock] = time(NULL);
        }
        
	if (ports_busy < load_limit) {
	    monitor_ports(NOWAIT);
	} else {
	    while (ports_busy >= load_limit) {
		monitor_ports(WAIT);
            }
	}
    }
}



/* main - command-line interface */

main(argc, argv)
int     argc;
char   *argv[];
{
    int     c;
    struct protoent *pe;
    char  **ports;

    progname = argv[0];
    if (geteuid())
	error("This program needs root privileges");

    open_file_limit = open_limit();
    load_limit = open_file_limit - 10;
    banner_length = 0;

    while ((c = getopt(argc, argv, "abB:l:f:s:t:uUvw:")) != EOF) {
	switch (c) {
	case 'a':
	    show_all = 1;
	    break;
	case 'b':
	    if (banner_info == 0)
		banner_info = NEW(BANNER_INFO, open_file_limit);
	    break;
        case 'B':
            if ((banner_length = atoi(optarg)) <=0)
                usage("invalid banner length");
            break;
        case 'f':
	    if ((fw_wait.tv_sec = atoi(optarg)) <= 0)
		usage("firewall timeout not in range");
            fw_wait.tv_usec = 0;
            break;
	case 'l':
	    if ((load_limit = atoi(optarg)) <= 0)
		usage("invalid load limit");
	    if (load_limit > open_file_limit - 10)
		load_limit = open_file_limit - 10;
	    break;
	case 's':
	    send_string = optarg;
	    signal(SIGPIPE, SIG_IGN);
	    break;
 	case 't':
	    if ((response_time = atoi(optarg)) <= 0)
		usage("invalid timeout");
	    break;
	case 'u':
	    want_err = EHOSTUNREACH;
	    break;
	case 'U':
	    want_err = ~EHOSTUNREACH;
	    break;
	case 'v':
	    verbose = 1;
	    break;
	case 'w':
	    if ((banner_time = atoi(optarg)) <= 0)
		usage("invalid timeout");
	    break;
	default:
	    usage((char *) 0);
	    break;
	}
    }
    argc -= (optind - 1);
    argv += (optind - 1);
    if (argc < 3)
	usage("missing host or service argument");

    socket_to_port = NEW(int, open_file_limit);
    s_ttl = NEW(time_t, open_file_limit);
    memset(s_ttl, 0, sizeof(time_t) * open_file_limit);

    FD_ZERO(&write_socket_mask);
    FD_ZERO(&read_socket_mask);
    ports_busy = 0;

    /*
     * Allocate the socket to read ICMP replies.
     */
    if ((pe = getprotobyname("icmp")) == 0)
	error("icmp: unknown protocol");
    if ((icmp_sock = socket(AF_INET, SOCK_RAW, pe->p_proto)) < 0)
	error("icmp socket: %m");
    FD_SET(icmp_sock, &read_socket_mask);

    /*
     * Scan the ports.
     */
    memset((char *) &sin, 0, sizeof(sin));
    sin.sin_addr = find_addr(argv[1]);
    sin.sin_family = AF_INET;

    if (response_time > 0)
	alarm(response_time);

    for (ports = argv + 2; *ports; ports++)
	scan_ports(*ports);
    while (ports_busy > 0)
    {
	monitor_ports(WAIT);
    }

    return (0);
}


/* read_socket - read data from server */

read_socket(sock)
int     sock;
{
    BANNER_INFO *bp = banner_info + sock;
    unsigned char *cp;
    int     len;
    int     count;

    if (banner_length == 0) {
      banner_length = BANNER_LENGTH;
    }
    if (bp->buf == 0)
	bp->buf = (unsigned char *) mymalloc(banner_length);
    cp = bp->buf + bp->count;
    len = banner_length - bp->count;

    if (len == 0)
	return (0);

    bp->read_time = now;

    /*
     * Process banners with one-character reads so that we can detect telnet
     * options.
     */

    if ((count = read(sock, cp, 1)) == 1) {
	if (cp[0] == IAC) {
	    if ((count = read(sock, cp + 1, 2)) == 2) {
		if (cp[1] == WILL || cp[1] == WONT) {
		    cp[1] = DONT;
		    bp->flags |= F_TELNET;
		    write(sock, cp, 3);
		} else if (cp[1] == DO || cp[1] == DONT) {
		    cp[1] = WONT;
		    bp->flags |= F_TELNET;
		    write(sock, cp, 3);
		}
	    }
	} else {				/* cp[0] != IAC */
	    bp->count++;
	}
    }
    return (count);
}


/* time_since_read - how long since read() completed? */

time_since_read(sock)
int     sock;
{
    BANNER_INFO *bp = banner_info + sock;

    return (bp->count == 0 ? 0 : time_since(bp->read_time));
}

/* time_since_connect - how long since connect() completed? */

time_since_connect(sock)
int     sock;
{
    BANNER_INFO *bp = banner_info + sock;

    return (time_since(bp->connect_time));
}

