Chinaunix首页 | 论坛 | 博客
  • 博客访问: 619620
  • 博文数量: 178
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 2162
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-12 20:06
文章分类

全部博文(178)

文章存档

2011年(1)

2010年(94)

2009年(86)

我的朋友

分类:

2009-12-09 14:31:14

From:

Introduction

In this article, I will explain how to create UDP packets and then send them to a remote server through the Internet using WinPCap for Windows. The code has been tested to work with Windows XP SP2 and Vista SP1 on Linksys routers, and on Toshiba modems connected directly to the Internet. Please note that the code here is very minimalistic, and can be greatly expanded depending on your needs. The reason I use WinPCap in this article is that it solves the issue of Winsock for Windows (XP SP2 and above) not allowing raw UDP packets to be sent (in Linux, you can just use regular sockets). With WinPcap, it is possible to specify your own source IP and source hardware addresses in packets.

Background

You should know the basics of how computers communicate through the Internet; this includes knowing what packets, sockets, UDP, IP addresses, and MAC addresses are. Additionally, you might want to review the packet headers before reading over this material. The headers involved are , , and . Also, know how works; it's used a lot. Lastly, you must know how to install headers and libraries for use with your compiler.

Before we begin

Getting WinPCap

The WinPCap 4.02 libraries I use here can be downloaded . Once the libraries are set up, you need to add "HAVE_REMOTE" to your preprocessor. In Visual Studio 2008, this can be done in the C++ Options of your project. Make sure you do this because I spent a good time wondering why my WinPCAp project would not compile despite me checking for errors many times. Also, if you want to run WinPCap applications, you will have to install the .

Windows SDK

Some functions and structures used in this article are from Winsock2 and the Iphlp API. These are included in the Windows SDK, and can be downloaded for free (1.33 GB; good luck dial-up users).

How a UDP packet works

Headers

First part of the packet - Ethernet II header

A packet to be sent through the Internet usually starts with an Ethernet II header. This header consists of three main parts: the destination hardware address, the source hardware address, and the type. The most important thing here is the destination hardware address because it determines the first place the packet is sent after being created. In this article, I set the destination hardware address to that of my "". A default gateway is a modem/router/computer that connects a network to the Internet or another network. If you use this code in a network with more than one LAN, you will have to determine what default gateway address to use with GetIpNetTable and your own addresses. The "type" part of the Ethernet II header specifies what kind of packet is being used. In this case, "0x0800" is used to specify IPv4.

(An image showing the individual bytes we will have to fill in later. The packet was made using the example application and captured using Wireshark.)

Second part of the packet - IP header

The IP header stores the IP addresses of the source and the destination as well as other important data. Information about the IP header can be found . We will have to fill all of this in after we fill in the Ethernet code.

Third part of the packet - UDP header

UDP is used by many applications, and so there has to be a way for an application to know which information is meant for it. Where an IP and MAC address are used to determine what computer the information is meant for, ports are used by UDP to determine what application the information is meant for. Information about UDP headers can be found .

Checksums

The IP and UDP headers require a checksum to be calculated. This is probably the most annoying part of crafting UDP packets, but is fortunately pretty straightforward. In the IP header, the "".

In the UDP header, (described later).

Using the code

Choosing the correct device

The first thing we must code is a way to determine what device is to be used to send the packets. Most home computers today have a "" that is used to access the computer itself with "localhost". This device cannot be used for sending packets to remote servers, and so you must make sure to use another one. In the sample project, I use the "ShowDeviceList()" function in the "NetworkStuff.h" file to show a list of network devices installed on the computer, using WinPCap.

Collapse
void ShowDeviceList(void)
{
// Error buffer for Pcap functions, not optional!
char Error[PCAP_ERRBUF_SIZE];
pcap_if_t* Devices;pcap_findalldevs_ex(PCAP_SRC_IF_STRING,NULL,
&Devices,Error);
int i = 1;
for(pcap_if_t* CurrentDevice = Devices;CurrentDevice != NULL;
CurrentDevice = CurrentDevice->next)
{
cout<<i << ". "<< CurrentDevice->description << endl;
i++;
}
}

