int ethernet_open (char *dev_name, device_t master_device, 
		   struct port_bucket *etherport_bucket,
		   struct port_class *etherreadclass)
{
  error_t err;

  assert (ether_port == MACH_PORT_NULL);

  err = ports_create_port (etherreadclass, etherport_bucket,
			   sizeof (struct port_info), &readpt);
  if (err)
    error (2, err, "ports_create_port");
  readptname = ports_get_right (readpt);
  mach_port_insert_right (mach_task_self (), readptname, readptname,
			  MACH_MSG_TYPE_MAKE_SEND);

  mach_port_set_qlimit (mach_task_self (), readptname, MACH_PORT_QLIMIT_MAX);

  err = device_open (master_device, D_WRITE | D_READ, "eth", &ether_port);
  mach_port_deallocate (mach_task_self (), master_device);
  if (err)
    error (2, err, "device_open: %s", dev_name);

  err = device_set_filter (ether_port, ports_get_right (readpt),
			   MACH_MSG_TYPE_MAKE_SEND, 0,
			   (unsigned short *)ether_filter, ether_filter_len);
  if (err)
    error (2, err, "device_set_filter: %s", dev_name);

  set_promisc (dev_name, ether_port, 1);
  return 0;
}
Example #2
0
File: rarpd.c Project: afett/rarpd
bool setup_link(struct link *link, void *aux)
{
	int fd = open_socket();
	if (fd < 0) {
		goto err;
	}

	if (do_bind(fd, link->ifindex) != 0) {
		goto err;
	}

	if (set_promisc(fd, link->ifindex) != 0) {
		goto err;
	}

	struct dispatcher *dispatcher = (struct dispatcher *) aux;
	link->handler = dispatcher_watch(
		dispatcher, fd, rarp_handler, link);
	dispatcher_flags(&link->handler, POLLIN);

	return true;
err:
	close(fd);
	XLOG_ERR("error setting up %s", link->name);
	return false;
}
Example #3
0
int main(int argc, char **argv)
{
	const char *options="c:i:";
	int opt_status=0;
	int pppoe_count=1;
	char *NIC_name;
	while((opt_status=getopt(argc,argv,options))!=-1)
		switch (opt_status) {
			case 'c':
				pppoe_count=atoi(optarg);
				break;
			case 'i':
				NIC_name=optarg;
				break;
			default:
				break;
		}
	//how many pppoe client to fork is determined!
	
	struct Connection_info infos[pppoe_count];
	memset(infos,0,sizeof(infos));
	//shuttles for pppoe infomations
	
	srand((unsigned int)getpid()); //ready for rand
	set_promisc(NIC_name); //set the NIC to be used promisc mode
	
	
	
	int count1;
	for(count1=0;count1<pppoe_count;++count1) {
		infos[count1].ifindex=get_ifindex(NIC_name); //get the ifindex of NIC
		infos[count1].my_mac[0]=0x11;
		infos[count1].my_mac[1]=0x22;
		infos[count1].my_mac[2]=0x33;
		int loop_count;
		for(loop_count=3;loop_count<6;++loop_count) {
		infos[count1].my_mac[loop_count]=(int)(rand()/(float)RAND_MAX*255);
		}
		//src mac of package done!
		infos[count1].discovery_sock=socket(AF_PACKET,SOCK_RAW,htons(ETHER_TYPE_DISCOVERY));
		if(infos[count1].discovery_sock<0) {
			printf("error in creating discovery socket\n%s\n",strerror(errno));
			exit(1);
		}
		//discovery socket's ready!
		sendPADI(&infos[count1]);
		recv_PADO(&infos[count1]);
		sendPADR(&infos[count1]);
		recv_PADS(&infos[count1]);
		if(fork()==0) {
			session(&infos[count1]);
		}
		printf("client %i is forked!\n",count1+1);
		sleep(1);
	}
	return 0;
}
Example #4
0
int main(int argc, char **argv)
{
get_sys_info(f[0],10);
usleep(600000);

 size_mac=sizeof(struct ether_header);
 size_ip=sizeof(struct ip);
///////////////////////////////////

signal(SIGINT, sigproc);
  signal(SIGTERM, sigproc);
  signal(SIGINT, sigproc);

//perror("what's wrong\n");
//init_loop(&shmp,&shmid,shmpath);
//init_loop(&shmp,&shmid,shmpath1);
int i;
char buf[256];
initBCBuff();
printf("1111111111111111\n");
for(i=0;i<snortnum;++i)//create shm
{
losep[i]=0LL;
	sprintf(buf,"%s",shmpath);
	//puts(buf);
	init_loop(&shmp[i],&shmid[i],buf,i);
}
hb=init_HB(HB_MAX);
	init_free_link(FREE_NODE);
	init_BC();//the cache for the pro classificationd
	printf("EIinit bc\n");
	init_patterns();
int sockfd;
struct pcap_pkthdr pkthdr;
   if ((sockfd = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL))) < 0)
   {
       printf ("create socket failed\n");
       return -1;
   }

   if (0 != set_promisc ("eth0", sockfd))
   {
       printf ("Failed to set interface promisc mode\n");
   }
unsigned char buffer[65535] = {0};
   while (1)
   {
   	
   			//memset (&packet, 0x0, sizeof (packet));
        memset (buffer, 0x0, sizeof (buffer));
       pkthdr.caplen = recvfrom (sockfd, buffer, sizeof (buffer), 0, NULL, NULL);
      my_callback(NULL,&pkthdr,buffer);
		}

  return 0;
}
/*----------------------------------------------------------------------------*/
void
netmap_load_module_lower_half(void)
{
	struct netdev_entry **ent;
	int j;

	ent = g_config.mos->netdev_table->ent;
	
	for (j = 0; j < g_config.mos->netdev_table->num; j++) {
		set_promisc(ent[j]->dev_name);		
	}
}
Example #6
0
void mb8795_device::device_reset()
{
	txstat = EN_TXS_READY;
	txmask = 0x00;
	rxstat = 0x00;
	rxmask = 0x00;
	txmode = 0x00;
	rxmode = 0x00;

	drq_tx = drq_rx = false;
	irq_tx = irq_rx = false;

	txlen = rxlen = txcount = 0;

	set_promisc(true);

	start_send();
}
Example #7
0
void
setup_receiver(struct receiver_arg* arg, int* s, unsigned char** payload,
	       int payload_len, struct msghdr* msg, struct iovec* entry,
	       struct control* control, struct sockaddr_in* from_addr)
{
    arg->inf_index = inf_to_index(arg->dev);
    arg->send_sfd = create_sending_socket(arg->dev, &(arg->sk));

    *payload = malloc(payload_len);
    if (NULL == payload){
	printf("malloc failed\n");
	exit(1);
    }
    memset(*payload, 0, payload_len);

