<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Binary Tides &#187; winpcap</title>
	<atom:link href="http://www.binarytides.com/blog/category/winpcap/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.binarytides.com/blog</link>
	<description></description>
	<lastBuildDate>Sat, 24 Jul 2010 05:31:26 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Raw Sockets &#8211; Packets with Winpcap</title>
		<link>http://www.binarytides.com/blog/raw-sockets-packets-with-winpcap/</link>
		<comments>http://www.binarytides.com/blog/raw-sockets-packets-with-winpcap/#comments</comments>
		<pubDate>Sun, 13 Jan 2008 09:56:00 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Winsock]]></category>
		<category><![CDATA[winpcap]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=20</guid>
		<description><![CDATA[A previous post mentions how to send raw packets using winsock api on windows xp. Winpcap is a packet driver useful for packet capturing and sending raw packets on the windows platform.
Raw means we have to cook the whole packet ourselves. A TCP packet for example consists of:
1. Ethernet header
2. IP header
3. TCP header
4. The [...]]]></description>
			<content:encoded><![CDATA[<p>A previous post mentions how to send raw packets using winsock api on windows xp. Winpcap is a packet driver useful for packet capturing and sending raw packets on the windows platform.</p>
<p>Raw means we have to cook the whole packet ourselves. A TCP packet for example consists of:<br />
1. Ethernet header<br />
2. IP header<br />
3. TCP header<br />
4. The data supposed to be send</p>
<p><span id="more-20"></span></p>
<p>Each header has its own job to do in the whole transmission process.</p>
<p>Code :</p>
<pre class="brush: cpp;">
u_char packet[65536];
char *dump = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;
</pre>
<p>Winpcap gives us one function called pcap_sendpacket() to throw the packet on the network  adapter which forwards it. We have to responsibly construct the ethernet , ip and tcp headers and attach the data.</p>
<p>1. Ethernet header looks like</p>
<pre class="brush: cpp;">

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |       Ethernet destination address (first 32 bits)            |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 | Ethernet dest (last 16 bits)  |Ethernet source (first 16 bits)|
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |       Ethernet source address (last 32 bits)                  |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |        Type code              |                               |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
</pre>
<p>Ethernet destination address is the mac-address of the primary gateway of the network interface being used.<br />
Ethernet source is the mac-address of the network interface itself.<br />
Type field determines the type of the packet e.g. IP , ARP etc.</p>
<p>Now our first task is to get the source and destination mac address.<br />
Winpcap gives the ip-addresses of all available network interfaces that can be used.</p>
<p>now if srcip has the source ip in in_addr or long format then we can get the mac-address of this ip address using the function</p>
<pre class="brush: cpp;">

GetMacAddress(s_mac , srcip);
printf(&quot;Selected device has mac address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X&quot;,s_mac[0],s_mac[1],s_mac[2],s_mac[3],s_mac[4],s_mac[5]);
</pre>
<p>GetMacAddress is like :</p>
<pre class="brush: cpp;">
void GetMacAddress(unsigned char *mac , in_addr destip) {
    DWORD ret;
    in_addr srcip;
    ULONG MacAddr[2];
    ULONG PhyAddrLen = 6;  /* default to length of six bytes */

    srcip.s_addr=0;

    //Now print the Mac address also
    ret = SendArp(destip , srcip , MacAddr , &amp;PhyAddrLen);
    if(PhyAddrLen) {
        BYTE *bMacAddr = (BYTE *) &amp; MacAddr;
        for (int i = 0; i &lt; (int) PhyAddrLen; i++)
            mac[i] = (char)bMacAddr[i];
    }
}
</pre>
<p>SendArp is the method that is used to retrieve the &#8220;mac-address of a IP&#8221; ;simple!<br />
The above demonstration is mostly self-explaining. We got the mac-address of the network interface we want to use. Next we need the IP address of the primary gateway of this interface and then it mac-address.</p>
<p>GetGateway gets the gateway :</p>
<pre class="brush: cpp;">
void GetGateway(struct in_addr ip , char *sgatewayip , int *gatewayip) {
    char pAdapterInfo[5000];
    PIP_ADAPTER_INFO  AdapterInfo;
    ULONG OutBufLen = sizeof(pAdapterInfo) ;

    GetAdaptersInfo((PIP_ADAPTER_INFO) pAdapterInfo, &amp;OutBufLen);
    for(AdapterInfo = (PIP_ADAPTER_INFO)pAdapterInfo; AdapterInfo ; AdapterInfo = AdapterInfo-&gt;Next) {
        if(ip.s_addr == inet_addr(AdapterInfo-&gt;IpAddressList.IpAddress.String))
     strcpy(sgatewayip , AdapterInfo-&gt;GatewayList.IpAddress.String);
    }
    *gatewayip = inet_addr(sgatewayip);
}
</pre>
<p>GetAdaptersInfo is the function that retrieves a lot of information about a adapter.<br />
This and SendArp are inside iphlpapi.dll ; IP helper api which we shall load and get the function pointers inside!</p>
<p>Buzz!</p>
<pre class="brush: cpp;">
void loadiphlpapi() {
    HINSTANCE hDll = LoadLibrary(&quot;iphlpapi.dll&quot;);

    GetAdaptersInfo = (pgetadaptersinfo)GetProcAddress(hDll,&quot;GetAdaptersInfo&quot;);
    if(GetAdaptersInfo==NULL)
        printf(&quot;Error in iphlpapi.dll%d&quot;,GetLastError());
    SendArp = (psendarp)GetProcAddress(hDll,&quot;SendARP&quot;);
    if(SendArp==NULL)
 printf(&quot;Error in iphlpapi.dll%d&quot;,GetLastError());
}
</pre>
<p>So by now the source-ip , its mac-address , primary-gateway-mac should be into their respective variables. So now we have enough information to build our ethernet header.</p>
<p>Enjoy!</p>
<pre class="brush: cpp;">
ETHER_HDR *ehdr;
    memcpy(ehdr-&gt;source , s_mac , 6); //Source Mac address
    memcpy(ehdr-&gt;dest,d_mac,6); //Destination MAC address
    ehdr-&gt;type = htons(0x0800); //IP Frames
</pre>
<p>Next comes the IP Header</p>
<p>RFC 791 gives the structure of an IP header as:</p>
<pre class="brush: cpp;">
0                   1                   2                   3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version|  IHL  |Type of Service|          Total Length         |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|         Identification        |Flags|      Fragment Offset    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Time to Live |    Protocol   |         Header Checksum       |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                       Source Address                          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Destination Address                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Options                    |    Padding    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
</pre>
<p>and our structure for this header :</p>
<pre class="brush: cpp;">
typedef struct ip_hdr
{
    unsigned char  ip_header_len:4;  // 4-bit header length (in 32-bit words) normally=5 (Means 20 Bytes may be 24 also)
    unsigned char  ip_version   :4;  // 4-bit IPv4 version
    unsigned char  ip_tos;           // IP type of service
    unsigned short ip_total_length;  // Total length
    unsigned short ip_id;            // Unique identifier 

    unsigned char  ip_frag_offset   :5;        // Fragment offset field

    unsigned char  ip_more_fragment :1;
    unsigned char  ip_dont_fragment :1;
    unsigned char  ip_reserved_zero :1;

    unsigned char  ip_frag_offset1;    //fragment offset

    unsigned char  ip_ttl;           // Time to live
    unsigned char  ip_protocol;      // Protocol(TCP,UDP etc)
    unsigned short ip_checksum;      // IP checksum
    unsigned int   ip_srcaddr;       // Source address
    unsigned int   ip_destaddr;      // Source address
}   IPV4_HDR, *PIPV4_HDR, FAR * LPIPV4_HDR , IPHeader;
</pre>
<p>and then the TCP Header</p>
<pre class="brush: cpp;">
0                   1                   2                   3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          Source Port          |       Destination Port        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                        Sequence Number                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Acknowledgment Number                      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Data |           |U|A|P|R|S|F|                               |
| Offset| Reserved  |R|C|S|S|Y|I|            Window             |
|       |           |G|K|H|T|N|N|                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|           Checksum            |         Urgent Pointer        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Options                    |    Padding    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             data                              |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
</pre>
<p>and our structure for this header :</p>
<pre class="brush: cpp;">
// TCP header
typedef struct tcp_header
{
 unsigned short source_port;   // source port
 unsigned short dest_port;     // destination port
 unsigned int sequence;        // sequence number - 32 bits
 unsigned int acknowledge;     // acknowledgement number - 32 bits

 unsigned char ns :1;          //Nonce Sum Flag Added in RFC 3540.
 unsigned char reserved_part1:3; //according to rfc
 unsigned char data_offset:4;    /*The number of 32-bit words
                                   in the TCP header.
                                   This indicates where the data begins.
                                   The length of the TCP header
                                   is always a multiple
                                   of 32 bits.*/

 unsigned char fin :1; //Finish Flag
 unsigned char syn :1; //Synchronise Flag
 unsigned char rst :1; //Reset Flag
 unsigned char psh :1; //Push Flag
 unsigned char ack :1; //Acknowledgement Flag
 unsigned char urg :1; //Urgent Flag

 unsigned char ecn :1; //ECN-Echo Flag
 unsigned char cwr :1; //Congestion Window Reduced Flag

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

 unsigned short window; // window
 unsigned short checksum; // checksum
 unsigned short urgent_pointer; // urgent pointer
} TCP_HDR , *PTCP_HDR , FAR * LPTCP_HDR , TCPHeader , TCP_HEADER;
</pre>
<p>Now the headers can be build easily :</p>
<pre class="brush: cpp;">
// *******************  IP Header *****************
    iphdr = (PIPV4_HDR)(packet + sizeof(ETHER_HDR));

    iphdr-&gt;ip_version = 4;
    iphdr-&gt;ip_header_len = 5; //In double words thats 4 bytes
    iphdr-&gt;ip_tos = 0;
    iphdr-&gt;ip_total_length = htons (sizeof(IPV4_HDR) + sizeof(TCP_HDR) + strlen(dump));
    iphdr-&gt;ip_id = htons(2);
    iphdr-&gt;ip_frag_offset = 0;
    iphdr-&gt;ip_reserved_zero=0;
    iphdr-&gt;ip_dont_fragment=1;
    iphdr-&gt;ip_more_fragment=0;
    iphdr-&gt;ip_frag_offset1 = 0;
    iphdr-&gt;ip_ttl    = 3;
    iphdr-&gt;ip_protocol = IPPROTO_TCP;
    iphdr-&gt;ip_srcaddr  = inet_addr(&quot;1.2.3.4&quot;);   //srcip.s_addr;
    iphdr-&gt;ip_destaddr = inet_addr(&quot;1.2.3.5&quot;);
    iphdr-&gt;ip_checksum =0;
    iphdr-&gt;ip_checksum = in_checksum((unsigned short*)iphdr, sizeof(IPV4_HDR));

    // *******************  TCP Header *****************
    tcphdr = (PTCP_HDR)(packet + sizeof(ETHER_HDR) + sizeof(IPV4_HDR));

    tcphdr-&gt;source_port = htons(SOURCE_PORT);
    tcphdr-&gt;dest_port = htons(80);
    tcphdr-&gt;sequence=0;
    tcphdr-&gt;acknowledge=0;
    tcphdr-&gt;reserved_part1=0;
    tcphdr-&gt;data_offset=5;
    tcphdr-&gt;fin=0;
    tcphdr-&gt;syn=1;
    tcphdr-&gt;rst=0;
    tcphdr-&gt;psh=0;
    tcphdr-&gt;ack=0;
    tcphdr-&gt;urg=0;
    tcphdr-&gt;ecn=0;
    tcphdr-&gt;cwr=0;
    tcphdr-&gt;window = htons(64240);
    tcphdr-&gt;checksum=0;
    tcphdr-&gt;urgent_pointer = 0;
</pre>
<p>almost done</p>
<pre class="brush: cpp;">
data = (char*)(packet + sizeof(ETHER_HDR) + sizeof(IPV4_HDR) + sizeof(TCP_HDR));
strcpy(data,dump);

pcap_sendpacket(fp , packet , sizeof(ETHER_HDR) + sizeof(IPV4_HDR) + sizeof(TCP_HDR) + strlen(dump));
</pre>
<p>Thats should send the packet. Use Ethereal to check whether the packet was successfully transmitted. The above was an example of a TCP packet, similarly UDP ICMP or any other packet can be build.</p>
<p><strong>Source Code</strong> : <a href="http://www.binarytides.com/download/raw-sockets-packets-with-winpcap/"><br />
Download<br />
</a></p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=20&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/raw-sockets-packets-with-winpcap/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Tcp Syn Portscan with Winpcap and Raw Sockets</title>
		<link>http://www.binarytides.com/blog/tcp-syn-portscan-with-winpcap-and-raw-sockets/</link>
		<comments>http://www.binarytides.com/blog/tcp-syn-portscan-with-winpcap-and-raw-sockets/#comments</comments>
		<pubDate>Sun, 13 Jan 2008 09:35:00 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Winsock]]></category>
		<category><![CDATA[winpcap]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=19</guid>
		<description><![CDATA[Port Scanning searches for open ports on a remote system. The basic logic for a portscanner would be to connect to the port we want to check. If the socket gives a valid connection without any error then the port is open , closed otherwise (or inaccessible, or filtered).

This basic technique is called TCP Connect [...]]]></description>
			<content:encoded><![CDATA[<p>Port Scanning searches for open ports on a remote system. The basic logic for a portscanner would be to connect to the port we want to check. If the socket gives a valid connection without any error then the port is open , closed otherwise (or inaccessible, or filtered).</p>
<p><span id="more-19"></span></p>
<p>This basic technique is called TCP Connect Port Scanning in which we use something like a loop to connect to ports one by one and check for valid connections on the socket. But this technique has many drawbacks.
<div>It is slow as well as detectable. Slow means that it takes some time for connect() function to return and detectable since this technique leaves a lot of entries in the firewall logs of the remote system. </p>
<p>TCP-Syn Port scanning is a technique which intends to cure these two problems. The mechanism behind it is the handshaking which takes place while establishing a connection. It sends syn packets and waits for an syn+ack reply. If such a reply is received then the port is open otherwise keep waiting till timeout and report the port as closed. Quite simple! In the TCP connect technique the connect() function sends a ack after receiving syn+ack and this establishes a complete connection. But in Syn scanning the complete connection is not made. This results in :<br />1. Faster scans<br />2. Incomplete connections so less detectable</p>
<p>TCP Connect Port Scan looks like :</p>
<p>You -> Send Syn packet -> Host:port<br />Host -> send syn/ack packet -> You<br />You -> send ack packet -> Host<br />&#8230; and connection is established</p>
<p>TCP-Syn Port scan looks like<br />You -> send syn packet ->Host:port<br />Host -> send syn/ack or rst packet or nothing depending on the port status -> You<br />&#8230; stop and analyse the reply the host send : if syn/ack then port open closed/filtered otherwise.</p>
<p>Results are almost as accurate as that of TCP connection and the scan is extremely faster.</p>
<p>So the process is :<br />1. Send a Syn packet to a port A<br />2. Wait for a reply of Syn+Ack till timeout<br />3. Syn+Ack reply means the port is open , Rst packet means port is closed , and otherwise it might be inaccessible or in a filtered state.</p>
<p>Coding>></p>
<p>We shall code a TCP-Syn Port scanner on windows using winsock api. The tools we need are :<br />VC++ 6.0 , Winpcap and Ethereal(Optional : for better understanding).</p>
<p>Winpcap is a raw packet driver for windows platform which has features for sniffing(packet capturing) and sending raw packets.</p>
<p><span class="Apple-style-span" style="font-weight: bold;">Now onto the program logic.</span></p>
<p>1. Take  a hostname to scan.<br />2. Start a sniffer thread of winpcap sniffer which shall sniff for all incoming packets and pick up those which are from hostname and are syn+ack packets.<br />3. start sending syn packets to ports in a loop. to make syn packets we need raw packet feature of winpcap</div>
<div>4. if the sniffer thread receives a syn/ack packet from the host then get the source port of the packet and report the packet as open.</div>
<div>5. Keep looping as long as you have nothing else to do.</div>
<div></div>
<div><span class="Apple-style-span" style="font-weight: bold;">The Code</span></div>
<div><span class="Apple-style-span" style="font-weight: bold;"><br /></span></div>
<div>Coming Soon&#8230;</div>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=19&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/tcp-syn-portscan-with-winpcap-and-raw-sockets/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
