• Viernes 15 de Noviembre de 2024, 08:29

Autor Tema:  Programa Tcpdump En C  (Leído 1595 veces)

hedar

  • Nuevo Miembro
  • *
  • Mensajes: 13
    • Ver Perfil
Programa Tcpdump En C
« en: Viernes 3 de Febrero de 2006, 05:03 »
0
Este post es con el motivo de pedir ayuda sobre como desarrollar un sniffer con turbo c o c++, que me muestre  todo el trafico de una red. Es decir que capturar todo lo que pasa por la red, colocando la tarjeta de red en modo promiscuo es decir que me yo pueda tomar y ver todo lo que se captura en la tarjeta de red hasta la capa de internet del protocolo tcp/ip. El otro inconveniente es que es bajo unix, yo se programar bajo unix y se que para esto se utiliza la libreria pcap que me permite capturar los datos del buffer de la tarjeta de red. Si alguien me ayuda se lo agradezco tengo dos semanas para desarrollar ese software. :lightsabre:

NRM

  • Miembro MUY activo
  • ***
  • Mensajes: 279
  • Nacionalidad: ar
    • Ver Perfil
    • http://www.narrowmind.com.ar
Re: Programa Tcpdump En C
« Respuesta #1 en: Viernes 3 de Febrero de 2006, 06:00 »
0
Lo podes hacer sin usar la libreria pcap.

Aca te posteo un  source que esta en el libro "Programación de Socket Linux" de Walton.

