# Layer 4: Transport

The **Transport Layer** is the **fourth layer** of the OSI model and is critical for facilitating communication between **two devices** across a network. It ensures **reliable end-to-end communication** by performing several key tasks, such as:

* **Error detection**: Ensures that any errors in data transmission between the two devices are identified and corrected.
* **Flow control**: Manages the rate of data transmission between the two devices, ensuring that one device does not overwhelm the other with too much data at once.
* **Segmentation**: Breaks down large data streams into smaller units (segments) to make transmission more manageable, then reassembles them at the destination.

The transport layer also guarantees the **reliable and ordered delivery** of data, ensuring that packets arrive at the destination device in the correct sequence.

## TCP

**TCP (Transmission Control Protocol)** is a **connection-oriented protocol** that operates at the **Transport Layer** of the OSI model. It ensures **reliable and ordered delivery** of data between two devices over a network.

* **Connection-Oriented**: TCP establishes a connection between the two devices before data transmission begins, ensuring a stable communication link.
* **Reliable Delivery**: It guarantees that the data sent from one application on a device reaches the intended application on another device accurately and completely.
* **Ordered Delivery**: TCP ensures that data packets arrive in the correct sequence, even if they are transmitted out of order during network traversal.
* **Error Detection and Recovery**: TCP performs error detection, retransmitting any lost or corrupted data, ensuring the integrity of the communication.

TCP is widely used in applications like web browsing (HTTP/HTTPS) and email (SMTP), where reliable transmission is essential.

### TCP 3-Way Handshake

The **TCP 3-way handshake** is a process used to establish a **reliable connection** between two devices (client and server) before they begin data transmission. It ensures that both devices are ready to communicate and sets the parameters for the connection.

#### Steps in the 3-Way Handshake:

**SYN (Synchronize)**\
The **client** sends a **SYN** message to the server, indicating that it wants to establish a connection and synchronize sequence numbers.

**SYN-ACK (Synchronize-Acknowledgment)**\
The **server** responds with a **SYN-ACK** message, acknowledging the client's request and also sending its own synchronization message.

**ACK (Acknowledgment)**\
The **client** sends an **ACK** message, acknowledging the server's SYN-ACK. At this point, the connection is established, and data transmission can begin.

This handshake process ensures both devices agree on initial sequence numbers and are ready for reliable, ordered communication.

<figure><img src="https://244896893-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTy5fNwfsaV6DbqjnheTF%2Fuploads%2FFxLBpFAkNGn73EbCn4bx%2Fimage.png?alt=media&#x26;token=010b90c0-d14e-42d3-90cd-a50cbc5c0fae" alt=""><figcaption></figcaption></figure>

### TCP Headers

{% code overflow="wrap" %}

```
Source Port: 49152 # The port number of the sender
Destination Port: 80 # The port number of the reciever
Sequence Number: 1001 # A unique number assigned to each byte of data to ensure ordered delivery.
Acknowledgment Number: 2002 # Indicates the next sequence number the sender is expecting from the receiver.
Data Offset: 5 # Specifies the size of the TCP header (in 32-bit words).
Flags: SYN, ACK # Control flags used to manage the state of the connection.
Window Size: 8192 # Indicates how much data the receiver is willing to accept.
Checksum: 0x1a2b # Used for error-checking the header and data to ensure data integrity.
Urgent Pointer: 0 # Used when the URG flag is set, indicating urgent data in the packet.
Options: MSS = 1460 # Allows additional features such as maximum segment size (MSS) or timestamp.
```

{% endcode %}

### TCP Control Flags

**Establish a Connection: SYN (Set)**, **ACK (Clear)**, **FIN (Clear) -**\
The client initiates the connection by sending a **SYN** flag to the server, indicating a request to establish a connection.

**Establish a Connection (Response)**: **SYN (Set)**, **ACK (Set)**, **FIN (Clear) -**\
The server responds to the client's request by sending a **SYN-ACK** message, acknowledging the connection request and synchronizing sequence numbers.

**Terminating a Connection**: **SYN (Clear)**, **ACK (Set)**, **FIN (Set) -** \
Either the client or server can terminate the connection by sending a **FIN** flag along with an **ACK** to acknowledge receipt of the previous segment, signaling the intention to close the connection.

These flags are key to establishing and terminating reliable TCP connections.

### TCP Port Range

TCP uses **port numbers** to differentiate between various services or applications running on a device. These are **16-bit unsigned integers**, and the total port range spans from **0 to 65535**. The port numbers are divided into three ranges:

* **Well-Known Ports (0-1023)**:\
  These ports are reserved for **well-known services and protocols** and are managed by the **Internet Assigned Numbers Authority (IANA)**. Reserved for **common services** like HTTP (80), HTTPS (443), FTP (21), and SMTP (25).
* **Registered Ports (1024-49151)**:\
  These ports are registered for specific services or applications and are often assigned by **IANA** to **software vendors** or **developers** for their applications. Although not standardized, these ports are frequently used for well-known services. RDP (3389), MySQL (3306), Alternative HTTP (8080), MongoDB (27017)
* **Dynamic/Private Ports (49152-65535)**:\
  Primarily used for **temporary or client-side connections**. These ports are dynamically assigned by the operating system during a session.