The function first creates an error buffer for use by the pcap_findalldevs_Ex function. Remember that this buffer is not optional, and will result in a program crash if set to null. The pcap_findalldevs_ex function sets a "pcap_if_t" pointer at the beginning of a linked list of network devices. A loop is then executed to show the description of each device. (If you do not have an understanding of linked lists, I suggest you read .)

Next, the user enters the number of his selection, and the program loops that number of times and sets the global "CurrentDevice" to the appropriate pcap_if_t* device.

Collapse
cout << "Enter the number of your device (example: 2)" << endl;
ShowDeviceList();
int chosen;
cin >> chosen;

int i = 1;char Error[PCAP_ERRBUF_SIZE];
pcap_findalldevs_ex(PCAP_SRC_IF_STRING,NULL,&ChosenDevice,Error);

//Set CurrentDevice to the beginning of the list and loop until
//the correct device is found or until there are no more devices
for(pcap_if_t* CurrentDevice = ChosenDevice;
CurrentDevice != NULL;
CurrentDevice = CurrentDevice->next)
{
if(i == chosen)
{
ChosenDevice = CurrentDevice;
break;
}
i++;
}

ChosenDevice should now be set to the device chosen by the user.

Getting the required device information

Now, we must find the required information about the chosen device. This is the MAC address of the device's default gateway, and in the case that the user wants to use real information, it is also the device's MAC and IP addresses. In the sample application, I created a structure called "DeviceInfo" to store this information, and the function "GetAdapterInfo()" to fill it in. The GetAdapterInfo() function uses the by Microsoft to greatly simplify getting device information. (Previously, I believe you had to use Windows Drivers to read NIC data.)

Collapse
DeviceInfo GetAdapterInfo(pcap_if_t* Device)
{
DeviceInfo DevInfo;
ZeroMemory(&DevInfo,sizeof(DevInfo));

IP_ADAPTER_INFO* AdapterInfo = new IP_ADAPTER_INFO [48];
ULONG AIS = sizeof(IP_ADAPTER_INFO) * 48;
GetAdaptersInfo(AdapterInfo,&AIS); // Allocate 48 Devices.
for(IP_ADAPTER_INFO* Current = AdapterInfo;Current != NULL;
Current = Current->Next)
{
if(strstr(Device->name,Current->AdapterName)!=0)

{
DevInfo.DefaultGateway = inet_addr(Current->GatewayList.IpAddress.String);
//The default gateway is the device that connects lan to internet
DevInfo.IP = inet_addr(Current->IpAddressList.IpAddress.String);
//inet_addr converts an IP address string to a 4 byte integer.
memcpy((void*)DevInfo.PhysicalAddress,(void*)(Current->Address),6);
ULONG MACSize = 6;
if(SendARP(DevInfo.DefaultGateway,NULL,
(void*)DevInfo.GatewayPhysicalAddress,&MACSize)
!=NO_ERROR){cout << "SendARP Failed. No default gateway\n"; }
//SendARP gets the MAC address of the default gateway we got earlier
// If this is false, the device was probably invalid
DevInfo.Exists = true;
return DevInfo;
}
}
DevInfo.Exists = false;
return DevInfo;
}

We are now able to get the information of the pcap_if_t* device chosen earlier into a DeviceInfo structure for use in packets. Note that if you choose a loop-back interface, the DeviceInfo.Exists member will be set to false for error checking. (GetAdaptersInfo() does not get loopback interfaces, and so the if() condition will never be satisfied.)

Input

Next, we can get input for use in the RawPacket class. It is easier if all the input is in a char buffer and is then converted to a data type supported by the class.

Collapse
DeviceInfo di;
di = GetAdapterInfo(ChosenDevice);
if(di.Exists == false)
{
cout << "Invalid Selection (Try another device)\n";
return 0;
}

cout << "You chose: " << ChosenDevice->name << endl;

char SourceIP[16];
char SourcePort[6];
char SourceMAC[19];

char DestinationIP[16];
char DestinationPort[6];

char DataString[2048];