Código: Text
  1. /* snooper.c
  2.  *
  3.  * Copyright (c) 2000 Sean Walton and Macmillan Publishers.  Use may be in
  4.  * whole or in part in accordance to the General Public License (GPL).
  5.  *
  6.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  7.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  8.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  9.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  10.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  11.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  14.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  15.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  16.  * SUCH DAMAGE.
  17. */
  18.  
  19. /*****************************************************************************/
  20. /*** snooper.c                                                             ***/
  21. /***                                                                       ***/
  22. /*** This program captures *all* packets that the network interface sees.  ***/
  23. /*** Be very careful with this tool, because you may see all lot of info.  ***/
  24. /*** Also, it uses the deprecated SOCK_PACKET socket type.  The newer and  ***/
  25. /*** preferred method is with PF_PACKET.                                   ***/
  26. /*****************************************************************************/
  27.  
  28. #include <stdio.h>
  29. #include <sys/socket.h>
  30. #include <resolv.h>
  31. #include <arpa/inet.h>
  32. #include <errno.h>
  33. #include <sys/types.h>
  34. #include <linux/if_ether.h>
  35.  
  36. #define IP_SIZE    4
  37. #define ETH_SIZE  6
  38.  
  39. typedef enum { eETH_ADDR, eIP_ADDR } EAddress;
  40.  
  41. typedef unsigned char uchar;
  42.  
  43. /*--------------------------------------------------------------------*/
  44. /* Ethernet Frame                                                     */
  45. /*                                                                    */
  46. /* This structure defines the fields within the ethernet frame. Since */
  47. /* this programs gets the lowest-level packet, fragmented packets are */
  48. /* not reassembled.  The first few fields contain the MAC addresses   */
  49. /* of the source and destination. Note that this structure is set for */
  50. /* little-endian format.                                              */
  51. /*--------------------------------------------------------------------*/
  52. struct ip_packet {
  53.   struct {
  54.     uchar dst_eth[ETH_SIZE];
  55.     uchar src_eth[ETH_SIZE];
  56.     uchar __unknwn[2];
  57.   } hw_header;             /* hardware header */
  58.     uint header_len:4;       /* header length in words in 32bit words */
  59.     uint version:4;          /* 4-bit version */
  60.     uint serve_type:8;       /* how to service packet */
  61.     uint packet_len:16;      /* total size of packet in bytes */
  62.     uint ID:16;              /* fragment ID */
  63.     uint frag_offset:13;     /* to help reassembly */
  64.     uint more_frags:1;       /* flag for "more frags to follow" */
  65.     uint dont_frag:1;        /* flag to permit fragmentation */
  66.     uint __reserved:1;       /* always zero */
  67.     uint time_to_live:8;     /* maximum router hop count */
  68.     uint protocol:8;         /* ICMP, UDP, TCP */
  69.     uint hdr_chksum:16;      /* ones-comp. checksum of header */
  70.     uchar IPv4_src[IP_SIZE]; /* IP address of originator */
  71.     uchar IPv4_dst[IP_SIZE]; /* IP address of destination */
  72.     uchar options[0];        /* up to 40 bytes */
  73.     uchar data[0];           /* message data up to 64KB */
  74. };
  75.  
  76. /*--------------------------------------------------------------------*/
  77. /* dump                                                               */
  78. /*                                                                    */
  79. /* Dump a block of data in hex & ascii.                               */
  80. /*--------------------------------------------------------------------*/
  81. void dump(void* b, int len)
  82. {   unsigned char *buf = b;
  83.     int i, cnt=0;
  84.     char str[17];
  85.     memset(str, 0, 17);
  86.     for ( i = 0; i < len; i++ )
  87.     {
  88.         if ( cnt % 16 == 0 )
  89.         {
  90.             printf("  %s\nX: ", str, cnt);
  91.             memset(str, 0, 17);
  92.         }
  93.         if ( buf[cnt] < ' '  ||  buf[cnt] >= 127 )
  94.             str[cnt] = '.';
  95.         else
  96.             str[cnt] = buf[cnt];
  97.         printf("X ", buf[cnt++]);
  98.     }
  99.     printf("  %*s\n\n", 16+(16-len)*2, str);
  100. }
  101.  
  102. /*--------------------------------------------------------------------*/
  103. /* PrintAddr                                                          */
  104. /*                                                                    */
  105. /* Print the different types of address (MAC or IP).                  */
  106. /*--------------------------------------------------------------------*/
  107. void PrintAddr(char* msg, uchar *addr, EAddress is_ip)
  108. {  int i;
  109.   static struct {
  110.     int len;
  111.     char *fmt;
  112.     char delim;
  113.   } addr_fmt[] = {{ETH_SIZE, "%x", ':'}, {IP_SIZE, "%d", '.'}};
  114.  
  115.   printf("%s", msg);
  116.   for ( i = 0; i < addr_fmt[is_ip].len; i++ )
  117.   {
  118.     printf(addr_fmt[is_ip].fmt, addr[i]);
  119.     if ( i < addr_fmt[is_ip].len-1 )
  120.       putchar(addr_fmt[is_ip].delim);
  121.   }
  122. }
  123.  
  124. /*--------------------------------------------------------------------*/
  125. /* GetProtocol                                                        */
  126. /*                                                                    */
  127. /* Convert the protocol value into the alphabetic representation.     */
  128. /*--------------------------------------------------------------------*/
  129. char* GetProtocol(int value)
  130. {
  131.   switch (value)
  132.   {
  133.     case IPPROTO_IP: return "IP";
  134.     case IPPROTO_ICMP: return "ICMP";
  135.     case IPPROTO_IGMP: return "IGMP";
  136.     case IPPROTO_IPIP: return "IPIP";
  137.     case IPPROTO_TCP: return "TCP";
  138.     case IPPROTO_EGP: return "EGP";
  139.     case IPPROTO_PUP: return "PUP";
  140.     case IPPROTO_UDP: return "UDP";
  141.     case IPPROTO_IDP: return "IDP";
  142.     case IPPROTO_RSVP: return "RSVP";
  143.     case IPPROTO_GRE: return "GRE";
  144.     case IPPROTO_IPV6: return "IPV6/4";
  145.     case IPPROTO_PIM: return "PIM";
  146.     case IPPROTO_RAW: return "RAW";
  147.     default: return "???";
  148.   }
  149. }
  150.  
  151. /*--------------------------------------------------------------------*/
  152. /* DumpPacket                                                         */
  153. /*                                                                    */
  154. /* Display the read packet with data and fields.                      */
  155. /*--------------------------------------------------------------------*/
  156. void DumpPacket(char *buffer, int len)
  157. {  struct ip_packet *ip=(void*)buffer;
  158.  
  159.   printf("-------------------------------------------------\n");
  160.   dump(buffer, len);
  161.   PrintAddr("Destination EtherID=", ip->hw_header.dst_eth, eETH_ADDR);
  162.   PrintAddr(", Source EtherID=", ip->hw_header.src_eth, eETH_ADDR);
  163.   printf("\nIPv%d: header-len=%d, type=%d, packet-size=%d, ID=%d\n",
  164.     ip->version, ip->header_len*4, ip->serve_type,
  165.     ntohs(ip->packet_len), ntohs(ip->ID));
  166.   printf("frag=%c, more=%c, offset=%d, TTL=%d, protocol=%s\n",
  167.     (ip->dont_frag? 'N': 'Y'),
  168.     (ip->more_frags? 'N': 'Y'),
  169.     ip->frag_offset,
  170.     ip->time_to_live, GetProtocol(ip->protocol));
  171.   printf("checksum=%d, ", ntohs(ip->hdr_chksum));
  172.   PrintAddr("source=", ip->IPv4_src, eIP_ADDR);
  173.   PrintAddr(", destination=", ip->IPv4_dst, eIP_ADDR);
  174.   printf("\n");
  175.   fflush(stdout);
  176. }
  177.  
  178. void PANIC(char *msg);
  179. #define PANIC(msg)  {perror(msg);exit(0);}
  180.  
  181. /*--------------------------------------------------------------------*/
  182. /* main                                                               */
  183. /*                                                                    */
  184. /* Open socket.  Repeatedly read and display records.                 */
  185. /*--------------------------------------------------------------------*/
  186. int main()
  187. {   int sd, bytes_read;
  188.     char data[1024];
  189.  
  190.     sd  = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
  191.     if ( sd < 0 )
  192.     PANIC("Snooper socket");
  193.     do
  194.   {
  195.       bytes_read = recvfrom(sd, data, sizeof(data), 0, 0, 0);
  196.         if ( bytes_read > 0 )
  197.       DumpPacket(data, bytes_read);
  198.     }
  199.   while ( bytes_read > 0 );
  200.     return 0;
  201. }
  202.  
  203.  
  204.  