The highest possible port number is **65535**.

### Some TCP Common Ports

<table data-header-hidden><thead><tr><th width="304">Port Number and Service Name</th><th>Details</th></tr></thead><tbody><tr><td><strong>20 (FTP Data)</strong></td><td>File Transfer Protocol (data transfer between client and server)</td></tr><tr><td><strong>21 (FTP Control)</strong></td><td>FTP control commands for establishing the connection</td></tr><tr><td><strong>22 (SSH)</strong></td><td>Secure Shell, used for secure remote login and command execution</td></tr><tr><td><strong>23 (Telnet)</strong></td><td>Unencrypted text communication, remote login protocol (insecure)</td></tr><tr><td><strong>25 (SMTP)</strong></td><td>Simple Mail Transfer Protocol, used for sending emails</td></tr><tr><td><strong>53 (DNS)</strong></td><td>Domain Name System, translates domain names into IP addresses</td></tr><tr><td><strong>80 (HTTP)</strong></td><td>HyperText Transfer Protocol, used for unencrypted web traffic</td></tr><tr><td><strong>443 (HTTPS)</strong></td><td>Secure version of HTTP, used for encrypted web traffic</td></tr><tr><td><strong>110 (POP3)</strong></td><td>Post Office Protocol version 3, used for retrieving emails from a server</td></tr><tr><td><strong>143 (IMAP)</strong></td><td>Internet Message Access Protocol, used for managing and retrieving emails</td></tr><tr><td><strong>67 (DHCP Server)</strong></td><td>Dynamic Host Configuration Protocol, assigns IP addresses from the server</td></tr><tr><td><strong>68 (DHCP Client)</strong></td><td>DHCP client port used to receive IP addresses assigned by a DHCP server</td></tr><tr><td><strong>161 (SNMP)</strong></td><td>Simple Network Management Protocol, used for monitoring and managing network devices</td></tr><tr><td><strong>162 (SNMP Trap)</strong></td><td>SNMP notifications sent from agents to the management server</td></tr><tr><td><strong>389 (LDAP)</strong></td><td>Lightweight Directory Access Protocol, used for directory services and authentication</td></tr><tr><td><strong>3389 (RDP)</strong></td><td>Remote Desktop Protocol, used for remote desktop access to Windows systems</td></tr><tr><td><strong>6660-6669 (IRC)</strong></td><td>Internet Relay Chat, used for real-time text communication</td></tr><tr><td><strong>27017 (MongoDB)</strong></td><td>Default port for MongoDB database server communication</td></tr><tr><td><strong>3306 (MySQL)</strong></td><td>Default port for MySQL database server communication</td></tr><tr><td><strong>8080 (Alternative HTTP)</strong></td><td>Alternative port for HTTP, often used for web development or proxy servers</td></tr><tr><td><strong>8443 (Alternative HTTPS)</strong></td><td>Alternative port for HTTPS, commonly used for secure web services</td></tr><tr><td><strong>4444 (Metasploit)</strong></td><td>Commonly used for Metasploit Framework exploits and payload handling</td></tr><tr><td><strong>445 (SMB)</strong></td><td>Server Message Block, used for sharing files, printers, and serial ports across a network</td></tr></tbody></table>

## UDP

UDP is a **connectionless** and lightweight transport layer protocol, focused on fast data transmission without guaranteeing **order** or **reliability** of delivery. Unlike TCP, UDP does not establish a connection before sending data, making it more **efficient** but less reliable.

#### Key Characteristics

* **Connectionless**: No need to establish or maintain a connection.
* **Unreliable**: No guarantees for data delivery, order, or error correction.
* **Stateless**: Each packet is independent of previous or future packets.

#### Functions

* **Real-time applications**: Commonly used in streaming, gaming, VoIP, where speed is more important than reliability.
* **Simple and efficient**: Suitable for applications that can tolerate some data loss and require low-latency communication.

*Note: **Ports 137 and 138 are used for NetBIOS Name Service (NBNS) and NetBIOS Datagram Service**, respectively. These are critical in older Windows networking environments and can be used to identify NetBIOS names on a network.*

## TCP vs UDP

<table data-header-hidden><thead><tr><th width="163">Feature</th><th>UDP</th><th>TCP</th></tr></thead><tbody><tr><td><strong>Connection</strong></td><td>Connectionless: No need to establish a connection</td><td>Connection-oriented: Requires connection establishment</td></tr><tr><td><strong>Reliability</strong></td><td>Unreliable: No guarantees of data delivery or ordering</td><td>Reliable: Ensures accurate, ordered delivery of data</td></tr><tr><td><strong>Header Size</strong></td><td>Smaller: 8 bytes</td><td>Larger: 20-60 bytes</td></tr><tr><td><strong>Applications</strong></td><td>Used for applications where speed is crucial, and some data loss is tolerable</td><td>Used for applications requiring reliable data transmission</td></tr><tr><td><strong>Examples</strong></td><td>Video streaming, VoIP, online gaming</td><td>Web browsing (HTTP/HTTPS), email (SMTP), file transfer (FTP)</td></tr></tbody></table>
