Skip to main content

Attacking Network Device PART - 5

Exploits using ICMP protocol

Internet Control Message Protocol (shorthand, ICMP) is a part of the Internet Protocol used by network devices to send error messages to other connected hosts; for example, to indicate that a requested service is not available or a router could not be reached. But many times, this protocol is abused in transferring malicious data packets. This article discusses the vulnerabilities and security loopholes associated with such types of data transfers and potential options to prevent these security attacks. 

What you will learn... 

● Understanding ICMP and its role in networking 

● ICMP as a potential host for malicious activities

● Potential Attacks with ICMP 

● Security measures 

What you should know? 

● Basic knowledge of Computer networks and protocols like IP and ICMP 

● Basic knowledge of network infrastructure. 

● Basic knowledge of packet programming.

Understanding ICMP and its role in networking

Overview

  IP is the principle protocol used for delivery of packets across network boundaries (source:wikipedia). The Internet Protocol (IP) is based on a connectionless mode of transmission and hence is not designed to be absolutely reliable. Since the network infrastructure is unreliable, it is important to notify the sender with appropriate messages in case something goes wrong like packet loss, data corruption or out-ofdelivery order. This is where Internet Control Message Protocol steps in. It is the mechanism used to give feedback on network problems that have blocked or intercepted packet delivery. Higher-level protocols, like TCP, are able to realize that packets aren't getting through, but ICMP provides a method for discovering more specific problems, such as "TTL exceeded" or "need more fragments." ICMP differs from transport protocols such as TCP and UDP in that it is not typically used to exchange data between systems (although ICMP has been used for data transfer for quite some time now via ICMP Tunnelling).

 The point to note is that the purpose of these control messages is to provide feedback about problems in the communication environment, not to make IP reliable. There is still no guarantee that a packet will be delivered or a control message will be returned. But the majority of ICMP message types are required for proper operation of IP, TCP and other protocols, ping and traceroute being one of the prominent utilities using ICMP.

ICMP Packet Structure and Details 

   ICMP uses the basic support of IP like a higher level protocol; however, ICMP is actually an integral part of IP and must be implemented by every IP module. An ICMP packet is therefore an IP packet with ICMP in the IP data portion. Every ICMP message also contains the entire IP header from the original message so the end system will know which packet actually failed. The first eight bytes of the original IP data will be included as well, and this is normally the TCP or UDP header.

  Below is a figure of IP packet format. The ICMP module can be seen in the shaded portion. Some of the important fields are mentioned below.



● IP Header: Protocol set to 1 (for ICMP) 

● Type (8 bits): For example 0- ping reply, 3 - Destination Unreachable, 8- ping request 11- Time Exceeded 

● Code (8 bits): Subtype of message

● Checksum (16 bits): It is the 16-bit one's complement of the one's complement sum of the ICMP message starting with the Type field. 

● Data load (Can be an arbitrary length, left to implementation detail. However, must be less than the Maximum Transmission Unit of the network or risk being fragmented). 

  The address of the source in an echo message will be the destination of the echo reply message. To form an echo reply message, the source and destination addresses are simply reversed, the type code changed to 0, and the checksum recomputed. The data received in the echo message must be returned in the echo reply message.

 The identifier and sequence number may be used by the echo sender to aid in matching the replies with the echo requests. For example, the identifier can be used to identify a session (similar to ports in TCP and UDP), and the sequence number might be incremented on each echo request sent. Code 0 may be received from a gateway or a host.

 Infrequent problems, such as the IP checksum being wrong, will not be reported by ICMP. The premise is that TCP or other reliable protocols can deal with this type of packet corruption else do not care about such small packet losses.

 The ICMP messages typically report errors encountered in the processing of packets. To avoid the infinite regress of messages on messages, no ICMP messages are sent about ICMP messages. If ICMP messages are sent in response to other ICMP messages, they quickly multiply and create a storm of ICMP packets. ICMP messages cannot be sent in response to a broadcast or multicast addresses either, to prevent broadcast storms. Similarly, ICMP messages are only sent about errors in handling fragment zero of fragmented packets (Fragment zero has the fragment offset equal zero). [Source:RFC 792]

 ICMP as a potential host for malicious activities

  ICMP Vulnerability

  ICMP is generally not considered a threat, at least not by the majority of network administrators. It is very common to add security mechanisms (Intrusion detection and prevention systems, etc) to a corporate network, but in the end all types of ICMP packets, with all payload sizes etc, pass freely at least from within the private network to the outside world. This technique is used to send sensitive data outside a private network without relying on SMTP, HTTP or other upper layer protocols that are commonly monitored and logged. 

  The vulnerability in ICMP exists because RFC 792, which is IETF's rules governing ICMP packets, allows for an arbitrary data length for any type 0 (echo reply) or 8 (echo message) ICMP packets.

 Firewalls, depending on the services required by their internal networks, totally block or partially filter Internet packets. IP Filter, for example uses stateful packet filtering. The state engine not only inspects the presence of ACK flags in TCP packets but also includes sequence numbers and window sizes in its decision to block or to allow packets. However, IP Filter does not check the content of ICMP packets and hence fails to prevent covert channels that can arise due to misuse of the payload of ICMP packets. Therefore, although TCP and UDP continue to be a subject for studies in vulnerabilities, ICMP also provides several means for stealth traffic

 Past Security Threats and Attacks 

  In early February 2000, a distributed denial of service attack was launched against many popular Internet sites. It is reported that almost all of the tools used on the distributed denial of service (DDOS) attacks these internet sites, have used ICMP for covert communications between the DDOS clients and the attacker’s handler program. Since ICMP tunneling is very simple to deploy and can cause a significant amount of damage, it has been classified as a high risk security threat by Internet Security Services. Some of the most widely known distributed denial of service attack tools like Tribe Flood Net2K and Stacheldraht rely on ICMP tunneling to establish communication channels between the compromised machines and the hacker’s machine.

 Potential Attacks through ICMP 

 ICMP is supposed to be a relatively simple protocol, but it can be altered to act as a medium for evil purposes. It is therefore important to understand how this protocol can be used for malicious purposes. This understanding further enables us to counter such attacks and be prepared for them.