cout << "Enter source IP (or -1 for real)\n";
cin >> SourceIP;
cout << "Enter source port (0-65535)\n";
cin >> SourcePort;
cout << "Enter source MAC (or -1 for real) \n";
cin >> SourceMAC;
cout << "Enter destination IP\n";
cin >> DestinationIP;
cout << "Enter destination port(0-65535)\n";
cin >> DestinationPort;
cout << "Enter data string\n";
cin >> DataString;

The way you handle input is, of course, dependent on your needs. Just remember that if you want to have an option to use real device data (real MAC or IP), it is stored in the DeviceInfo structure for ease of access.

The RawPacket class and how it works

The following code is executed in the sample application if neither the source MAC or the source IP were -1:

Collapse
// (Yes I know having one huge function isnt very cool, but this is just a sample)

RawPacket RP;

RP.CreatePacket(MACStringToBytes(SourceMAC),
di.GatewayPhysicalAddress,
inet_addr(SourceIP),
inet_addr(DestinationIP),
atoi(SourcePort),
atoi(DestinationPort),
(UCHAR*)DataString,
strlen(DataString));

RP.SendPacket(ChosenDevice);

The usage of RawPacket.CreatePacket and RawPacket.SendPacket should be pretty straightforward. Just know that the function converts a string containing a decimal dot IP address to a 4 byte integer, and converts a string representation of a number to an integer. DataString is the data carried at the end of the packet that is separate from the headers. The last argument is the length of DataString in bytes. MACStringToBytes converts a MAC address in the format of (xx:xx:xx:xx:xx:xx) (each xx represents a 2 digit hexadecimal number) to a 6 byte array. Its definition follows:

Collapse
unsigned char* MACStringToBytes(LPSTR String)
{
char* Tmp = new char[strlen(String)];
memcpy((void*)Tmp,(void*)String,strlen(String));
//The 6 byte array
unsigned char* Returned = new unsigned char[6];
for(int i = 0;i<6;i++)
{
sscanf(Tmp,"%2X",&Returned[i]); // Read data as hexadecimal
memmove((void*)(Tmp),(void*)(Tmp+3),19-i*3);//Unsafe I think...
}
return Returned;
}

Inside the class

Now, here is the first function we call from RawPacket. This function basically creates a buffer big enough to hold the data plus the headers of the packet, and then appends the data to the buffer. Note that most of the hard coded values here can be changed depending on your needs. Also, you should know what the "Length" in each header means. In the IP header, it means the length of the IP header itself plus the length of the UDP header plus the length of the data at the end. In the UDP header, it means the length of the UDP header plus the length of the end data. Usually, IP headers are 20 bytes, and UDP headers are 8 bytes. Remember to put shorts and ints into network byte order using htons() or htonl() before copying them to the packet.

