/*
 * dds $Revision: 1.6 $ - a distributed DoS tool scanner
 * 
 * Based on the gag scanner, written by David Dittrich, University
 * of Washington, Marcus Ranum, Network Flight Recorder, with
 * code contributed by others, and based on an idea stolen from
 * George Weaver, Pennsylvania State University.
 * 
 * Dave Dittrich <dittrich@cac.washington.edu>
 * Marcus Ranum <mjr@nfr.net>
 * George Weaver <gmw@psu.edu>
 * David Brumley <dbrumley@rtfm.stanford.edu>
 */

#if YOU_HAVE_NOT_READ_THIS_YET

This software should only be used in compliance with all applicable laws and
the policies and preferences of the owners of any networks, systems, or hosts
scanned with the software

The developers and licensors of the software provide the software on an "as
is" basis, excluding all express or implied warranties, and will not be liable
for any damages arising out of or relating to use of the software.

THIS SOFTWARE IS MADE AVAILABLE "AS IS", AND THE UNIVERSITY OF WASHINGTON
DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD TO THIS SOFTWARE,
INCLUDING WITHOUT LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE, AND IN NO EVENT SHALL THE UNIVERSITY OF
WASHINGTON BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, TORT (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING
OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  

#endif

#define VERSION "$Revision: 1.6 $"

#include <stdlib.h>
#include <ctype.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/ip_icmp.h>

#define BS 1024
#define __FAVOR_BSD

/* The two arrays below are for address range calculations.  They
   should have been automatically generated, but
   1) I am lazy.
   2) There are a few special cases in them.

   I will not scan more than a /16.  When we do scan a CIDR block, we
   assume that it actually is a CIDR block, and do not scan the
   network or broadcast address.

   */

static unsigned long MaskBits[] = {
  0x00000000,			/* /0 */
  0x00000000,			/* /1 */
  0x00000000,			/* /2 */
  0x00000000,			/* /3 */
  0x00000000,			/* /4 */
  0x00000000,			/* /5 */
  0x00000000,			/* /6 */
  0x00000000,			/* /7 */
  0x00000000,			/* /8 */
  0x00000000,			/* /9 */
  0x00000000,			/* /10 */
  0x00000000,			/* /11 */
  0x00000000,			/* /12 */
  0x00000000,			/* /13 */
  0x00000000,			/* /14 */
  0x00000000,			/* /15 */
  0xffff0000,			/* /16, Class B */
  0xffff8000,			/* /17, 128 * Class C */
  0xffffc000,			/* /18, 64 * Class C */
  0xffffe000,			/* /19, 32 * Class C */
  0xfffff000,			/* /20, 16 * Class C */
  0xfffff800,			/* /21, 8 * Class C */
  0xfffffc00,			/* /22, 4 * Class C */
  0xfffffe00,			/* /23, 2* Class C */
  0xffffff00,			/* /24, Class C */
  0xffffff80,			/* /25, 128 hosts */
  0xffffffc0,			/* /26, 64 hosts */
  0xffffffe0,			/* /27, 32 hosts */
  0xfffffff0,			/* /28, 16 hosts */
  0xfffffff8,			/* /29, 8 hosts */
  0xfffffffc,			/* /30, 4 hosts (PPP link) */
  0xfffffffe,			/* /31, invalid */
  0xffffffff,			/* /32, host */
};

static int NumHosts[] = {
  0, 0, 0, 0,
  0, 0, 0, 0,
  0, 0, 0, 0,
  0, 0, 0, 0,			/* don't scan more than a /16 */
  65534,			/* These are all -2 so that we don't
				   scan the broadcast addr or the
				   network addr */
  32766,
  16382,
  8190,
  4094,
  2046,
  1022,
  510,
  254,
  126,
  62,
  30,
  14,
  6,
  2,
  0,
  1,
};

extern	char		*optarg;

struct icmppkt_t {
	struct ip	ipi;
	struct icmp	icmpi;
	char		buffer[BS];
} icmppkt;

struct udppkt_t {
	struct ip	ipi;
	struct udphdr	udpi;
	char		buffer[BS];
} udppkt;

static unsigned short	ip_sum(u_short *,int);
static void		listener();
static int		usage();

static int		vflg = 0;	/* verbosity */
static int		dflg = 0;	/* debugging */

/* stacheldraht variables */
static int		stach_test = 668;	/* sends test */
static int		stach_echo = 669;	/* gets reply "sicken" */
char			stach_gagstr[] = "gesundheit!";
char 			stach_echostr[] = "sicken";

/* trinoo variables */
static short		trinoo_dstport = 27444;	/* handler listen port */
static short		trinoo_rctport = 31335;	/* agent listen port */
char 			trinoo_scmd[] = "png";
char 			trinoo_spass[] = "l44adsl";
char 			trinoo_echostr[] = "PONG";

/* TFN variables */
u_short			tfn_test = 789;
u_short			tfn_reply = 123;

int 
main(int argc, char **argv)
{
	int             pid, host;
	char            target[128];
	unsigned long	target_host;
	struct in_addr  target_ip;
	int		mask;
	char *		mask_ptr;
	int		result;
	int		isock, usock;
	char            buf[BS];
	struct icmp    *icmpi = (struct icmp *)buf;
	struct sockaddr_in
			isa,usa;
	int             i;
	char		*jnk1;
	char		*jnk2;
	int		sleepytime = 500;
	int		bigsleep = 30;
	int		num_hosts;
	char		scmd[BS], spass[BS], sbuf[BS];


	while((i = getopt(argc,argv,"ds:S:v")) != -1) {
		switch(i) {
		case 'd':
			dflg++;
			break;
		case 's':
			sleepytime = atoi(optarg);
			if(sleepytime <= 0) {
				fprintf(stderr,"WARNING: zero interping sleep time will probably overflow your system's transmit buffers and yield poor results\n");
				sleepytime = 1;
			}
			break;
		case 'S':
			bigsleep = atoi(optarg);
			if(bigsleep <= 0) {
				fprintf(stderr,"WARNING: negative sleep value - staying with default of %d\n", bigsleep);
			}
			break;
		case 'v':
			vflg++;
			break;
		default:
			exit(usage());
		}
	}

	if(optind >= argc || argc - optind > 1)
		exit(usage());

	mask_ptr = strchr(argv[optind], '/');

	/* if a CIDR block is passed in */
	if (mask_ptr) {
	  *mask_ptr = '\0';
	  mask_ptr ++;
	  
	  sscanf(mask_ptr, "%d", &mask);
	  
	} else {
	  printf("No mask passed, assuming host scan (/32)\n");
	  mask = 32;
	}

		 
	result = inet_aton(argv[optind], &target_ip);

	if (result == 0) {
	  fprintf(stderr, "%s: Bad IP address: %s\n", argv[0],
		  argv[optind]);
	  exit(-1);
	}

	if (mask < 16) {
	  fprintf(stderr, "Bad Network Admin!  Bad!  Do not scan more than a /16 at once!\n");
	  exit(-1);
	}

	num_hosts = NumHosts[mask];

	if (num_hosts == 0) {
	  fprintf(stderr, "Cannot scan a /%d.  Exiting...\n", mask);
	  exit(-1);
	}
	
	if(vflg) {
	  printf("Mask: %d\n", mask);	
	  printf("Target: %s\n", inet_ntoa(target_ip));
	  printf("dds %s - scanning...\n\n", VERSION);
	}

	sprintf(sbuf,"%s %s",trinoo_scmd,trinoo_spass);

	target_host = ntohl(target_ip.s_addr);
	target_host &= MaskBits[mask];

	target_ip.s_addr = htonl(target_host);

	if((pid = fork()) < 0) {
		perror("cannot fork");
		exit(1);
	}

	/* child side listens for return packets */
	if (pid == 0)
		listener();

	sleep(1);
	/* let's see if we can open a raw ICMP socket */
	if((isock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
		perror("cannot open raw ICMP socket");
		exit(1);
	}

	/* main ping loop - COULD be expanded to whole Internet but... */
	/* but that would be _very_ bad.... */
	while (num_hosts) {
	  if (mask != 32) {
	    target_host ++;
	  }
	  target_ip.s_addr = htonl(target_host);

	  num_hosts--;

	  if(vflg)
	    printf("Probing address %s\n", inet_ntoa(target_ip));
	  
			bzero(buf, sizeof(struct icmp) +
				sizeof(stach_gagstr));
			memcpy(buf + sizeof(struct icmp), stach_gagstr,
				sizeof(stach_gagstr));
			/* stacheldraht check */
			icmpi->icmp_type = 0;
			icmpi->icmp_hun.ih_idseq.icd_id =
				htons(stach_test);
			icmpi->icmp_cksum = ip_sum((u_short *)icmpi,
				sizeof(struct icmp) + sizeof(stach_gagstr));

			bzero((char *) &isa, sizeof(isa));
			isa.sin_family = AF_INET;
			isa.sin_addr.s_addr = target_ip.s_addr;

			if(dflg)
				fprintf(stderr,"Sending ICMP to: %s\n",
					inet_ntoa(isa.sin_addr));

			i = sendto(isock,buf,
				sizeof(struct icmp)+sizeof(stach_gagstr),0,
				(struct sockaddr *)&isa, sizeof(isa));

			if (i < 0) {
				char ebuf[BS];
				sprintf(ebuf,"sendto: icmp %s",
					inet_ntoa(isa.sin_addr));
				perror(ebuf);
				break;
			}

			/* tfn check */
			bzero(buf, sizeof(struct icmp) + sizeof(stach_gagstr));
			
			if(dflg)
				fprintf(stderr,"Sending tfn ICMP to: %s\n",
					inet_ntoa(isa.sin_addr));
			icmpi->icmp_type = ICMP_ECHOREPLY;
			icmpi->icmp_code= icmpi->icmp_seq = 0;
			icmpi->icmp_id = htons(tfn_test);
			icmpi->icmp_cksum = ip_sum((u_short *)icmpi, 
						sizeof(struct icmp));
			i = sendto(isock, buf, sizeof(struct icmp), 0, 
				   (struct sockaddr *)&isa, sizeof(isa));
			if(i != sizeof(struct icmp)){
				perror("Error sending full tfn packet\n");
				break;
			}

			/* trinoo check */
			bzero((char *) &usa, sizeof(usa));
			usa.sin_family = AF_INET;
			usa.sin_addr.s_addr = target_ip.s_addr;
			usa.sin_port = htons(trinoo_dstport);

			if (dflg)
				fprintf(stderr,"Sending UDP to: %s\n",
					inet_ntoa(usa.sin_addr));
			if ((usock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
				perror("cannot open UDP socket");
				exit(1);
			}

			i = sendto(usock,sbuf,strlen(sbuf), 0,
				(struct sockaddr *)&usa,
				sizeof(usa));

			if (i < 0) {
				char ebuf[BS];
				sprintf(ebuf,"sendto: udp %s",
					inet_ntoa(usa.sin_addr));
				perror(ebuf);
				break;
			}
			close(usock);

			usleep(sleepytime);
		}
	(void)close(isock);


	/* wait for any late responses */
	if (dflg)
		fprintf(stderr,"Waiting %d seconds for late responses.\n",
			bigsleep);
	sleep(bigsleep);

	/* shut listener. if this fails the listener exits on its own */
	(void)kill(pid, SIGHUP);
	exit(0);
}


static	void	listener()
{
	int             isock, usock;
	int             i, len;
	fd_set          fdset;
	char		buf[BS];
	char		rcmd[BS], filler[BS], rpass[BS];
	struct timeval  timi;
	struct icmppkt_t
			ipacket;
	struct udppkt_t
			upacket;
	struct sockaddr_in
			sa, from;

	/* child becomes a listener process */

	if ((isock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
		perror("cannot open raw ICMP socket");
		exit(1);
	}
	if ((usock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		perror("cannot open raw UDP listen socket");
		exit(1);
	}

	bzero((char *) &sa, sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_addr.s_addr = INADDR_ANY;
	sa.sin_port = htons(trinoo_rctport);

	if (bind(usock, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
		perror("cannot bind to socket");
		exit(-1);
	}
  
	while (1) {
		/* if parent has exitted, die */
		if(getppid() == 1)
			exit(0);

		FD_ZERO(&fdset);
		FD_SET(isock, &fdset);
		FD_SET(usock, &fdset);
		timi.tv_sec = 1;
		timi.tv_usec = 0;
		select(FD_SETSIZE, &fdset, NULL, NULL, &timi);
		usleep(100);
		if (FD_ISSET(isock, &fdset)) {
			/* read data from ICMP listen socket */
			memset((void *) &ipacket, 0, sizeof(struct icmppkt_t));
			i = read (isock, (char *) &ipacket, BS) -
				(sizeof (struct ip) + sizeof (struct icmp));
			sa.sin_addr.s_addr = ipacket.ipi.ip_src.s_addr;
			if(dflg)
				fprintf(stderr,"Listener got an ICMP packet\n");

			/* stacheldraht check */
			if ((ipacket.icmpi.icmp_type == ICMP_ECHOREPLY) &&
		 	   (ntohs(ipacket.icmpi.icmp_hun.ih_idseq.icd_id)
				== stach_echo)) {
				if (strstr(ipacket.buffer, stach_echostr)) {
					printf("Received '%s' from %s",
						stach_echostr,
						inet_ntoa(sa.sin_addr));
					printf(" - probable stacheldraht agent\n");
				}
				else {
					printf("Unexpected ICMP packet from %s\n",
						inet_ntoa(sa.sin_addr));
				}
			}

			/* TFN Check */
			if ((ipacket.icmpi.icmp_type == ICMP_ECHOREPLY) &&
			   (ntohs(ipacket.icmpi.icmp_hun.ih_idseq.icd_id) == 
				tfn_reply)) {
				printf("Received TFN Reply from %s",
 					inet_ntoa(sa.sin_addr));
				printf(" - probable tfn agent\n");
			}
			
		}

		if (FD_ISSET (usock, &fdset)) {
			/* read data from UDP listen socket */
			memset((void *) &upacket, 0, sizeof(struct udppkt_t));
			len = sizeof(from);
#if 1
			if ((i = recvfrom(usock, buf, BS, 0,
				(struct sockaddr *) &from, &len)) < 0) {
				perror("recvfrom");
				continue;
			}
#else
			i = read (usock, (char *) buf, BS) -
				(sizeof (struct ip) + sizeof (struct udphdr));
#endif
			sa.sin_addr.s_addr = upacket.ipi.ip_src.s_addr;
			if(dflg)
				fprintf(stderr,
					"Listener got a UDP packet on port %s\n",
					trinoo_rctport);

			/* trinoo check */
			if (strstr(buf,trinoo_echostr)) { 
				printf("Received '%s' from %s",
					trinoo_echostr,
					inet_ntoa(from.sin_addr));
				printf(" - probable trinoo agent\n");
			}
			else {
				printf("Unexpected UDP packet received on port %d from %s\n",
					trinoo_rctport, inet_ntoa(from.sin_addr));
			}
		}
	}
}


/* standard IP checksum */
static unsigned short
ip_sum(u_short *addr, int len)
{
	register int    nleft = len;
	register u_short *w = addr;
	register int    sum = 0;
	u_short         answer = 0;

	while (nleft > 1) {
		sum += *w++;
		nleft -= 2;
	}
	if (nleft == 1) {
		*(u_char *) (&answer) = *(u_char *) w;
		sum += answer;
	}
	sum = (sum >> 16) + (sum & 0xffff);
	sum += (sum >> 16);
	answer = ~sum;
	return (answer);
}



static int
usage()
{
	fprintf(stderr,"usage: dds [options] <target>\n");
	fprintf(stderr,"target is CIDR block to scan in form:\n");
	fprintf(stderr,"\tA.B.C.D/mask\n");
	fprintf(stderr,"Options:\n");
	fprintf(stderr,"\t[-v] turns on verbosity\n");
	fprintf(stderr,"\t[-d] turns on debugging\n");
	fprintf(stderr,"\t[-s] interpacket sleep in microseconds\n");
	fprintf(stderr,"\t[-S] delay for late packets\n");
	
	return(1);
}
