# TCP

## 🌐 **Visão Geral do TCP**

Protocolo de transporte **orientado a conexão** (Layer 4 OSI) que garante:\
✔ Entrega ordenada e sem erros\
✔ Controle de fluxo/congestionamento\
✔ Full-duplex communication

```mermaid
graph TD
    A[Aplicação] -->|Dados| B(TCP)
    B -->|Segmentos| C(IP)
```

## 🔧 **Anatomia do Segmento TCP**

![TCP Header](/files/24fb78dce8ab78853fdf375162cc2cf65e0d6d46) (Diagrama oficial RFC 793)

### 📋 **Tabela de Campos Críticos**

| Campo (Offset)      | Tamanho | Descrição                       | Pentest Relevance         |
| ------------------- | ------- | ------------------------------- | ------------------------- |
| Source Port (0)     | 16 bits | Porta origem (ephemeral/common) | Identificação de serviços |
| Dest Port (2)       | 16 bits | Porta destino (e.g., 80, 443)   | Target scanning           |
| Sequence Number (4) | 32 bits | Ordenação de bytes              | Session hijacking         |
| Ack Number (8)      | 32 bits | Próximo byte esperado           | MITM attacks              |
| Data Offset (12)    | 4 bits  | Tamanho do header (×4 bytes)    | Packet crafting           |
| Flags (13)          | 6 bits  | Controle de conexão             | Port scanning (SYN/FIN)   |
| Window Size (14)    | 16 bits | Espaço no buffer do receptor    | DoS detection             |
| Checksum (16)       | 16 bits | Integridade do segmento         | Packet injection          |

### 🚩 **Flags TCP (Bits 13-14)**

| Flag | Bit Pos | Função                          | Uso em Pentests          |
| ---- | ------- | ------------------------------- | ------------------------ |
| URG  | 5       | Dados urgentes                  | Raros em ataques         |
| ACK  | 4       | Confirma recebimento            | Presente em 99% dos pkts |
| PSH  | 3       | Push imediato para aplicação    | Bypass buffers           |
| RST  | 2       | Reset imediato da conexão       | Detecta firewalls        |
| SYN  | 1       | Sincroniza números de sequência | SYN scans                |
| FIN  | 0       | Finalização graciosa            | FIN scans                |

## 🔄 **Ciclo de Vida da Conexão (3-Way Handshake)**

```mermaid
sequenceDiagram
    Cliente->>Servidor: SYN (Seq=J)
    Servidor->>Cliente: SYN-ACK (Seq=K, Ack=J+1)
    Cliente->>Servidor: ACK (Seq=J+1, Ack=K+1)
```

## ⚠️ **Vulnerabilidades e Explorações**

### 1. **SYN Flood Attack**

```python
from scapy.all import *
send(IP(dst="target")/TCP(sport=RandShort(), dport=80, flags="S"), loop=1)
```

**Mitigação**: SYN cookies, limite de conexões

### 2. **TCP Session Hijacking**

* Predição de números de sequência
* Injeção de comandos via RST hijacking

### 3. **Port Scanning Techniques**

| Tipo      | Flags Usadas  | Detecção  |
| --------- | ------------- | --------- |
| SYN Scan  | SYN → SYN/ACK | Stealth   |
| FIN Scan  | FIN → RST     | Evade IDS |
| XMAS Scan | FIN/URG/PSH   | Obscuro   |

## 🛠️ **Ferramentas Essenciais**

```bash
# Análise com tcpdump
tcpdump -ni eth0 'tcp[tcpflags] & (tcp-syn|tcp-ack) != 0'

# Crafting manual (hping3)
hping3 -S -p 80 -c 3 target.com

# Teste de resistência
nmap -sS -Pn -T4 --max-retries 1 target.com
```

## 📚 **Referências Avançadas**

* RFC 793 (Especificação original)
* RFC 6528 (Defesa contra reset spoofing)
* MITRE ATT\&CK: T1046 (Network Service Scanning)

> 🔍 **Dica para Pentesters**: Monitore padrões de Window Size para identificar sistemas operacionais! Valores típicos:
>
> * Linux: 5840 bytes
> * Windows: 64240 bytes
> * Cisco IOS: 4128 bytes


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/conceitos/redes/tcp.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