Link al source code original.

hedar

  • Nuevo Miembro
  • *
  • Mensajes: 13
    • Ver Perfil
Re: Programa Tcpdump En C
« Respuesta #2 en: Sábado 11 de Febrero de 2006, 21:27 »
0
muchas gracias por el programa pero al compilarlo me esta votando un error en la line 93-94-95 que no se que es si me colaboras te lo agradeceria.

NRM

  • Miembro MUY activo
  • ***
  • Mensajes: 279
  • Nacionalidad: ar
    • Ver Perfil
    • http://www.narrowmind.com.ar
Re: Programa Tcpdump En C
« Respuesta #3 en: Domingo 12 de Febrero de 2006, 02:06 »
0
Disculpame el error, al parecer estaba mal el source. Este lo verifique y funciona.

Saludos

Código: Text
  1. /* snooper.c
  2.  *
  3.  * Copyright (c) 2000 Sean Walton and Macmillan Publishers.  Use may be in
  4.  * whole or in part in accordance to the General Public License (GPL).
  5.  *
  6.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  7.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  8.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  9.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  10.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  11.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  14.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  15.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  16.  * SUCH DAMAGE.
  17. */
  18.  
  19. /*****************************************************************************/
  20. /*** snooper.c                                                             ***/
  21. /***                                                                       ***/
  22. /*** This program captures *all* packets that the network interface sees.  ***/
  23. /*** Be very careful with this tool, because you may see all lot of info.  ***/
  24. /*** Also, it uses the deprecated SOCK_PACKET socket type.  The newer and  ***/
  25. /*** preferred method is with PF_PACKET.                                   ***/
  26. /*****************************************************************************/
  27.  
  28. #include <stdio.h>
  29. #include <sys/socket.h>
  30. #include <resolv.h>
  31. #include <arpa/inet.h>
  32. #include <errno.h>
  33. #include <sys/types.h>
  34. #include <linux/if_ether.h>
  35.  
  36. #define IP_SIZE    4
  37. #define ETH_SIZE  6
  38.  
  39. typedef enum { eETH_ADDR, eIP_ADDR } EAddress;
  40.  
  41. typedef unsigned char uchar;
  42.  
  43. /*--------------------------------------------------------------------*/
  44. /* Ethernet Frame                                                     */
  45. /*                                                                    */
  46. /* This structure defines the fields within the ethernet frame. Since */
  47. /* this programs gets the lowest-level packet, fragmented packets are */
  48. /* not reassembled.  The first few fields contain the MAC addresses   */
  49. /* of the source and destination. Note that this structure is set for */
  50. /* little-endian format.                                              */
  51. /*--------------------------------------------------------------------*/
  52. struct ip_packet {
  53.   struct {
  54.     uchar dst_eth[ETH_SIZE];
  55.     uchar src_eth[ETH_SIZE];
  56.     uchar __unknwn[2];
  57.   } hw_header;             /* hardware header */
  58.     uint header_len:4;       /* header length in words in 32bit words */
  59.     uint version:4;          /* 4-bit version */
  60.     uint serve_type:8;       /* how to service packet */
  61.     uint packet_len:16;      /* total size of packet in bytes */
  62.     uint ID:16;              /* fragment ID */
  63.     uint frag_offset:13;     /* to help reassembly */
  64.     uint more_frags:1;       /* flag for "more frags to follow" */
  65.     uint dont_frag:1;        /* flag to permit fragmentation */
  66.     uint __reserved:1;       /* always zero */
  67.     uint time_to_live:8;     /* maximum router hop count */
  68.     uint protocol:8;         /* ICMP, UDP, TCP */
  69.     uint hdr_chksum:16;      /* ones-comp. checksum of header */
  70.     uchar IPv4_src[IP_SIZE]; /* IP address of originator */
  71.     uchar IPv4_dst[IP_SIZE]; /* IP address of destination */
  72.     uchar options[0];        /* up to 40 bytes */
  73.     uchar data[0];           /* message data up to 64KB */
  74. };
  75.  
  76. /*--------------------------------------------------------------------*/
  77. /* dump                                                               */
  78. /*                                                                    */
  79. /* Dump a block of data in hex & ascii.                               */
  80. /*--------------------------------------------------------------------*/
  81. void dump(void* b, int len)
  82. {   unsigned char *buf = b;
  83.     int i, cnt=0;
  84.     char str[17];
  85.     memset(str, 0, 17);
  86.     for ( i = 0; i < len; i++ )
  87.     {
  88.         if ( cnt % 16 == 0 )
  89.         {
  90.             printf("  %s\n%04X: ", str, cnt);
  91.             memset(str, 0, 17);
  92.         }
  93.         if ( buf[cnt] < ' '  ||  buf[cnt] >= 127 )
  94.             str[cnt%16] = '.';
  95.         else
  96.             str[cnt%16] = buf[cnt];
  97.         printf("%02X ", buf[cnt++]);
  98.     }
  99.     printf("  %*s\n\n", 16+(16-len%16)*2, str);
  100. }
  101.  
  102. /*--------------------------------------------------------------------*/
  103. /* PrintAddr                                                          */
  104. /*                                                                    */
  105. /* Print the different types of address (MAC or IP).                  */
  106. /*--------------------------------------------------------------------*/
  107. void PrintAddr(char* msg, uchar *addr, EAddress is_ip)
  108. {  int i;
  109.   static struct {
  110.     int len;
  111.     char *fmt;
  112.     char delim;
  113.   } addr_fmt[] = {{ETH_SIZE, "%x", ':'}, {IP_SIZE, "%d", '.'}};
  114.  
  115.   printf("%s", msg);
  116.   for ( i = 0; i < addr_fmt[is_ip].len; i++ )
  117.   {
  118.     printf(addr_fmt[is_ip].fmt, addr[i]);
  119.     if ( i < addr_fmt[is_ip].len-1 )
  120.       putchar(addr_fmt[is_ip].delim);
  121.   }
  122. }
  123.  
  124. /*--------------------------------------------------------------------*/
  125. /* GetProtocol                                                        */
  126. /*                                                                    */
  127. /* Convert the protocol value into the alphabetic representation.     */
  128. /*--------------------------------------------------------------------*/
  129. char* GetProtocol(int value)
  130. {
  131.   switch (value)
  132.   {
  133.     case IPPROTO_IP: return "IP";
  134.     case IPPROTO_ICMP: return "ICMP";
  135.     case IPPROTO_IGMP: return "IGMP";
  136.     case IPPROTO_IPIP: return "IPIP";
  137.     case IPPROTO_TCP: return "TCP";
  138.     case IPPROTO_EGP: return "EGP";
  139.     case IPPROTO_PUP: return "PUP";
  140.     case IPPROTO_UDP: return "UDP";
  141.     case IPPROTO_IDP: return "IDP";
  142.     case IPPROTO_RSVP: return "RSVP";
  143.     case IPPROTO_GRE: return "GRE";
  144.     case IPPROTO_IPV6: return "IPV6/4";
  145.     case IPPROTO_PIM: return "PIM";
  146.     case IPPROTO_RAW: return "RAW";
  147.     default: return "???";
  148.   }
  149. }
  150.  
  151. /*--------------------------------------------------------------------*/
  152. /* DumpPacket                                                         */
  153. /*                                                                    */
  154. /* Display the read packet with data and fields.                      */
  155. /*--------------------------------------------------------------------*/
  156. void DumpPacket(char *buffer, int len)
  157. {  struct ip_packet *ip=(void*)buffer;
  158.  
  159.   printf("-------------------------------------------------\n");
  160.   dump(buffer, len);
  161.   PrintAddr("Destination EtherID=", ip->hw_header.dst_eth, eETH_ADDR);
  162.   PrintAddr(", Source EtherID=", ip->hw_header.src_eth, eETH_ADDR);
  163.   printf("\nIPv%d: header-len=%d, type=%d, packet-size=%d, ID=%d\n",
  164.     ip->version, ip->header_len*4, ip->serve_type,
  165.     ntohs(ip->packet_len), ntohs(ip->ID));
  166.   printf("frag=%c, more=%c, offset=%d, TTL=%d, protocol=%s\n",
  167.     (ip->dont_frag? 'N': 'Y'),
  168.     (ip->more_frags? 'N': 'Y'),
  169.     ip->frag_offset,
  170.     ip->time_to_live, GetProtocol(ip->protocol));
  171.   printf("checksum=%d, ", ntohs(ip->hdr_chksum));
  172.   PrintAddr("source=", ip->IPv4_src, eIP_ADDR);
  173.   PrintAddr(", destination=", ip->IPv4_dst, eIP_ADDR);
  174.   printf("\n");
  175.   fflush(stdout);
  176. }
  177.  
  178. void PANIC(char *msg);
  179. #define PANIC(msg)  {perror(msg);exit(0);}
  180.  
  181. /*--------------------------------------------------------------------*/
  182. /* main                                                               */
  183. /*                                                                    */
  184. /* Open socket.  Repeatedly read and display records.                 */
  185. /*--------------------------------------------------------------------*/
  186. int main()
  187. {   int sd, bytes_read;
  188.     char data[1024];
  189.  
  190.     sd  = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
  191.     if ( sd < 0 )
  192.     PANIC("Snooper socket");
  193.     do
  194.   {
  195.       bytes_read = recvfrom(sd, data, sizeof(data), 0, 0, 0);
  196.         if ( bytes_read > 0 )
  197.       DumpPacket(data, bytes_read);
  198.     }
  199.   while ( bytes_read > 0 );
  200.     return 0;
  201. }
  202.  
  203.