Collapse
void RawPacket::CreatePacket
(unsigned char* SourceMAC,
unsigned char* DestinationMAC,
unsigned int SourceIP,
unsigned int DestIP,
unsigned short SourcePort,
unsigned short DestinationPort,
unsigned char* UserData,
unsigned int UserDataLen)
{
RawPacket::UserDataLen = UserDataLen;
// DataLength + 42 Bytes of Headers
FinalPacket = new unsigned char [UserDataLen + 42];
//Len for IPHeader (UDPLen + IPLen + DataLen)
USHORT TotalLen = UserDataLen + 20 + 8;

//Beginning of Ethernet II Header
memcpy((void*)FinalPacket,(void*)DestinationMAC,6);//DestMAC
memcpy((void*)(FinalPacket+6),(void*)SourceMAC,6); //SrcMAC
USHORT TmpType = 8; // Type: IPv4
memcpy((void*)(FinalPacket+12),(void*)&TmpType,2);
// Beginning of IP Header
memcpy((void*)(FinalPacket+14),(void*)"\x45",1);
// First 4 bits = Version (4)
// Last 4 bits = HeaderLen (20)

//Differntiated services field. Usually 0
memcpy((void*)(FinalPacket+15),(void*)"\x00",1);
TmpType = htons(TotalLen);
memcpy((void*)(FinalPacket+16),(void*)&TmpType,2);
TmpType = htons(0x1337);
memcpy((void*)(FinalPacket+18),(void*)&TmpType,2);
// ID Number. Usually not needed
// Set to 0x1337 here

// Flags. Used more by TCP.
memcpy((void*)(FinalPacket+20),(void*)"\x00",1);
// Fragment Offset. NOt much use in udp
memcpy((void*)(FinalPacket+21),(void*)"\x00",1);
// Time To Live. I see 128 alot
memcpy((void*)(FinalPacket+22),(void*)"\x80",1);
// Protocol. UDP is 0x11;TCP is 6;ICMP is 1 etc
memcpy((void*)(FinalPacket+23),(void*)"\x11",1);
memcpy((void*)(FinalPacket+24),(void*)"\x00\x00",2);
//checksum, should be zero before
// checksum calculation

//inet_addr does htonl() for us
memcpy((void*)(FinalPacket+26),(void*)&SourceIP,4);
// if inet_addr not used, use htonl()
memcpy((void*)(FinalPacket+30),(void*)&DestIP,4);
//Beginning of UDP Header
TmpType = htons(SourcePort);
memcpy((void*)(FinalPacket+34),(void*)&TmpType,2);
TmpType = htons(DestinationPort);
memcpy((void*)(FinalPacket+36),(void*)&TmpType,2);
USHORT UDPTotalLen = htons(UserDataLen + 8); // UDP Len + DataLen
// Note missing 2 bytes for checksum
memcpy((void*)(FinalPacket+38),(void*)&UDPTotalLen,2);
/Finally append our own data
memcpy((void*)(FinalPacket+42),(void*)UserData,UserDataLen);

unsigned short UDPChecksum = CalculateUDPChecksum(UserData,
UserDataLen,SourceIP,DestIP,htons(SourcePort),
htons(DestinationPort),0x11);
memcpy((void*)(FinalPacket+40),(void*)&UDPChecksum,2);
// The UDP Checksum

unsigned short IPChecksum = htons(CalculateIPChecksum();
memcpy((void*)(FinalPacket+24),(void*)&IPChecksum,2);

return;
}

Checksums

Now, for the checksum functions. These are CalculateUDPChecksum and CalculateIPChecksum. I will go over the latter first.

Collapse
unsigned short RawPacket::CalculateIPChecksum(void)
{
unsigned short CheckSum = 0;
for(int i = 14;i<34;i+=2)
{
unsigned short Tmp = BytesTo16(FinalPacket[i],FinalPacket[i+1]);
unsigned short Difference = 65535 - CheckSum;
CheckSum += Tmp;
if(Tmp > Difference){CheckSum += 1;}
}
CheckSum = ~CheckSum;
return htons(CheckSum);
}

The cool thing about calculating the IP checksum is that we don't need items that are spread across the packet. The IP checksum is based only on the 20 bytes of the entire IP header. Since the IP header in our packet starts at the 15th byte, we set i to 14 (arrays start at zero) and stop at 14+20 (34). The checksum for the IP header is based on the 16 bit complement of the 16 bit . This means that we must join every two bytes into one, then add it to the checksum, and if the addition causes the checksum total to go over 65535 (the maximum an unsigned short can hold), we add one to the checksum. In the function, BytesTo16() joins the two bytes and puts the result in Tmp, and then Difference holds the highest number Tmp can be without causing CheckSum to go over 65535. At the end of every loop, a check is made to see if Tmp is higher than Difference, and one is added accordingly. At the very end of the function, the ~ operator is used to get the of CheckSum. (The one's complement of the one's complement sum).

Here is the BytesTo16 function used to join two chars into a short:

Collapse
unsigned short BytesTo16(unsigned char X,unsigned char Y)
{
unsigned short Tmp = X;
Tmp = Tmp << 8;
Tmp = Tmp | Y;
return Tmp;
}

The UDP checksum function is very similar to the IP checksum one, except that first a "pseduoheader" must be constructed. The pseudoheader is made up of the source IP, the destination IP, the source port, the destination port, the length (the length should be in the pseudoheader twice), the protocol, and the actual data. Note that if the length of the pseudoheader is an odd number, a zero should be added at the end for check sum purposes. Make sure that all things are in the network byte order because otherwise there will be problems.

Collapse
unsigned short RawPacket::CalculateUDPChecksum(unsigned char* UserData,
int UserDataLen,
unsigned int SourceIP,
unsigned int DestIP,
unsigned short SourcePort,
unsigned short DestinationPort,
unsigned char Protocol)
{
unsigned short CheckSum = 0;
unsigned short PseudoLength = UserDataLen + 8 + 9; //Length of PseudoHeader =
//Data Length + 8 bytes UDP header
//+ Two 4 byte IP's + 1 byte protocol

PseudoLength += PseudoLength % 2; //If bytes are not an even number, add an extra.

unsigned short Length = UserDataLen + 8; // This is just UDP + Data length.
//needed for actual data in udp header

unsigned char* PseudoHeader = new unsigned char [PseudoLength];
for(int i = 0;i < PseudoLength;i++){PseudoHeader[i] = 0x00;}//Init

PseudoHeader[0] = Protocol; // Protocol

memcpy((void*)(PseudoHeader+1),(void*)(FinalPacket+26),8); // Source and Dest IP

Length = htons(Length); // Length is not network byte order yet
memcpy((void*)(PseudoHeader+9),(void*)&Length,2); //Included twice
memcpy((void*)(PseudoHeader+11),(void*)&Length,2);

memcpy((void*)(PseudoHeader+13),(void*)(FinalPacket+34),2);//Source Port
memcpy((void*)(PseudoHeader+15),(void*)(FinalPacket+36),2); // Dest Port

memcpy((void*)(PseudoHeader+17),(void*)UserData,UserDataLen);


for(int i = 0;i < PseudoLength;i+=2)
{
unsigned short Tmp = BytesTo16(PseudoHeader[i],PseudoHeader[i+1]);
unsigned short Difference = 65535 - CheckSum;
CheckSum += Tmp;
if(Tmp > Difference){CheckSum += 1;}
}
CheckSum = ~CheckSum; //One's complement
return CheckSum;
}

Woot, that's about it. Just use these functions to place the UDP or IP checksum where they belong. Also, I am not yet sure why I need to do htons() on the IP checksum but not the UDP checksum.

Sending the information

The next function to look at is RawPacket.SendPacket(pcap_if_t* Device). This is where WinPCap sends the packets. Fortunately for us, this function is very simple.

Collapse
void RawPacket::SendPacket(pcap_if_t* Device)
{
char Error[256];
pcap_t* t;
t = pcap_open(Device->name,65535,PCAP_OPENFLAG_DATATX_UDP,1,NULL,Error);
pcap_sendpacket(t,FinalPacket,UserDataLen + 42);
pcap_close(t);
}

pcap_sendpacket sends packets, but first, we must get a pcap_t* for its first parameter. Since we already have the ChosenDevice variable, we can just pass its device->name to pcap_open so that pcap_t* t contains a handle to the device we want. is described . pcap_sendpacket just takes a pcap_t* variable, the data to send in an unsigned char buffer, and the length of the data. The length here is the length of the data plus 42 bytes of headers.

Improving the code

This class could use variables (instead of taking them all in one function), accessor functions, and perhaps some sort of division between headers.

Points of interest

I thought it was interesting that some ISPs don't allow packets with spoofed source IPs or MAC addresses to be sent. I tried this myself, and could only send using my real IP and MAC (using spoofed values made the packets visible to me on Wireshark, but not at the target server), but my friend in Mexico was able to successfully send packets with both of these items being spoofed. (I was the server, and was able to see his packets coming from "11.33.33.77"). Just remember that if you are only using this in a local network, you should be able to use any IP or MAC address that exists in your LAN (192.168.1.0 - 192.168.1.100, for example). Another problem I had was knowing what the destination MAC was. At first, I thought it was the hardware address of the device at the destination IP. Then, I learned that it is actually just the hardware address of the next device to which the data should be sent. (For me, the default gateway.)

阅读(1519) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~