I'm programming software which can send tcp packets to an host.
I'm able to create a packet with IP header, TCP Headers and data but I can't manage how to add TCP options like MSS, NOP, STACK, Window scaling or Timestamp.
I mean i'm not able to add options to the TCP header, calculate the correct checksum to send a good TCP packet to the host.
I can just send correct TCP packets without TCP options.
Do you think I'm on the correct patch? Could somebody please help me?
/* TCP Header structure */
struct tcphdr
{
u_int16_t th_sport; /* source port */
u_int16_t th_dport; /* destination port */
u_int32_t th_seq; /* sequence number */
u_int32_t th_ack; /* acknowledgement number */
#if __BYTE_ORDER == __LITTLE_ENDIAN
u_int8_t th_x2:4; /* (unused) */
u_int8_t th_off:4; /* data offset */
#endif
#if __BYTE_ORDER == __BIG_ENDIAN
u_int8_t th_off:4; /* data offset */
u_int8_t th_x2:4; /* (unused) */
#endif
u_int8_t th_flags;
# define TH_FIN 0x01
# define TH_SYN 0x02
# define TH_RST 0x04
# define TH_PUSH 0x08
# define TH_ACK 0x10
# define TH_URG 0x20
# define TH_ECE 0x40
# define TH_CWR 0x80
u_int16_t th_win; /* window */
u_int16_t th_sum; /* checksum */
u_int16_t th_urp; /* urgent pointer */
};
struct tcp_option_mss
{
uint8_t kind; /* 2 */
uint8_t len; /* 4 */
uint16_t mss;
} __attribute__((packed));
struct tcphdr_mss
{
struct tcphdr tcphdr;
struct tcp_option_mss mss;
};
/* IP Header structure */
struct ip
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
unsigned int ip_hl:4; /* header length */
unsigned int ip_v:4; /* version */
#endif
#if __BYTE_ORDER == __BIG_ENDIAN
unsigned int ip_v:4; /* version */
unsigned int ip_hl:4; /* header length */
#endif
u_int8_t ip_tos; /* type of service */
u_short ip_len; /* total length */
u_short ip_id; /* identification */
u_short ip_off; /* fragment offset field */
# define IP_RF 0x8000 /* reserved fragment flag */
# define IP_DF 0x4000 /* dont fragment flag */
# define IP_MF 0x2000 /* more fragments flag */
# define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
u_int8_t ip_ttl; /* time to live */
u_int8_t ip_p; /* protocol */
u_short ip_sum; /* checksum */
struct in_addr ip_src, ip_dst; /* source and dest address */
};
int send_packet(int sock, long dest_ip , long source_ip, long port, u_int8_t th_flags, unsigned long seq, unsigned long ack, unsigned long port1, unsigned char * data, unsigned long data_i)
{
char * packet;
struct ip * pkt_ip;
struct tcphdr * pkt_tcp;
struct tcphdr_mss * tcp_header;
struct sockaddr_in sin;
packet = malloc(sizeof(struct ip) + sizeof(struct tcphdr_mss) + data_i);
if (packet == NULL)
{
if (ECHO)
fprintf(stderr, "Error in allocating memory\n");
exit(EXIT_FAILURE);
}
memset(packet, 0, sizeof(struct ip) + sizeof(struct tcphdr_mss));
pkt_ip = (struct ip *) packet;
pkt_tcp = (struct tcphdr *) (packet + sizeof(struct ip));
pkt_tcp->th_sport = htons(port1);
pkt_tcp->th_dport = htons(port);
pkt_tcp->th_seq = htonl(seq);
pkt_tcp->th_ack = htonl(ack);
pkt_tcp->th_off = sizeof(struct tcphdr) / 4 + 1;
pkt_tcp->th_flags = th_flags;
pkt_tcp->th_win = htons(32768);
pkt_tcp->th_sum = 0;
tcp_header = malloc(sizeof(struct tcphdr));
tcp_header->tcphdr = *pkt_tcp;
tcp_header->mss.kind = 2;
tcp_header->mss.len = 4;
tcp_header->mss.mss = htons(32000);
pkt_ip->ip_v = 4;
pkt_ip->ip_hl = sizeof(struct ip) >> 2;
pkt_ip->ip_tos = 0;
pkt_ip->ip_len = htons(sizeof(struct ip) + sizeof(struct tcphdr) + data_i);
if (ipid > 65000)
ipid = 0;
ipid++;
pkt_ip->ip_id = ipid;
pkt_ip->ip_off = 0;
pkt_ip->ip_ttl = 64;
pkt_ip->ip_p = IPPROTO_TCP ;
pkt_ip->ip_sum = 0;
pkt_ip->ip_src.s_addr = source_ip;
pkt_ip->ip_dst.s_addr = dest_ip;
pkt_ip->ip_sum = checksum((unsigned short*)pkt_ip, sizeof( struct ip) );
pkt_tcp->th_sum = in_cksum_tcp(pkt_ip->ip_src.s_addr, pkt_ip->ip_dst.s_addr, (unsigned short *) pkt_tcp, sizeof(struct tcphdr_mss), data, data_i);
memcpy(((char *)pkt_tcp + sizeof(struct tcphdr_mss)), data, data_i);
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = pkt_ip->ip_dst.s_addr;
if (sendto(sock, packet, sizeof(struct ip) + sizeof(struct tcphdr_mss) + data_i, 0, (struct sockaddr *) &sin, sizeof(sin)) < 0)
{
perror("sendto");
free(packet);
return -1;
}
free(packet);
return 0;
}
In the line:
pkt_tcp->th_sum = in_cksum_tcp(pkt_ip->ip_src.s_addr, pkt_ip->ip_dst.s_addr, (unsigned short *) pkt_tcp, sizeof(struct tcphdr_mss), data, data_i);
According to the in_cksum_tcp function that i've seen in the wild:
unsigned short in_cksum_tcp(int src, int dst, unsigned short *addr, int len, unsigned char * data, int data_i)
You are passing the size of the options header (sizeof(struct tcphdr_mss)), instead the size of the complete TCP header (sizeof (tcphdr) + sizeof(tcphdr_mss)). I think this could be the problem (you don't compute correctly the TCP checksum).
A good way to check wich is the problem creating raw packets is to save the packet with libpcap to a pcap file and open with the wireshark. You could check easily the integrity of the packet.
Below is a function which calculate correct checksum for a packet
unsigned short csum(unsigned short * ptr, int nbytes) {
register long sum;
unsigned short oddbyte;
register short answer;
sum = 0;
while (nbytes > 1) {
sum += * ptr++;
nbytes -= 2;
}
if (nbytes == 1) {
oddbyte = 0; * ((u_char * ) & oddbyte) = * (u_char * ) ptr;
sum += oddbyte;
}
sum = (sum >> 16) + (sum & 0xffff);
sum = sum + (sum >> 16);
answer = (short)~sum;
return (answer);
}
call the function to get checksum for ip and tcp.
other then this inorder to use option like options like MSS, NOP, STACK you need to declare all this in your TCP header. and when you are using all this in your program you have to set the value of th_off accordingly
Related
I am working on a sniffing and spoofing project using C and the pcap library. I have to admit, I am still learning this library and it is taking me forever. That being said, I am having some issues with my program. I cannot get it to properly send my ICMP reply. The idea of the program is that it sniffs for any ICMP requests on its network and sends a reply. Currently, the program executes but I cannot seem to get the reply to actually send correctly. I am fairly certain that the error is in the "SpoofReply()" function or the "Send_Raw_Packet()". Here is code:
*EDIT FOR CLARITY: The program should send an ICMP Reply to any ICMP request. Test using a ping command to any non functional IP desitination (1.1.1.1). Without program, there should be no response. If program is running on same network as ping request, (I just run from the same machine) then it should create an ICMP reply from "1.1.1.1". Spoofing. However, my reply never actually sends when I run the program. It detects the request and attemps to create a response, but the logic is wrong somewhere.
#include <pcap.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <unistd.h>
/* ethernet headers are always exactly 14 bytes [1] */
#define SIZE_ETHERNET 14
/* Ethernet addresses are 6 bytes */
#define ETHER_ADDR_LEN 6
#define PACKET_LEN 1500
#define BUFSIZE 1500
/* Ethernet header */
struct ethheader {
u_char ether_dhost[ETHER_ADDR_LEN]; /* destination host address */
u_char ether_shost[ETHER_ADDR_LEN]; /* source host address */
u_short ether_type; /* IP? ARP? RARP? etc */
};
/* IP Header */
struct ipheader {
unsigned char iph_ihl:4, iph_ver:4; //IP Header length & Version.
unsigned char iph_tos; //Type of service
unsigned short int iph_len; //IP Packet length (Both data and header)
unsigned short int iph_ident; //Identification
unsigned short int iph_flag:3, iph_offset:13; //Flags and Fragmentation offset
unsigned char iph_ttl; //Time to Live
unsigned char iph_protocol; //Type of the upper-level protocol
unsigned short int iph_chksum; //IP datagram checksum
struct in_addr iph_sourceip; //IP Source address (In network byte order)
struct in_addr iph_destip;//IP Destination address (In network byte order)
};
/* ICMP Header */
struct icmpheader {
unsigned char icmp_type; //ICMP message type
unsigned char icmp_code; //Error code
unsigned short int icmp_chksum; //Checksum for ICMP Header and data
unsigned short int icmp_id; //Used in echo request/reply to identify request
unsigned short int icmp_seq;//Identifies the sequence of echo messages,
//if more than one is sent.
};
/* TCP Header */
struct tcpheader {
u_short tcp_sport; /* source port */
u_short tcp_dport; /* destination port */
u_int tcp_seq; /* sequence number */
u_int tcp_ack; /* acknowledgement number */
u_char tcp_offx2; /* data offset, rsvd */
#define TH_OFF(th) (((th)->tcp_offx2 & 0xf0) >> 4)
u_char tcp_flags;
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
#define TH_ECE 0x40
#define TH_CWR 0x80
#define TH_FLAGS (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR)
u_short tcp_win; /* window */
u_short tcp_sum; /* checksum */
u_short tcp_urp; /* urgent pointer */
};
/* UDP Header */
struct udpheader
{
u_int16_t udp_sport; /* source port */
u_int16_t udp_dport; /* destination port */
u_int16_t udp_ulen; /* udp length */
u_int16_t udp_sum; /* udp checksum */
};
struct pseudo_tcp
{
unsigned saddr, daddr;
unsigned char mbz;
unsigned char ptcl;
unsigned short tcpl;
struct tcpheader tcp;
char payload[PACKET_LEN];
};
// DNS layer header's structure
struct dnsheader {
unsigned short int query_id;
unsigned short int flags;
unsigned short int QDCOUNT;
unsigned short int ANCOUNT;
unsigned short int NSCOUNT;
unsigned short int ARCOUNT;
};
unsigned short in_cksum(unsigned short *buf,int length)
{
unsigned short *w = buf;
int nleft = length;
int sum = 0;
unsigned short temp=0;
/*
* The algorithm uses a 32 bit accumulator (sum), adds
* sequential 16 bit words to it, and at the end, folds back all the
* carry bits from the top 16 bits into the lower 16 bits.
*/
while (nleft > 1) {
sum += *w++;
nleft -= 2;
}
/* treat the odd byte at the end, if any */
if (nleft == 1) {
*(u_char *)(&temp) = *(u_char *)w ;
sum += temp;
}
/* add back carry outs from top 16 bits to low 16 bits */
sum = (sum >> 16) + (sum & 0xffff); // add hi 16 to low 16
sum += (sum >> 16); // add carry
return (unsigned short)(~sum);
}
/****************************************************************************
TCP checksum is calculated on the pseudo header, which includes the
the TCP header and data, plus some part of the IP header. Therefore,
we need to construct the pseudo header first.
*****************************************************************************/
unsigned short calculate_tcp_checksum(struct ipheader *ip)
{
struct tcpheader *tcp = (struct tcpheader *)((u_char *)ip +
sizeof(struct ipheader));
int tcp_len = ntohs(ip->iph_len) - sizeof(struct ipheader);
/* pseudo tcp header for the checksum computation */
struct pseudo_tcp p_tcp;
memset(&p_tcp, 0x0, sizeof(struct pseudo_tcp));
p_tcp.saddr = ip->iph_sourceip.s_addr;
p_tcp.daddr = ip->iph_destip.s_addr;
p_tcp.mbz = 0;
p_tcp.ptcl = IPPROTO_TCP;
p_tcp.tcpl = htons(tcp_len);
memcpy(&p_tcp.tcp, tcp, tcp_len);
return (unsigned short)in_cksum((unsigned short *)&p_tcp, tcp_len + 12);
}
/****************************************************************************
Function to actually send the spoofed IP reply.
*****************************************************************************/
void send_raw_packet (struct ipheader* ip)
{
int n = 0;
struct sockaddr_in dest_info;
int enable = 1;
//create a raw network socket and set its options.
int sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &enable, sizeof(enable));
//provide needed information about destination
dest_info.sin_family = AF_INET;
dest_info.sin_addr = ip->iph_destip;
//dest_info.sin_addr.s_addr = ip->iph_sourceip.s_addr;
//send out the packet
printf("Attmpting to send a spoofed ICMP packet! \n");
printf("......................................\n");
/*print the source and destination IP Addresses*/
printf(" From: %s\n", inet_ntoa(ip->iph_sourceip));
printf(" To: %s\n", inet_ntoa(ip->iph_destip));
printf("......................................\n");
while (n<2){
sendto(sock, ip, ntohs(ip->iph_len), 0, (struct sockaddr *)&dest_info, sizeof(dest_info));
printf("Oooooo....a spoofed ICMP packet has successfully been sent! \n");
n++;
}
close(sock);
}
/****************************************************************************
Function designed to spoof the ICMP reply
*****************************************************************************/
void spoofReply(struct ipheader* ip)
{
int ip_header_len = ip->iph_ihl * 4;
const char buffer[BUFSIZE];
struct icmpheader* icmp = (struct icmpheader *) ((u_char *)ip + ip_header_len);
if (icmp->icmp_type != 8) //this is not a reply, this is a request
{
printf("Packet received was not an ICMP request. Nothing sent.\n");
return;
}
//copy the original packet to a buffer
memset((char*)buffer, 0, BUFSIZE);
memset((char*)buffer, (int) ip, ntohs(ip->iph_len));
struct ipheader * newip = (struct ipheader *) buffer; //check this line for an error!!!
struct icmpheader * newicmp = (struct icmpheader *) ((u_char *)buffer + ip_header_len);
//new IP construction
newip->iph_sourceip.s_addr = ip->iph_destip.s_addr;
newip->iph_destip.s_addr = ip->iph_sourceip.s_addr;
newip->iph_ttl = 20;
newip->iph_protocol = IPPROTO_ICMP;
//fill ICMP info
newicmp->icmp_type = 0;
//checksum
newicmp->icmp_chksum = 0;
newicmp->icmp_chksum = in_cksum((unsigned short *)newicmp, ntohs(ip->iph_len) - ip_header_len);
printf("Packet is for sure an ICMP Request. Lets send a raw packet!\n");
send_raw_packet(newip);
}
/****************************************************************************
Packet Handler- This function handles incoming packets and checks for ICMP
protocol. Calls spoofReply() if the packet is an ICMP Request.
spoofed ICMP reply if the incoming packet is an ICMP request.
*****************************************************************************/
void gotPacket (u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
struct ethheader *eth = (struct ethheader *) packet;
if (eth->ether_type != ntohs(0x0800)) return; //this is not an IP packet
struct ipheader* ip = (struct ipheader*)(packet + SIZE_ETHERNET);
int ip_header_len = ip->iph_ihl * 4;
printf("......................................\n");
/*print the source and destination IP Addresses*/
printf(" From: %s\n", inet_ntoa(ip->iph_sourceip));
printf(" To: %s\n", inet_ntoa(ip->iph_destip));
if (ip->iph_protocol == IPPROTO_ICMP)
{
printf("Whoa! An ICMP packet has been found! Lets check it out.\n");
spoofReply(ip);
}
}
int main()
{
pcap_t *handle;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program fp;
char filter_exp[] = "";
bpf_u_int32 net;
//Print name of program and its filter:
printf("Sniff...Sniff...Sniff...\n");
printf("Cole Sniffer Started. Filtering %s \n", filter_exp);
//open the live session using the pcap_open function
handle = pcap_open_live("eth13", BUFSIZ, 1, 1000, errbuf);
//set the filter for whichever type of traffic you would like to receive
pcap_compile(handle, &fp, filter_exp, 0, net);
//set filter (continued)
pcap_setfilter(handle, &fp);
pcap_loop(handle, 100, gotPacket, NULL); // captures the packets
pcap_close(handle);
return 0;
};
This program should catch a packet from offline dump file and decode it. Here I have problems with ntohs() function (it's near the end, headers description in the start). Why it does not work?
OS win7 x86, VS 2010 express.
#include "pcap.h"
#define SIZE_ETHERNET 14
#define ETHER_ADDR_LEN 6
/* 4 bytes IP address */
typedef struct ip_address{
u_char byte1;
u_char byte2;
u_char byte3;
u_char byte4;
}ip_address;
/* IPv4 header */
typedef struct ip_header{
u_char ver_ihl; // Version (4 bits) + Internet header length (4 bits)
u_char tos; // Type of service
u_short tlen; // Total length
u_short identification; // Identification
u_short flags_fo; // Flags (3 bits) + Fragment offset (13 bits)
u_char ttl; // Time to live
u_char proto; // Protocol
u_short crc; // Header checksum
ip_address saddr; // Source address
ip_address daddr; // Destination address
u_int op_pad; // Option + Padding
}ip_header;
/* UDP header*/
typedef struct udp_header{
u_short sport; // Source port
u_short dport; // Destination port
u_short len; // Datagram length
u_short crc; // Checksum
}udp_header;
typedef struct ethernet_address{
u_char byte1;
u_char byte2;
u_char byte3;
u_char byte4;
u_char byte5;
u_char byte6;
}ethernet_address;
/* Ethernet header */
typedef struct ethernet_header {
ethernet_address ether_dhost; /* Destination host address */
ethernet_address ether_shost; /* Source host address */
u_short ether_type; /* IP? ARP? RARP? etc */
};
/* TCP header */
typedef struct tcp_header {
u_short th_sport; /* source port */
u_short th_dport; /* destination port */
u_char th_offx2; /* data offset, rsvd */
#define TH_OFF(th) (((th)->th_offx2 & 0xf0) >> 4)
u_char th_flags;
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
#define TH_ECE 0x40
#define TH_CWR 0x80
#define TH_FLAGS (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR)
u_short th_win; /* window */
u_short th_sum; /* checksum */
u_short th_urp; /* urgent pointer */
}tcp_header;
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
/* Packet count */
int num = 1;
int main(int argc, char **argv)
{
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
char source[PCAP_BUF_SIZE];
u_int netmask;
char packet_filter[] = "";
struct bpf_program fcode;
if(argc != 2){
printf("usage: %s filename", argv[0]);
return -1;
}
/* Create the source string according to the new WinPcap syntax */
if ( pcap_createsrcstr( source, // variable that will keep the source string
PCAP_SRC_FILE, // we want to open a file
NULL, // remote host
NULL, // port on the remote host
argv[1], // name of the file we want to open
errbuf // error buffer
) != 0)
{
fprintf(stderr,"\nError creating a source string\n");
return -1;
}
/* Open the adapter */
if ( (adhandle= pcap_open(source, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // remote authentication
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n");
return -1;
}
/* Check the link layer. We support only Ethernet for simplicity. */
if(pcap_datalink(adhandle) != DLT_EN10MB)
{
fprintf(stderr,"\nThis program works only on Ethernet networks.\n");
return -1;
}
/* if(d->addresses != NULL)
Retrieve the mask of the first address of the interface
netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
else */
/* If the interface is without addresses we suppose to be in a C class network */
netmask=0xffffff;
//compile the filter
if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0 )
{
fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
return -1;
}
//set the filter
if (pcap_setfilter(adhandle, &fcode)<0)
{
fprintf(stderr,"\nError setting the filter.\n");
return -1;
}
/* start the capture */
pcap_loop(adhandle, 0, packet_handler, NULL);
return 0;
}
/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
struct tm ltime;
char timestr[16];
time_t local_tv_sec;
u_int ip_len;
u_short sport,dport;
ip_header *ih;
const struct ethernet_header *ethh; /* The ethernet header */
/*
* Unused variable
*/
(VOID)(param);
printf("Packet %d\n", num);
num++;
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
localtime_s(<ime, &local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", <ime);
/* print timestamp and length of the packet */
// printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len);
/* retireve the position of the ethernet header */
ethh = (struct ethernet_header*)(pkt_data);
/* retireve the position of the ip header */
ih = (ip_header *) (pkt_data + 14); //length of ethernet header
/* retireve the position of the udp header */
ip_len = (ih->ver_ihl & 0xf) * 4;
/* print ip addresses and ports */
printf("Eth Src: %x:%x:%x:%x:%x:%x >>> Dest: %x:%x:%x:%x:%x:%x\nIP Src: %d.%d.%d.%d >>> Dest: %d.%d.%d.%d\n",
ethh->ether_shost.byte1,
ethh->ether_shost.byte2,
ethh->ether_shost.byte3,
ethh->ether_shost.byte4,
ethh->ether_shost.byte5,
ethh->ether_shost.byte6,
ethh->ether_dhost.byte1,
ethh->ether_dhost.byte2,
ethh->ether_dhost.byte3,
ethh->ether_dhost.byte4,
ethh->ether_dhost.byte5,
ethh->ether_dhost.byte6,
ih->saddr.byte1,
ih->saddr.byte2,
ih->saddr.byte3,
ih->saddr.byte4,
ih->daddr.byte1,
ih->daddr.byte2,
ih->daddr.byte3,
ih->daddr.byte4
);
/* Panage protocols */
if(ih->proto == 0x11)
{
udp_header *uh;
uh = (udp_header *) ((u_char*)ih + ip_len);
printf("UDP Src: %d >>> Dest: %d\n", uh->sport,uh->dport);
}
else if(ih->proto == 0x06)
{
tcp_header *tcp = NULL;
/* convert from network byte order to host byte order */
tcp = (tcp_header *) ((u_char*)ih + ip_len);
/*HERE*/ sport = ntohs(tcp->th_sport);
/*HERE*/ dport = ntohs(tcp->th_dport);
printf("TCP Src: %d >>> Dest: %d\n", sport,dport);
}
}
error log:
1>------ Build started: Project: cw1, Configuration: Debug Win32 ------
1> cw1.c
1>cw1.obj : error LNK2019: unresolved external symbol __imp__ntohs#4 referenced in function _packet_handler
1>C:\Users\Medardas\Desktop\ComputerScience\C.SC251 - CW1\cw1\Debug\cw1.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Try including <arpa/inet.h> or <netinet/in.h>. Failing that, check your linker settings.
That's a linker error. Consult the documentation of the function. At the bottom of that page (all such pages are laid out the same way) you will find the details of what header, lib and DLL are needed. In this case you need to link against Ws2_32.lib.
#include<stdlib.h>
#include<netinet/ip.h>
#include<netinet/tcp.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#define P 5000 /* lets flood the port */
unsigned short /* this function generates header checksums */
csum (unsigned short *buf, int nwords)
{
unsigned long sum;
for (sum = 0; nwords > 0; nwords--)
sum += *buf++;
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
return ~sum;
}
int
main (void)
{
char ipp[10] = "1.2.3.4";
int s = socket (PF_INET, SOCK_RAW, IPPROTO_TCP); /* open raw socket */
char datagram[4096]; /* this buffer will contain ip header, tcp header,
and payload. we'll point an ip header structure
at its beginning, and a tcp header structure after
that to write the header values into it */
struct ip *iph = (struct ip *) datagram;
struct tcphdr *tcph = (struct tcphdr *) datagram + sizeof (struct ip);
struct sockaddr_in sin;
/* the sockaddr_in containing the dest. address is used
in sendto() to determine the datagrams path */
sin.sin_family = AF_INET;
sin.sin_port = htons (P);/* you byte-order >1byte header values to network
byte order (not needed on big endian machines) */
sin.sin_addr.s_addr = inet_addr ("192.168.1.12");
memset (datagram, 0, 4096); /* zero out the buffer */
/* we'll now fill in the ip/tcp header values, see above for explanations */
iph->ip_hl = 5;
iph->ip_v = 4;
iph->ip_tos = 0;
iph->ip_len = sizeof (struct ip) + sizeof (struct tcphdr); /* no payload */
iph->ip_id = htonl (54321); /* the value doesn't matter here */
iph->ip_off = 0;
iph->ip_ttl = 255;
iph->ip_p = 6;
iph->ip_sum = 0; /* set it to 0 before computing the actual checksum later */
iph->ip_src.s_addr = inet_addr (ipp);/* SYN's can be blindly spoofed */
iph->ip_dst.s_addr = sin.sin_addr.s_addr;
tcph->source = htons (1234); /* arbitrary port */
tcph->dest = htons (P);
tcph->seq = random ();/* in a SYN packet, the sequence is a random */
tcph->ack_seq = 0;/* number, and the ack sequence is 0 in the 1st packet */
tcph->doff = 0; /* first and only tcp segment */
tcph->syn = 1;
tcph->window = htonl (65535); /* maximum allowed window size */
tcph->check = 0;/* if you set a checksum to zero, your kernel's IP stack
should fill in the correct checksum during transmission */
tcph->urg_ptr = 0;
iph->ip_sum = csum ((unsigned short *) datagram, iph->ip_len >> 1);
/* finally, it is very advisable to do a IP_HDRINCL call, to make sure
that the kernel knows the header is included in the data, and doesn't
insert its own header into the packet before our data */
{ /* lets do it the ugly way.. */
int one = 1;
const int *val = &one;
if (setsockopt (s, IPPROTO_IP, IP_HDRINCL, val, sizeof (one)) < 0)
printf ("Warning: Cannot set HDRINCL!\n");
}
int i1=49;
char i2 = 49;
int cc = 0;
int r1;
while (cc<99)
{
ipp[6] = i1;
ipp[7] = i2;
if(i1 == 57)
{
break;
}
if(i2 == 57 )
{ i2 = 48;
i1++;
}
i2++;
cc++;
iph->ip_src.s_addr = inet_addr (ipp);
if (sendto (s, /* our socket */
datagram, /* the buffer containing headers and data */
iph->ip_len, /* total length of our datagram */
0, /* routing flags, normally always 0 */
(struct sockaddr *) &sin, /* socket addr, just like in */
sizeof (sin)) < 0) /* a normal send() */
printf ("error\n");
else
printf ("sent \n");
}
return 0;
}
the code creates a raw socket with proper ip address and the source addrewss is 192.168.1.12...port 5000 ... the problem is that when i try to capture the packets sent using wireshark, it says something like bogus tcp headee length...should be atleast 20 ... how can i correct this error ...
P.S. you can refer link for the code explanation if you find the code lengthy ...
After further reading: change this line
struct tcphdr *tcph = (struct tcphdr *) datagram + sizeof (struct ip);
to this
struct tcphdr *tcph = (struct tcphdr *) (datagram + sizeof (struct ip));
In the first case tcph would pointer far beyond iph.
char *datagramshould be unsigned char *too.
I want to know how to generate a packet in c. Supposed we have a type as follows:
struct ipheader {
int version;
int hdLen;
int tos;
int totLen;
int id;
......
int dstIp;
}
And we have a ipheader type:
struct ipheader ip;
//init the ip
.....
How can I generate a packet(just ip header part) from "ip". Could anyone show me how?
I want to know to generate packets with information such as mac address, ip header, tcp header, payload. Then I can use the "pcap_sendpacket" function to send the packets I have generated. Could someone give me a little example.
You can create custom ip packet as below. The below code snippet also makes the custom TCP part which is inside the ip packet. Also the custom function checksum generates the checksum for the packet. You can use rawsocket to send this packet directly to the network. I think the code is easy and self explanatory. Let me know if you have any queries.
#include <netinet/ip.h>
#include <netinet/tcp.h>
****************************************
ipv4 packet structure
****************************************
struct ipv4_packet {
struct iphdr iph;
struct tcphdr tcph;
void *data;
};
****************************************
snippet of the IPV4 packet making code
****************************************
struct iphdr ip_head;
struct tcphdr tcp_head;
struct sockaddr_in target;
char packet[2048];
int i;
struct tcp_pseudo /*the tcp pseudo header*/
{
__u32 src_addr;
__u32 dst_addr;
__u8 dummy;
__u8 proto;
__u16 length;
} pseudohead;
struct help_checksum /*struct for checksum calculation*/
{
struct tcp_pseudo pshd;
struct tcphdr tcphd;
char tcpdata[1024];
} tcp_chk_construct;
/*Prepare IP header*/
ip_head.ihl = 5; /*headerlength with no options*/
ip_head.version = 4;
ip_head.tos = 0;
ip_head.tot_len = htons(sizeof(struct iphdr) + sizeof(struct tcphdr) + len);
ip_head.id = htons(31337 + (rand() % 100));
ip_head.frag_off = 0;
ip_head.ttl = 255;
ip_head.protocol = IPPROTO_TCP;
ip_head.check = 0; /*Fill in later*/
ip_head.saddr = htonl(src);
ip_head.daddr = htonl(dst);
ip_head.check = in_cksum((unsigned short *) &ip_head, sizeof(struct iphdr));
/*Prepare TCP header*/
tcp_head.source = htons(src_p);
tcp_head.dest = htons(dst_p);
tcp_head.seq = htonl(seq);
tcp_head.ack_seq = htonl(ack);
tcp_head.doff = 5;
/* set or reset ack, fin or syn flags as needed */
tcp_head.ack = 0;
tcp_head.syn = 0;
tcp_head.fin = 0;
tcp_head.res1 = 0;
tcp_head.urg = 0;
tcp_head.psh = 0;
tcp_head.rst = 0;
tcp_head.res2 = 0;
tcp_head.window = htons(0x7c00);
tcp_head.check = 0; /*Fill in later*/
tcp_head.urg_ptr = 0;
/*Assemble structure for checksum calculation and calculate checksum*/
pseudohead.src_addr = ip_head.saddr;
pseudohead.dst_addr = ip_head.daddr;
pseudohead.dummy = 0;
pseudohead.proto = ip_head.protocol;
pseudohead.length = htons(sizeof(struct tcphdr) + len);
tcp_chk_construct.pshd = pseudohead;
tcp_chk_construct.tcphd = tcp_head;
memcpy(tcp_chk_construct.tcpdata, buffer, len);
tcp_head.check = in_cksum((unsigned short *) &tcp_chk_construct,
sizeof(struct tcp_pseudo) + sizeof(struct tcphdr) + len);
/*Assemble packet*/
memcpy(packet, (char *) &ip_head, sizeof(ip_head));
memcpy(packet + sizeof(ip_head), (char *) &tcp_head, sizeof(tcp_head));
memcpy(packet + sizeof(ip_head) + sizeof(tcp_head), buffer, len);
/*Send packet*/
target.sin_family = AF_INET;
target.sin_addr.s_addr = ip_head.daddr;
target.sin_port = tcp_head.dest;
i = sendto(sfd, packet, sizeof(struct iphdr) + sizeof(struct tcphdr) + len,
0, (struct sockaddr *) &target, sizeof(struct sockaddr_in));
if (i < 0)
return (-1); /*Error*/
else
return (i); /*Return number of bytes sent*/
****************************************
FUNCTION FOR CHECKSUM
****************************************
/* function to calculate the checksum for the packet */
unsigned short in_cksum(unsigned short *ptr, int nbytes) {
register long sum; /* assumes long == 32 bits */
u_short oddbyte;
register u_short answer; /* assumes u_short == 16 bits */
/*
* the algorithm is simple, using a 32-bit accumulator (sum),
* we add sequential 16-bit words to it, and at the end, fold back
* all the carry bits from the top 16 bits into the lower 16 bits.
*/
sum = 0;
while (nbytes > 1) {
sum += *ptr++;
nbytes -= 2;
}
/* mop up an odd byte, if necessary */
if (nbytes == 1) {
oddbyte = 0; /* make sure top half is zero */
*((u_char *) &oddbyte) = *(u_char *) ptr; /* one byte only */
sum += oddbyte;
}
/*
* Add back carry outs from top 16 bits to low 16 bits.
*/
sum = (sum >> 16) + (sum & 0xffff); /* add high-16 to low-16 */
sum += (sum >> 16); /* add carry */
answer = ~sum; /* ones-complement, then truncate to 16 bits */
return (answer);
}
Since you haven't specified the details (looks suspiciously like homework to me as well), all i can do is give pointers.
Look up how structures are formed in the memory.
Look up Ip header format which will show you what member is where in an Ip header.
Look up Raw sockets.
So, provided you properly structure your struct and use raw sockets, you only need to write this struct to the socket.
I am trying to write a sample Raw socket program to clear my understanding of raw sockets. I create a Raw UDP socket and then call sendto. My sendto succeeds but I never see the packet received by the other side. I don't have any receive side running so I am relying on Wireshark running on both the sender and receiver.
I am pasting the code snippet here. Please point out any errors.
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<string.h>
#include "protHeaders.x"
#include "gen.h"
U16 csum(U16* buf, S32 nwords)
{
U32 sum;
for (sum = 0; nwords > 0; nwords--)
sum += *buf++;
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
return ~sum;
}/*csum*/
int main(int argc,char** argv)
{
U8 datagram[MAX_IPPACKET];
U8 udpPayLoad[MAX_UDPPAYLOAD];
CustIpHeader* ipH;
CustUdpHeader* udpH;
struct sockaddr_in sin;
S32 sockFd;
S32 one = 1;
const S32* val = &one;
ipH = (CustIpHeader *)datagram;
udpH = (CustUdpHeader *)(datagram + sizeof(CustIpHeader));
memset(datagram,0,sizeof(datagram));
memset(udpPayLoad,0,sizeof(udpPayLoad));
memset(&sin,0,sizeof(struct sockaddr_in));
strcpy(udpPayLoad,"<<<<Aditya>>>>");
sin.sin_family = AF_INET;
sin.sin_port = htons(atoi(argv[4]));
/* fill the Ip header */
ipH->ip_hl = 5;
ipH->ip_v = 4;
ipH->ip_tos = 0;
ipH->ip_len = sizeof(CustIpHeader) + sizeof(CustUdpHeader) + strlen(udpPayLoad);
ipH->ip_id = htonl(54321);
ipH->ip_off = 0;
ipH->ip_p = 17;
ipH->ip_ttl = 65;
ipH->ip_sum = 0;
ipH->ip_src.s_addr = inet_addr(argv[1]);
ipH->ip_dst.s_addr = inet_addr(argv[3]);
/* fill the Udp header */
udpH->uh_sport = htons(atoi(argv[2]));
udpH->uh_dport = htons(atoi(argv[4]));
udpH->uh_len = sizeof(CustUdpHeader) + strlen(udpPayLoad);
udpH->uh_check = 0;
printf("Checksum = %u\n",udpH->uh_check);
/* copy udpPayLoad */
strcpy(datagram+sizeof(CustIpHeader)+sizeof(CustUdpHeader),udpPayLoad);
#if 1
printf("Datagram %p,UdpPayload %p\n",(void *)datagram,(void *)datagram+sizeof(CustIpHeader)+sizeof(CustUdpHeader));
printf("IpHeader %p, UdpHeader %p\n",(void *)ipH,udpH);
#endif
/* fill in the checksum */
ipH->ip_sum = csum((U16 *)datagram,ipH->ip_len >> 1);
printf("Checksum = %u\n",ipH->ip_sum);
if ((sockFd = socket(PF_INET,SOCK_RAW,IPPROTO_UDP)) < 0)
{
perror("socket:create");
RETURN(RFAILED);
}
/* doing the IP_HDRINCL call */
if (setsockopt(sockFd,IPPROTO_IP,IP_HDRINCL,val,sizeof(one)) < 0)
{
perror("Client:setsockopt");
}
while(1)
{
if ( sendto(sockFd,
datagram,
ipH->ip_len,
0,
(struct sockaddr *)&sin,
sizeof (sin)) < 0)
{ perror("Client:sendto"); }
else
printf(".");
}
RETURN(ROK);
}
The IP and UDP headers are:
typedef struct _ipheader
{
U8 ip_hl:4,ip_v:4; /* ip_hl: the ip header length in 32bit octets.
* ip_v : ip version (always 4 for our case).
*/
U8 ip_tos; /* reliability of the service. 0x00 is Normal */
U16 ip_len; /* totoal length including ip header,icmp/tcp/udp header
* and payload size in bytes
*/
U16 ip_id; /* sequence no. used for reassembly of fragmented IP packets */
U16 ip_off; /* the fragment offset used for reassembly of fragmented packets */
U16 ip_p; /* the transport layer protocol. can be tcp (6), udp(17) */
U8 ip_ttl; /* time to live */
U16 ip_sum; /* the datagram checksum for the whole IP packet */
struct in_addr ip_src; /* the source IP address, converted to a long format */
struct in_addr ip_dst; /* the desitnation IP address, converted to a long format */
}CustIpHeader; /* total ip header length: 20 bytes */
typedef struct _udpheader
{
U16 uh_sport; /* The source port that a client bind()s to */
U16 uh_dport; /* The desination port that a server bind()s to*/
U16 uh_len; /* The length of udp header and payload data in bytes */
U16 uh_check; /* The checksum of header and data */
}CustUdpHeader; /* total udp header length: 8 bytes (=64 bits) */
I am running as root user, so privileges is not a problem.
Language: C
Os: Linux
I had the wireshark running on a slow system. The packets were indeed being send but the Wireshark could only show them after a gap of 6 minutes or so. Moving to a faster system helped. I am therefore closing this myself.
This may help you to get started http://www.securitytube.net/Raw-Sockets-Basics-Presentation-video.aspx.
if you are using libcap/wincap i would have helped. but above video help you get started.