ICMP Tunneling:

  An ICMP tunnel (also known as ICMPTX) establishes a covert connection between two remote computers (a client and proxy), using ICMP echo requests and reply packets. An example of this technique is tunneling complete TCP traffic over ping requests and replies. ICMP tunneling works by injecting arbitrary data into an echo packet sent to a remote computer. The remote computer replies in the same manner, injecting an answer into another ICMP packet and sending it back. The client performs all communication using ICMP echo request packets, while the proxy uses echo reply packets.

 ICMP tunneling can be used to bypass firewall rules through obfuscation of the actual traffic. Depending on the implementation of the ICMP tunneling software, this type of connection can also be categorized as an encrypted communication channel between two computers. Without proper deep packet inspection or log review, network administrators will not be able to detect this type of traffic through their network.

 The following code snippet gives an example of a chat application developed using ICMP tunnelling :

 1.Impacket: Install the latest stable release from here : https://pypi.python.org/pypi/impacket 

 2. Socket : This python library is used to make a SOCK_RAW for receiving and sending data packets. Using SOCK_RAW, the application connects directly to the IP layer and does not use either the TCP or UDP transport. 

3. Threading : We made two threading classes : Reader and Writer. Instantiate one thread from each class so that one thread listens to the incoming ICMP packets and the other replies to those packets. 

 4. Chat Protocol : The program will send the message in a ICMP ECHO_REQUEST to the other computer.

$ sudo python chat_application.py (enter your IP address and destination IP address and start chatting)






Here is the snapshot of the ICMP packet as captured by wireshark.



Trojan Horse 

 Covert Channels are methods in which an attacker can send data in a protocol that is undetectable. Covert Channels rely on techniques called tunneling, which allows one protocol to be carried over another protocol. ICMP tunneling is a method of using ICMP echo-request and echo-reply as a carrier of any payload an attacker may wish to use, in an attempt to stealthily access, or control a compromised system. Since such channels are hidden, covert channels are generally difficult to detect using a system's normal or unmodified security policy. This makes it an attractive mode of transmission for a Trojan.

  Although the payload of ICMP packet often contains timing information of packet delivery, there is no check by any device about the content of the data. So, as it turns out, this amount of data can also be arbitrary in content as well. We can construct Trojan packets which are masqueraded as common ICMP_ECHO traffic and can be used as a backdoor into a system by providing a covert method of getting information and control on a target machine. Generally, Trojan softwares come injected into a reliable looking software archive intended to gain the system password. When a user downloads this software, the software demands to install it using `sudo` powers. At this time the trojan gets entry into the computer and starts executing itself. The software restarts itself even after reboot, so unless someone is looking for it specifically, it is very difficult to find it. This trojan can be used to execute commands remotely on the victim’s machine which sends the output to the hacker’s computer. Since the entire communication happens through ICMP packets, which are normally used for network and host detection, such messages are often ignored.

 As shown earlier, trojan packets can be programmed through ICMP tunneling and can be used to transfer files across systems or execute system commands remotely (some commands may need a sudo access, but that information can be easily compromised if the user sufficiently trusts the wrapping software and enters the credentials). A rough example of the program that can execute the command on the victim’s machine can be made out of the chat program we discussed earlier by changing the process Message function on the victim’s computer application to act something like the following: 



  Distributed Denial Of Service attacks 

  Following is a simple ICMP based DDOS attack program. It exposes the vulnerability of a user even if his/her machine has not been compromised. It sends ICMP packets to the victim's machine containing random data to which the victim's computer is forced to send replies. The packets may have a spoofed source address (and cloned MAC address if possible) so that the hacker source does not get bombarded with the echo replies and it makes it difficult to trace back the origin of the attack.

