代码改变世界

Tcp syn portscan code in C with Linux sockets

2012-07-13 23:38  Rollen Holt  阅读(2029)  评论(0编辑  收藏  举报

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 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 :

1. It is slow since it establishes a complete 3 way TCP handshake. It waits for the connect() function to return.
2. It is detectable. It leaves more logs on the remote system and on any firewall that is running.

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 :
1. Faster scans – Partial TCP handshake is done. Only 2 packets exchanged , syn and syn+ack.
2. Incomplete connections so less detectable. But modern firewalls are smart enough to log all syn activites. So this technique is more or less detectable to same extent as TCP connect port scanning.

TCP Connect Port Scan looks like :

You -> Send Syn packet -> Host:port
Host -> send syn/ack packet -> You
You -> send ack packet -> Host

… and connection is established

TCP-Syn Port scan looks like

You -> send syn packet ->Host:port
Host -> send syn/ack or rst packet or nothing depending on the port status -> You

… stop and analyse the reply the host send :
If syn+ack reply then port open.
Closed/filtered otherwise.

Results are almost as accurate as that of TCP connection and the scan is much faster.

So the process is :

1. Send a Syn packet to a port A
2. Wait for a reply of Syn+Ack till timeout.
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.

Tools

We shall code a TCP-Syn Port scanner on Linux using sockets and posix thread api.
The tools we need are :
1. Linux system with gcc and posix libraries installed
2. Wireshark for analysing the packets (Optional : for better understanding).

Program Logic

1. Take a hostname to scan.
2. Start a sniffer thread shall sniff all incoming packets and pick up those which are from hostname and are syn+ack packets.
3. start sending syn packets to ports in a loop. This needs raw sockets
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.
5. Keep looping as long as you have nothing else to do.
6. Quit the program if someone is calling you.

Code

1 /*
2     TCP Syn port scanner code in C with Linux Sockets :)
3 */
4  
5 #include<stdio.h> //printf
6 #include<string.h> //memset
7 #include<stdlib.h> //for exit(0);
8 #include<sys/socket.h>
9 #include<errno.h> //For errno - the error number
10 #include<pthread.h>
11 #include<netdb.h> //hostend
12 #include<arpa/inet.h>
13 #include<netinet/tcp.h>   //Provides declarations for tcp header
14 #include<netinet/ip.h>    //Provides declarations for ip header
15  
16 void * receive_ack( void *ptr );
17 void process_packet(unsigned char* , int);
18 unsigned short csum(unsigned short * , int );
19 char * hostname_to_ip(char * );
20 int get_local_ip (char *);
21  
22 struct pseudo_header    //needed for checksum calculation
23 {
24     unsigned int source_address;
25     unsigned int dest_address;
26     unsigned char placeholder;
27     unsigned char protocol;
28     unsigned short tcp_length;
29      
30     struct tcphdr tcp;
31 };
32  
33 struct in_addr dest_ip;
34  
35 int main(int argc, char *argv[])
36 {
37     //Create a raw socket
38     int s = socket (AF_INET, SOCK_RAW , IPPROTO_TCP);
39     if(s < 0)
40     {
41         printf ("Error creating socket. Error number : %d . Error message : %s \n" errno ,strerror(errno));
42         exit(0);
43     }
44     else
45     {
46         printf("Socket created.\n");
47     }
48          
49     //Datagram to represent the packet
50     char datagram[4096];   
51      
52     //IP header
53     struct iphdr *iph = (struct iphdr *) datagram;
54      
55     //TCP header
56     struct tcphdr *tcph = (struct tcphdr *) (datagram + sizeof (struct ip));
57      
58     struct sockaddr_in  dest;
59     struct pseudo_header psh;
60      
61     char *target = argv[1];
62      
63     if(argc < 2)
64     {
65         printf("Please specify a hostname \n");
66         exit(1);
67     }
68      
69     if( inet_addr( target ) != -1)
70     {
71         dest_ip.s_addr = inet_addr( target );
72     }
73     else
74     {
75         char *ip = hostname_to_ip(target);
76         if(ip != NULL)
77         {
78             printf("%s resolved to %s \n" , target , ip);
79             //Convert domain name to IP
80             dest_ip.s_addr = inet_addr( hostname_to_ip(target) );
81         }
82         else
83         {
84             printf("Unable to resolve hostname : %s" , target);
85             exit(1);
86         }
87     }
88      
89     int source_port = 43591;
90     char source_ip[20];
91     get_local_ip( source_ip );
92      
93     printf("Local source IP is %s \n" , source_ip);
94      
95     memset (datagram, 0, 4096); /* zero out the buffer */
96      
97     //Fill in the IP Header
98     iph->ihl = 5;
99     iph->version = 4;
100     iph->tos = 0;
101     iph->tot_len = sizeof (struct ip) + sizeof (struct tcphdr);
102     iph->id = htons (54321); //Id of this packet
103     iph->frag_off = htons(16384);
104     iph->ttl = 64;
105     iph->protocol = IPPROTO_TCP;
106     iph->check = 0;      //Set to 0 before calculating checksum
107     iph->saddr = inet_addr ( source_ip );    //Spoof the source ip address
108     iph->daddr = dest_ip.s_addr;
109      
110     iph->check = csum ((unsigned short *) datagram, iph->tot_len >> 1);
111      
112     //TCP Header
113     tcph->source = htons ( source_port );
114     tcph->dest = htons (80);
115     tcph->seq = htonl(1105024978);
116     tcph->ack_seq = 0;
117     tcph->doff = sizeof(struct tcphdr) / 4;      //Size of tcp header
118     tcph->fin=0;
119     tcph->syn=1;
120     tcph->rst=0;
121     tcph->psh=0;
122     tcph->ack=0;
123     tcph->urg=0;
124     tcph->window = htons ( 14600 );  // maximum allowed window size
125     tcph->check = 0; //if you set a checksum to zero, your kernel's IP stack should fill in the correct checksum during transmission
126     tcph->urg_ptr = 0;
127      
128     //IP_HDRINCL to tell the kernel that headers are included in the packet
129     int one = 1;
130     const int *val = &one;
131      
132     if (setsockopt (s, IPPROTO_IP, IP_HDRINCL, val, sizeof (one)) < 0)
133     {
134         printf ("Error setting IP_HDRINCL. Error number : %d . Error message : %s \n" errnostrerror(errno));
135         exit(0);
136     }
137      
138     printf("Starting sniffer thread...\n");
139     char *message1 = "Thread 1";
140     int  iret1;
141     pthread_t sniffer_thread;
142  
143     if( pthread_create( &sniffer_thread , NULL ,  receive_ack , (void*) message1) < 0)
144     {
145         printf ("Could not create sniffer thread. Error number : %d . Error message : %s \n" ,errno strerror(errno));
146         exit(0);
147     }
148  
149     printf("Starting to send syn packets\n");
150      
151     int port;
152     dest.sin_family = AF_INET;
153     dest.sin_addr.s_addr = dest_ip.s_addr;
154     for(port = 1 ; port < 100 ; port++)
155     {
156         tcph->dest = htons ( port );
157         tcph->check = 0; // if you set a checksum to zero, your kernel's IP stack should fill in the correct checksum during transmission
158          
159         psh.source_address = inet_addr( source_ip );
160         psh.dest_address = dest.sin_addr.s_addr;
161         psh.placeholder = 0;
162         psh.protocol = IPPROTO_TCP;
163         psh.tcp_length = htons( sizeof(struct tcphdr) );
164          
165         memcpy(&psh.tcp , tcph , sizeof (struct tcphdr));
166          
167         tcph->check = csum( (unsigned short*) &psh , sizeof (struct pseudo_header));
168          
169         //Send the packet
170         if ( sendto (s, datagram , sizeof(struct iphdr) + sizeof(struct tcphdr) , 0 , (struct sockaddr *) &dest, sizeof (dest)) < 0)
171         {
172             printf ("Error sending syn packet. Error number : %d . Error message : %s \n" ,errno strerror(errno));
173             exit(0);
174         }
175     }
176      
177     pthread_join( sniffer_thread , NULL);
178     printf("%d" , iret1);
179      
180     return 0;
181 }
182  
183 /*
184     Method to sniff incoming packets and look for Ack replies
185 */
186 void * receive_ack( void *ptr )
187 {
188     //Start the sniffer thing
189     start_sniffer();
190 }
191  
192 int start_sniffer()
193 {
194     int sock_raw;
195      
196     int saddr_size , data_size;
197     struct sockaddr saddr;
198      
199     unsigned char *buffer = (unsigned char *)malloc(65536); //Its Big!
200      
201     printf("Sniffer initialising...\n");
202     fflush(stdout);
203      
204     //Create a raw socket that shall sniff
205     sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
206      
207     if(sock_raw < 0)
208     {
209         printf("Socket Error\n");
210         fflush(stdout);
211         return 1;
212     }
213      
214     saddr_size = sizeof saddr;
215      
216     while(1)
217     {
218         //Receive a packet
219         data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &saddr , &saddr_size);
220          
221         if(data_size <0 )
222         {
223             printf("Recvfrom error , failed to get packets\n");
224             fflush(stdout);
225             return 1;
226         }
227          
228         //Now process the packet
229         process_packet(buffer , data_size);
230     }
231      
232     close(sock_raw);
233     printf("Sniffer finished.");
234     fflush(stdout);
235     return 0;
236 }
237  
238 void process_packet(unsigned char* buffer, int size)
239 {
240     //Get the IP Header part of this packet
241     struct iphdr *iph = (struct iphdr*)buffer;
242     struct sockaddr_in source,dest;
243     unsigned short iphdrlen;
244      
245     if(iph->protocol == 6)
246     {
247         struct iphdr *iph = (struct iphdr *)buffer;
248         iphdrlen = iph->ihl*4;
249      
250         struct tcphdr *tcph=(struct tcphdr*)(buffer + iphdrlen);
251              
252         memset(&source, 0, sizeof(source));
253         source.sin_addr.s_addr = iph->saddr;
254      
255         memset(&dest, 0, sizeof(dest));
256         dest.sin_addr.s_addr = iph->daddr;
257          
258         if(tcph->syn == 1 && tcph->ack == 1 && source.sin_addr.s_addr == dest_ip.s_addr )
259         {
260             printf("Port %d open \n" , ntohs(tcph->source));
261             fflush(stdout);
262         }
263     }
264 }
265  
266 /*
267  Checksums - IP and TCP
268  */
269 unsigned short csum(unsigned short *ptr,int nbytes)
270 {
271     register long sum;
272     unsigned short oddbyte;
273     register short answer;
274  
275     sum=0;
276     while(nbytes>1) {
277         sum+=*ptr++;
278         nbytes-=2;
279     }
280     if(nbytes==1) {
281         oddbyte=0;
282         *((u_char*)&oddbyte)=*(u_char*)ptr;
283         sum+=oddbyte;
284     }
285  
286     sum = (sum>>16)+(sum & 0xffff);
287     sum = sum + (sum>>16);
288     answer=(short)~sum;
289      
290     return(answer);
291 }
292  
293 /*
294     Get ip from domain name
295  */
296 char* hostname_to_ip(char * hostname)
297 {
298     struct hostent *he;
299     struct in_addr **addr_list;
300     int i;
301          
302     if ( (he = gethostbyname( hostname ) ) == NULL)
303     {
304         // get the host info
305         herror("gethostbyname");
306         return NULL;
307     }
308  
309     addr_list = (struct in_addr **) he->h_addr_list;
310      
311     for(i = 0; addr_list[i] != NULL; i++)
312     {
313         //Return the first one;
314         return inet_ntoa(*addr_list[i]) ;
315     }
316      
317     return NULL;
318 }
319  
320 /*
321  Get source IP of system , like 192.168.0.6 or 192.168.1.2
322  */
323  
324 int get_local_ip ( char * buffer)
325 {
326     int sock = socket ( AF_INET, SOCK_DGRAM, 0);
327  
328     const char* kGoogleDnsIp = "8.8.8.8";
329     int dns_port = 53;
330  
331     struct sockaddr_in serv;
332  
333     memset( &serv, 0, sizeof(serv) );
334     serv.sin_family = AF_INET;
335     serv.sin_addr.s_addr = inet_addr(kGoogleDnsIp);
336     serv.sin_port = htons( dns_port );
337  
338     int err = connect( sock , (const struct sockaddr*) &serv , sizeof(serv) );
339  
340     struct sockaddr_in name;
341     socklen_t namelen = sizeof(name);
342     err = getsockname(sock, (struct sockaddr*) &name, &namelen);
343  
344     const char *p = inet_ntop(AF_INET, &name.sin_addr, buffer, 100);
345  
346     close(sock);
347 }

Compile and Run

1 $ gcc syn_portscan.c -lpthread -o syn_portscan

-lpthread option is needed to link the posix thread libraries.

Now Run

1 sudo ./syn_portscan www.google.com
2 Socket created.
3 www.google.com resolved to 74.125.235.16
4 Local source IP is 192.168.0.6
5 Starting sniffer thread...
6 Starting to send syn packets
7 Sniffer initialising...
8 Port 53 open
9 Port 80 open

Note :

1. For the program to run correctly the local ip and the hostname ip should be resolved correctly. Wireshark should also show the TCP Syn packets as “Good” and not bogus or something.

2. The get_local_ip method is used to find the local ip of the machine which is filled in the source ip of packets. For example : 192.168.1.2 if you are on a LAN or 172.x.x.x if you are directly connected to internet. The local source ip value will show this.

3. The hostname_to_ip function resolves a domain name to its ip address. It uses the gethostbyname method.