Tcp syn portscan code in C with Linux sockets

简介:

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.

相关实践学习
通过Ingress进行灰度发布
本场景您将运行一个简单的应用,部署一个新的应用用于新的发布,并通过Ingress能力实现灰度发布。
容器应用与集群管理
欢迎来到《容器应用与集群管理》课程,本课程是“云原生容器Clouder认证“系列中的第二阶段。课程将向您介绍与容器集群相关的概念和技术,这些概念和技术可以帮助您了解阿里云容器服务ACK/ACK Serverless的使用。同时,本课程也会向您介绍可以采取的工具、方法和可操作步骤,以帮助您了解如何基于容器服务ACK Serverless构建和管理企业级应用。 学习完本课程后,您将能够: 掌握容器集群、容器编排的基本概念 掌握Kubernetes的基础概念及核心思想 掌握阿里云容器服务ACK/ACK Serverless概念及使用方法 基于容器服务ACK Serverless搭建和管理企业级网站应用
目录
相关文章
|
2月前
|
网络协议 Linux 网络性能优化
Linux C/C++之TCP / UDP通信
这篇文章详细介绍了Linux下C/C++语言实现TCP和UDP通信的方法,包括网络基础、通信模型、编程示例以及TCP和UDP的优缺点比较。
38 0
Linux C/C++之TCP / UDP通信
|
2月前
|
网络协议 Linux 网络性能优化
Linux基础-socket详解、TCP/UDP
综上所述,Linux下的Socket编程是网络通信的重要组成部分,通过灵活运用TCP和UDP协议,开发者能够构建出满足不同需求的网络应用程序。掌握这些基础知识,是进行更复杂网络编程任务的基石。
127 1
|
4月前
|
移动开发 监控 网络协议
在Linux中,如何查看 http 的并发请求数与其 TCP 连接状态?
在Linux中,如何查看 http 的并发请求数与其 TCP 连接状态?
|
4月前
|
监控 网络协议 Linux
在Linux中,如何实时抓取并显示当前系统中tcp 80 端口的网络数据信息?
在Linux中,如何实时抓取并显示当前系统中tcp 80 端口的网络数据信息?
|
4月前
|
存储 监控 网络协议
在Linux中,如何使用 tcpdump 监听主机为 192.168.1.1,tcp 端⼝为 80 的数据,并将将输出结果保存输出到tcpdump.log?
在Linux中,如何使用 tcpdump 监听主机为 192.168.1.1,tcp 端⼝为 80 的数据,并将将输出结果保存输出到tcpdump.log?
|
4月前
|
缓存 负载均衡 网络协议
Linux的TCP连接数量与百万千万并发应对策略
【8月更文挑战第15天】在Linux系统中,关于TCP连接数量的一个常见误解是认为其最大不能超过65535个。这一数字实际上是TCP端口号的上限,而非TCP连接数的直接限制。实际上,Linux服务器能够处理的TCP连接数远远超过这一数字,关键在于理解TCP连接的标识方式、系统配置优化以及应用架构设计。
509 2
|
4月前
|
网络协议 安全 Linux
在Linux中,tcp三次握⼿的过程及原理?
在Linux中,tcp三次握⼿的过程及原理?
|
4月前
|
域名解析 网络协议 Linux
在Linux中,我们都知道,dns采用了tcp协议,又采用了udp协议,什么时候采用tcp协议?什么 时候采用udp协议?为什么要这么设计?
在Linux中,我们都知道,dns采用了tcp协议,又采用了udp协议,什么时候采用tcp协议?什么 时候采用udp协议?为什么要这么设计?
|
4月前
|
网络协议 Linux
在Linux中,如何查看 http 的并发请求数与其 TCP 连接状态?
在Linux中,如何查看 http 的并发请求数与其 TCP 连接状态?
|
4月前
|
机器学习/深度学习 网络协议 安全
在Linux中,如何追踪TCP连接和网络数据包,如使用tcpdump或Wireshark?
在Linux中,如何追踪TCP连接和网络数据包,如使用tcpdump或Wireshark?