import random, string 

def DDOS(sock, destination_ip):


while True: 

 try: 

 randomString = ''.join(random.choice(string.lowercase) for i in range(34)) 

 packet = constructPacket(8, randomString, '', destination_ip) 

sock.sendto(packet, (dest, 0)) 

 except : 

   pass

   In the presence of requests with a fake source address ("spoofing"), hackers can make a target machine send relatively large packets to another host. Note that an ICMP response is not substantially larger than the corresponding request, so there is no multiplier effect there: it will not give extra power to the attacker in the context of a denial of service attack. It might protect the attacker against identification, though.


 The "smurf" attack, named after its exploit program, is a similar network-level attack against hosts. A perpetrator sends a large amount of ICMP echo (ping) traffic at IP broadcast addresses with the spoofed source address of a victim. On a multiaccess broadcast network, there could potentially be hundreds of machines to reply to each packet. Currently, the providers/machines most commonly hit are IRC servers and their providers. The spoofed address system gets hit by a large amount of traffic that the intermediary (broadcast) devices generate.

Security Measures: 

Blocking ICMP: 

It is common practice to disable or block ICMP requests altogether on publicly visible servers. Google responds to Ping requests while Microsoft does not. Although this is effective, it may not be realistic for a production or real-world environment.

 Take the case of PATH MTU. Path MTU (PMTU) discovery is the mechanism that protocols use to discover the largest supported MTU (maximum transmit unit) along the path, in hopes of avoiding fragmentation. The largest possible size is determined by the sender beginning with the MTU size of its local interface, and then simply shipping the data with the DF (don't fragment) bit set in the IP header. Everything will work as expected, or the sender will get back a type 3 ICMP error, with the code for "Fragmentation Required but the DF Flag is Set." When this happens, the sender knows that it must reduce the size of the data it is sending. If an error doesn't return, it assumes that the MTU is fine.

 The main problem with PMTU discovery is that when people block ICMP, the error cannot reach the sending host. Certain TCP implementations automatically retransmit with a smaller segment size if they detect a packet acknowledgement failure, but it is not common.
 
 Understanding ICMP can be used for making firewall policy decisions and understanding routing issues. There are applications and other protocols relying on ICMP to work properly. The impact of blocking ICMP completely should be assessed prior to taking such action. Instead of blocking ICMP all together, it is wiser to allow type 3, type 4 code (Dest unreachable, Don’t fragment) and specifying explicit network areas from where you can get/receive or blocking the addresses from where you do not want any ping request and reply messages.

 Firewall Rules 

  Disable part of the ICMP traffic allowed by a firewall. For example, disable incoming echo requests, while allowing outgoing echo requests. If naively implemented, policies like this will still allow covert communication, limiting only which host needs to start a communication. In addition, outgoing ICMP packets could be used to establish an unidirectional channel to send compromised information. It is important to understanding how operating systems respond to ICMP Messages. This will allow us to determine what type of ICMP Messages should only be allowed in and out of the network. With appropriate configuration of the packet filtering device to block unnecessary ICMP Messages, potential threats resulting from ICMP Messages can be reduced. This, however, should be done wisely and selectively.

  Hence the first stage in network security against these type of attacks is to build up sophisticated firewall rules, which allow only trustworthy nodes into your network. 

 Some examples of firewall rules which can be implemented are:
 

1. Drops all incoming echo-request packets. 

                         iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

2. Disable all the outgoing ICMP echo request packets from a source IP to destination IP. 

             iptables -A OUTPUT -p icmp --icmp-type 8 -s $SOURCE_IP -d $DEST_IP -j DROP

3. Drop all incoming echo reply packets.

         iptables -A INPUT -p icmp --icmp-type 0 -j DROP

4. Drop all outgoing echo reply packets.

        iptables -A OUTPUT -p icmp --icmp-type echo-reply -j DROP 

   However, setting up such rules leads to a large number of problems for those who want to work in an open network or need the ICMP messages over the entire network for proper functioning.

General ways to mitigate attacks 

  ● Limit the size of ICMP packets. Large ICMP packets can be seen as suspicious by an IDS system that could inspect the ICMP packet and raise an alarm. However, since there are legitimate uses for large ICMP packets it is difficult to determine if a large ICMP packet is malicious. For example, large echo request packets are used to check if a network is able to carry large packets. Diff erentiating legal from illegal large packets is even more difficult if covert communication is encrypted.

 But allowing only fixed size ICMP packets would not avoid ICMP Tunnel since the data can be broken into smaller chunks, fixed ones, and reassembled by the Receiver. We can easily change the size of the data, even writing fixed size data, by adding one layer to control sequence numbering, offset, etc.

  ● Preserve the state of the ICMP packet to check for covert channels. This can be done by constructing a daemon that will construct a new echo request with a new sequence number, new time to live, and a new payload (with new checksum). When the reply is received it is ensured that the data is the same as what had been sent, and the sequence number and responder’s IP address are valid and as expected. After a successful check, the echo reply can be transmitted back to the original client.

Although the state preserving technique can easily prevent ICMP tunneling, it is a computing intensive process.

● Another way to remove ICMP tunneling could be to simply truncate the data field of ICMP. However, truncation of the data field will require amendments in the RFC. Scanning and erasing of the ICMP data field is compliant with RFC and prevents ICMP tunneling irrespective of the type of firewall used.

  ● Simply marking out unused and potentially dangerous portions of ICMP packets is a straightforward task and requires little overhead on a modest system. Simple string scans are also not costly and can be done to test for unencrypted covert communication. This is highly recommended for the end hosts where it off ers minimal overhead on the system. For routers it can be expensive, where a simple disable on ICMP Echo Reply can work. Encrypted channels are more difficult to scan.

ICMPSec 

  The idea of ICMPSec is inspired from IPSec used to secure IP packet transfer in IPv6. Internet Protocol version 6 (IPv6) is the latest revision of the Internet Protocol (IP). IPv6 was developed by the Internet Engineering Task Force (IETF) to deal with the long-anticipated problem of IPv4 address exhaustion. IPv4 and IPv6 are not interoperable. ICMPv6 forms a critical part in functioning of the protocol and is majorly used in error detection, Stateless address autoconfiguration (SLAAC) and packet fragmentation. IPSec uses Security Associations (SA) along with Authentication Headers (AH) and Encapsulation Security Protocol(ESP) to protect IP messages on an end-to end basis. An ICMP message not protected by AH or ESP is unauthenticated and its processing and/or forwarding may result in denial of service.

  But it is expected that many routers and hosts will not implement IPsec for transit traffic owing to its complexity and thus strict adherence to IPSec would cause many ICMP messages to be discarded. Also, when transmitting small packets, the encryption process of IPSec generates a large overhead. This diminishes the performance of the network.

 To minimise the complexities involved in building up an IPSec module in kernel, we propose to build an ICMP-security application (ICMPSec) which will try to address the vulnerability concerns of ICMP protocol. It is a module which will capture ICMP packets at the kernel level and scan and filter them accordingly for intrusion detection and intrusion prevention.

 The program that we aim to develop to counter these security vulnerabilities will include some of the strategies already discussed to prevent ICMP data leakage: 

     ● IDENTIFY PACKET RATIO: Large number of ICMP packets from a same single source can be a sign of a DDOS attack. The program will identify such packets and only allow packets which do not exceed a certain number of packets vs time ratio (keeping the source fixed). But DDOS attacks generally originate from multiple sources; to tackle that we can generalise the program to not exceed the ratio irrespective of the source. 

   ● PATTERN DETECTION OF DATA FIELD: The number of bytes in the data field must be limited to a number not greater than a fixed number (for example 56 bytes). This will prevent large amounts of data from going out in a single packet (unless hacker programs support fragmentation, in which case stricter measures are required). Major amounts of data leak can be prevented by proper scanning of the data field. Keywords like “sudo”, “ls”, and “system” commands can be detected with a proper filter in place. Although the data could be encrypted and hacker programs might have sophisticated encryption decryption techniques. ● PROPER SEQUENCING of PING PACKETS: Multiple echo replies to a single echo request packet must be stopped. Also all packets must follow a proper sequencing protocol so that packets from unreliable source programs (with random sequence numbers) at the application level are not sent.

   ● ENCRYPTION OF DATA FIELD: Generally the data in ping packets is not useful. Most of the information could be inferred from the code number as well. The payload of ICMP packet is often timing information, which can be dealt as a special case. Otherwise all the packets going out can have their data field encrypted with the key the host chooses, so that even if the hacker receives any of the packets, it does not make sense to him unless he has to key too.

 The module is based on a self-learning algorithm which identifies the average number of incoming packets and outgoing packets and the ratio between them. The algorithm works well for implementation purposes with simple test data, but is naive and can easily be generalised to larger test data packets and complex algorithms involving clustering and the Markov module.

 Even with proper filtering of ICMP traffic, an Intrusion Detection System must be deployed further to monitor the kind of ICMP activities and analyse any anomalies in the received data.

Basic outline for the LEARNING MODULE ALGORITHM (Pseudo Code): 

GENERAL_SCAN() : 

Set T; 

Set MAX_TOT; # max number of packets allowed in T seconds 

Set BUFFER_PACKETS; # For allowing more or less number of packets  

Set OVERFLOW; # max times MAX_TOT can be increased 

Get MAX_RECV; # number of icmp packets received in T seconds 

Set times_increase = 0;

if MAX_RECV < MAX_TOT: 

    MAX_TOT = MAX_RECV - BUFFER_PACKETS 

else 
 
    MAX_TOT = MAX_RECV + BUFFER_PACKETS; # Increasing MAX_TOT

 times_increase++ 

 if (times_increase > OVERFLOW)

     FILTER_THE_PACKETS()


FILTER_THE_PACKETS() 

        Set the ip_address in an array where MAX_RECV > MAX_TOTAL and number of times it goes like that in intervals of T seconds. 

   If happens for more than X times:

       PATTERN_DETECTION() 

   If happens for more than Y times:  

      Block the ip address

  PATTERN DETECTION() 

   Check data packet size <= 56 bytes 

    Make the data payload null if possible. 

    Or encrypt the payload and send to application layer.

    Else look if the payload field has commands like ‘rm’ or ‘ls’. 

   Check the sequence numbers of all incoming packets - generally they do not follow the incremental pattern in case of an attack.

Popular posts from this blog

Haking On Demand_WireShark - Part 5

Detect/Analyze Scanning Traffic Using Wireshark “Wireshark”, the world’s most popular Network Protocol Analyzer is a multipurpose tool. It can be used as a Packet Sniffer, Network Analyser, Protocol Analyser & Forensic tool. Through this article my focus is on how to use Wireshark to detect/analyze any scanning & suspect traffic. Let’s start with Scanning first. As a thief studies surroundings before stealing something from a target, similarly attackers or hackers also perform foot printing and scanning before the actual attack. In this phase, they want to collect all possible information about the target so that they can plan their attack accordingly. If we talk about scanning here they want to collect details like: • Which IP addresses are in use? • Which port/services are active on those IPs? • Which platform (Operating System) is in use? • What are the vulnerabilities & other similar kinds of information. • Now moving to some popular scan methods and ho

Bypassing Web Application Firewall Part - 2

WAF Bypassing with SQL Injection HTTP Parameter Pollution & Encoding Techniques HTTP Parameter Pollution is an attack where we have the ability to override or add HTTP GET/POST parameters by injecting string delimiters. HPP can be distinguished in two categories, client-side and server-side, and the exploitation of HPP can result in the following outcomes:  •Override existing hardcoded HTTP parameters  •Modify the application behaviors   •Access and potentially exploit uncontrollable variables  • Bypass input validation checkpoints and WAF rules HTTP Parameter Pollution – HPP   WAFs, which is the topic of interest, many times perform query string parsing before applying the filters to this string. This may result in the execution of a payload that an HTTP request can carry. Some WAFs analyze only one parameter from the string of the request, most of the times the first or the last, which may result in a bypass of the WAF filters, and execution of the payload in the server.  Let’s e

Bypassing Web Application Firewall Part - 4

Securing WAF and Conclusion DOM Based XSS DOM based XSS is another type of XSS that is also used widely, and we didn’t discuss it in module 3. The DOM, or Document Object Model, is the structural format used to represent documents in a browser. The DOM enables dynamic scripts such as JavaScript to reference components of the document such as a form field or a session cookie, and it is also a security feature that limits scripts on different domains from obtaining cookies for other domains. Now, the XSS attacks based on this is when the payload that we inject is executed as a result of modifying the DOM environment in the victim’s browser, so that the code runs in an unexpected way. By this we mean that in contrast with the other two attacks, here the page that the victim sees does not change, but the injected code is executed differently because of the modifications that have been done in the DOM environment, that we said earlier. In the other XSS attacks, we saw the injected code was