home *** CD-ROM | disk | FTP | other *** search
/ Steganos Hacker Tools / SHT151.iso / programme / scanner / nmapNTsp1 / Win_2000.exe / nmapNT-src / nmapNT / wintcpip.c < prev   
Encoding:
C/C++ Source or Header  |  2000-10-18  |  55.0 KB  |  1,918 lines

  1. #include "../tcpip.h"
  2.  
  3. extern struct ops o;
  4.  
  5. //DWORD getreg_ip(char *path);
  6. //DWORD getreg_gw(char *path);
  7. //DWORD getreg_ip9x(int iface);
  8. //DWORD getreg_gw9x(DWORD IP);
  9. BYTE *getmac_info(LPADAPTER adapter);
  10. BOOL send_arp(DWORD IP,struct interface_info *ainfo);
  11. BYTE * FindMAC(DWORD IP,struct interface_info *ainfo);
  12. BYTE * get_remote_mac(DWORD IP,struct interface_info *ainfo);
  13. int build_ethernet(u_char *dst, u_char *src, u_short type, const u_char *payload, int payload_s, u_char *buf);
  14. char *readarp_pcap(pcap_t *pd, unsigned int *len, long to_usec);
  15.  
  16. int FillIfList(struct _IFlist *iflist, int *icount);
  17. int FillIpList(struct _IPlist *iplist);
  18.  
  19.  
  20. struct ethernet_hdr
  21. {
  22. #ifndef ETHER_ADDR_LEN
  23. #define ETHER_ADDR_LEN 6
  24. #endif
  25.     u_char  ether_dhost[ETHER_ADDR_LEN];    /* destination ethernet address */
  26.     u_char  ether_shost[ETHER_ADDR_LEN];    /* source ethernet address */
  27.     u_short ether_type;                     /* packet type ID */
  28. };
  29.  
  30. struct arp_hdr
  31. {
  32.     u_short ar_hrd;                         /* format of hardware address */
  33. #define ARPHRD_ETHER     1                  /* ethernet hardware format */
  34.     u_short ar_pro;                         /* format of protocol address */
  35.     u_char  ar_hln;                         /* length of hardware address */
  36.     u_char  ar_pln;                         /* length of protocol addres */
  37.     u_short ar_op;                          /* operation type */
  38. #define ARPOP_REQUEST    1                  /* req to resolve address */
  39. #define ARPOP_REPLY      2                  /* resp to previous request */
  40. #define ARPOP_REVREQUEST 3                  /* req protocol address given hardware */
  41. #define ARPOP_REVREPLY   4                  /* resp giving protocol address */
  42. #define ARPOP_INVREQUEST 8                  /* req to identify peer */
  43. #define ARPOP_INVREPLY   9                  /* resp identifying peer */
  44.  
  45.     /*
  46.      *  These should implementation defined but I've hardcoded eth/IP.
  47.      */
  48.     BYTE ar_sha[6];                         /* sender hardware address */
  49.     DWORD ar_spa;                         /* sender protocol address */
  50.    BYTE ar_tha[6];                         /* target hardware address */
  51.     DWORD ar_tpa;                         /* target protocol address */
  52. };
  53.  
  54. inline void sethdrinclude(int sd) 
  55. {
  56.     int one = 1;
  57.     //setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (void *) &one, sizeof(one));
  58. }
  59.  
  60.  
  61. //inline void max_rcvbuf(int sd) {
  62. //}
  63.  
  64. inline void max_rcvbuf(int sd) {
  65.     int optval = 524288 /*2^19*/, optlen = sizeof(int);
  66.  
  67.     if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void *) &optval, optlen))
  68.     if (o.debugging) perror("Problem setting large socket recieve buffer");
  69.     if (o.debugging) 
  70.     {
  71.         getsockopt(sd, SOL_SOCKET, SO_RCVBUF,(void *) &optval, &optlen);
  72.         log_write(LOG_STDOUT, "Our buffer size is now %d\n", optval);
  73.     }
  74. }
  75. /* Maximize the open file descriptor limit for this process go up to the
  76.    max allowed  */
  77.  
  78. int max_sd() 
  79. {
  80.     return 64;
  81. }
  82.  
  83. /* gotta make theese using winsock*/
  84. inline int block_socket(int sd) 
  85. {
  86.     unsigned long options=0;
  87.     ioctlsocket(sd, FIONBIO, (unsigned long *)&options);
  88.     return 1;
  89. }
  90.  
  91. inline int unblock_socket(int sd) 
  92. {
  93.     u_long b=1;
  94.     ioctlsocket (sd, FIONBIO, &b);
  95.     return 1;
  96. }
  97.  
  98.  
  99. inline void broadcast_socket(int sd) 
  100. {
  101.     BOOL one = TRUE;
  102.     if (setsockopt(sd, SOL_SOCKET, SO_BROADCAST, (char *)&one, sizeof(BOOL)) != 0) 
  103.     {
  104.         fprintf(stderr, "Failed to secure socket broadcasting permission\n");
  105.         perror("setsockopt");
  106.     }
  107. }
  108. /* We set the socket lingering so we will RST connection instead of wasting
  109.    bandwidth with the four step close  */
  110. inline void init_socket(int sd) 
  111. {
  112.   struct linger l;
  113.   int res;
  114.   static int bind_failed=0;
  115.   struct sockaddr_in sin;
  116.  
  117.   l.l_onoff = 1;
  118.   l.l_linger = 0;
  119.  
  120.     if (setsockopt(sd, SOL_SOCKET, SO_LINGER,  (void *) &l, sizeof(struct linger)))
  121.     {
  122.         fprintf(stderr, "Problem setting socket SO_LINGER, errno: %d\n", errno);
  123.         perror("setsockopt");
  124.     }
  125.     if (o.spoofsource && !bind_failed)
  126.     {
  127.         bzero(&sin,sizeof(sin));
  128.         sin.sin_family=AF_INET;
  129.         memcpy(&sin.sin_addr,o.source,sizeof(sin.sin_addr));
  130.         res=bind(sd,(struct sockaddr*)&sin,sizeof(sin));
  131.         if (res<0)
  132.         {
  133.             fprintf(stderr, "init_socket: Problem binding source address (%s), errno :%d\n", inet_ntoa(sin.sin_addr), errno);
  134.             perror("bind");
  135.             bind_failed=1;
  136.         }
  137.     }
  138. }
  139.  
  140.  
  141.  
  142.  
  143. /* Tests whether a packet sent to  IP is LIKELY to route 
  144.  through the kernel localhost interface */
  145. int islocalhost(struct in_addr *addr) 
  146. {
  147.     struct interface_info dev;
  148.   /* If it is 0.0.0.0 or starts with 127.0.0.1 then it is 
  149.      probably localhost */
  150.     if ((addr->s_addr & htonl(0xFF000000)) == htonl(0x7F000000)) return 1;
  151.     if (!addr->s_addr) return 1;
  152.   /* If it is the same addy as a local interface, then it is
  153.      probably localhost */
  154.     if (ipaddr2dev(&dev, addr) != -1) return 1;
  155.   /* OK, so to a first approximation, this addy is probably not
  156.      localhost */
  157.     return 0;
  158. }
  159.  
  160. /* Calls pcap_open_live and spits out an error (and quits) if the call faile.
  161.    So a valid pcap_t will always be returned. */
  162. pcap_t *my_pcap_open_live(char *device, int snaplen, int promisc, int to_ms) 
  163. {
  164.     char err0r[PCAP_ERRBUF_SIZE];
  165.     pcap_t *pt;
  166.     if (!((pt = pcap_open_live(device, snaplen, promisc, to_ms, err0r)))) 
  167.     {
  168.         fatal("pcap_open_live: %s\nThere are several possible reasons for this, depending on your operating system:\n"
  169.           "LINUX: If you are getting Socket type not supported, try modprobe af_packet or recompile your kernel with SOCK_PACKET enabled.\n"
  170.           "*BSD:  If you are getting device not configured, you need to recompile your kernel with Berkeley Packet Filter support.  If you are getting No such file or directory, try creating the device (eg cd /dev; MAKEDEV <device>; or use mknod).\n"
  171.           "SOLARIS:  If you are trying to scan localhost and getting '/dev/lo0: No such file or directory', complain to Sun.  I don't think Solaris can support advanced localhost scans.  You can probably use \"-P0 -sT localhost\" though.\n\n", err0r);
  172.     }
  173.     return pt;
  174. }
  175.  
  176. /* Standard swiped internet checksum routine */
  177. inline unsigned short in_cksum(unsigned short *ptr,int nbytes) 
  178. {
  179.     register int        sum;            /* XXX assumes long == 32 bits */
  180.     u_short                oddbyte;
  181.     register u_short    answer;         /* assumes u_short == 16 bits */
  182.  
  183. /*
  184.  * Our algorithm is simple, using a 32-bit accumulator (sum),
  185.  * we add sequential 16-bit words to it, and at the end, fold back
  186.  * all the carry bits from the top 16 bits into the lower 16 bits.
  187.  */
  188.  
  189.     sum = 0;
  190.     while (nbytes > 1)  
  191.     {
  192.         sum += *ptr++;
  193.         nbytes -= 2;
  194.     }
  195. /* mop up an odd byte, if necessary */
  196.     if (nbytes == 1) 
  197.     {
  198.         oddbyte = 0;            /* make sure top half is zero */
  199.         *((u_char *) &oddbyte) = *(u_char *)ptr;   /* one byte only */
  200.         sum += oddbyte;
  201.     }
  202. /*
  203.  * Add back carry outs from top 16 bits to low 16 bits.
  204.  */
  205.     sum  = (sum >> 16) + (sum & 0xffff);    /* add high-16 to low-16 */
  206.     sum += (sum >> 16);                     /* add carry */
  207.     answer = ~sum;          /* ones-complement, then truncate to 16 bits */
  208.     return(answer);
  209. }
  210.  
  211.  
  212.  
  213. /* Tries to resolve given hostname and stores
  214.    result in ip .  returns 0 if hostname cannot
  215.    be resolved */
  216. int resolve(char *hostname, struct in_addr *ip) 
  217. {
  218.     struct hostent *h;
  219.     if (!hostname || !*hostname) fatal("NULL or zero-length hostname passed to resolve()");
  220.     if (inet_aton(hostname, ip)) return 1; /* damn, that was easy ;) */
  221.     if ((h = gethostbyname(hostname))) 
  222.     {
  223.         memcpy(ip, h->h_addr_list[0], sizeof(struct in_addr));
  224.         return 1;
  225.     }
  226.     return 0;
  227. }
  228.  
  229. int send_tcp_raw_decoys( int sd, struct in_addr *victim, unsigned short sport, 
  230.              unsigned short dport, unsigned int seq,
  231.              unsigned int ack, unsigned char flags,
  232.              unsigned short window, char *options, int optlen,
  233.              char *data, unsigned short datalen,struct interface_info *ainfo) 
  234. {
  235.     int decoy;
  236.     for(decoy = 0; decoy < o.numdecoys; decoy++) 
  237.     {
  238.         if (send_tcp_raw(sd, &o.decoys[decoy], victim, sport, dport, seq, ack, flags, window, options, optlen, data, datalen,ainfo) == -1) return -1;
  239.     }
  240.     return 0;
  241. }
  242.  
  243.  
  244. int send_tcp_raw( int sd, struct in_addr *source, 
  245.           struct in_addr *victim, unsigned short sport, 
  246.           unsigned short dport, unsigned int seq,
  247.           unsigned int ack, unsigned char flags,
  248.           unsigned short window, char *options, int optlen,
  249.           char *data, unsigned short datalen,struct interface_info *ainfo) 
  250. {
  251.  
  252.     struct pseudo_header 
  253.     { 
  254.   /*for computing TCP checksum, see TCP/IP Illustrated p. 145 */
  255.         unsigned int s_addy;
  256.         unsigned int d_addr;
  257.         char zer0;
  258.         unsigned char protocol;
  259.         unsigned short length;
  260.     };
  261.     char *packet = safe_malloc(sizeof(struct ip) + sizeof(struct tcphdr) + optlen + datalen);
  262.     struct ip *ip = (struct ip *) packet;
  263.     struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct ip));
  264.     struct pseudo_header *pseudo =  (struct pseudo_header *) (packet + sizeof(struct ip) - sizeof(struct pseudo_header)); 
  265.     static int myttl = 0;
  266.  
  267.     /*With these placement we get data and some field alignment so we aren't
  268.     wasting too much in computing the checksum */
  269.     int res = -1;
  270.     struct sockaddr_in sock;
  271.     char myname[MAXHOSTNAMELEN + 1];
  272.     struct hostent *myhostent = NULL;
  273.     int source_malloced = 0;
  274.  
  275.     /* check that required fields are there and not too silly */
  276.     /* We used to check that sport and dport were nonzer0, but scr3w that! */
  277.     if ( !victim || sd < 0) 
  278.     {
  279.         fprintf(stderr, "send_tcp_raw: One or more of your parameters suck!\n");
  280.         free(packet);
  281.         return -1;
  282.     }
  283.  
  284.     if (optlen % 4) 
  285.     {
  286.         fatal("send_tcp_raw called with an option length argument of %d which is illegal because it is not divisible by 4", optlen);
  287.     }
  288.  
  289.  
  290.     if (!myttl) myttl = (get_random_uint() % 23) + 37;
  291.  
  292.     /* It was a tough decision whether to do this here for every packet
  293.     or let the calling function deal with it.  In the end I grudgingly decided
  294.     to do it here and potentially waste a couple microseconds... */
  295.     sethdrinclude(sd); 
  296.  
  297.     /* if they didn't give a source address, fill in our first address */
  298.     if (!source) 
  299.     {
  300.         source_malloced = 1;
  301.         source = safe_malloc(sizeof(struct in_addr));
  302.         if (gethostname(myname, MAXHOSTNAMELEN) || !(myhostent = gethostbyname(myname)))
  303.         {
  304.             fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
  305.         }
  306.         memcpy(source, myhostent->h_addr_list[0], sizeof(struct in_addr));
  307. #if ( TCPIP_DEBUGGING )
  308.         printf("We skillfully deduced that your address is %s\n", inet_ntoa(*source));
  309. #endif
  310.     }
  311.  
  312.     /*do we even have to fill out this damn thing?  This is a raw packet, 
  313.     after all */
  314.     sock.sin_family = AF_INET;
  315.     sock.sin_port = htons(dport);
  316.     sock.sin_addr.s_addr = victim->s_addr;
  317.     bzero((char *) packet, sizeof(struct ip) + sizeof(struct tcphdr));
  318.     pseudo->s_addy = source->s_addr;
  319.     pseudo->d_addr = victim->s_addr;
  320.     pseudo->protocol = IPPROTO_TCP;
  321.     pseudo->length = (unsigned short)htons(sizeof(struct tcphdr) + optlen + datalen);
  322.  
  323.     tcp->th_sport = htons(sport);
  324.     tcp->th_dport = htons(dport);
  325.     if (seq) 
  326.     {
  327.         tcp->th_seq = htonl(seq);
  328.     }
  329.     else if (flags & TH_SYN) 
  330.     {
  331.         get_random_bytes(&(tcp->th_seq), 4);
  332.     }
  333.  
  334.     if (ack) tcp->th_ack = htonl(ack);
  335.     /*else if (flags & TH_ACK)
  336.     tcp->th_ack = rand() + rand();*/
  337.  
  338.     tcp->th_off = 5 + (optlen /4) /*words*/;
  339.     tcp->th_flags = flags;
  340.  
  341.     if (window) tcp->th_win = htons(window);
  342.     else tcp->th_win = htons(1024 * (myttl % 4 + 1)); /* Who cares */
  343.  
  344.     /* We should probably copy the data over too */
  345.     if (data && datalen) memcpy(packet + sizeof(struct ip) + sizeof(struct tcphdr) + optlen, data, datalen);
  346.     /* And the options */
  347.     if (optlen) 
  348.     {
  349.         memcpy(packet + sizeof(struct ip) + sizeof(struct tcphdr), options, optlen);
  350.     }
  351.  
  352.     tcp->th_sum = in_cksum((unsigned short *)pseudo, sizeof(struct tcphdr) + optlen + sizeof(struct pseudo_header) + datalen);
  353.  
  354.     /* Now for the ip header */
  355.     bzero(packet, sizeof(struct ip)); 
  356.     ip->ip_v = 4;
  357.     ip->ip_hl = 5;
  358.     ip->ip_len = BSDFIX(sizeof(struct ip) + sizeof(struct tcphdr) + optlen + datalen);
  359.     get_random_bytes(&(ip->ip_id), 2);
  360.     ip->ip_ttl = myttl;
  361.     ip->ip_p = IPPROTO_TCP;
  362.     if(source->s_addr == victim->s_addr) source->s_addr++;
  363.     ip->ip_src.s_addr = source->s_addr;
  364.     ip->ip_dst.s_addr= victim->s_addr;
  365.  
  366.     ip->ip_sum = in_cksum((unsigned short *)ip, sizeof(struct ip));
  367.  
  368.  
  369.     if (TCPIP_DEBUGGING > 1) 
  370.     {
  371.         log_write(LOG_STDOUT, "Raw TCP packet creation completed!  Here it is:\n");
  372.         readtcppacket(packet,BSDUFIX(ip->ip_len));
  373.     }
  374.  
  375.     res = Sendto("send_tcp_raw", sd, packet, BSDUFIX(ip->ip_len), 0, (struct sockaddr *)&sock,  (int)sizeof(struct sockaddr_in),ainfo);
  376.     if (source_malloced) free(source);
  377.     free(packet);
  378.     return res;
  379. }
  380.  
  381. inline int Sendto(char *functionname, int sd, char *packet, int len, 
  382.        unsigned int flags, struct sockaddr *to, int tolen,struct interface_info *ainfo) 
  383. {
  384.     struct sockaddr_in *sin = (struct sockaddr_in *) to;
  385. //    DWORD scanlocalip;
  386.     u_char packetbuf[2048];
  387. //    DWORD remoteip;
  388. //    struct in_addr *addr;
  389.     LPPACKET   lpPacket;
  390.     BYTE *r_mac=NULL;
  391. //    BYTE s_mac[]= {0xAB,0xCD,0xEF,0x12,0x34,0x56};
  392.     if(ainfo->adapter != NULL)
  393.     {
  394.             if (TCPIP_DEBUGGING > 1) 
  395.         {  
  396.             log_write(LOG_STDOUT, "trying sendto(%d, packet, %d, 0, %s, %d)", sd, len, inet_ntoa(sin->sin_addr), tolen);
  397.         }
  398.     memset(packetbuf,0,2048);
  399. //    addr = &sin->sin_addr;
  400.     //memcpy(&remoteip,packet+16,4);
  401.     //scanning ourselves
  402. //        build_ethernet(r_mac,s_mac,0x0800,packet,len,packetbuf);        
  403. //    }
  404. //    else
  405. //    {
  406. //    r_mac=get_remote_mac(sin->sin_addr.S_un.S_addr);
  407.     r_mac=get_remote_mac(sin->sin_addr.S_un.S_addr,ainfo);
  408.     if (islocalhost(&sin->sin_addr))// filter[0] = '\0';
  409.     {
  410.         build_ethernet(ainfo->MAC,r_mac,0x0800,packet,len,packetbuf);
  411.     }
  412.     else
  413.     {
  414.  
  415.         build_ethernet(r_mac,ainfo->MAC,0x0800,packet,len,packetbuf);        
  416.     }
  417. //    }
  418. //    build_ethernet(r_mac,global_adapter.MAC,0x0800,packet,len,packetbuf);        
  419.     if((lpPacket = PacketAllocatePacket())==NULL){
  420.         printf("\nError:failed to allocate the LPPACKET structure.");
  421.         return (-1);
  422.     }
  423. //    printf("OUTPACKET\n");
  424. //    hdump(packetbuf, len+14);
  425.     PacketInitPacket(lpPacket,packetbuf,len+14);
  426.     PacketSendPacket(ainfo->adapter,lpPacket,TRUE);
  427.     PacketFreePacket(lpPacket);
  428.     if (TCPIP_DEBUGGING > 1) log_write(LOG_STDOUT, "successfully sent %d bytes of raw_tcp!\n", len);
  429.     }
  430.     return (len);
  431.  
  432.     
  433.  
  434. //    return res;
  435. }
  436.  
  437. /* A simple function I wrote to help in debugging, shows the important fields
  438.    of a TCP packet*/
  439. int readtcppacket(char *packet, int readdata) 
  440. {
  441.     struct ip *ip = (struct ip *) packet;
  442.     struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct ip));
  443.     char *data = packet +  sizeof(struct ip) + sizeof(struct tcphdr);
  444.     int tot_len;
  445.     struct in_addr bullshit, bullshit2;
  446.     char sourcehost[16];
  447.     int i;
  448.     int realfrag = 0;
  449.  
  450.     if (!packet) 
  451.     {
  452.         fprintf(stderr, "readtcppacket: packet is NULL!\n");
  453.         return -1;
  454.     }
  455.     bullshit.s_addr = ip->ip_src.s_addr; bullshit2.s_addr = ip->ip_dst.s_addr;
  456.     /* this is gay */
  457.     realfrag = BSDFIX(ntohs(ip->ip_off) & 8191 /* 2^13 - 1 */);
  458.     tot_len = BSDFIX(ip->ip_len);
  459.     strncpy(sourcehost, inet_ntoa(bullshit), 16);
  460.     i =  4 * (ntohs(ip->ip_hl) + ntohs(tcp->th_off));
  461.     if (ip->ip_p== IPPROTO_TCP) 
  462.     {
  463.         if (realfrag) printf("Packet is fragmented, offset field: %u\n", realfrag);
  464.         else 
  465.         {
  466.             printf("TCP packet: %s:%d -> %s:%d (total: %d bytes)\n", sourcehost, ntohs(tcp->th_sport), inet_ntoa(bullshit2), ntohs(tcp->th_dport), tot_len);
  467.             printf("Flags: ");
  468.             if (!tcp->th_flags) printf("(none)");
  469.             if (tcp->th_flags & TH_RST) printf("RST ");
  470.             if (tcp->th_flags & TH_SYN) printf("SYN ");
  471.             if (tcp->th_flags & TH_ACK) printf("ACK ");
  472.             if (tcp->th_flags & TH_PUSH) printf("PSH ");
  473.             if (tcp->th_flags & TH_FIN) printf("FIN ");
  474.             if (tcp->th_flags & TH_URG) printf("URG ");
  475.             printf("\n");
  476.             printf("ttl: %hu ", ip->ip_ttl);
  477.             if (tcp->th_flags & (TH_SYN | TH_ACK)) printf("Seq: %u\tAck: %u\n", (unsigned int) ntohl(tcp->th_seq), (unsigned int) ntohl(tcp->th_ack));
  478.             else if (tcp->th_flags & TH_SYN) printf("Seq: %u\n", (unsigned int) ntohl(tcp->th_seq));
  479.             else if (tcp->th_flags & TH_ACK) printf("Ack: %u\n", (unsigned int) ntohl(tcp->th_ack));
  480.         }
  481.     }
  482.     if (readdata && i < tot_len) 
  483.     {
  484.         printf("Data portion:\n");
  485.         while(i < tot_len)  printf("%2X%c", data[i], (++i%16)? ' ' : '\n');
  486.         printf("\n");
  487.     }
  488.     return 0;
  489. }
  490.  
  491. /* A simple function I wrote to help in debugging, shows the important fields
  492.    of a UDP packet*/
  493. int readudppacket(char *packet, int readdata) 
  494. {
  495.  
  496.     struct ip *ip = (struct ip *) packet;
  497.     udphdr_bsd *udp = (udphdr_bsd *) (packet + sizeof(struct ip));
  498.     char *data = packet +  sizeof(struct ip) + sizeof(udphdr_bsd);
  499.     int tot_len;
  500.     struct in_addr bullshit, bullshit2;
  501.     char sourcehost[16];
  502.     int i;
  503.     int realfrag = 0;
  504.  
  505.     if (!packet) 
  506.     {
  507.         fprintf(stderr, "readudppacket: packet is NULL!\n");
  508.         return -1;
  509.     }
  510.  
  511.     bullshit.s_addr = ip->ip_src.s_addr; bullshit2.s_addr = ip->ip_dst.s_addr;
  512.     /* this is gay */
  513.     realfrag = BSDFIX(ntohs(ip->ip_off) & 8191 /* 2^13 - 1 */);
  514.     tot_len = BSDFIX(ip->ip_len);
  515.     strncpy(sourcehost, inet_ntoa(bullshit), 16);
  516.     i =  4 * (ntohs(ip->ip_hl)) + 8;
  517.     if (ip->ip_p== IPPROTO_UDP) 
  518.     {
  519.         if (realfrag) printf("Packet is fragmented, offset field: %u\n", realfrag);
  520.         else 
  521.         {
  522.             printf("UDP packet: %s:%d -> %s:%d (total: %d bytes)\n", sourcehost, ntohs(udp->uh_sport), inet_ntoa(bullshit2), ntohs(udp->uh_dport), tot_len);
  523.             printf("ttl: %hu ", ip->ip_ttl);
  524.         }
  525.     }
  526.     if (readdata && i < tot_len) 
  527.     {
  528.         printf("Data portion:\n");
  529.         while(i < tot_len)  printf("%2X%c", data[i], (++i%16)? ' ' : '\n');
  530.         printf("\n");
  531.     }
  532.     return 0;
  533. }
  534.  
  535. int send_udp_raw_decoys( int sd, struct in_addr *victim, unsigned short sport, 
  536.           unsigned short dport, char *data, unsigned short datalen,struct interface_info *ainfo) 
  537. {
  538.     int decoy;
  539.   
  540.     for(decoy = 0; decoy < o.numdecoys; decoy++)
  541.     {
  542.         if (send_udp_raw(sd, &o.decoys[decoy], victim, sport, dport, data, datalen,ainfo) == -1) return -1;
  543.     }
  544.     return 0;
  545. }
  546.  
  547.  
  548.  
  549. int send_udp_raw( int sd, struct in_addr *source, 
  550.           struct in_addr *victim, unsigned short sport, 
  551.           unsigned short dport, char *data, unsigned short datalen,struct interface_info *ainfo) 
  552. {
  553.  
  554.     char *packet = safe_malloc(sizeof(struct ip) + sizeof(udphdr_bsd) + datalen);
  555.     struct ip *ip = (struct ip *) packet;
  556.     udphdr_bsd *udp = (udphdr_bsd *) (packet + sizeof(struct ip));
  557.     static int myttl = 0;
  558.  
  559.     int res;
  560.     struct sockaddr_in sock;
  561.     char myname[MAXHOSTNAMELEN + 1];
  562.     struct hostent *myhostent = NULL;
  563.     int source_malloced = 0;
  564.     struct pseudo_udp_hdr 
  565.     {
  566.         struct in_addr source;
  567.         struct in_addr dest;        
  568.         char zero;
  569.         char proto;        
  570.         unsigned short length;
  571.     } *pseudo = (struct pseudo_udp_hdr *) ((char *)udp - 12) ;
  572.  
  573.     /* check that required fields are there and not too silly */
  574.     if ( !victim || !sport || !dport || sd < 0) 
  575.     {
  576.         fprintf(stderr, "send_udp_raw: One or more of your parameters suck!\n");
  577.         free(packet);
  578.         return -1;
  579.     }
  580.     if (!myttl) myttl = (get_random_uint() % 23) + 37;
  581.     /* It was a tough decision whether to do this here for every packet
  582.     or let the calling function deal with it.  In the end I grudgingly decided
  583.     to do it here and potentially waste a couple microseconds... */
  584.     sethdrinclude(sd); 
  585.     /* if they didn't give a source address, fill in our first address */
  586.     if (!source) 
  587.     {
  588.         source_malloced = 1;
  589.         source = safe_malloc(sizeof(struct in_addr));
  590.         if (gethostname(myname, MAXHOSTNAMELEN) || !(myhostent = gethostbyname(myname)))
  591.         {
  592.             fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
  593.         }
  594.         memcpy(source, myhostent->h_addr_list[0], sizeof(struct in_addr));
  595. #if ( TCPIP_DEBUGGING )
  596.         printf("We skillfully deduced that your address is %s\n", inet_ntoa(*source));
  597. #endif
  598.     }
  599.     /*do we even have to fill out this damn thing?  This is a raw packet, 
  600.     after all */
  601.     sock.sin_family = AF_INET;
  602.     sock.sin_port = htons(dport);
  603.     sock.sin_addr.s_addr = victim->s_addr;
  604.     bzero((char *) packet, sizeof(struct ip) + sizeof(udphdr_bsd));
  605.     udp->uh_sport = htons(sport);
  606.     udp->uh_dport = htons(dport);
  607.     udp->uh_ulen = htons(8 + datalen);
  608.     /* We should probably copy the data over too */
  609.     if (data) memcpy(packet + sizeof(struct ip) + sizeof(udphdr_bsd), data, datalen);
  610.     /* Now the psuedo header for checksuming */
  611.     pseudo->source.s_addr = source->s_addr;
  612.     pseudo->dest.s_addr = victim->s_addr;
  613.     pseudo->proto = IPPROTO_UDP;
  614.     pseudo->length = htons(sizeof(udphdr_bsd) + datalen);
  615.     /* OK, now we should be able to compute a valid checksum */
  616.     udp->uh_sum = in_cksum((unsigned short *)pseudo, 20 /* pseudo + UDP headers */ + datalen);
  617.     /* Goodbye, pseudo header! */
  618.     bzero(pseudo, 12);
  619.     /* Now for the ip header */
  620.     ip->ip_v = 4;
  621.     ip->ip_hl = 5;
  622.     ip->ip_len = BSDFIX(sizeof(struct ip) + sizeof(udphdr_bsd) + datalen);
  623.     get_random_bytes(&(ip->ip_id), 2);
  624.     ip->ip_ttl = myttl;
  625.     ip->ip_p = IPPROTO_UDP;
  626.     if(source->s_addr == victim->s_addr) source->s_addr++;
  627.     ip->ip_src.s_addr = source->s_addr;
  628.     ip->ip_dst.s_addr= victim->s_addr;
  629.     ip->ip_sum = in_cksum((unsigned short *)ip, sizeof(struct ip));
  630.  
  631.  
  632.     if (TCPIP_DEBUGGING > 1) 
  633.     {
  634.         printf("Raw UDP packet creation completed!  Here it is:\n");
  635.         readudppacket(packet,1);
  636.     }
  637.     res = Sendto("send_udp_raw", sd, packet, BSDUFIX(ip->ip_len), 0, (struct sockaddr *)&sock,  (int)sizeof(struct sockaddr_in),ainfo);
  638.     if (source_malloced) free(source);
  639.     free(packet);
  640.     return res;
  641. }
  642.  
  643. int send_small_fragz_decoys(int sd, struct in_addr *victim, unsigned long seq, 
  644.                 int sport, int dport, int flags,struct interface_info *ainfo) {
  645.     int decoy;
  646.  
  647.     for(decoy = 0; decoy < o.numdecoys; decoy++)
  648.     {
  649.         if (send_small_fragz(sd, &o.decoys[decoy], victim, seq, sport, dport, flags,ainfo) == -1) return -1;
  650.     }
  651.     return 0;
  652. }
  653.  
  654. /* Much of this is swiped from my send_tcp_raw function above, which 
  655.    doesn't support fragmentation */
  656. int send_small_fragz(int sd, struct in_addr *source, struct in_addr *victim,
  657.              unsigned long seq, int sport, int dport, int flags,struct interface_info *ainfo)
  658. {
  659.     struct pseudo_header 
  660.     { 
  661.         /*for computing TCP checksum, see TCP/IP Illustrated p. 145 */
  662.         unsigned long s_addy;
  663.         unsigned long d_addr;
  664.         char zer0;
  665.         unsigned char protocol;
  666.         unsigned short length;
  667.     };
  668.     /*In this placement we get data and some field alignment so we aren't wasting
  669.     too much to compute the TCP checksum.*/
  670.     char packet[sizeof(struct ip) + sizeof(struct tcphdr) + 100];
  671.     struct ip *ip = (struct ip *) packet;
  672.     struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct ip));
  673.     struct pseudo_header *pseudo = (struct pseudo_header *) (packet + sizeof(struct ip) - sizeof(struct pseudo_header)); 
  674.     char *frag2 = packet + sizeof(struct ip) + 16;
  675.     struct ip *ip2 = (struct ip *) (frag2 - sizeof(struct ip));
  676.     static int myttl = 0;
  677.     int res;
  678.     struct sockaddr_in sock;
  679.     int id;
  680.  
  681.     if (!myttl)  myttl = (time(NULL) % 14) + 51;
  682.     /* It was a tough decision whether to do this here for every packet
  683.     or let the calling function deal with it.  In the end I grudgingly decided
  684.     to do it here and potentially waste a couple microseconds... */
  685.     sethdrinclude(sd);
  686.     /*Why do we have to fill out this damn thing? This is a raw packet, after all */
  687.     sock.sin_family = AF_INET;
  688.     sock.sin_port = htons(dport);
  689.     sock.sin_addr.s_addr = victim->s_addr;
  690.     bzero((char *)packet, sizeof(struct ip) + sizeof(struct tcphdr));
  691.     pseudo->s_addy = source->s_addr;
  692.     pseudo->d_addr = victim->s_addr;
  693.     pseudo->protocol = IPPROTO_TCP;
  694.     pseudo->length = htons(sizeof(struct tcphdr));
  695.     tcp->th_sport = htons(sport);
  696.     tcp->th_dport = htons(dport);
  697.     tcp->th_seq = (seq)? htonl(seq) : get_random_uint();
  698.     tcp->th_off = 5 /*words*/;
  699.     tcp->th_flags = flags;
  700.     tcp->th_win = htons(2048); /* Who cares */
  701.     tcp->th_sum = in_cksum((unsigned short *)pseudo, sizeof(struct tcphdr) + sizeof(struct pseudo_header));
  702.     /* Now for the ip header of frag1 */
  703.     bzero((char *) packet, sizeof(struct ip)); 
  704.     ip->ip_v = 4;
  705.     ip->ip_hl = 5;
  706.     /*RFC 791 allows 8 octet frags, but I get "operation not permitted" (EPERM)
  707.     when I try that.  */
  708.     ip->ip_len = BSDFIX(sizeof(struct ip) + 16);
  709.     id = ip->ip_id = get_random_uint();
  710.     ip->ip_off = BSDFIX(MORE_FRAGMENTS);
  711.     ip->ip_ttl = myttl;
  712.     ip->ip_p = IPPROTO_TCP;
  713.     ip->ip_src.s_addr = source->s_addr;
  714.     ip->ip_dst.s_addr = victim->s_addr;
  715.  
  716.     ip->ip_sum= in_cksum((unsigned short *)ip, sizeof(struct ip));
  717.     if (o.debugging > 1) 
  718.     {
  719.         log_write(LOG_STDOUT, "Raw TCP packet fragment #1 creation completed!  Here it is:\n");
  720.         log_write(LOG_STDOUT, "\nTrying sendto(%d , packet, %d, 0 , %s , %d)\n", sd, ntohs(ip->ip_len), inet_ntoa(*victim),(int) sizeof(struct sockaddr_in));
  721.         hdump(packet,20);
  722.     }
  723.  
  724.         
  725.     /* Lets save this and send it AFTER we send the second one, just to be
  726.     cute ;) */
  727.         /*if ((res = sendto(sd, packet,sizeof(struct ip) + 16 , 0, (struct sockaddr *)&sock, sizeof(struct sockaddr_in))) == -1)*/
  728.     if ((res = Sendto("send_small_fragz",sd, packet,sizeof(struct ip) + 16 , 0, (struct sockaddr *)&sock, sizeof(struct sockaddr_in),ainfo)) == -1)
  729.     {
  730.         perror("sendto in send_syn_fragz");
  731.         return -1;
  732.     }
  733.     if (o.debugging > 1) log_write(LOG_STDOUT, "successfully sent %d bytes of raw_tcp!\n", res);
  734.  
  735.     /* Create the second fragment */
  736.     bzero((char *) ip2, sizeof(struct ip));
  737.     ip2->ip_v= 4;
  738.     ip2->ip_hl = 5;
  739.     ip2->ip_len = BSDFIX(sizeof(struct ip) + 4); /* the rest of our TCP packet */
  740.     ip2->ip_id = id;
  741.     ip2->ip_off = BSDFIX(2);
  742.     ip2->ip_ttl = myttl;
  743.     ip2->ip_p = IPPROTO_TCP;
  744.         if(source->s_addr == victim->s_addr) source->s_addr++;
  745.     ip2->ip_src.s_addr = source->s_addr;
  746.     ip2->ip_dst.s_addr = victim->s_addr;
  747.     ip2->ip_sum = in_cksum((unsigned short *)ip2, sizeof(struct ip));
  748.     if (o.debugging > 1) 
  749.     {
  750.         log_write(LOG_STDOUT, "Raw TCP packet fragment creation completed!  Here it is:\n");
  751.         hdump(packet,20);
  752.         log_write(LOG_STDOUT, "\nTrying sendto(%d , ip2, %d, 0 , %s , %d)\n", sd, ntohs(ip2->ip_len), inet_ntoa(*victim), (int) sizeof(struct sockaddr_in));
  753.     }
  754.         /*if ((res = sendto(sd, (void *)ip2,sizeof(struct ip) + 4 , 0, (struct sockaddr *)&sock, (int) sizeof(struct sockaddr_in))) == -1)*/
  755.     if ((res = Sendto("send_small_fragz",sd, (void *)ip2,sizeof(struct ip) + 4 , 0, (struct sockaddr *)&sock, (int) sizeof(struct sockaddr_in),ainfo)) == -1)
  756.     {
  757.         perror("sendto in send_tcp_raw frag #2");
  758.         return -1;
  759.     }
  760.     return 1;
  761. }
  762.  
  763. int send_ip_raw_decoys( int sd, struct in_addr *victim, unsigned char proto,
  764.             char *data, unsigned short datalen,struct interface_info *ainfo) 
  765. {
  766.     int decoy;
  767.     for(decoy = 0; decoy < o.numdecoys; decoy++)
  768.     {
  769.         if (send_ip_raw(sd, &o.decoys[decoy], victim, proto, data, datalen,ainfo) == -1) return -1;
  770.     }
  771.     return 0;
  772. }
  773.  
  774. int send_ip_raw( int sd, struct in_addr *source, 
  775.           struct in_addr *victim, unsigned char proto,
  776.           char *data, unsigned short datalen,struct interface_info *ainfo) 
  777. {
  778.     char *packet = safe_malloc(sizeof(struct ip) + datalen);
  779.     struct ip *ip = (struct ip *) packet;
  780.     static int myttl = 0;
  781.     int res = -1;
  782.     struct sockaddr_in sock;
  783.     char myname[MAXHOSTNAMELEN + 1];
  784.     struct hostent *myhostent = NULL;
  785.     int source_malloced = 0;
  786.     /* check that required fields are there and not too silly */
  787.     if ( !victim || sd < 0) 
  788.     {
  789.         fprintf(stderr, "send_ip_raw: One or more of your parameters suck!\n");
  790.         free(packet);
  791.         return -1;
  792.     }
  793.     if (!myttl) myttl = (get_random_uint() % 23) + 37;
  794.     /* It was a tough decision whether to do this here for every packet
  795.     or let the calling function deal with it.  In the end I grudgingly decided
  796.     to do it here and potentially waste a couple microseconds... */
  797.     sethdrinclude(sd); 
  798.     /* if they didn't give a source address, fill in our first address */
  799.     if (!source) 
  800.     {
  801.         source_malloced = 1;
  802.         source = safe_malloc(sizeof(struct in_addr));
  803.         if (gethostname(myname, MAXHOSTNAMELEN) || !(myhostent = gethostbyname(myname))) fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
  804.         memcpy(source, myhostent->h_addr_list[0], sizeof(struct in_addr));
  805. #if ( TCPIP_DEBUGGING )
  806.         printf("We skillfully deduced that your address is %s\n", inet_ntoa(*source));
  807. #endif
  808.     }
  809.     /*do we even have to fill out this damn thing?  This is a raw packet, 
  810.     after all */
  811.     sock.sin_family = AF_INET;
  812.     sock.sin_port = 0;
  813.     sock.sin_addr.s_addr = victim->s_addr;
  814.     bzero((char *) packet, sizeof(struct ip));
  815.     /* Now for the ip header */
  816.     ip->ip_v = 4;
  817.     ip->ip_hl = 5;
  818.     ip->ip_len= BSDFIX(sizeof(struct ip) + datalen);
  819.     get_random_bytes(&(ip->ip_id), 2);
  820.     ip->ip_ttl = myttl;
  821.     ip->ip_p = proto;
  822.     if(source->s_addr == victim->s_addr) source->S_un.S_addr = ainfo->Gateway.S_un.S_addr;
  823.     ip->ip_src.s_addr = source->s_addr;
  824.     ip->ip_dst.s_addr= victim->s_addr;
  825. //#if HAVE_IP_IP_SUM
  826.     ip->ip_sum = in_cksum((unsigned short *)ip, sizeof(struct ip));
  827. //#endif
  828.  
  829.     /* We should probably copy the data over too */
  830.     if (data) memcpy(packet + sizeof(struct ip), data, datalen);
  831.     if (TCPIP_DEBUGGING > 1) 
  832.     {
  833.         printf("Raw IP packet creation completed!  Here it is:\n");
  834.         hdump(packet, BSDUFIX(ip->ip_len));
  835.     }
  836.     res = Sendto("send_ip_raw", sd, packet, BSDUFIX(ip->ip_len), 0,(struct sockaddr *)&sock,  (int)sizeof(struct sockaddr_in),ainfo);
  837.     if (source_malloced) free(source);
  838.     free(packet); 
  839.     return res;
  840. }
  841.  
  842.  
  843.  
  844.  
  845.  
  846.  
  847. int getsourceip(struct in_addr *src, struct in_addr *dst) 
  848. {
  849.     int sd;
  850.     struct sockaddr_in sock;
  851.     int socklen = sizeof(struct sockaddr_in);
  852.     unsigned short p1;
  853.     struct interface_info *mydevs;
  854.     int numinterfaces = 0;
  855.  
  856.     get_random_bytes(&p1, 2);
  857.     if (p1 < 5000) p1 += 5000;
  858.  
  859.     if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
  860.     {
  861.         perror("Socket troubles"); 
  862.         return 0;
  863.     }
  864.     sock.sin_family = AF_INET;
  865.     sock.sin_addr = *dst;
  866.     sock.sin_port = htons(p1);
  867.     if (connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in)) == -1)
  868.     {     
  869.         close(sd);
  870.         mydevs = getinterfaces(&numinterfaces);
  871.         return 1;
  872.     }
  873.     bzero(&sock, sizeof(struct sockaddr_in));
  874.     if (getsockname(sd, (SA *)&sock, &socklen) == -1) 
  875.     {
  876.         perror("getsockname");
  877.         close(sd);
  878.         return 0;
  879.     }
  880.  
  881.     src->s_addr = sock.sin_addr.s_addr;
  882.     close(sd);
  883.     return 1; /* Calling function responsible for checking validity */
  884. }
  885.  
  886.  
  887. /* Read an IP packet using libpcap .  We return the packet and take
  888.    a pcap descripter and a pointer to the packet length (which we set
  889.    in the function. If you want a maximum length returned, you
  890.    should specify that in pcap_open_live() */
  891.  
  892. /* to_usec is the timeout period in microseconds -- use 0 to skip the
  893.    test and -1 to block forever.  Note that we don't interrupt pcap, so
  894.    low values (and 0) degenerate to the timeout specified 
  895.    in pcap_open_live()
  896.  */
  897.  
  898. char *readip_pcap(pcap_t *pd, unsigned int *len, long to_usec) 
  899. {
  900.     int offset = -1;
  901.     struct pcap_pkthdr head;
  902.     char *p;
  903.     int datalink;
  904.     int timedout = 0;
  905.     struct timeval tv_start, tv_end;
  906.  
  907.     if (!pd) fatal("NULL packet device passed to readip_pcap");
  908.  
  909. /* New packet capture device, need to recompute offset */
  910.     if ( (datalink = pcap_datalink(pd)) < 0) fatal("Cannot obtain datalink information: %s", pcap_geterr(pd));
  911.     switch(datalink) 
  912.     { 
  913.         case DLT_EN10MB: 
  914.             offset = 14; 
  915.             break;
  916.         case DLT_IEEE802: 
  917.             offset = 22; 
  918.             break;
  919. #ifdef DLT_LOOP
  920.         case DLT_LOOP:
  921. #endif
  922.         case DLT_NULL: 
  923.             offset = 4; 
  924.             break;
  925.         case DLT_SLIP:
  926.             offset = 24; /* Anyone use this??? */
  927.             break;
  928.         case DLT_PPP: 
  929.             offset = 24; /* Anyone use this? */
  930.             break;
  931.         case DLT_RAW:
  932.             offset = 0; 
  933.             break;
  934.         case DLT_FDDI:
  935.             offset = 21; 
  936.             break;
  937.         default: 
  938.             fatal("Unknown datalink type (%d)", datalink);
  939.     }
  940.  
  941.     if (to_usec > 0) 
  942.     {
  943.         gettimeofday(&tv_start, NULL);
  944.     }
  945.     do 
  946.     {
  947.         p = (char *) pcap_next(pd, &head);
  948.         if (p) p += offset;
  949.         if (!p || (*p & 0x40) != 0x40) 
  950.         {
  951.             /* Should we timeout? */
  952.             if (to_usec == 0) 
  953.             {
  954.                 timedout = 1;
  955.             } 
  956.             else if (to_usec > 0) 
  957.             {
  958.                 gettimeofday(&tv_end, NULL);
  959.                 if (TIMEVAL_SUBTRACT(tv_end, tv_start) >= to_usec) 
  960.                 {
  961.                     timedout = 1;     
  962.                 }
  963.             }
  964.         }
  965.     } while(!timedout && (!p || (*p & 0x40) != 0x40)); /* Go until we get IPv4 packet */
  966.     if (timedout) 
  967.     {
  968.         *len = 0;
  969.         return NULL;
  970.     }
  971.     *len = head.caplen - offset;
  972.     return p;
  973. }
  974.  
  975.  
  976. char *readarp_pcap(pcap_t *pd, unsigned int *len, long to_usec) 
  977. {
  978.     //int offset = -1;
  979.     struct pcap_pkthdr head;
  980.     char *p;
  981.     //int datalink;
  982.     int timedout = 0;
  983.     struct timeval tv_start, tv_end;
  984.  
  985.     if (!pd) fatal("NULL packet device passed to readip_pcap");
  986.  
  987. /* New packet capture device, need to recompute offset */
  988.  
  989.     if (to_usec > 0) 
  990.     {
  991.         gettimeofday(&tv_start, NULL);
  992.     }
  993.     do 
  994.     {
  995.         p = (char *) pcap_next(pd, &head);
  996. //        if (p) p += offset;
  997.         if (!p) 
  998.         {
  999.             /* Should we timeout? */
  1000.             if (to_usec == 0) 
  1001.             {
  1002.                 timedout = 1;
  1003.             } 
  1004.             else if (to_usec > 0) 
  1005.             {
  1006.                 gettimeofday(&tv_end, NULL);
  1007.                 if (TIMEVAL_SUBTRACT(tv_end, tv_start) >= to_usec) 
  1008.                 {
  1009.                     timedout = 1;     
  1010.                 }
  1011.             }
  1012.         }
  1013.     } while(!timedout && (!p)); /* Go until we get IPv4 packet */
  1014.     if (timedout) 
  1015.     {
  1016.         *len = 0;
  1017.         return NULL;
  1018.     }
  1019.     *len = head.caplen;
  1020.     return p;
  1021. }
  1022.  
  1023. int ipaddr2dev( struct interface_info *ainfo, struct in_addr *addr ) 
  1024. {
  1025.     struct interface_info *mydevs;
  1026.     int numdevs;
  1027.     int i;
  1028.     
  1029.     mydevs = getinterfaces(&numdevs);
  1030.     if (!mydevs) return -1;
  1031.     for(i=0; i < numdevs; i++) 
  1032.     {
  1033.         if (addr->s_addr == mydevs[i].addr.s_addr) 
  1034.         {
  1035.             *ainfo = mydevs[i];
  1036.             return 0;
  1037.         }
  1038.     }
  1039.     return -1;
  1040. }
  1041.  
  1042. int id2dev(struct interface_info *ret, long id) 
  1043. {
  1044.     struct interface_info *mydevs;
  1045.     int numdevs;
  1046.     int i;
  1047.  
  1048.     mydevs = getinterfaces(&numdevs);
  1049.     if (!mydevs) return -1;
  1050.  
  1051.     for(i=0; i < numdevs; i++) 
  1052.     {
  1053.         if (id == mydevs[i].ifid ) 
  1054.         {
  1055.             *ret=mydevs[i];
  1056.             return 0;
  1057.         }
  1058.     }
  1059.     return -1;
  1060. }
  1061.  
  1062.  
  1063. int devname2ipaddr(char *dev, struct in_addr *addr) 
  1064. {
  1065.     struct interface_info *mydevs;
  1066.     int numdevs;
  1067.     int i;
  1068.  
  1069.  
  1070.     mydevs = getinterfaces(&numdevs);
  1071.     if (!mydevs) return -1;
  1072.     for(i=0; i < numdevs; i++) 
  1073.     {
  1074.         if (!strcmp(dev, mydevs[i].name)) 
  1075.         {  
  1076.             memcpy(addr, (char *) &mydevs[i].addr, sizeof(struct in_addr));
  1077.             return 0;
  1078.         }
  1079.     }    
  1080.     return -1;
  1081. }
  1082.  
  1083.  
  1084.  
  1085. struct interface_info *getinterfaces(int *howmany) 
  1086. {
  1087.     static int initialized = 0;
  1088.     static struct interface_info mydevs[10];
  1089.     static int numinterfaces = 0;
  1090.     DWORD dwVersion;
  1091.     DWORD dwWindowsMajorVersion;
  1092.  
  1093.     static struct _IPlist iplist[100];
  1094.     static struct myroute routelist[100];
  1095.     static struct _IFlist iflist[100];
  1096.     //    int sd;
  1097. //    int len;
  1098. //    char buf[10240];
  1099. //    DWORD dwVersion;
  1100. //    DWORD dwWindowsMajorVersion;
  1101.     char AdapterList[10][1024];
  1102.     LPADAPTER  lpAdapter = 0;
  1103.         //unicode strings (winnt)
  1104.     WCHAR        AdapterName[512]; // string that contains a list of the network adapters
  1105.     WCHAR        *temp,*temp1;
  1106.     int i,x,holdi,j;    
  1107.     DWORD      dwErrorCode;
  1108.     char        AdapterNamea[512]; // string that contains a list of the network adapters
  1109.     char        *tempa,*temp1a;
  1110.     int            icount;
  1111.  
  1112. //setup temp vars for all the cool stuff
  1113.     BYTE tempMAC[6];
  1114.     DWORD tempIP=0,tempGW=0;
  1115.     LPADAPTER tempadapter;
  1116.     char tempname[512],tempchop[512],tempwname[1024];
  1117.     long tempid;
  1118.  
  1119.  
  1120.     char temp3[512];
  1121.     int            AdapterNum=0;
  1122.     ULONG        AdapterLength=512;
  1123.  
  1124.  
  1125.     if (!initialized) 
  1126.     { 
  1127.         FillIpList(iplist);
  1128.         FillRouteList(routelist);
  1129.         FillIfList(iflist, &icount);
  1130.  
  1131.         numinterfaces=0;
  1132.         initialized = 1;    
  1133.         dwVersion=GetVersion();
  1134.         dwWindowsMajorVersion =  (DWORD)(LOBYTE(LOWORD(dwVersion)));
  1135.         if (!(dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4))
  1136.         {  // Windows NT
  1137.             //set up the adapter list
  1138.             for(x=0;x<10;x++)
  1139.             {
  1140.                 memset (AdapterList[x],0,1024);
  1141.             }
  1142.             x=0;
  1143.             
  1144.             PacketGetAdapterNames((char *)AdapterName,&AdapterLength);
  1145.             temp=AdapterName;
  1146.             temp1=AdapterName;
  1147.             while ((*temp!='\0')||(*(temp-1)!='\0'))
  1148.             {
  1149.                 if (*temp=='\0') 
  1150.                 {
  1151.                     memcpy(AdapterList[x],temp1,(temp-temp1)*2);
  1152.                     temp1=temp+1;
  1153.                     x++;
  1154.                 }
  1155.                 temp++;
  1156.             }
  1157.  
  1158.             if(o.debugging) printf("%d\n",x);
  1159. //            for(numinterfaces=0;numinterfaces<=i;numinterfaces++)
  1160.             for(holdi=0;holdi<x;holdi++)
  1161.             {
  1162.                 //clean the temp vars
  1163.                 memset(tempMAC,0,6);
  1164.                 j=0;
  1165.                 
  1166.                 tempIP=0;
  1167.                 tempGW=0;
  1168.                 tempadapter = NULL;
  1169.                 memset(tempname,0,512);
  1170.                 memset(tempchop,0,512);
  1171.                 memset(tempwname,0,1024);
  1172.                     
  1173.  
  1174.                 
  1175.                 //copy the unicode chosen adapterlist to ascii
  1176.                 wcstombs(temp3,(WCHAR *)AdapterList[holdi],512);
  1177.                 strncpy(tempname,temp3,512);
  1178.                 if(o.debugging) printf("interface:%d\n",holdi);
  1179.                 if(o.debugging) printf("name:%s\n",temp3);
  1180.                 i=0;
  1181.                 //fuill the g_aname with info 
  1182.                 while(temp3[i]!='\0')
  1183.                 {
  1184.                     if(temp3[i]=='_')
  1185.                     {
  1186.                         strncpy(tempchop,&temp3[i+1],512);    
  1187.                         break;
  1188.                     };
  1189.                     i++;        
  1190.                 };
  1191.                 if(o.debugging) printf("%s\n",tempchop);
  1192.                 wcscpy((WCHAR *)tempwname,(WCHAR *)AdapterList[holdi]);
  1193.                 //open the adapter
  1194.                 tempadapter = PacketOpenAdapter(tempwname);
  1195.                 if (!tempadapter || (tempadapter->hFile == INVALID_HANDLE_VALUE))
  1196.                 {
  1197.                     dwErrorCode=GetLastError();
  1198.                     if(o.debugging) printf("Unable to open the driver, Error Code : %lx\n",dwErrorCode); 
  1199.                     //return FALSE;
  1200.                 }
  1201.                 else
  1202.                 {    
  1203.                     memcpy(tempMAC, getmac_info(tempadapter),6);
  1204.                     while(iflist[j].id>0)
  1205.                     {
  1206.                         if(!memcmp(tempMAC,iflist[j].MAC,6))
  1207.                         {
  1208.                             tempid = iflist[j].id;
  1209.                             break;
  1210.                         }
  1211.                         j++;
  1212.                     };
  1213.                     j=0;
  1214.                     while(iplist[j].id>0)
  1215.                     {
  1216.                         if(tempid == iplist[j].id)
  1217.                         {
  1218.                             tempIP = iplist[j].ip;
  1219.                             break;
  1220.                         }
  1221.                         j++;
  1222.                     };
  1223.                     j=0;
  1224.                     while(routelist[j].ifid>0)
  1225.                     {
  1226.                         if(routelist[j].dest == 0)
  1227.                         {
  1228.                             tempGW = routelist[j].nexthop;
  1229.                             break;
  1230.                         }
  1231.                         j++;
  1232.                     };
  1233. //                    tempIP=getreg_ip(tempchop);
  1234. //                    tempGW=getreg_gw(tempchop);
  1235.                     //memcpy(tempMAC, getmac_info(tempadapter),6);
  1236.                     if(o.debugging) printf("IP:%d\n",tempIP);
  1237.                     if(o.debugging) printf("GW:%d\n",tempGW);
  1238.                     if(o.debugging) printf("MAC:%d\n",tempMAC);
  1239.                     //PacketSetBuff(tempadapter,512000);
  1240.                     PacketSetHwFilter(tempadapter,NDIS_PACKET_TYPE_PROMISCUOUS);
  1241.                 }
  1242.                 // if it's bad, skip setting it up
  1243.                 if ((tempIP >0) && (tempGW >0) && tempadapter)
  1244.                 {
  1245.                     mydevs[numinterfaces].adapter=tempadapter;
  1246.                     mydevs[numinterfaces].ifid=tempid;
  1247.                     strncpy(mydevs[numinterfaces].name,tempname,512);
  1248.                     mydevs[numinterfaces].addr.S_un.S_addr = tempIP;
  1249.                     mydevs[numinterfaces].Gateway.S_un.S_addr = tempGW;
  1250.                     memcpy(mydevs[numinterfaces].MAC,tempMAC,6);
  1251.                     //else it's good
  1252.                     numinterfaces++;
  1253.                 }
  1254.                 //adjust the sending buffer
  1255.                 if(o.debugging) printf("next NT device\n");
  1256.                 //    PacketSetNumWrites(g_Info->lpAdapter,100);
  1257.             }
  1258.         }
  1259. //    }
  1260.         else
  1261.         {
  1262.             for(x=0;x<10;x++)
  1263.             {
  1264.                 memset (AdapterList[x],0,1024);
  1265.             }
  1266.             x=0;
  1267.             PacketGetAdapterNames((char *)AdapterNamea,&AdapterLength);
  1268.             tempa=AdapterNamea;
  1269.             temp1a=AdapterNamea;
  1270.  
  1271.  
  1272.             while ((*tempa!='\0')||(*(tempa-1)!='\0'))
  1273.             {
  1274.                 if (*tempa=='\0') 
  1275.                 {
  1276.                     memcpy(AdapterList[x],temp1a,(tempa-temp1a)*2);
  1277.                     temp1a=tempa+1;
  1278.                     x++;
  1279.                 }
  1280.                 tempa++;
  1281.             }
  1282.     
  1283.             for(holdi=0;holdi<x;holdi++)
  1284.             {
  1285.                 //copy the unicode chosen adapterlist to ascii
  1286.                 //wcstombs(temp3,(WCHAR *)AdapterList[numinterfaces],512);
  1287.                 strcpy(tempname,AdapterList[holdi]);
  1288.                 i=0;
  1289.                 if(o.debugging) printf("adapter:%s\n",tempname);
  1290.                 //fuill the g_aname with info 
  1291.                 //                sprintf(tempchop,"Class\\NetTrans\\%s",tempchop);
  1292.                 //if(o.debugging) printf("postchop:%s\n",tempchop);
  1293.                 tempadapter = PacketOpenAdapter(tempname);
  1294.                 if (!tempadapter || (tempadapter->hFile == INVALID_HANDLE_VALUE))
  1295.                 {
  1296.                     dwErrorCode=GetLastError();
  1297.                     if(o.debugging) printf("Unable to open the driver, Error Code : %lx\n",dwErrorCode); 
  1298.                     //return FALSE;
  1299.                 }
  1300.                 else
  1301.                 {    
  1302.                     memcpy(tempMAC, getmac_info(tempadapter),6);
  1303.                     j=0;
  1304.                     while(iflist[j].id>0)
  1305.                     {
  1306.                         if(!memcmp(tempMAC,iflist[j].MAC,6))
  1307.                         {
  1308.                             tempid = iflist[j].id;
  1309.                             break;
  1310.                         }
  1311.                         j++;
  1312.                     };
  1313.                     j=0;
  1314.                     while(iplist[j].id>0)
  1315.                     {
  1316.                         if(tempid == iplist[j].id)
  1317.                         {
  1318.                             tempIP = iplist[j].ip;
  1319.                             break;
  1320.                         }
  1321.                         j++;
  1322.                     };
  1323.                     j=0;
  1324.                     while(routelist[j].ifid>0)
  1325.                     {
  1326.                         if(routelist[j].dest == 0)
  1327.                         {
  1328.                             tempGW = routelist[j].nexthop;
  1329.                             break;
  1330.                         }
  1331.                         j++;
  1332.                     };                    
  1333.                     if(o.debugging) printf("IP:%d\n",tempIP);
  1334.                     if(o.debugging) printf("adapter symbolic link:%s\n",tempadapter->SymbolicLink);
  1335.                     if(o.debugging) printf("GW:%d\n",tempGW);
  1336.                     if(o.debugging) printf("MAC:%d\n",tempMAC);
  1337.                     PacketSetHwFilter(tempadapter,NDIS_PACKET_TYPE_PROMISCUOUS);
  1338.                     PacketSetBuff(tempadapter,512000);
  1339.                 }
  1340.  
  1341.                 if ((tempIP >0) && (tempGW >0) && tempadapter)
  1342.                 {
  1343.                     mydevs[numinterfaces].adapter=tempadapter;
  1344.                     mydevs[numinterfaces].ifid=tempid;
  1345.                     strncpy(mydevs[numinterfaces].name,tempname,512);
  1346.                     mydevs[numinterfaces].addr.S_un.S_addr = tempIP;
  1347.                     mydevs[numinterfaces].Gateway.S_un.S_addr = tempGW;
  1348.                     memcpy(mydevs[numinterfaces].MAC,tempMAC,6);
  1349.                     //else it's good
  1350.                     numinterfaces++;
  1351.                 }
  1352.                 //adjust the sending buffer                
  1353.                 //    PacketSetNumWrites(g_Info->lpAdapter,100);
  1354.                 if(o.debugging) printf("next 95 device\n");
  1355.             }
  1356.         }
  1357.     }
  1358.     if (howmany) *howmany = numinterfaces;
  1359.     return mydevs;
  1360. }
  1361.  
  1362.  
  1363. /* An awesome function to determine what interface a packet to a given
  1364.    destination should be routed through.  It returns NULL if no appropriate
  1365.    interface is found, oterwise it returns the device name and fills in the
  1366.    source parameter.   Some of the stuff is
  1367.    from Stevens' Unix Network Programming V2.  He had an easier suggestion
  1368.    for doing this (in the book), but it isn't portable :( */
  1369. #define ROUTETHROUGH_MAXROUTES 512
  1370. struct interface_info routethrough(struct in_addr *dest, struct in_addr *source) {
  1371.   static int initialized = 0;
  1372.   int i;
  1373.   //struct in_addr addy;
  1374.   static enum { procroutetechnique, connectsockettechnique, guesstechnique } technique = procroutetechnique;
  1375. //  char buf[10240];
  1376.   struct interface_info *mydevs;
  1377.   static struct myroute myroutes[ROUTETHROUGH_MAXROUTES];
  1378.   int numinterfaces = 0;
  1379. //  char *p, *endptr;
  1380. //  char iface[64];
  1381.   static int numroutes = 0;
  1382.   struct interface_info ret;
  1383. //  routez;
  1384.  
  1385.   if (!dest) fatal("ipaddr2devname passed a NULL dest address");
  1386.     memset (&ret,0,sizeof(struct interface_info));
  1387.   if (!initialized) 
  1388.   {  
  1389.     /* Dummy socket for ioctl */
  1390.     initialized = 1;
  1391.     mydevs = getinterfaces(&numinterfaces);
  1392.     memset(myroutes,0,sizeof(struct myroute)*ROUTETHROUGH_MAXROUTES);
  1393.     numroutes=FillRouteList(myroutes);
  1394.  
  1395. //#if TCPIP_DEBUGGING
  1396. //      printf("#%d: for dev %s, The dest is %X and the mask is %X\n", numroutes, iface, myroutes[numroutes].dest, myroutes[numroutes].mask);
  1397. //#endif
  1398. //    for(i=0; i < numroutes; i++)
  1399. //    {
  1400. //         myroutes[numroutes].dev=id2dev(myroutes[i].ifid);
  1401. //    }
  1402. //    if (i == numinterfaces) fatal("Failed to find interface %s mentioned in route table\n", iface);
  1403.     
  1404.     if (numroutes == ROUTETHROUGH_MAXROUTES)
  1405.       fatal("My god!  You seem to have WAY to many routes!\n");
  1406.   }
  1407.     
  1408.     
  1409. //  } else {  
  1410. //    mydevs = getinterfaces(&numinterfaces);
  1411. //  }
  1412.   /* WHEW, that takes care of initializing, now we have the easy job of 
  1413.      finding which route matches */
  1414.  // if (islocalhost(dest)) {
  1415.  //   if (source)
  1416.  //     source->s_addr = htonl(0x7F000001);
  1417.  //   /* Now we find the localhost interface name, assuming 127.0.0.1 is
  1418.  //      localhost (it damn well better be!)... */
  1419.  //   for(i=0; i < numinterfaces; i++) {    
  1420.  //     if (mydevs[i].addr.s_addr == htonl(0x7F000001)) {
  1421. //    return mydevs[i];
  1422. //      }
  1423. //    }
  1424. //    return ret;
  1425. //  }
  1426.  
  1427.  // if (technique == procroutetechnique) {    
  1428.     for(i=0; i < numroutes; i++) 
  1429.     {  
  1430.         if ((dest->s_addr & myroutes[i].mask) == myroutes[i].dest) 
  1431.         {
  1432.             id2dev(&ret,myroutes[i].ifid);
  1433.             if (source) 
  1434.             {
  1435.                 source->s_addr = ret.addr.s_addr;
  1436.             }
  1437.             return ret;      
  1438.         }
  1439.     }
  1440. //  } else if (technique == connectsockettechnique) {
  1441.   //    if (!getsourceip(&addy, dest))
  1442. //    return NULL;
  1443. //      if (!addy.s_addr)  {  /* Solaris 2.4 */
  1444. //      struct hostent *myhostent = NULL;
  1445. //      char myname[MAXHOSTNAMELEN + 1];
  1446. //      if (gethostname(myname, MAXHOSTNAMELEN) || 
  1447. //         !(myhostent = gethostbyname(myname)))
  1448. // fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
  1449. //      memcpy(&(addy.s_addr), myhostent->h_addr_list[0], sizeof(struct in_addr));
  1450. //#if ( TCPIP_DEBUGGING )
  1451. //      printf("We skillfully deduced that your address is %s\n", 
  1452. //        inet_ntoa(*source));
  1453. //#endif
  1454. //      }
  1455.  
  1456.       /* Now we insure this claimed address is a real interface ... */
  1457. //      for(i=0; i < numinterfaces; i++)
  1458. //    if (mydevs[i].addr.s_addr == addy.s_addr) {
  1459. //      if (source) {
  1460. //        source->s_addr = addy.s_addr;      
  1461. //      }
  1462. //      return mydevs[i].name;
  1463. //    }  
  1464. //    return NULL;
  1465. //    } else 
  1466. //      fatal("I know sendmail technique ... I know rdist technique ... but I don't know what the hell kindof technique you are attempting!!!");
  1467.     return ret;
  1468. }
  1469.  
  1470. /* An awesome function to determine what interface a packet to a given
  1471.    destination should be routed through.  It returns NULL if no appropriate
  1472.    interface is found, oterwise it returns the device name and fills in the
  1473.    source parameter.   Some of the stuff is
  1474.    from Stevens' Unix Network Programming V2.  He had an easier suggestion
  1475.    for doing this (in the book), but it isn't portable :( *
  1476. #define ROUTETHROUGH_MAXROUTES 512
  1477. struct interface_info routethrough(struct in_addr *dest, struct in_addr *source) 
  1478. {
  1479.     static int initialized = 0;
  1480.     int i;
  1481.     struct in_addr addy;
  1482. //    static enum { procroutetechnique, connectsockettechnique, guesstechnique } technique = procroutetechnique;
  1483. //    char buf[10240];
  1484.     struct interface_info *mydevs;
  1485.  
  1486.     struct interface_info ret;
  1487.     int numinterfaces = 0;
  1488. //    char *p, *endptr;
  1489. //    char iface[64];
  1490.     static int numroutes = 0;
  1491. //    FILE *routez;
  1492.  
  1493.     memset (&ret,0,sizeof(struct interface_info));
  1494.     if (!dest) fatal("ipaddr2devname passed a NULL dest address");
  1495.     if (!initialized) 
  1496.     {  
  1497.         /* Dummy socket for ioctl 
  1498.         initialized = 1;
  1499.         mydevs = getinterfaces(&numinterfaces);
  1500.     } 
  1501.     else 
  1502.     {  
  1503.         mydevs = getinterfaces(&numinterfaces);
  1504.     }
  1505.     /* WHEW, that takes care of initializing, now we have the easy job of 
  1506.      finding which route matches 
  1507. //    if (islocalhost(dest)) 
  1508. //    {
  1509. //        if (source) source->s_addr = htonl(0x7F000001);
  1510. //        /* Now we find the localhost interface name, assuming 127.0.0.1 is
  1511. //        localhost (it damn well better be!)... 
  1512. //        for(i=0; i < numinterfaces; i++) 
  1513. //        {
  1514. //            if (mydevs[i].addr.s_addr == htonl(0x7F000001)) 
  1515. //            {
  1516. //                return mydevs[i].name;
  1517. //            }
  1518. //        }
  1519. //        if (mydevs[0].adapter != NULL) global_adapter = mydevs[0];
  1520. //        return mydevs[0].name;
  1521. //    }
  1522.  
  1523.         if (!getsourceip(&addy, dest)) return ret;
  1524.         if (!addy.s_addr)  
  1525.         {  
  1526.             //struct hostent *myhostent = NULL;
  1527.             //char myname[MAXHOSTNAMELEN + 1];
  1528.             //if (gethostname(myname, MAXHOSTNAMELEN) || !(myhostent = gethostbyname(myname))) 
  1529.                 fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
  1530.             //memcpy(&(addy.s_addr), myhostent->h_addr_list[0], sizeof(struct in_addr));
  1531. //#if ( TCPIP_DEBUGGING )
  1532.             //printf("We skillfully deduced that your address is %s\n", inet_ntoa(*source));
  1533. //#endif
  1534.         }
  1535.           /* Now we insure this claimed address is a real interface ... 
  1536.         for(i=0; i < numinterfaces; i++)
  1537.         {
  1538.             if (mydevs[i].addr.s_addr == addy.s_addr) 
  1539.             {
  1540.                 if (source) 
  1541.                 {
  1542.                     if (addy.S_un.S_addr == dest->S_un.S_addr) addy.s_addr++;      
  1543.                     source->s_addr = addy.s_addr;      
  1544.                 }
  1545.                 //if (mydevs[i].adapter != NULL) global_adapter = mydevs[i];
  1546.                 return mydevs[i];
  1547.             }  
  1548.             return ret;
  1549.         }
  1550.     return ret;
  1551. }*/
  1552.  
  1553. BYTE *getmac_info(LPADAPTER adapter)
  1554. {
  1555.     ULONG      IoCtlBufferLength=(sizeof(PACKET_OID_DATA)+sizeof(ULONG)-1);
  1556.     PPACKET_OID_DATA OidData;
  1557.     BOOL    torf;
  1558.  
  1559.     char *MAC;
  1560.  
  1561.     MAC = malloc(6);
  1562.     OidData=(struct _PACKET_OID_DATA *) malloc(IoCtlBufferLength);
  1563.     if (OidData == NULL) {
  1564.         return NULL;
  1565.     }
  1566.     OidData->Oid = OID_802_3_CURRENT_ADDRESS;
  1567.     OidData->Length = 6;
  1568.     torf=PacketRequest(adapter,FALSE,OidData);
  1569.     if(torf==FALSE)
  1570.     {
  1571.         memset(MAC,0,6);
  1572.     }
  1573.     else
  1574.     {
  1575.         memcpy(MAC,OidData->Data,6);
  1576.     }
  1577.     return MAC;
  1578. }
  1579.  
  1580.  
  1581. /* come back to this at a later date, needs some serious rework
  1582. BYTE * get_remote_mac(DWORD IP,struct interface_info *ainfo)
  1583. {
  1584.     struct macs
  1585.     {
  1586.         DWORD    ip;
  1587.         BYTE    MAC[6];
  1588.     };
  1589.  
  1590.     static struct macs foundmacs[512];
  1591.     static int init;
  1592.     static int countmacs;
  1593.     BYTE *MAC=malloc(6);
  1594.     BYTE bcastmac[]= {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
  1595.     int i=0,x;
  1596.     pcap_t *pd;
  1597.  
  1598.     unsigned int localnet, netmask;
  1599.     char err0r[PCAP_ERRBUF_SIZE];
  1600.     char filter[512];
  1601.     static struct bpf_program fcode;
  1602.     int bytes,xmac=0,timedout=0;
  1603.  
  1604.     BYTE *packet;
  1605.  
  1606.     
  1607.     if(!init)
  1608.     {
  1609.         countmacs=0;
  1610.     }
  1611.     
  1612.     memset (MAC,0,6);
  1613.     for (i=0;i<=countmacs;i++)
  1614.     {
  1615.         if (IP == foundmacs[i].ip) return foundmacs[i].MAC;
  1616.     }
  1617.  
  1618.     pd = my_pcap_open_live(ainfo->name, 650,  1, 3000000);
  1619.  
  1620.  
  1621.     if (pcap_lookupnet(ainfo->name, &localnet, &netmask, err0r) < 0) fatal("Failed to lookup device subnet/netmask: %s", err0r);
  1622.  
  1623.     snprintf(filter, sizeof(filter), "arp && ether[0] & 0x1 = 0");
  1624.  
  1625.  
  1626.     if (o.debugging) log_write(LOG_STDOUT, "Packet capture filter: %s\n", filter);
  1627.     if(!init)
  1628.     {
  1629.             init =1;
  1630.         if (pcap_compile(pd, &fcode, filter, 0, netmask) < 0) 
  1631.         {
  1632.             fatal("Error compiling our pcap filter: %s\n", pcap_geterr(pd));
  1633.         }    
  1634.     }
  1635.  
  1636. //    if (pcap_compile(pd, &fcode, filter, 0, netmask) < 0) 
  1637. //    {
  1638. //        fatal("Error compiling our pcap filter: %s\n", pcap_geterr(pd));
  1639. //    }
  1640.     if (pcap_setfilter(pd, &fcode) < 0 ) fatal("Failed to set the pcap filter: %s\n", pcap_geterr(pd));
  1641.  
  1642.     send_arp(IP,ainfo);
  1643.     Sleep(50);
  1644.     for(x=0;x<3;x++)
  1645.     {
  1646.         packet=NULL;
  1647.         packet = (BYTE *) readarp_pcap(pd, &bytes, 6000);
  1648.         if (packet !=NULL)
  1649.         {
  1650.             if ((!memcmp(&packet[28],&IP,4)) && (memcmp(packet,bcastmac,6))  )
  1651.             {    
  1652.                 memcpy(MAC,&packet[22],6);
  1653.                 xmac=1;
  1654.                 break;
  1655.             }
  1656.         }
  1657.     }
  1658.     if (!xmac)
  1659.     {
  1660.         timedout=0;
  1661.         send_arp(ainfo->Gateway.S_un.S_addr,ainfo);
  1662.         Sleep(50);
  1663.         for(x=0;x<3;x++)
  1664.         {
  1665.             packet=NULL;
  1666.             packet = (BYTE *) readarp_pcap(pd, &bytes, 6000000);
  1667.             if (packet !=NULL)
  1668.             {
  1669.                 if ((!memcmp(&packet[28],&ainfo->Gateway.S_un.S_addr,4)) && (memcmp(packet,bcastmac,6))  )
  1670.                 {    
  1671.                     memcpy(MAC,&packet[22],6);
  1672.                     xmac=1;
  1673.                     break;
  1674.                 }
  1675.             }
  1676.         }                
  1677.     }
  1678.     if (!xmac)
  1679.     {
  1680.         memcpy(MAC,bcastmac,6);
  1681.     }
  1682.  
  1683.     if (pd)
  1684.     {
  1685.         //pcap_freecode(pd, &fcode);
  1686.         pcap_close(pd);
  1687.     }
  1688.     foundmacs[countmacs].ip = IP;
  1689.     memcpy(foundmacs[countmacs].MAC,MAC,6);
  1690.     countmacs++;
  1691.     return MAC;
  1692. }
  1693. */
  1694.  
  1695.  
  1696.  
  1697.  
  1698. BYTE * FindMAC(DWORD IP,struct interface_info *ainfo)
  1699. {
  1700.     BYTE *MAC=NULL;
  1701.     int status,status2,ci,i;
  1702.     PMIB_IPNETTABLE pIpNetTable = NULL;
  1703.     PMIB_IPADDRTABLE pIpAddrTable = NULL;
  1704.     DWORD Size,Size2;
  1705.     BOOL fOrder=TRUE;
  1706.  
  1707.     Size = Size2 = 0;
  1708.  
  1709.     if(ainfo->adapter!= NULL)
  1710.     {
  1711.         status = GetIpNetTable(pIpNetTable, &Size, fOrder);
  1712.     if (status == ERROR_INSUFFICIENT_BUFFER)
  1713.     {
  1714.         pIpNetTable = (PMIB_IPNETTABLE) malloc(Size);
  1715.         assert(pIpNetTable);        
  1716.         status = GetIpNetTable(pIpNetTable, &Size, fOrder);
  1717.     }
  1718.  
  1719.  
  1720.     if(status == NO_ERROR)
  1721.     {
  1722.     
  1723.         if (pIpNetTable == NULL)    
  1724.         {
  1725.             printf( "pIpNetTable == NULL in line %d\n", __LINE__);    
  1726.         }
  1727.         status2 = GetIpAddrTable(pIpAddrTable, &Size2, fOrder);
  1728.         if (status2 == ERROR_INSUFFICIENT_BUFFER)
  1729.         {
  1730.             pIpAddrTable = (PMIB_IPADDRTABLE) malloc(Size2);
  1731.             assert(pIpAddrTable);        
  1732.             status2 = GetIpAddrTable(pIpAddrTable, &Size2, fOrder);
  1733.         }
  1734.  
  1735.         if ( status2 != NO_ERROR)
  1736.         {
  1737.             printf("GetIpAddrTable returned 0x%x\n", status2);
  1738.             if (pIpAddrTable) free(pIpAddrTable);
  1739.             MAC = NULL;
  1740.         }
  1741.         assert(pIpAddrTable);
  1742.         ci = pIpNetTable->table[0].dwIndex;
  1743.  
  1744.         
  1745.         for (i = 0; i < (int)pIpNetTable->dwNumEntries; ++i)
  1746.         {
  1747.             if ((int)pIpNetTable->table[i].dwIndex != ci)
  1748.             {
  1749.                 ci = (int)pIpNetTable->table[i].dwIndex;
  1750.             }
  1751.  
  1752.             if(pIpNetTable->table[i].dwAddr==IP)
  1753.             {
  1754.                 return pIpNetTable->table[i].bPhysAddr;
  1755.             }        
  1756.         }
  1757.         free(pIpNetTable);
  1758.     }
  1759.     else if ( status == ERROR_NO_DATA)
  1760.     {
  1761.         printf("No entries in arp cache.\n");
  1762.         if (pIpNetTable)
  1763.             free (pIpNetTable);
  1764.         MAC=NULL;
  1765. //        memset(MAC,0,6);    
  1766.     }
  1767.     else
  1768.     {
  1769.         if (pIpNetTable)
  1770.             free (pIpNetTable);
  1771.         printf("mac lookup returned 0x%x\n", status);
  1772.         //memset(MAC,0,6);    
  1773.                 MAC=NULL;
  1774.     }
  1775.     }
  1776. return NULL;
  1777. }
  1778.  
  1779. BYTE * get_remote_mac(DWORD IP,struct interface_info *ainfo)
  1780. {
  1781.     struct macs
  1782.     {
  1783.         DWORD    ip;
  1784.         BYTE    MAC[6];
  1785.     };
  1786.  
  1787.     static struct macs foundmacs[512];
  1788.     static int init;
  1789.     static int countmacs;
  1790.     BYTE *MAC=malloc(6);
  1791.     BYTE bcastmac[]= {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
  1792.     int i=0;
  1793.  
  1794.     if(!init)
  1795.     {
  1796.         init =1;
  1797.         countmacs=0;
  1798.     }
  1799.     
  1800.     for (i=0;i<=countmacs;i++)
  1801.     {
  1802.         if (IP == foundmacs[i].ip) return foundmacs[i].MAC;
  1803.     }
  1804.  
  1805.  
  1806.     MAC=FindMAC(IP,ainfo);
  1807.     if (MAC==NULL)
  1808.     {
  1809.         send_arp(IP,ainfo);
  1810.         Sleep(10);
  1811.         MAC=FindMAC(IP,ainfo);
  1812.         if (MAC==NULL)
  1813.         {
  1814.             MAC=FindMAC(ainfo->Gateway.S_un.S_addr,ainfo);
  1815.             if (MAC==NULL)
  1816.             {
  1817.                 send_arp(ainfo->Gateway.S_un.S_addr,ainfo);
  1818.                 Sleep(10);
  1819.                 MAC=FindMAC(ainfo->Gateway.S_un.S_addr,ainfo);
  1820.                 if (MAC==NULL)
  1821.                 {
  1822.                     MAC=bcastmac;
  1823.                 }
  1824.             }
  1825.         }
  1826.     }
  1827.     
  1828.     foundmacs[countmacs].ip = IP;
  1829.     memcpy(foundmacs[countmacs].MAC,MAC,6);
  1830.     countmacs++;
  1831.     return MAC;
  1832. }
  1833.  
  1834.  
  1835. BOOL send_arp(DWORD IP,struct interface_info *ainfo)
  1836. {
  1837.     LPPACKET   lpPacket;
  1838.     int len;
  1839.     u_char    buf[42]={
  1840.         0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  1841.         0x00,0x00,0x00,0x00,0x00,0x00,
  1842.         0x08,0x06,
  1843.         0x00,0x01,
  1844.         0x08,0x00,
  1845.         0x06,
  1846.         0x04,
  1847.         0x00,0x01,
  1848.         0x00,0x00,0x00,0x00,0x00,0x00,
  1849.         0x00,0x00,0x00,0x00,
  1850.         0x00,0x00,0x00,0x00,0x00,0x00,
  1851.         0x00,0x00,0x00,0x00};
  1852.     BOOL ret;
  1853.     memcpy(buf+6,ainfo->MAC,6);
  1854.     memcpy(buf+22,ainfo->MAC,6);
  1855.     memcpy(buf+28,&ainfo->addr.S_un.S_addr,4);
  1856.     memcpy(buf+38,&IP,4);
  1857.     len=42;
  1858.  
  1859.     if((lpPacket = PacketAllocatePacket())==NULL){
  1860.         printf("\nError:failed to allocate the LPPACKET structure.");
  1861.         return (-1);
  1862.     }
  1863.     PacketInitPacket(lpPacket,buf,len);
  1864.     ret=PacketSendPacket(ainfo->adapter,lpPacket,TRUE);
  1865.     if(ret==FALSE)
  1866.     {
  1867.         printf("PacketSendPacket failed\n");
  1868.     }
  1869.     PacketFreePacket(lpPacket);
  1870.  
  1871.     return TRUE;
  1872. }
  1873.  
  1874.  
  1875.  
  1876. int build_ethernet(u_char *dst, u_char *src, u_short type, const u_char *payload, int payload_s, u_char *buf)
  1877. {
  1878.     struct ethernet_hdr eth_hdr;
  1879.  
  1880.     if (!buf)
  1881.     {
  1882.         return (-1);
  1883.     }
  1884.  
  1885.     memcpy(eth_hdr.ether_dhost, dst, ETHER_ADDR_LEN);  /* destination address */
  1886.     memcpy(eth_hdr.ether_shost, src, ETHER_ADDR_LEN);  /* source address */
  1887.     eth_hdr.ether_type = htons(type);                  /* packet type */
  1888.  
  1889.     if (payload && payload_s)
  1890.     {
  1891.         /*
  1892.          *  Unchecked runtime error for buf + ETH_H payload to be greater than
  1893.          *  the allocated heap memory.
  1894.          */
  1895.         memcpy(buf + 14, payload, payload_s);
  1896.     }
  1897.     memcpy(buf, ð_hdr, sizeof(eth_hdr));
  1898.     return (1);
  1899. }
  1900.  
  1901. void print_interfaces()
  1902. {
  1903.     struct interface_info *mydevs;
  1904.     int numinterfaces = 0,count=0;
  1905.   
  1906.     mydevs=getinterfaces(&numinterfaces);
  1907.  
  1908.     printf("WINDOWS Interface enumeration:\n");
  1909.     if(numinterfaces)
  1910.     {
  1911.         for(count=0;count < numinterfaces;count++) printf("\nInterface %d: %s : %s\n",count, inet_ntoa(mydevs[count].addr), mydevs[count].name);
  1912.         printf("\nYou can select a specific interface by using the number with the -e switch \n");
  1913.     }
  1914.     else printf("No Suitible Interfaces!\n");
  1915.  
  1916. }
  1917.  
  1918.