Malformed packet in dns client implementation - c

Hi there for fun i'm developing a tiny dns client on a unix system.
I've read the documentation about dns protocol i wrote a tiny function
int makeQuestion(char* dns_addr,char *name){
int s = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
register int len_name = strlen(name);
if(s<0)
return errno;
struct sockaddr_in address;
bzero(&address,sizeof(address));
address.sin_port = htons(53);
address.sin_addr.s_addr = inet_addr(dns_addr);
dns_header header;
memset(&header,0,sizeof(dns_header));
header.id = htons(getpid());
header.q_count = htons(1);
dns_question quest = {
.qclass = htons(IN),
.qtype = htons(A)
};
register int pack_size = sizeof(dns_header)+len_name+2+sizeof(dns_question);
char *packet = malloc(pack_size);
memcpy(packet,&header,sizeof(dns_header));
for(int i = 0;i<len_name;i++)
*(packet +i +sizeof(dns_header)) = name[i];
packet[len_name+sizeof(dns_header)] = '.';
packet[len_name+sizeof(dns_header)+1] = '\0';
memcpy(packet+sizeof(dns_header)+len_name+2,&quest,sizeof(dns_question));
sendto(s,packet,pack_size,NULL,&address,sizeof(address));
return OK;
}
The structure for the dns header and dns query are declared like:
//DNS header structures
typedef struct dns_header
{
uint16_t id; // identification number
uint8_t rd :1; // recursion desired
uint8_t tc :1; // truncated message
uint8_t aa :1; // authoritive answer
uint8_t opcode :4; // purpose of message
uint8_t qr :1; // query/response flag
uint8_t rcode :4; // response code
uint8_t cd :1; // checking disabled
uint8_t ad :1; // authenticated data
uint8_t z :1; // its z! reserved
uint8_t ra :1; // recursion available
uint16_t q_count; // number of question entries
uint16_t ans_count; // number of answer entries
uint16_t auth_count; // number of authority entries
uint16_t add_count; // number of resource entries
}dns_header;
typedef struct dns_question
{
uint16_t qtype;
uint16_t qclass;
}dns_question;
Now i executed the code while wireshark was running and i saw the packet that seemed to be correct but in the query section wireshark said
Name: <Unknown extended label>
So the question is there is a way i have to use to store the dns name of the queried host in the packet or there is something wrong in the implementation. Sorry for the loosing of time and sorry for my English. Thanks indeed