    *s = create_recv_rawsocket_ts(arg->dev);
    set_promisc(arg->dev, *s);
    setup_raw_msghdr(msg, entry,
                    control, *payload,
                    payload_len, from_addr);
}
Example #8
0
void threecom3c505_device::device_reset()
{
	LOG1(("reset 3COM 3C505"));

	m_rx_fifo.reset();
	m_rx_data_buffer.reset();
	m_tx_data_buffer.reset();
	m_program_buffer.reset();

	memset(m_reg, 0, sizeof(m_reg));
	m_status = HCRE | DIR_;
	m_control = 0;
	m_command_index = 0;
	m_command_pending = 0;
	m_wait_for_nak = 0;
	m_wait_for_ack = 0;
	m_rx_data_index = 0;
	m_rx_pending = 0;
	m_tx_data_length = 0;
	m_response_length = 0;
	m_response_index = 0;
	m_microcode_running = 0;
	m_microcode_version = 0;
	m_i82586_config = 0;

	// these will appear in /etc/nodestat -l
	m_netstat.tot_recv = 0;
	m_netstat.tot_xmit = 0;
	m_netstat.err_CRC = 0;
	m_netstat.err_align = 0;
	m_netstat.err_res = 0;
	m_netstat.err_ovrrun = 0;

	memset(m_station_address, 0, sizeof(m_station_address));
	memset(m_multicast_list, 0, sizeof(m_multicast_list));
	set_filter_list();
	set_promisc(true);
}
Example #9
0
void threecom3c505_device::device_reset()
{
	LOG1(("reset 3COM 3C505"));

	m_rx_fifo.reset();
	m_rx_data_buffer.reset();
	m_tx_data_buffer.reset();
	m_program_buffer.reset();

	memset(m_reg, 0, sizeof(m_reg));
	m_status = HCRE;
	m_control = 0;
	m_command_index = 0;
	m_command_pending = 0;
	m_mc_f9_pending = 0;
	m_wait_for_ack = 0;
	m_rx_data_index = 0;
	m_rx_pending = 0;
	m_tx_data_length = 0;
	m_response_length = 0;
	m_response_index = 0;
	m_microcode_running = 0;
	m_microcode_version = 0;
	m_i82586_config = 0;

	// FIXME: test data
	m_netstat.tot_recv = 1;
	m_netstat.tot_xmit = 2;
	m_netstat.err_CRC = 3;
	m_netstat.err_align = 4;
	m_netstat.err_res = 5;
	m_netstat.err_ovrrun = 6;

	memset(m_station_address, 0 , sizeof(m_station_address));
	memset(m_multicast_list, 0 , sizeof(m_multicast_list));
	set_filter_list();
	set_promisc(true);
}
Example #10
0
int main(int argc, char *argv[]) {
  struct sockaddr_in addr;
  struct ether_header *peth;    //以太网帧报头指针
  struct ether_arp *parph;      //ARP报头
  struct ip *pip;
  struct iphdr *piph;           //IP头结构

  Boolean noopt = FALSE;        //记录程序执行是否带有命令行参数,没有则按照默认参数配置执行

  int cmd_option_protocol = DEFAULTPROTO_ALL; //在主函数中使用局部变量代替全局变量opts,
                                //一是为了书写方便,
                                //二是避免全局变量的使用,虽然opts在赋值后应该不会再有代码修改它,但是为了以防万一.
  unsigned long cmd_option_interval = 10;  //记录输出链表内容的次数间隔
  unsigned long count = 0;      //记录抓包的次数

  int sock;                     //建立socket连接
  int r;                        //recv返回值
  int len;                      //sizeof(addr),取地址用于recv中
  char *ptemp;                  //重要的指针!
  unsigned int ptype;           //判断层次协议类型变量(如ARP或者IP)
  int ret = 0;

  struct sigaction sig_interrupt_action;
  struct sigaction sig_alarm_action;

  head = tail = search = NULL;  //初始化链表指针

  memset(buf, 0, MAXPACKBUFF);

  //判断参数合法性
  get_command_line_option(argc, argv, &noopt);

  //输出参数分析的最终结果
  if (TRUE == noopt) {
    printf("\nNo option got, use default value:\n");
  }
  else if (FALSE == noopt) {
    printf("\nCommand line options list below:\n");
  }

  printf("protocol:%d    \n", opts[0].rightopt.protocol);
  printf("cmd_option_interval:%ld    \n", opts[1].rightopt.interval);
  printf("count:%ld\n", opts[2].rightopt.endcount);
  printf("display:%d\n", opts[3].rightopt.print_data);
  printf("\n");

  cmd_option_protocol = opts[0].rightopt.protocol;
  cmd_option_interval = opts[1].rightopt.interval;
  count = 0;
  len = sizeof(addr);

  //设置中断信号的信号处理
  sig_interrupt_action.sa_handler = before_interupt;
  sigemptyset(&sig_interrupt_action.sa_mask);
  sig_interrupt_action.sa_flags = 0;
  sigaddset(&sig_interrupt_action.sa_mask, SIGINT);

  //设置无包抓到时的信号处理
  sig_alarm_action.sa_handler = print_msg_while_catch_nothing;
  sigemptyset(&sig_alarm_action.sa_mask);
  sig_alarm_action.sa_flags = 0;
  sigaddset(&sig_alarm_action.sa_mask, SIGALRM);

  //建立原始套接字socket
  if ((sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) {
    print_msg_for_last_errno("socket", 1);
  }

  //设置网卡eth0为混杂模式,并执行system查看结果,eth0为网卡名称
  set_promisc("eth0", sock);
  // Just get ret to avoid compile warning, like:
  // 警告: 忽略声明有 warn_unused_result 属性的‘system’的返回值 [-Wunused-result]
  ret = system("ifconfig");

  for (;;) {
    alarm(1);
    //每次循环建立信号处理
    if (sigaction(SIGALRM, &sig_alarm_action, NULL ) < 0) {
      printf("signal SIGIALRM error!\n");
      exit(1);
    }

    if (sigaction(SIGINT, &sig_interrupt_action, NULL ) < 0) {
      printf("signal SIGINT error!\n");
      exit(1);
    }

    //输出语句判断是否抓到包
    if ((r = recvfrom(sock, (char *) buf, sizeof(buf), 0,
        (struct sockaddr *) &addr, &len)) <= 0) {
      //为了输出'.',和print_msg_while_catch_nothing中的else把catch_count_in_alarm
      //置0是双重保险.
      catch_count_in_alarm = 0;
      continue;
    }


    ptemp = buf;                            //初始化指针ptemp
    peth = (struct ether_header *) ptemp;
    ptype = ntohs(peth->ether_type);        //从以太网帧获得协议名称

    //Only print ARP/RARP if ALLPROTOCOL | DEFAULTPROTO_ALL
    if (((ptype == ETHERTYPE_ARP) || (ptype == ETHERTYPE_REVARP))
        && ((cmd_option_protocol == ALLPROTOCOL)
            || (cmd_option_protocol == DEFAULTPROTO_ALL))) {
      parph = (struct ether_arp *) (ptemp + sizeof(struct ether_header));
      catch_count_in_alarm++;
      printf("\n[%3ld] ", ++count);
      print_time();
      printf("Package total length:[%d Byte] ", r);
      print_arp_rarp(parph, ptype);
    }
    else if (ptype == ETHERTYPE_IP) {
      ptemp += sizeof(struct ether_header); //指针后移ether_header的长度,4字节
      pip = (struct ip *) ptemp;
      piph = (struct iphdr *) ptemp;        //piph指向ip层的头

      //ihl即IP header length
      //<<2相当于乘以4,为什么ptemp要移到ihl*4的位置?
      //哦也,对了!因为ihl是4bit,最大是二进制1111,即十进制15。
      //而每个1代表4Byte,所以IP包头的最大长度是15*4=60字节。
      //参见http://blog.csdn.net/achejq/article/details/7040687
      ptemp += (piph->ihl << 2);

      //根据不同协议判断指针类型
      if (piph->protocol == IPPROTO_TCP
          && (cmd_option_protocol == TCP
              || cmd_option_protocol == ALLPROTOCOL
              || cmd_option_protocol == DEFAULTPROTO_ALL)) {

        ret = search_and_add_node(piph, ptemp, (struct node **) &search,
            (struct node **) &head, (struct node **) &tail, r, IPPROTO_TCP);
        if (ret == -1) {
          printf("[ERR] search_and_add_node failed. Protocol: TCP.\n\n");
          exit(-1);
        }
        catch_count_in_alarm++;
        printf_ip_header(piph, ++count, r);
        printf_tcp(ptemp, piph, opts[3].rightopt.print_data);
      }
      else if (piph->protocol == IPPROTO_UDP
          && (cmd_option_protocol == UDP
              || cmd_option_protocol == ALLPROTOCOL
              || cmd_option_protocol == DEFAULTPROTO_ALL)) {
        ret = search_and_add_node(piph, ptemp, (struct node **) &search,
            (struct node **) &head, (struct node **) &tail, r, IPPROTO_UDP);
        if (ret == -1) {
          printf("[ERR] search_and_add_node failed. Protocol: UDP.\n\n");
          exit(-1);
        }
        catch_count_in_alarm++;
        printf_ip_header(piph, ++count, r);
        printf_udp(ptemp, piph, opts[3].rightopt.print_data);
      }
      else if (piph->protocol == IPPROTO_ICMP
          && (cmd_option_protocol == ICMP
              || cmd_option_protocol == ALLPROTOCOL
              || cmd_option_protocol == DEFAULTPROTO_ALL)) {
        ret = search_and_add_node(piph, ptemp, (struct node **) &search,
            (struct node **) &head, (struct node **) &tail, r, -1);
        if (ret == -1) {
          printf("[ERR] search_and_add_node failed. Protocol: ICMP.\n\n");
          exit(-1);
        }
        catch_count_in_alarm++;
        printf_ip_header(piph, ++count, r);
        printf("ICMP:%s \n", inet_ntoa(*(struct in_addr*) &(piph->saddr)));
      }
      else if (piph->protocol == IPPROTO_IGMP
          && (cmd_option_protocol == IGMP
              || cmd_option_protocol == ALLPROTOCOL
              || cmd_option_protocol == DEFAULTPROTO_ALL)) {
        ret = search_and_add_node(piph, ptemp, (struct node **) &search,
            (struct node **) &head, (struct node **) &tail, r, -1);
        if (ret == -1) {
          printf("[ERR] search_and_add_node failed. Protocol: IGMP.\n\n");
          exit(-1);
        }
        catch_count_in_alarm++;
        printf_ip_header(piph, ++count, r);
        printf("IGMP \n");
      }
      else if (cmd_option_protocol == ALLPROTOCOL
          || cmd_option_protocol == DEFAULTPROTO_ALL) {
        ret = search_and_add_node(piph, ptemp, (struct node **) &search,
            (struct node **) &head, (struct node **) &tail, r, -1);
        if (ret == -1) {
          printf("[ERR] search_and_add_node failed. Protocol: Unknown.\n\n");
          exit(-1);
        }
        catch_count_in_alarm++;
        printf_ip_header(piph, ++count, r);
        printf("Unknown protocol %d\n", piph->protocol);
      }                   //end analyse, we can't go to next else.
//      else {
//
//      }
    } //else if (ptype == ETHERTYPE_IP) {       //如果是IP协议数据包
    else if (cmd_option_protocol == ALLPROTOCOL
        || cmd_option_protocol == DEFAULTPROTO_ALL) {
      catch_count_in_alarm++;
      count++;
      printf("\nUnknown package,protocol type:%d\n", ptype);
    }

    //判断interval参数
    if ((cmd_option_interval != 0)
        && (count % cmd_option_interval == 0)) {
      // Only traversal_list if we caught package (that is count !=0) and
      // the package match the protocol we specified.
      if (count != 0
          && ((piph->protocol == (cmd_option_protocol)
              || (cmd_option_protocol == ALLPROTOCOL)
              || (cmd_option_protocol == DEFAULTPROTO_ALL)))) {
        traversal_list(head, search);
        have_traversal_list_by_interval = TRUE;
      }
    }
    //判断endcount参数
    if ((opts[2].rightopt.endcount > 0)
        && (count == opts[2].rightopt.endcount)) {
      if (!have_traversal_list_by_interval) {
        traversal_list(head, search);
        have_traversal_list_by_endcount = TRUE;
        exit(0);
      }
      else {
        have_traversal_list_by_endcount = TRUE;
        //If go to here, means we have run traversal_list, now just need exit.
        exit(0);
      }
    }
    //sleep(1);
    have_traversal_list_by_interval = FALSE;
    have_traversal_list_by_endcount = FALSE;
  }//end for(;;)

  printf("\n");

}
Example #11
0
int main(int argc, char *argv[])
{
	int get_tmp = 1, get_cmd;

	if(argc < 3) {
		print_help(argv[0]);
		exit(2);
	}

	int option_index = 0;
	static struct option long_options[] = {
		{ "mac", required_argument, 0, 'm' },
		{ "interface", required_argument, 0, 'i' },
		{ "vlan", required_argument, 0, 'v' },
		{ "dhcp_xid", required_argument, 0, 'x' },
		{ "tos", required_argument, 0, 't' },
		{ "option51-lease_time", required_argument, 0, 'L' },
		{ "option50-ip", required_argument, 0, 'I' },
		{ "option60-vci", required_argument, 0, 'o' },
		{ "option12-hostname", required_argument, 0, 'h' },
		{ "timeout", required_argument, 0, 'T' },
		{ "bind-ip", no_argument, 0, 'b' },
		{ "bind-timeout", required_argument, 0, 'k' },
		{ "bcast_flag", no_argument, 0, 'f'},
		{ "verbose", no_argument, 0, 'V'},
		{ "fqdn-server-not-update", no_argument, 0, 'n'},
		{ "fqdn-server-update-a", no_argument, 0, 's'},
		{ "fqdn-domain-name", required_argument, 0, 'd'},
		{ "padding", no_argument, 0, 'p'},
		{ "port", required_argument, 0, 'P'},
		{ "giaddr", required_argument, 0, 'g'},
		{ "unicast", optional_argument, 0, 'u'},
		{ "nagios", no_argument, 0, 'a'},
		{ "server", required_argument, 0, 'S'},
		{ "release", no_argument, 0, 'r'},
		{ 0, 0, 0, 0 }
	};

	/*getopt routine to get command line arguments*/
	while(get_tmp < argc) {
		get_cmd  = getopt_long(argc, argv, "m:i:v:t:bfVrpansu::T:P:g:S:I:o:k:L:h:d:",\
				long_options, &option_index);
		if(get_cmd == -1 ) {
			break;
		}
		switch(get_cmd) {
			case 'm':
				{
					u_char aux_dhmac[ETHER_ADDR_LEN + 1];

					if(strlen(optarg) > 18) {
						fprintf(stdout, "Invalid mac address\n");
						exit(2);
					}
					strcpy(dhmac_fname, optarg);
					sscanf((char *)optarg, "%2X:%2X:%2X:%2X:%2X:%2X",
							(u_int32_t *) &aux_dhmac[0], (u_int32_t *) &aux_dhmac[1],
							(u_int32_t *) &aux_dhmac[2], (u_int32_t *) &aux_dhmac[3],
							(u_int32_t *) &aux_dhmac[4], (u_int32_t *) &aux_dhmac[5]);
					memcpy(dhmac, aux_dhmac, sizeof(dhmac));
					dhmac_flag = 1;
				}
				break;

			case 'i':
				iface = if_nametoindex(optarg);
				if(iface == 0) {
					fprintf(stdout, "Interface doesnot exist\n");
					exit(2);
				}
				strncpy(iface_name, optarg, 29);
				break;

			case 'v':
				if(atoi(optarg) < 1 || atoi(optarg) > 4095)
				{
					fprintf(stdout, "VLAN ID is not valid. Range 1 to 4095\n");
					exit(2);
				}
				vlan = atoi(optarg);
				l2_hdr_size = 18;
				break;

			case 'r':
				dhcp_release_flag = 1;
				break;

			case 'b':
				ip_listen_flag = 1;
				break;

			case 'k':
				listen_timeout = atoi(optarg);
				tval_listen.tv_sec = listen_timeout;
				break;

			case 'x':
				{
					u_int32_t aux_dhcp_xid[2];
					aux_dhcp_xid[0] = 0;
					sscanf((char *)optarg, "%X", &aux_dhcp_xid[0]);
					dhcp_xid = aux_dhcp_xid[0];
				}
				break;

			case 't':
				if(atoi(optarg) >= 256 || atoi(optarg) < 0) {
					fprintf(stdout, "Invalid TOS value\n");
					exit(2);
				}
				l3_tos = atoi(optarg);
				break;

			case 'L':
				option51_lease_time = atoi(optarg);
				break;

			case 'I':
				option50_ip = inet_addr(optarg);
				break;

			case 'o':
				if(strlen(optarg) > 256) {
					fprintf(stdout, "VCI string size should be less than 256\n");
					exit(2);
				}
				vci_flag = 1;
				memcpy(vci_buff, optarg, sizeof(vci_buff));
				break;

			case 'h':
				if(strlen(optarg) > 256) {
					fprintf(stdout, "Hostname string size should be less than 256\n");
					exit(2);
				}
				hostname_flag = 1;
				memcpy(hostname_buff, optarg, sizeof(hostname_buff));
				break;

			case 'd':
				if(strlen(optarg) > 256) {
					fprintf(stdout, "FQDN domain name string size should be less than 256\n");
					exit(2);
				}
				fqdn_flag = 1;
				memcpy(fqdn_buff, optarg, sizeof(fqdn_buff));
				break;

			case 'n':
				fqdn_n = 1;
				break;

			case 's':
				fqdn_s = 1;
				break;

			case 'T':
				if(atoi(optarg) < 5 || atoi(optarg) > 3600) {
					fprintf(stdout, "Invalid timout value. Range 5 to 3600\n");
					exit(2);
				}
				timeout = atoi(optarg);
				break;

			case 'P':
				if(atoi(optarg) <=0 || atoi(optarg) > 65535) {
					fprintf(stdout, "Invalid portt value. Range 1 to 65535\n");
					exit(2);
				}
				port = atoi(optarg);
				break;

			case 'g':
				giaddr = optarg;
				break;

			case 'S':
				server_addr = optarg;
				break;

			case 'p':
				padding_flag = 1;
				break;

			case 'f':
				bcast_flag = htons(0x8000);
				break;

			case 'V':
				verbose = 1;
				break;

			case 'u':
				if (optarg) {
					struct in_addr out;

					if (!inet_aton(optarg, &out)) {
						fprintf(stdout, "Invalid unicast IP address.");
						exit(2);
					}
					unicast_ip_address = out.s_addr;
				}
				unicast_flag = 1;
				break;

			case 'a':
				nagios_flag = 1;
				break;

			default:
				exit(2);
		}
		get_tmp++;
	}	

	if(!dhmac_flag) {
		print_help(argv[0]);
		exit(2);
	}
	/* Opens the PF_PACKET socket */
	if(open_socket() < 0) {
		if (nagios_flag)
			fprintf(stdout, "CRITICAL: Socket error.");
		else
			fprintf(stdout, "Socket error\n");
		exit(2);
	}

	/* Sets the promiscuous mode */
	set_promisc();

	if (unicast_flag && !unicast_ip_address) {
		unicast_ip_address = get_interface_address();
	}

	/* Sets a random DHCP xid */
	set_rand_dhcp_xid(); 

	/*
	 * If DHCP release flag is set, send DHCP release packet
	 * and exit. get_dhinfo parses the DHCP info from log file
	 * and unlinks it from the system
	 */
	if(dhcp_release_flag) {
		if(get_dhinfo() == ERR_FILE_OPEN) {
			if (nagios_flag) {
				fprintf(stdout, "CRITICAL: Error on opening DHCP info file.");
			} else {
				fprintf(stdout, "Error on opening DHCP info file\n");
				fprintf(stdout, "Release the DHCP IP after acquiring\n");
			}
			exit(2);
		}
		build_option53(DHCP_MSGRELEASE); /* Option53 DHCP release */
		if(hostname_flag) {
			build_option12_hostname();
		}
		if(fqdn_flag) {
			build_option81_fqdn();
		}
		build_option54();		 /* Server id */
		build_optioneof();		 /* End of option */
		build_dhpacket(DHCP_MSGRELEASE); /* Build DHCP release packet */
		send_packet(DHCP_MSGRELEASE);	 /* Send DHCP release packet */
		clear_promisc();		 /* Clear the promiscuous mode */
		close_socket();
		return 0; 
	}
	if(timeout) {
		time_last = time(NULL);
	}
	build_option53(DHCP_MSGDISCOVER);	/* Option53 for DHCP discover */
	if(hostname_flag) {
		build_option12_hostname();
	}
	if(fqdn_flag) {
		build_option81_fqdn();
	}
	if(option50_ip) {
		build_option50();		/* Option50 - req. IP  */
	}
	if(option51_lease_time) {
		build_option51();               /* Option51 - DHCP lease time requested */
	}

	if(vci_flag == 1) {
		build_option60_vci(); 		/* Option60 - VCI  */
	}
	build_optioneof();			/* End of option */
	build_dhpacket(DHCP_MSGDISCOVER);	/* Build DHCP discover packet */

	int dhcp_offer_state = 0;
	while(dhcp_offer_state != DHCP_OFFR_RCVD) {

		/* Sends DHCP discover packet */
		send_packet(DHCP_MSGDISCOVER);
		/*
		 * recv_packet functions returns when the specified 
		 * packet is received
		 */
		dhcp_offer_state = recv_packet(DHCP_MSGOFFER); 

		if(timeout) {
			time_now = time(NULL);
			if((time_now - time_last) > timeout) {
				if (nagios_flag)
					fprintf(stdout, "CRITICAL: Timeout reached: DISCOVER.");
				close_socket();
				exit(2);
			}
		}
		if(dhcp_offer_state == DHCP_OFFR_RCVD) {
			if (!nagios_flag)
				fprintf(stdout, "DHCP offer received\t - ");
			set_serv_id_opt50();
			if (!nagios_flag)
  				fprintf(stdout, "Offered IP : %s\n", get_ip_str(dhcph_g->dhcp_yip));
			if(!nagios_flag && verbose) { 
				print_dhinfo(DHCP_MSGOFFER);
			}
		}
	}
	/* Reset the dhopt buffer to build DHCP request options  */
	reset_dhopt_size();
	build_option53(DHCP_MSGREQUEST); 
	build_option50();
	build_option54();
	if(hostname_flag) {
		build_option12_hostname();
	}
	if(fqdn_flag) {
		build_option81_fqdn();
	}
	if(vci_flag == 1) {
		build_option60_vci();  
	}
	if(option51_lease_time) {
		build_option51();                       /* Option51 - DHCP lease time requested */
	}
	build_option55();
	build_optioneof();
	build_dhpacket(DHCP_MSGREQUEST); 		/* Builds specified packet */
	int dhcp_ack_state = 1;
	while(dhcp_ack_state != DHCP_ACK_RCVD) { 

		send_packet(DHCP_MSGREQUEST);
		dhcp_ack_state = recv_packet(DHCP_MSGACK); 

		if(timeout) {
			time_now = time(NULL);
			if((time_now - time_last) > timeout) {
				if (nagios_flag)
					fprintf(stdout, "CRITICAL: Timeout reached: REQUEST.");
				else
					fprintf(stdout, "Timeout reached. Exiting\n");
				close_socket();
				exit(1);
			}
		}

		if(dhcp_ack_state == DHCP_ACK_RCVD) {
			if (nagios_flag) {
				fprintf(stdout, "OK: Acquired IP: %s", get_ip_str(dhcph_g->dhcp_yip));
			} else {
				fprintf(stdout, "DHCP ack received\t - ");
				fprintf(stdout, "Acquired IP: %s\n", get_ip_str(dhcph_g->dhcp_yip));
			}

			/* Logs DHCP IP details to log file. This file is used for DHCP release */
			log_dhinfo(); 
			if(!nagios_flag && verbose) {
				print_dhinfo(DHCP_MSGACK);
			}
		} else if (dhcp_ack_state == DHCP_NAK_RCVD) {
			if (!nagios_flag) {
				fprintf(stdout, "DHCP nack received\t - ");
				fprintf(stdout, "Client MAC : %02x:%02x:%02x:%02x:%02x:%02x\n", \
					dhmac[0], dhmac[1], dhmac[2], dhmac[3], dhmac[4], dhmac[5]); 
			}
		}
	}
	/* If IP listen flag is enabled, Listen on obtained for ARP, ICMP protocols  */
	if(!nagios_flag && ip_listen_flag) {
		fprintf(stdout, "\nListening on %s for ARP and ICMP protocols\n", iface_name);
		fprintf(stdout, "IP address: %s, Listen timeout: %d seconds\n", get_ip_str(htonl(ip_address)), listen_timeout);
		int arp_icmp_rcv_state = 0;
		while(arp_icmp_rcv_state != LISTEN_TIMOUET) { 
			arp_icmp_rcv_state = recv_packet(ARP_ICMP_RCV);
			/* Send ARP reply if ARP request received */
			if(arp_icmp_rcv_state == ARP_RCVD) {
				/*if(verbose) {
				  fprintf(stdout, "ARP request received\n");
				  fprintf(stdout, "Sending ARP reply\n");
				  }*/
				build_packet(ARP_SEND);
				send_packet(ARP_SEND);
			} else if(arp_icmp_rcv_state == ICMP_RCVD) {
				/* Send ICMP reply if ICMP echo request received */
				/*if(verbose) {
				  fprintf(stdout, "ICMP request received\n");
				  fprintf(stdout, "Sending ICMP reply\n");
				  }*/
				build_packet(ICMP_SEND);
				send_packet(ICMP_SEND);  
			} 
		}
		fprintf(stdout, "Listen timout reached\n");
	}
	/* Clear the promiscuous mode */
	clear_promisc();
	/* Close the socket */
	close_socket();
	return 0;
}
Example #12
0
int ethernet_close (char *dev_name)
{
  set_promisc (dev_name, ether_port, 0);
  return 0;
}
Example #13
0
int main(int argc, char *argv[])
{
	int get_tmp = 1, get_cmd;

	if(argc < 3) {
	print_help(argv[0]);
	exit(1);
	}

	int option_index = 0;
	static struct option long_options[] = {
	{ "mac", required_argument, 0, 'm' },
	{ "interface", required_argument, 0, 'i' },
	{ "vlan", required_argument, 0, 'v' },
	{ "dhcp_xid", required_argument, 0, 'x' },
	{ "tos", required_argument, 0, 't' },
	{ "option12-name", required_argument, 0, 'n' },
	{ "option51-lease_time", required_argument, 0, 'L' },
	{ "option50-ip", required_argument, 0, 'I' },
	{ "option60-vci", required_argument, 0, 'o' },
	{ "timeout", required_argument, 0, 'T' },
	{ "bind-ip", no_argument, 0, 'b' },
	{ "bind-timeout", required_argument, 0, 'k' },
	{ "bcast_flag", no_argument, 0, 'f'},
	{ "verbose", no_argument, 0, 'V'},
	{ "write-log", no_argument, 0, 'W'},
	{ "release", no_argument, 0, 'r'},
	{ 0, 0, 0, 0 }
	};

	/*getopt routine to get command line arguments*/
	while(get_tmp < argc) {
	get_cmd  = getopt_long(argc, argv, "m:i:v:t:bfVWrT:I:o:k:L:n:",\
		long_options, &option_index);
	if(get_cmd == -1 ) {
		break;
	}
	switch(get_cmd) {
		case 'm':
		if(strlen(optarg) > 18) {
			fprintf(stdout, "Invalid mac address\n");
			exit(1);
		}
		strcpy(dhmac_fname, optarg);
		sscanf((char *)optarg, "%2hhX:%2hhX:%2hhX:%2hhX:%2hhX:%2hhX", &dhmac[0], \
		&dhmac[1], &dhmac[2], &dhmac[3], &dhmac[4], &dhmac[5]);
		dhmac_flag = 1;
		break;

		case 'i':
		iface = if_nametoindex(optarg);
		if(iface == 0) {
			fprintf(stdout, "Interface doesnot exist\n");
			exit(1);
		}
		strncpy(iface_name, optarg, 29);
		break;

		case 'v':
		if(atoi(optarg) < 1 || atoi(optarg) > 4095)
		{
			fprintf(stdout, "VLAN ID is not valid. Range 1 to 4095\n");
			exit(1);
		}
		vlan = atoi(optarg);
		l2_hdr_size = 18;
		break;

		case 'r':
		dhcp_release_flag = 1;
		break;

		case 'b':
		ip_listen_flag = 1;
		break;

		case 'k':
		listen_timeout = atoi(optarg);
		tval_listen.tv_sec = listen_timeout;
		break;

		case 'x':
		sscanf((char *)optarg, "%X", &dhcp_xid);
		break;

		case 't':
		if(atoi(optarg) >= 256 || atoi(optarg) < 0) {
			fprintf(stdout, "Invalid TOS value\n");
			exit(1);
		}
		l3_tos = atoi(optarg);
		break;

		case 'L':
		option51_lease_time = atoi(optarg);
		break;

		case 'I':
		option50_ip = inet_addr(optarg);
		break;

		case 'n':
		strncpy(option12_name, optarg, sizeof(option12_name));
		break;

		case 'o':
		if(strlen(optarg) > 256) {
			fprintf(stdout, "VCI string size should be less than 256\n");
			exit(1);
		}
		vci_flag = 1;
		memcpy(vci_buff, optarg, sizeof(vci_buff));
		break;

		case 'T':
		if(atoi(optarg) < 5 || atoi(optarg) > 3600) {
			fprintf(stdout, "Invalid timout value. Range 5 to 3600\n");
			exit(1);
		}
		timeout = atoi(optarg);
		break;

		case 'f':
			bcast_flag = htons(0x8000);
		break;

		case 'V':
		verbose = 1;
		break;

		case 'W':
		writelog = 1;
		break;

		default:
		exit(1);
	}
	get_tmp++;
	}

	if(!dhmac_flag) {
	print_help(argv[0]);
	exit(1);
	}
	/* Opens the PF_PACKET socket */
	if(open_socket() < 0) {
	fprintf(stdout, "Socket error\n");
	exit(1);
	}

	/* Sets the promiscuous mode */
	set_promisc();

	/* Sets a random DHCP xid */
	set_rand_dhcp_xid();

	/*
	 * If DHCP release flag is set, send DHCP release packet
	 * and exit. get_dhinfo parses the DHCP info from log file
	 * and unlinks it from the system
	 */
	if(dhcp_release_flag) {
	if(get_dhinfo() == ERR_FILE_OPEN) {
		fprintf(stdout, "Error on opening DHCP info file\n");
		fprintf(stdout, "Release the DHCP IP after acquiring\n");
		exit(1);
	}
	build_option53(DHCP_MSGRELEASE); /* Option53 DHCP release */
	build_option54();		 /* Server id */
	build_optioneof();		 /* End of option */
	build_dhpacket(DHCP_MSGRELEASE); /* Build DHCP release packet */
	send_packet(DHCP_MSGRELEASE);	 /* Send DHCP release packet */
	clear_promisc();		 /* Clear the promiscuous mode */
	close_socket();
	return 0;
	}
	if(timeout) {
	time_last = time(NULL);
	}
	build_option53(DHCP_MSGDISCOVER);	/* Option53 for DHCP discover */
	if(option50_ip) {
	build_option50();		/* Option50 - req. IP  */
	}
	if(option51_lease_time) {
		build_option51();			   /* Option51 - DHCP lease time requested */
	}

	if(vci_flag == 1) {
	build_option60_vci(); 		/* Option60 - VCI  */
	}
	build_optioneof();			/* End of option */
	build_dhpacket(DHCP_MSGDISCOVER);	/* Build DHCP discover packet */

	int dhcp_offer_state;
	while(dhcp_offer_state != DHCP_OFFR_RCVD) {

	/* Sends DHCP discover packet */
	send_packet(DHCP_MSGDISCOVER);
	/*
	 * recv_packet functions returns when the specified
	 * packet is received
	 */
	dhcp_offer_state = recv_packet(DHCP_MSGOFFER);

	if(timeout) {
		time_now = time(NULL);
		if((time_now - time_last) > timeout) {
		close_socket();
		exit(1);
		}
	}
	if(dhcp_offer_state == DHCP_OFFR_RCVD) {
		fprintf(stdout, "DHCP offer received\t - ");
		set_serv_id_opt50();
		fprintf(stdout, "Offered IP : %s\n", inet_ntoa(*(struct in_addr *)&dhcph_g->dhcp_yip));
		if(verbose) {
			print_dhinfo(DHCP_MSGOFFER);
		}
	}
	}
	/* Reset the dhopt buffer to build DHCP request options  */
	reset_dhopt_size();
	build_option53(DHCP_MSGREQUEST);
	build_option50();
	build_option54();
	if(vci_flag == 1) {
	build_option60_vci();
	}
	if(strlen(option12_name) > 0) {
		build_option12();	/* Option 12 - Client ID (hostname) */
	}
	if(option51_lease_time) {
		build_option51();					   /* Option51 - DHCP lease time requested */
	}
	build_option55();
	build_optioneof();
	build_dhpacket(DHCP_MSGREQUEST); 		/* Builds specified packet */
	int dhcp_ack_state;
	while(dhcp_ack_state != DHCP_ACK_RCVD) {

	send_packet(DHCP_MSGREQUEST);
	dhcp_ack_state = recv_packet(DHCP_MSGACK);

	if(timeout) {
		time_now = time(NULL);
		if((time_now - time_last) > timeout) {
		fprintf(stdout, "Timeout reached. Exiting\n");
		close_socket();
		exit(1);
		}
	}

	if(dhcp_ack_state == DHCP_ACK_RCVD) {
		fprintf(stdout, "DHCP ack received\t - ");
		fprintf(stdout, "Acquired IP: %s\n", inet_ntoa(*(struct in_addr *)&dhcph_g->dhcp_yip));

		/* Logs DHCP IP details to log file. This file is used for DHCP release */
		if(writelog) {
			log_dhinfo();
		}
		if(verbose) {
			print_dhinfo(DHCP_MSGACK);
		}
	} else if (dhcp_ack_state == DHCP_NAK_RCVD) {
		fprintf(stdout, "DHCP nack received\t - ");
		fprintf(stdout, "Client MAC : %02x:%02x:%02x:%02x:%02x:%02x\n", \
		dhmac[0], dhmac[1], dhmac[2], dhmac[3], dhmac[4], dhmac[5]);
	}
	}
	/* If IP listen flag is enabled, Listen on obtained for ARP, ICMP protocols  */
	if(ip_listen_flag) {
	struct in_addr taddr;

	taddr.s_addr=htonl(ip_address);
	fprintf(stdout, "\nListening on %s for ARP and ICMP protocols\n", iface_name);
	fprintf(stdout, "IP address: %s, Listen timeout: %d seconds\n", inet_ntoa(taddr), listen_timeout);
	int arp_icmp_rcv_state = 0;
	while(arp_icmp_rcv_state != LISTEN_TIMOUET) {
		arp_icmp_rcv_state = recv_packet(ARP_ICMP_RCV);
		/* Send ARP reply if ARP request received */
		if(arp_icmp_rcv_state == ARP_RCVD) {
		/*if(verbose) {
			fprintf(stdout, "ARP request received\n");
			fprintf(stdout, "Sending ARP reply\n");
		}*/
		build_packet(ARP_SEND);
		send_packet(ARP_SEND);
		} else if(arp_icmp_rcv_state == ICMP_RCVD) {
		/* Send ICMP reply if ICMP echo request received */
		/*if(verbose) {
			fprintf(stdout, "ICMP request received\n");
			fprintf(stdout, "Sending ICMP reply\n");
		}*/
		build_packet(ICMP_SEND);
		send_packet(ICMP_SEND);
		}
	}
	fprintf(stdout, "Listen timout reached\n");
	}
	/* Clear the promiscuous mode */
	clear_promisc();
	/* Close the socket */
	close_socket();
	return 0;
}
Example #14
0
void parse_options(int argc, char **argv)
{
   int c;

   static struct option long_options[] = {
      { "help", no_argument, NULL, 'h' },
      { "version", no_argument, NULL, 'v' },
      
      { "iface", required_argument, NULL, 'i' },
      { "lifaces", no_argument, NULL, 'I' },
      { "netmask", required_argument, NULL, 'n' },
      { "address", required_argument, NULL, 'A' },
      { "write", required_argument, NULL, 'w' },
      { "read", required_argument, NULL, 'r' },
      { "pcapfilter", required_argument, NULL, 'f' },
      
      { "reversed", no_argument, NULL, 'R' },
      { "proto", required_argument, NULL, 't' },
      
      { "plugin", required_argument, NULL, 'P' },
      
      { "filter", required_argument, NULL, 'F' },
#ifdef HAVE_EC_LUA
      { "lua-script", required_argument, NULL, 0 },
      { "lua-args", required_argument, NULL, 0 },
#endif
      
      { "superquiet", no_argument, NULL, 'Q' },
      { "quiet", no_argument, NULL, 'q' },
      { "script", required_argument, NULL, 's' },
      { "silent", no_argument, NULL, 'z' },
#ifdef WITH_IPV6
      { "ip6scan", no_argument, NULL, '6' },
#endif
      { "unoffensive", no_argument, NULL, 'u' },
      { "nosslmitm", no_argument, NULL, 'S' },
      { "load-hosts", required_argument, NULL, 'j' },
      { "save-hosts", required_argument, NULL, 'k' },
      { "wifi-key", required_argument, NULL, 'W' },
      { "config", required_argument, NULL, 'a' },
      
      { "dns", no_argument, NULL, 'd' },
      { "regex", required_argument, NULL, 'e' },
      { "visual", required_argument, NULL, 'V' },
      { "ext-headers", no_argument, NULL, 'E' },
      
      { "log", required_argument, NULL, 'L' },
      { "log-info", required_argument, NULL, 'l' },
      { "log-msg", required_argument, NULL, 'm' },
      { "compress", no_argument, NULL, 'c' },
      
      { "text", no_argument, NULL, 'T' },
      { "curses", no_argument, NULL, 'C' },
      { "daemon", no_argument, NULL, 'D' },
      { "gtk", no_argument, NULL, 'G' },

      
      { "mitm", required_argument, NULL, 'M' },
      { "only-mitm", no_argument, NULL, 'o' },
      { "bridge", required_argument, NULL, 'B' },
      { "broadcast", required_argument, NULL, 'b' },
      { "promisc", no_argument, NULL, 'p' },
      { "gateway", required_argument, NULL, 'Y' },
      { "certificate", required_argument, NULL, 0 },
      { "private-key", required_argument, NULL, 0 },

      
      { 0 , 0 , 0 , 0}
   };

   for (c = 0; c < argc; c++)
      DEBUG_MSG("parse_options -- [%d] [%s]", c, argv[c]);

   
/* OPTIONS INITIALIZATION */
   
   GBL_PCAP->promisc = 1;
   GBL_FORMAT = &ascii_format;
   GBL_OPTIONS->ssl_mitm = 1;
   GBL_OPTIONS->broadcast = 0;
   GBL_OPTIONS->ssl_cert = NULL;
   GBL_OPTIONS->ssl_pkey = NULL;

/* OPTIONS INITIALIZED */
   
   optind = 0;
   int option_index = 0;

   while ((c = getopt_long (argc, argv, "A:a:bB:CchDdEe:F:f:GhIi:j:k:L:l:M:m:n:oP:pQqiRr:s:STt:uV:vW:w:Y:z6", long_options, &option_index)) != EOF) {
      /* used for parsing arguments */
      char *opt_end = optarg;
      while (opt_end && *opt_end) opt_end++;
      /* enable a loaded filter script? */

      switch (c) {

         case 'M':
		  set_mitm(optarg);
                  break;
                  
         case 'o':
		  set_onlymitm();
                  //select_text_interface();
                  break;

         case 'b':
		  set_broadcast();
		  break;
                  
         case 'B':
		  set_iface_bridge(optarg);
                  break;
                  
         case 'p':
		  set_promisc();
                  break;
#ifndef JUST_LIBRARY 
         case 'T':
                  select_text_interface();
                  break;
                  
         case 'C':
                  select_curses_interface();
                  break;

         case 'G':
                  select_gtk_interface();
                  break;

                  
         case 'D':
                  select_daemon_interface();
                  break;
#endif
                  
         case 'R':
		  set_reversed();
                  break;
                  
         case 't':
		  set_proto(optarg);
                  break;
                  
         case 'P':
		  set_plugin(optarg);
                  break;
                  
         case 'i':
		  set_iface(optarg);
                  break;
                  
         case 'I':
                  /* this option is only useful in the text interface */
	          set_lifaces();
                  break;

         case 'Y':
                  set_secondary(optarg);
                  break;
         
         case 'n':
                  set_netmask(optarg);
                  break;

         case 'A':
                  set_address(optarg);
                  break;
                  
         case 'r':
                  set_read_pcap(optarg);
                  break;
                 
         case 'w':
		  set_write_pcap(optarg);
                  break;
                  
         case 'f':
		  set_pcap_filter(optarg);
                  break;
                  
         case 'F':
		  load_filter(opt_end, optarg);
                  break;
                  
         case 'L':
		  set_loglevel_packet(optarg);

         case 'l':
		  set_loglevel_info(optarg);
                  break;

         case 'm':
	          set_loglevel_true(optarg);
                  break;
                  
         case 'c':
		  set_compress();
                  break;

         case 'e':
                  opt_set_regex(optarg);
                  break;
         
         case 'Q':
                  set_superquiet();
                  /* no break, quiet must be enabled */
         case 'q':
		  set_quiet();
                  break;
                  
         case 's':
                  set_script(optarg);
                  break;
                  
         case 'z':
                  set_silent();
                  break;
                  
#ifdef WITH_IPV6
         case '6':
                  set_ip6scan();
                  break;
#endif

         case 'u':
                  set_unoffensive();
                  break;

         case 'S':
                  disable_sslmitm();
                  break;
 
         case 'd':
                  set_resolve();
                  break;
                  
         case 'j':
                  load_hosts(optarg);
                  break;
                  
         case 'k':
	          save_hosts(optarg);
                  break;
                  
         case 'V':
                  opt_set_format(optarg);
                  break;
                  
         case 'E':
                  set_ext_headers();
                  break;
                  
         case 'W':
                  set_wifi_key(optarg);
                  break;
                  
         case 'a':
                  set_conf_file(optarg);
                  break;
         
         case 'h':
                  ec_usage();
                  break;

         case 'v':
                  printf("%s %s\n", GBL_PROGRAM, GBL_VERSION);
                  clean_exit(0);
                  break;

        /* Certificate and private key options */
         case 0:
		if (!strcmp(long_options[option_index].name, "certificate")) {
			GBL_OPTIONS->ssl_cert = strdup(optarg);	
		} else if (!strcmp(long_options[option_index].name, "private-key")) {
			GBL_OPTIONS->ssl_pkey = strdup(optarg);
#ifdef HAVE_EC_LUA
                } else if (!strcmp(long_options[option_index].name,"lua-args")) {
                    ec_lua_cli_add_args(strdup(optarg));
                } 
                else if (!strcmp(long_options[option_index].name,"lua-script")) {
                    ec_lua_cli_add_script(strdup(optarg));
        break;
#endif
		} else {
			fprintf(stdout, "\nTry `%s --help' for more options.\n\n", GBL_PROGRAM);
			clean_exit(-1);
		}

		break;

         case ':': // missing parameter
            fprintf(stdout, "\nTry `%s --help' for more options.\n\n", GBL_PROGRAM);
            clean_exit(-1);
         break;

         case '?': // unknown option
            fprintf(stdout, "\nTry `%s --help' for more options.\n\n", GBL_PROGRAM);
            clean_exit(-1);
         break;
      }
   }

   DEBUG_MSG("parse_options: options parsed");
   
   /* TARGET1 and TARGET2 parsing */
   if (argv[optind]) {
      GBL_OPTIONS->target1 = strdup(argv[optind]);
      DEBUG_MSG("TARGET1: %s", GBL_OPTIONS->target1);
      
      if (argv[optind+1]) {
         GBL_OPTIONS->target2 = strdup(argv[optind+1]);
         DEBUG_MSG("TARGET2: %s", GBL_OPTIONS->target2);
      }
   }

   /* create the list form the TARGET format (MAC/IPrange/PORTrange) */
   compile_display_filter();
   
   DEBUG_MSG("parse_options: targets parsed");
   
   /* check for other options */
   
   if (GBL_SNIFF->start == NULL)
      set_unified_sniff();
   
   if (GBL_OPTIONS->read && GBL_PCAP->filter)
      FATAL_ERROR("Cannot read from file and set a filter on interface");
   
   if (GBL_OPTIONS->read && GBL_SNIFF->type != SM_UNIFIED )
      FATAL_ERROR("You can read from a file ONLY in unified sniffing mode !");
   
   if (GBL_OPTIONS->mitm && GBL_SNIFF->type != SM_UNIFIED )
      FATAL_ERROR("You can't do mitm attacks in bridged sniffing mode !");

   if (GBL_SNIFF->type == SM_BRIDGED && GBL_PCAP->promisc == 0)
      FATAL_ERROR("During bridged sniffing the iface must be in promisc mode !");
   
   if (GBL_OPTIONS->quiet && GBL_UI->type != UI_TEXT)
      FATAL_ERROR("The quiet option is useful only with text only UI");
  
   if (GBL_OPTIONS->load_hosts && GBL_OPTIONS->save_hosts)
      FATAL_ERROR("Cannot load and save at the same time the hosts list...");
  
   if (GBL_OPTIONS->unoffensive && GBL_OPTIONS->mitm)
      FATAL_ERROR("Cannot use mitm attacks in unoffensive mode");
   
   if (GBL_OPTIONS->read && GBL_OPTIONS->mitm)
      FATAL_ERROR("Cannot use mitm attacks while reading from file");
  
#ifndef JUST_LIBRARY 
   if (GBL_UI->init == NULL)
      FATAL_ERROR("Please select an User Interface");
#endif
     
   /* force text interface for only mitm attack */
  /* Do not select text interface for only MiTM mode 

   if (GBL_OPTIONS->only_mitm) {
      if (GBL_OPTIONS->mitm)
         select_text_interface();
      else
         FATAL_ERROR("Only mitm requires at least one mitm method");
   } */

   DEBUG_MSG("parse_options: options combination looks good");
   return;
}
Example #15
0
int main(int argc, char *argv[])
{
	int get_tmp = 1, get_cmd;
	int dhinfo_ret;

	if(argc < 3) {
		print_help(argv[0]);
		exit(2);
	}

	init_rand();
	atexit(cleanup);
	signal(SIGSEGV, sigcleanup);
	signal(SIGABRT, sigcleanup);
	signal(SIGTERM, sigcleanup);
	signal(SIGINT, sigcleanup);
	signal(SIGHUP, sigcleanup);

	int option_index = 0;
	static struct option long_options[] = {
		{ "mac", required_argument, 0, 'm' },
		{ "random-mac", no_argument, 0, 'R' },
		{ "log-filename", required_argument, 0, 'F' },
		{ "interface", required_argument, 0, 'i' },
		{ "vlan", required_argument, 0, 'v' },
		{ "dhcp_xid", required_argument, 0, 'x' },
		{ "tos", required_argument, 0, 't' },
		{ "option51-lease_time", required_argument, 0, 'L' },
		{ "option50-ip", required_argument, 0, 'I' },
		{ "option60-vci", required_argument, 0, 'o' },
		{ "option12-hostname", required_argument, 0, 'h' },
		{ "timeout", required_argument, 0, 'T' },
		{ "bind-ip", no_argument, 0, 'b' },
		{ "bind-timeout", required_argument, 0, 'k' },
		{ "bcast_flag", no_argument, 0, 'f'},
		{ "verbose", no_argument, 0, 'V'},
		{ "fqdn-server-not-update", no_argument, 0, 'n'},
		{ "fqdn-server-update-a", no_argument, 0, 's'},
		{ "fqdn-domain-name", required_argument, 0, 'd'},
		{ "padding", no_argument, 0, 'p'},
		{ "port", required_argument, 0, 'P'},
		{ "giaddr", required_argument, 0, 'g'},
		{ "unicast", optional_argument, 0, 'u'},
		{ "nagios", no_argument, 0, 'a'},
		{ "server", required_argument, 0, 'S'},
		{ "release", no_argument, 0, 'r'},
		{ "quiet", no_argument, 0, 'q'},
		{ "request-only", no_argument, 0, 'Q'},
		{ 0, 0, 0, 0 }
	};

	/*getopt routine to get command line arguments*/
	while(get_tmp < argc) {
		get_cmd  = getopt_long(argc, argv, "m:Ri:v:t:bfVrpansu::T:P:g:S:I:o:k:L:h:d:F:qQ",\
				long_options, &option_index);
		if(get_cmd == -1 ) {
			break;
		}
		switch(get_cmd) {
			case 'q':
				quiet = 1;
				break;

			case 'm':
				{
					u_char aux_dhmac[ETHER_ADDR_LEN + 1];

					if(strlen(optarg) != 17
							|| sscanf(optarg, ETH_F_FMT, ETH_F_PARG(aux_dhmac)) != 6
					  )
					{
						fprintf(stderr, "Invalid mac address\n");
						exit(2);
					}
					memcpy(dhmac, aux_dhmac, sizeof(dhmac));
					dhmac_flag = 1;
				}
				break;

			case 'R':
				{
					int i;

					for (i = 0; i < ETHER_ADDR_LEN; i++)
						dhmac[i] = rand() & 0xff;

					/* clear multicast bit, set the L bit, clear MSB */
					dhmac[0] &= ~0x81;
					dhmac[0] |= 0x02;

					dhmac_flag = 1;
				}
				break;

			case 'F':
				if (strlen(optarg) > sizeof(dhmac_fname) - 1) {
					fprintf(stderr, "-F filename given is too long\n");
					exit(2);
				}
				strcpy(dhmac_fname, optarg);
				dhmac_fname_flag = 1;
				break;

			case 'i':
				iface_name = optarg;
				break;

			case 'v':
				if(atoi(optarg) < 1 || atoi(optarg) > 4095)
				{
					fprintf(stderr, "VLAN ID is not valid. Range 1 to 4095\n");
					exit(2);
				}
				vlan = atoi(optarg);
				l2_hdr_size = 18;
				break;

			case 'r':
				dhcp_release_flag = 1;
				break;

			case 'Q':
				dhcp_request_flag = 1;
				break;

			case 'b':
				ip_listen_flag = 1;
				break;

			case 'k':
				listen_timeout = atoi(optarg);
				tval_listen.tv_sec = listen_timeout;
				break;

			case 'x':
				{
					u_int32_t aux_dhcp_xid[2];
					aux_dhcp_xid[0] = 0;
					sscanf((char *)optarg, "%X", &aux_dhcp_xid[0]);
					dhcp_xid = aux_dhcp_xid[0];
				}
				break;

			case 't':
				if(atoi(optarg) >= 256 || atoi(optarg) < 0) {
					fprintf(stderr, "Invalid TOS value\n");
					exit(2);
				}
				l3_tos = atoi(optarg);
				break;

			case 'L':
				option51_lease_time = atoi(optarg);
				break;

			case 'I':
				option50_ip = inet_addr(optarg);
				break;

			case 'o':
				if(strlen(optarg) >= 256) {
					fprintf(stderr, "VCI string size should be less than 256\n");
					exit(2);
				}
				vci_flag = 1;
				vci_buff = optarg;
				break;

			case 'h':
				if(strlen(optarg) >= 256) {
					fprintf(stderr, "Hostname string size should be less than 256\n");
					exit(2);
				}
				hostname_flag = 1;
				hostname_buff = optarg;
				break;

			case 'd':
				if(strlen(optarg) >= 253) {
					fprintf(stderr, "FQDN domain name string size should be less than 253\n");
					exit(2);
				}
				fqdn_flag = 1;
				fqdn_buff = optarg;
				break;

			case 'n':
				fqdn_n = 1;
				break;

			case 's':
				fqdn_s = 1;
				break;

			case 'T':
				if(atoi(optarg) < 5 || atoi(optarg) > 3600) {
					fprintf(stderr, "Invalid timout value. Range 5 to 3600\n");
					exit(2);
				}
				timeout = atoi(optarg);
				break;

			case 'P':
				if(atoi(optarg) <=0 || atoi(optarg) > 65535) {
					fprintf(stderr, "Invalid port value. Range 1 to 65535\n");
					exit(2);
				}
				port = atoi(optarg);
				break;

			case 'g':
				giaddr = optarg;
				break;

			case 'S':
				server_addr = optarg;
				break;

			case 'p':
				padding_flag = 1;
				break;

			case 'f':
				bcast_flag = htons(0x8000);
				break;

			case 'V':
				verbose = 1;
				break;

			case 'u':
				if (optarg) {
					struct in_addr out;

					if (!inet_aton(optarg, &out)) {
						fprintf(stderr, "Invalid unicast IP address.");
						exit(2);
					}
					unicast_ip_address = out.s_addr;
				}
				unicast_flag = 1;
				break;

			case 'a':
				nagios_flag = 1;
				break;

			default:
				exit(2);
		}
		get_tmp++;
	}	

	if(!dhmac_flag) {
		print_help(argv[0]);
		exit(2);
	}

	if (!dhmac_fname_flag)
		sprintf(dhmac_fname, ETH_F_FMT, ETH_F_ARG(dhmac));

	dhinfo_ret = get_dhinfo();

	iface = if_nametoindex(iface_name);
	if(iface == 0) {
		fprintf(stderr, "Interface %s does not exist\n", iface_name);
		exit(2);
	}
	/* Opens the PF_PACKET socket */
	if(open_socket() < 0)
		critical("Socket error: %m");

	/* Sets the promiscuous mode */
	set_promisc();

	if (unicast_flag && !unicast_ip_address) {
		unicast_ip_address = get_interface_address();
	}

	/* Sets a random DHCP xid */
	set_rand_dhcp_xid(); 

	time_now = time_last = time(NULL);

	/*
	 * If DHCP release flag is set, send DHCP release packet
	 * and exit. get_dhinfo parses the DHCP info from log file
	 * and unlinks it from the system
	 */
	if(dhcp_release_flag) {
		if(dhinfo_ret)
			critical("Error on opening DHCP info file: %s", strerror(dhinfo_ret));
		if (!server_id)
			critical("Can't release IP without an active lease");
		build_option53(DHCP_MSGRELEASE); /* Option53 DHCP release */
		if(hostname_flag) {
			build_option12_hostname();
		}
		if(fqdn_flag) {
			build_option81_fqdn();
		}
		build_option54();		 /* Server id */
		build_optioneof();		 /* End of option */
		build_dhpacket(DHCP_MSGRELEASE); /* Build DHCP release packet */
		send_packet(DHCP_MSGRELEASE);	 /* Send DHCP release packet */
		/* update status file: we no longer have our IP address */
		log_dhinfo();
		return 0; 
	}

	if (dhcp_request_flag) {
		if(dhinfo_ret)
			critical("Error on opening DHCP info file: %s", strerror(dhinfo_ret));
		if (!server_id)
			critical("Can't refresh IP without an active lease");
		/* Clients begin to attempt to renew their leases once half the lease interval has expired. */
		if (lease_expires_at - time_now > option51_lease_time / 2)
			return 0;

		goto request;
	}

	build_option53(DHCP_MSGDISCOVER);	/* Option53 for DHCP discover */
	if(hostname_flag) {
		build_option12_hostname();
	}
	if(fqdn_flag) {
		build_option81_fqdn();
	}
	if(option50_ip) {
		build_option50();		/* Option50 - req. IP  */
	}
	if(option51_lease_time) {
		build_option51();               /* Option51 - DHCP lease time requested */
	}

	if(vci_flag == 1) {
		build_option60_vci(); 		/* Option60 - VCI  */
	}
	build_optioneof();			/* End of option */
	build_dhpacket(DHCP_MSGDISCOVER);	/* Build DHCP discover packet */

	int dhcp_offer_state = 0;
	while(dhcp_offer_state != DHCP_OFFR_RCVD) {

		/* Sends DHCP discover packet */
		send_packet(DHCP_MSGDISCOVER);
		/*
		 * recv_packet functions returns when the specified 
		 * packet is received
		 */
		dhcp_offer_state = recv_packet(DHCP_MSGOFFER); 

		if(timeout) {
			time_now = time(NULL);
			if((time_now - time_last) > timeout)
				critical("Timeout reached: DISCOVER");
		}
		if(dhcp_offer_state == DHCP_OFFR_RCVD) {
			if (!nagios_flag && !quiet)
				printf("DHCP offer received\t - ");
			set_serv_id_opt50();
			if (!nagios_flag && !quiet)
  				printf("Offered IP : %s\n", get_ip_str(dhcph_g->dhcp_yip));
			if(!nagios_flag && verbose) { 
				print_dhinfo(DHCP_MSGOFFER);
			}
		}
	}

request:
	/* Reset the dhopt buffer to build DHCP request options  */
	reset_dhopt_size();
	build_option53(DHCP_MSGREQUEST); 
	build_option50();
	build_option54();
	if(hostname_flag) {
		build_option12_hostname();
	}
	if(fqdn_flag) {
		build_option81_fqdn();
	}
	if(vci_flag == 1) {
		build_option60_vci();  
	}
	if(option51_lease_time) {
		build_option51();                       /* Option51 - DHCP lease time requested */
	}
	build_option55();
	build_optioneof();
	build_dhpacket(DHCP_MSGREQUEST); 		/* Builds specified packet */
	int dhcp_ack_state = 1;
	while(dhcp_ack_state != DHCP_ACK_RCVD) { 

		send_packet(DHCP_MSGREQUEST);
		dhcp_ack_state = recv_packet(DHCP_MSGACK); 

		if(timeout) {
			time_now = time(NULL);
			if((time_now - time_last) > timeout)
				critical("Timeout reached: REQUEST");
		}

		if(dhcp_ack_state == DHCP_ACK_RCVD) {
			if (nagios_flag) {
				printf("OK: Acquired IP: %s", get_ip_str(dhcph_g->dhcp_yip));
			} else if (!quiet) {
				printf("DHCP ack received\t - ");
				printf("Acquired IP: %s\n", get_ip_str(dhcph_g->dhcp_yip));
			}
			else {
				/* quiet */
				printf("%s\n", get_ip_str(dhcph_g->dhcp_yip));
			}

			/* Logs DHCP IP details to log file. This file is used for DHCP release */
			log_dhinfo(); 
			if(!nagios_flag && verbose) {
				print_dhinfo(DHCP_MSGACK);
			}
		} else if (dhcp_ack_state == DHCP_NAK_RCVD) {
			if (!nagios_flag && !quiet) {
				printf("DHCP nack received\t - ");
				printf("Client MAC : %02x:%02x:%02x:%02x:%02x:%02x\n", \
					dhmac[0], dhmac[1], dhmac[2], dhmac[3], dhmac[4], dhmac[5]); 
			}
		}
	}
	/* If IP listen flag is enabled, Listen on obtained for ARP, ICMP protocols  */
	if(!nagios_flag && ip_listen_flag) {
		if (!quiet) {
			printf("\nListening on %s for ARP and ICMP protocols\n", iface_name);
			printf("IP address: %s, Listen timeout: %d seconds\n", get_ip_str(htonl(ip_address)), listen_timeout);
		}
		int arp_icmp_rcv_state = 0;
		while(arp_icmp_rcv_state != LISTEN_TIMEOUT) { 
			arp_icmp_rcv_state = recv_packet(ARP_ICMP_RCV);
			/* Send ARP reply if ARP request received */
			if(arp_icmp_rcv_state == ARP_RCVD) {
				/*if(verbose) {
				  printf("ARP request received\n");
				  printf("Sending ARP reply\n");
				  }*/
				build_packet(ARP_SEND);
				send_packet(ARP_SEND);
			} else if(arp_icmp_rcv_state == ICMP_RCVD) {
				/* Send ICMP reply if ICMP echo request received */
				/*if(verbose) {
				  printf("ICMP request received\n");
				  printf("Sending ICMP reply\n");
				  }*/
				build_packet(ICMP_SEND);
				send_packet(ICMP_SEND);  
			} 
		}
		printf("Listen timout reached\n");
	}
	return 0;
}