I solved finally. Studing better the protocoll ( the domain name system) where the reference is at this link a the wrong part was in the section called qname ( the name of the host that in my case the protocoll wasn't able to determinate the size)
So as the document said qname is:
a domain name represented as a sequence of labels, where
each label consists of a length octet followed by that
number of octets. The domain name terminates with the
zero length octet for the null label of the root. Note
that this field may be an odd number of octets; no
padding is used.
So i changed my code to transform www.example.com in 3www7example3com
and everything works

Related

How to display or do eDNS in dpdk packets?

I am using l2fwd-dpdk application from which I can extract 5-tuples, and can see if DNS Packet is present or not.
Now I want to classify the DNS Packet using dpdk, for which I am failing.
Here is my code.
struct rte_udp_hdr *udp_hdr;
struct dnshdr *dns_hdr;
if (rte_be_to_cpu_16(udp_hdr->dst_port) == 53)
{
printf("DNS Packet");
char *dns_hdr = (char *)udp_hdr + sizeof(rte_udp_hdr);
}
I want to separate
Flags
Rdata
Class
TTL
and save them separately. Is there any way around, I can comfortable to use cpp wrapper as well.
DPDK as of 21.08 does not house any header or structure to typecast to DNS packet. Hence easiest way to solve the issue as mentioned by #wildplasser is to declare your custom DNS header and use it. In your code snippet, you already have struct dnshdr *dns_hdr; So the easier way is to modify your existing code to reflect
struct rte_udp_hdr *udp_hdr;
struct dnshdr *dns_hdr;
/* use DPDK mtod API to get the start of ethernet frame */
/* check for packet size, ether type, IP protocol */
/* update udp_hdr to position in the packet */
if (rte_be_to_cpu_16(udp_hdr->dst_port) == 53)
{
printf("DNS Packet");
struct dnshdr *dns_hdr = (struct dnshdr *)((char *)udp_hdr + sizeof(rte_udp_hdr));
}
Note: Possible structure definition code snippet would be
typedef struct {
uint16_t id;
uint16_t rd:1;
uint16_t tc:1;
uint16_t aa:1;
uint16_t opcode:4;
uint16_t qr:1;
uint16_t rcode:4;
uint16_t zero:3;
uint16_t ra:1;
uint16_t qcount; /* question count */
uint16_t ancount; /* Answer record count */
uint16_t nscount; /* Name Server (Autority Record) Count */
uint16_t adcount; /* Additional Record Count */
} custom_dnshdr;
custom_dnshdr *dns_hdr = (custom_dnshdr *) ((char *)udp_hdr + sizeof(rte_udp_hdr));

How can I capture dns packets in c?

I'm writing a packet sniffer program in c. Now it can only find HTTP packets but I want to make it in a way to get also DNS packets. I know DNS packets are UDP but I don't know how to identify DNS ones. Is there a specific thing in DNS packets to check to find them? I know port 53 is default port for DNS requests, but is it a reliable way to find them?
There is no good way to tell if a UDP packet contains DNS data: There is nothing in the UDP header, or IP header that directly tells you the data is DNS. However what you could do is first see if the source port in the UDP header is port 53 (DNS's standard UDP port) and second see if the data fits the data structure you're using to decode the header (most likely a struct). This is a very good question.
To fit the packet to a strcut you can use the following code:
This is the actual structure of a DNS header packet laid out in a struct in c:
#pragma pack(push, 1)
typedef struct
{
uint16_t id; // identification number 2b
uint8_t rd : 1; // recursion desired
uint8_t tc : 1; // truncated message
uint8_t aa : 1; // authoritive answer
uint8_t opcode : 4; // purpose of message
uint8_t qr : 1; // query/response flag
uint8_t rcode : 4; // response code
uint8_t cd : 1; // checking disabled
uint8_t ad : 1; // authenticated data
uint8_t z : 1; // its z! reserved
uint8_t ra : 1; // recursion available 4b
uint16_t q_count; // number of question entries 6b
uint16_t ans_count; // number of answer entries 8b
uint16_t auth_count; // number of authority entries 10b
uint16_t add_count; // number of resource entries 12b
}Dns_Header, *Dns_Header_P;
#pragma pack(pop)
To test this you can do this:
Dns_Header_P header = (Dns_Header_P)capture;
capture being a byte array with you DNS header.
Depending on how you're capturing the packets and how you're storing them you might need to change the endianness of the struct. If you test this with your program and it doesn't seem to have the right data or the data is switched around let me know.

How to use structure with dynamically changing size of data?

Question for C only, C++ and vectors do not solve problem.
I have such structure:
typedef __packed struct Packet_s
{
U8 head;
U16 len;
U32 id;
U8 data;
U8 end;
U16 crc;
} Packet_t, *Packet_p;
(EDIT: U8 is uint8_t (unsigned char) and so on)
For example, I've received packet(hex):
24 0B 00 07 00 00 00 AA 0D 16 1C
where
head = 0x24
len = 0x0B 0x00
id = 0x07 0x00 0x00 0x00
data = 0xAA
end = 0x0D
crc = 0x16 0x1C
I can copy it from incoming buffer like this
U8 Buffer[SIZE]; // receives all bytes here
memcpy(&Packet, &Buffer, buffer_len);
and work futher with it.
Is it possible to use my structure if field "DATA" is longer than 1 byte?
How can I handle something like this?
24 0F 00 07 00 00 00 AA BB CC DD EE 0D BD 66
Length of packet will be always known (2 and 3 bytes have info about length).
EDIT: Under "handle" I mean that I want to do next:
if (isCRCmatch() )
{
if(Packet.id == SPECIAL_ID_1)
{
// do something
}
if(Packet.id == SPECIAL_ID_2)
{
// do other
}
if(Packet.data[0] == 0xAA)
{
// do one stuff
}
if(Packet.data[1] == 0xBB && Packet.id == SPECIAL_ID_3 )
{
// do another stuff
}
}
And also (if possible ofc) I would like to send "anwers" using same structure:
U8 rspData[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
SendResponce(Packet.id, rspData);
void SendResponce (U8 id_rsp, uint8_t* data_rsp)
{
Packet_t ResponceData;
uint16_t crc;
uint8_t *data;
ResponceData.head = 0x24;
ResponceData.len = sizeof(ResponceData); // HERE IS PROBLEM ONE
ResponceData.id = id_rsp;
ResponceData.data = *data_rsp; // HERE IS PROBLEM TWO
ResponceData.end = 0x0D; // symbol '\r'
data = (uint8_t*)&ResponceData;
crc = GetCrc(data, sizeof(ResponceData)-2); // last 2 bytes with crc
ResponceData.crc = crc;//(ack_crc >> 8 | ack_crc);
SendData((U8*)&ResponceData, sizeof(ResponceData)); // Send rsp packet
}
First problem - I cant get size of all structure automatically, since pointer will be always 4 bytes...
Second problem - I sure that I will lose rsp data since I don't know where is end of it.
You can't have dynamic buffer in middle of a struct.
Another way to solve the problem is divide the struct to two pieces.
For example (notice that data is here a flexible array member):
typedef __packed struct Packet_s
{
U8 head;
U16 len;
U32 id;
U8 data[];
} Packet_t, *Packet_p;
typedef __packed struct PacketEnd_s
{
U8 end;
U16 crc;
} PacketEnd_t, *PacketEnd_p;
Then use
Packet_t *pPacket = (Packet_t *)&Buffer;
PacketEnd_t *pPacketEnd = (PacketEnd_t *)( count pointer here by using pPacket->len );
Assuming that __packed allows to use unaligned access to members of __packed structs.
You should split your processing function into two distinct functions:
One which will discard everything until it finds the head byte. This byte usually is a constant byte, marking the start of a packet. This is done this way, in order to avoid start to read in the middle of a previously sent packet (think i.e. the startup order of the sender and the listener devices).
Once it finds the start of the packet, it can read the header, len and id and receive all the data storing it into your Buffer variable, until it reads the end byte or there is a buffer overflow, in which case it would just discard the data and start again.
NOTE that into the Buffer variable only should be written the actual data. All the other fields (len, id and so) can be stored in different variables, or in a struct containing only the Packet information, but no data. This way, you spit the application data from the transmission information.
Note also that this function does not interpret the idfield, nor the datafield. It just sends this information to the other funciton, which will do the processing or discard if the id or the dataare not correct / known.
Once the end byte is found, you can pass the information to the actual processing function. Its header would be something like:
void processPacket(U8 *data, U32 id, U16 len);
and the call to it would be:
void receiveFrame() {
//Receive head
//Receive id
//Receive len
//Fill in Buffer with the actual data
//Call the processPacket function
processPacket(&Buffer[0], id, len);
}
A more complete example could be:
//It is not packet, since you fill it reading from the buffer and assigning
//to it, not casting the buffer into it.
//It has no data field. The data is in a different variable.
typedef struct Packet_s
{
U8 head;
U16 len;
U32 id;
U8 end;
U16 crc;
} PacketInfo_t;
U8 Buffer[MAX_BUFFER_SIZE];
PacketInfo_t info;
void receiveFrame() {
info.head=//Receive head
info.len=//Receive len
info.id=//Receive id
//Fill the buffer variable
processPacket(&Buffer[0], &info);
}
void processPacket(U8 *data, PacketInfo_t *info);
For sending, just use the same format:
void sendPacket(U8 *data, PacketInfo_t *info);
This function sould prepare the Packet header from info and read the data from data.
And finally, a word of caution: casting (or memcpy) a received packet directly into a struct is almost never a good idea. You have to take into account not only the zero holes (using the __packet attribute), but also the endianness and the data format representation of the sender and receiver systems, since if they are different, you would end up with the wrong values.
Is it possible to use my structure if field "DATA" is longer than 1 byte?
No, since it has only room for 1 data byte. But you can use a slightly modified version of your structure.
typedef __packed struct Packet_s
{
U8 head;
U16 len;
U32 id;
U8 data[DATALENMAX]; // define appropriately
U8 end;
U16 crc;
} Packet_t, *Packet_p;
Of course, you'd have to adapt the copying accordingly:
memcpy(&Packet, &Buffer, buffer_len), memmove(&Packet.end, &Packet.data[buffer_len-7-3], 3);
Regarding the added problems, it's necessary to pass the data length to SendResponce():
SendResponce(rspData, sizeof rspData);
void SendResponce(uint8_t* data_rsp, int datalen)
{
Packet_t ResponceData;
uint16_t crc;
uint8_t *data;
ResponceData.head = 0x24;
ResponceData.len = 7+datalen+3; // HERE WAS PROBLEM ONE
ResponceData.id = SPECIAL_ID_X;
memcpy(ResponceData.data, data_rsp, datalen); // HERE WAS PROBLEM TWO
ResponceData.data[datalen] = 0x0D; // symbol '\r'
data = (uint8_t*)&ResponceData;
crc = GetCrc(data, 7+datalen+1); // last 2 bytes with crc
ResponceData.crc = crc;//(ack_crc >> 8 | ack_crc);
memmove(ResponceData.data+datalen+1, &ResponceData.crc, 2);
SendData((U8*)&ResponceData, ResponceData.len); // Send rsp packet
}

Layout of an ip header and network programming

I am taking a class on computer and network security. We are writing a packet spoofer. I could just download one from the internet and use it, but I prefer writing the stuff myself. Below is the struct that I use to represent the ip header which I am basing off of the wikipedia article. I am attempting to send an icmp ping packet. I have done it successfully, but only after assigning the value of the ip header length to the version field, and vice versa. Somehow I have setup my struct wrong, or I am assigning the values wrong, and I am not sure what I am doing incorrectly.
struct ip_header
{
uint8_t version : 4 // version
, ihl : 4; // ip header length
uint8_t dscp : 6 // differentiated services code point
, ecn : 2; // explicit congestion notification
uint16_t total_length; // entire packet size in bytes
uint16_t identification; // a unique identifier
uint16_t flags : 3 // control and identify fragments
, frag_offset : 13; // offset of fragment relative to the original
uint8_t ttl; // how many hops the packet is allowd to travel
uint8_t protocol; // what protocol is in use
uint16_t checksum; // value used to determine bad packets
uint32_t src_ip; // where the packet is form
uint32_t dest_ip; // where the packet is going
};
If I assign the version and ihl, like below, wireshark reports an error with the header, "Bogus IPV4 version (0, must be 4)".
char buffer[1024];
struct ip_header* ip = (struct ip_header*) buffer;
ip->version = 4;
ip->ihl = 5;
However, after changing to the following listing, the ICMP request goes through just fine.
char buffer[1024];
struct ip_header* ip = (struct ip_header*) buffer;
ip->version = 5;
ip->ihl = 4;
I have tried placing htons around the numbers, but that doesn't seem to do anything useful. What am I missing here?
You simply need to correct your structure's endianness. Look at the IP header structure defined in the <netinet/ip.h> file:
struct iphdr
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
unsigned int ihl:4;
unsigned int version:4;
#elif __BYTE_ORDER == __BIG_ENDIAN
unsigned int version:4;
unsigned int ihl:4;
#else
# error "Please fix <bits/endian.h>"
#endif
uint8_t tos;
uint16_t tot_len;
uint16_t id;
uint16_t frag_off;
uint8_t ttl;
uint8_t protocol;
uint16_t check;
uint32_t saddr;
uint32_t daddr;
/*The options start here. */
};

Memory alignment issue in received network packets

I'm writing a custom protocol in the linux kernel. I'm using the following structures
struct syn {
__be32 id;
__be64 cookie;
};
struct ack {
__be32 id; // Right now, setting it to 14 (Just a random choice)
__be32 sequence;
};
struct hdr {
............
__be32 type; //last element
};
When I send and receive packets, I map the structures syn and ack (for different packets) to the address of hdr->type.
This should ideally mean that the id (in syn and ack structures) should be mapped to the hdr->type and whatever follows the struct hdr should be mapped to either syn->cookie or ack->sequence, depending on which struct I'm mapping on to the hdr->type.
But on printing out the memory addresses for these variables, I get the following
//For struct syn
hdr->type at ffff880059f55444
syn->id at ffff880059f55444
syn->cookie at ffff880059f5544c //See the last two bits
//For struct ack_frame
hdr->type at ffff880059f55044
ack->id at ffff880059f55044
ack->sequence at ffff880059f55048 //See the last two bits
So why do syn->cookie and ack->sequence start at different offsets relative to hdr->type when ack->id and syn->id have the same size?
EDIT 1: I map these structures using
char *ptr = (char *)&hdr->type;
//For syn
struct syn *syn1 = (struct syn *)ptr
//For ack
struct ack *ack1 = (struct ack *)ptr
since you work in 64 bits the compiler fills struct the following:
struct syn {
uint32_t id
uint32_t hole -- the compiler must add here cause it mist align
uint64_t seq
}
I guess the data doesn't have holes, so to fix it you will need to set seq to uint32_t and cast it later.
https://gcc.gnu.org/onlinedocs/gcc/Common-Type-Attributes.html#Common-Type-Attributes
Look at packed. For whatever reason, GCC doesn't let me link directly to that section.
You should define your structure as following. Attribute packed means allignment should be as 1 byte.
Following structure will be 12 bytes longs. If you dont use "attribyte" key word, your structure would be 16 bytes long.
struct yours{
__be32 id;
__be64 cookie;
}__attribute__((__packed__));

Resources