# TTL (Time To Live)

### 📑 **Índice**

1. Fundamentos do TTL
2. Arquitetura e Funcionamento
3. TTL em Diferentes Protocolos
4. Valores Típicos e Fingerprinting
5. TTL em Pentesting
6. Ferramentas e Análise
7. Mitigações e Considerações

***

### 🔍 **Fundamentos do TTL**

#### **O que é TTL?**

O **TTL (Time To Live)** é um campo de 8 bits presente no cabeçalho do protocolo IP (IPv4). Apesar do nome sugerir uma unidade de tempo, ele funciona na verdade como um **contador de saltos** (*hops*). Cada roteador que processa o pacote decrementa este valor em 1. Quando o TTL chega a zero, o pacote é descartado e uma mensagem **ICMP Time Exceeded** é enviada de volta ao remetente.

#### **Para que serve?**

Sua função vital é **evitar o roteamento infinito**. Sem o TTL, se houvesse um loop de roteamento (erro de configuração onde o Roteador A envia para o B, que envia de volta para o A), o pacote circularia eternamente, consumindo largura de banda e processamento até derrubar a rede.

#### **Contexto Histórico**

```yaml
Evolução do TTL:
  1981: RFC 791 - Especificação original do IPv4
  1981: TTL implementado como campo de 8 bits
  1988: Uso em traceroute (Van Jacobson)
  1995: TTL importante para prevenção de loops
  1998: TTL Security (GTSM) proposto
  2000s: Uso em técnicas de fingerprinting
  2020: TTL ainda fundamental no roteamento IP
```

#### **Posição no Cabeçalho IP**

```python
#!/usr/bin/env python3
# ip_header_ttl.py

import struct
import socket

class IPHeader:
    """Estrutura do cabeçalho IPv4 com foco no TTL"""
    
    # Estrutura do cabeçalho IP (20 bytes mínimo)
    # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    # |Version|  IHL  |Type of Service|          Total Length         |
    # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    # |         Identification        |Flags|      Fragment Offset    |
    # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    # |  Time to Live |    Protocol    |         Header Checksum      |
    # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    # |                       Source Address                          |
    # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    # |                    Destination Address                        |
    # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    
    def __init__(self):
        self.version = 4
        self.ihl = 5  # 5 * 4 = 20 bytes
        self.tos = 0
        self.total_length = 0
        self.identification = 0
        self.flags = 0
        self.fragment_offset = 0
        self.ttl = 64  # Valor padrão
        self.protocol = 0
        self.checksum = 0
        self.src_ip = "0.0.0.0"
        self.dst_ip = "0.0.0.0"
    
    def build(self):
        """Construir cabeçalho IP"""
        version_ihl = (self.version << 4) | self.ihl
        flags_fragment = (self.flags << 13) | self.fragment_offset
        
        header = struct.pack('!BBHHHBBH',
            version_ihl,
            self.tos,
            self.total_length,
            self.identification,
            flags_fragment,
            self.ttl,
            self.protocol,
            self.checksum
        )
        
        header += socket.inet_aton(self.src_ip)
        header += socket.inet_aton(self.dst_ip)
        
        return header

# Exemplo
ip = IPHeader()
ip.ttl = 128
ip.src_ip = "192.168.1.1"
ip.dst_ip = "8.8.8.8"
print(f"📦 Cabeçalho IP com TTL={ip.ttl}: {ip.build().hex()[:40]}...")
```

***

### 🏗️ **Arquitetura e Funcionamento**

#### **Como o TTL Funciona**

```mermaid
sequenceDiagram
    participant C as Cliente (TTL=64)
    participant R1 as Roteador 1
    participant R2 as Roteador 2
    participant D as Destino

    C->>R1: Pacote TTL=64
    R1->>R1: TTL-- (agora 63)
    R1->>R2: Pacote TTL=63
    R2->>R2: TTL-- (agora 62)
    R2->>D: Pacote TTL=62
    
    Note over C,D: Rota normal - TTL > 0
    
    C->>R1: Pacote TTL=1
    R1->>R1: TTL-- (agora 0)
    R1->>C: ICMP Time Exceeded
    Note over C: TTL expirou - pacote descartado
```

#### **Mecanismo de Decremento**

```python
#!/usr/bin/env python3
# ttl_decrement.py

class TTLProcessor:
    """Processamento de TTL em roteadores"""
    
    def __init__(self, initial_ttl):
        self.ttl = initial_ttl
    
    def process_packet(self):
        """Processar pacote e decrementar TTL"""
        if self.ttl <= 1:
            print(f"❌ TTL={self.ttl} - Pacote descartado")
            self.send_time_exceeded()
            return False
        
        self.ttl -= 1
        print(f"✅ Pacote processado - TTL agora: {self.ttl}")
        return True
    
    def send_time_exceeded(self):
        """Enviar mensagem ICMP Time Exceeded"""
        print(f"📡 ICMP Time Exceeded enviado para origem")
        return True

# Simulação de roteamento
print("🔍 Simulação de processamento TTL")
print("=" * 40)

packet = TTLProcessor(3)
hops = 0

while packet.process_packet():
    hops += 1
    if hops > 10:
        break

print(f"\n📊 Saltos percorridos: {hops}")
```

#### **TTL e Fragmentação**

```python
# ttl_fragmentation.py

class TTLFragmentation:
    """Relação entre TTL e fragmentação IP"""
    
    @staticmethod
    def calculate_fragments(packet_size, mtu=1500, ttl=64):
        """Calcular fragmentos considerando TTL"""
        # Cabeçalho IP tem 20 bytes
        max_data = mtu - 20
        
        fragments = []
        offset = 0
        
        while offset < packet_size:
            fragment_ttl = ttl  # TTL é copiado para cada fragmento
            data_size = min(max_data, packet_size - offset)
            
            fragments.append({
                'offset': offset,
                'size': data_size,
                'ttl': fragment_ttl,
                'more_fragments': offset + data_size < packet_size
            })
            
            offset += data_size
        
        return fragments

# Exemplo
fragments = TTLFragmentation.calculate_fragments(4000, 1500, 64)
print("📦 Fragmentação de pacote de 4000 bytes:")
for i, frag in enumerate(fragments):
    print(f"  Fragmento {i+1}: offset={frag['offset']}, size={frag['size']}, TTL={frag['ttl']}")
```

***

### 📡 **TTL em Diferentes Protocolos**

#### **TTL vs Hop Limit (IPv6)**

| Característica       | IPv4 (TTL)         | IPv6 (Hop Limit)     |
| -------------------- | ------------------ | -------------------- |
| **Nome do Campo**    | Time To Live       | Hop Limit            |
| **Tamanho**          | 8 bits             | 8 bits               |
| **Função**           | Contador de saltos | Contador de saltos   |
| **Valor Padrão**     | 64, 128, 255       | 64, 128, 255         |
| **Decremento**       | Cada roteador      | Cada roteador        |
| **Mensagem de Erro** | ICMP Time Exceeded | ICMPv6 Time Exceeded |

#### **TTL em Protocolos de Roteamento**

| Protocolo       | TTL Típico           | Observação               |
| --------------- | -------------------- | ------------------------ |
| **ICMP (ping)** | 64, 128, 255         | Valor inicial do sistema |
| **TCP**         | 64, 128, 255         | Herdado do IP            |
| **UDP**         | 64, 128, 255         | Herdado do IP            |
| **BGP**         | 1 (eBGP), 255 (iBGP) | TTL security             |
| **OSPF**        | 1 (multicast)        | Pacotes não roteados     |
| **EIGRP**       | 1 (multicast)        | Pacotes não roteados     |

#### **Valores de TTL por Sistema Operacional**

```python
#!/usr/bin/env python3
# ttl_fingerprint.py

class TTLFingerprint:
    """Valores de TTL iniciais por sistema operacional"""
    
    OS_TTL_VALUES = {
        'Windows 10/11': 128,
        'Windows 8': 128,
        'Windows 7': 128,
        'Windows XP': 128,
        'Windows Server': 128,
        'Linux (kernel 2.6+)': 64,
        'Linux (kernel 3.x)': 64,
        'Linux (kernel 4.x)': 64,
        'macOS': 64,
        'FreeBSD': 64,
        'Solaris 10': 255,
        'Solaris 11': 255,
        'AIX': 255,
        'HP-UX': 255,
        'Cisco IOS': 255,
        'Juniper JunOS': 64,
        'Android': 64,
        'iOS': 64
    }
    
    @classmethod
    def guess_os_from_ttl(cls, observed_ttl, hops=0):
        """Estimar SO baseado no TTL observado"""
        initial_ttl = observed_ttl + hops
        
        candidates = []
        for os_name, ttl_value in cls.OS_TTL_VALUES.items():
            if abs(initial_ttl - ttl_value) <= 10:
                candidates.append(os_name)
        
        return candidates
    
    @classmethod
    def calculate_hops(cls, initial_ttl, observed_ttl):
        """Calcular número de saltos"""
        return initial_ttl - observed_ttl

# Exemplo
observed = 117
hops = TTLFingerprint.calculate_hops(128, observed)
os_guess = TTLFingerprint.guess_os_from_ttl(observed, hops)

print(f"📊 TTL observado: {observed}")
print(f"🔢 Saltos estimados: {hops}")
print(f"💻 SO possível: {', '.join(os_guess[:3])}")
```

***

### 🔍 **TTL em Pentesting**

#### **OS Fingerprinting via TTL**

```bash
# Exemplo: ping em diferentes sistemas
ping -c 1 192.168.1.10  # Windows - TTL 128
ping -c 1 192.168.1.20  # Linux - TTL 64
ping -c 1 192.168.1.30  # Router Cisco - TTL 255

# Análise de TTL em varreduras
nmap -O 192.168.1.0/24
```

#### **Traceroute e Mapeamento de Rede**

```python
#!/usr/bin/env python3
# traceroute_ttl.py

import socket
import struct
import time

class Traceroute:
    """Implementação de traceroute usando TTL"""
    
    def __init__(self, target, max_hops=30, timeout=2):
        self.target = target
        self.max_hops = max_hops
        self.timeout = timeout
        self.dest_ip = socket.gethostbyname(target)
    
    def create_icmp_packet(self, ttl, seq):
        """Criar pacote ICMP Echo Request com TTL específico"""
        # Em produção, usar socket raw
        # Esta é uma representação simplificada
        return {
            'ttl': ttl,
            'seq': seq,
            'type': 'ICMP Echo Request'
        }
    
    def send_probe(self, ttl, seq):
        """Enviar probe com TTL específico"""
        print(f"  Enviando probe TTL={ttl}")
        # Simular envio
        return True
    
    def trace(self):
        """Executar traceroute completo"""
        print(f"🔍 Traceroute para {self.target} ({self.dest_ip})")
        print(f"   Máximo de {self.max_hops} saltos\n")
        
        for ttl in range(1, self.max_hops + 1):
            start = time.time()
            success = self.send_probe(ttl, ttl)
            elapsed = (time.time() - start) * 1000
            
            if success:
                # Simular resposta
                print(f"  {ttl:2}  192.168.1.{ttl}  {elapsed:.2f}ms")
            else:
                print(f"  {ttl:2}  * * *  Timeout")
            
            if ttl == 5:  # Simular destino alcançado
                print(f"  {ttl:2}  {self.dest_ip}  {elapsed:.2f}ms ✨ DESTINO")
                break
        
        print("\n✅ Traceroute concluído")

# Exemplo
trace = Traceroute("8.8.8.8", max_hops=10)
trace.trace()
```

#### **Detecção de Firewall via TTL**

```python
#!/usr/bin/env python3
# ttl_firewall_detection.py

import socket
import struct

class TTLFirewallDetection:
    """Detecção de firewalls usando análise de TTL"""
    
    def __init__(self, target):
        self.target = target
    
    def analyze_ttl_anomalies(self):
        """Detectar anomalias de TTL indicando firewalls"""
        
        # Cenários de detecção
        scenarios = [
            {
                'name': 'TTL Inconsistente',
                'description': 'TTL varia muito entre pacotes consecutivos',
                'indicates': 'Possível firewall ou load balancer'
            },
            {
                'name': 'TTL Zero ou Muito Baixo',
                'description': 'TTL muito baixo para a distância estimada',
                'indicates': 'Firewall pode estar manipulando TTL'
            },
            {
                'name': 'TTL Constante',
                'description': 'TTL não muda mesmo após múltiplos saltos',
                'indicates': 'Firewall pode estar fixando TTL'
            }
        ]
        
        print("🔍 Análise de TTL para Detecção de Firewall")
        print("=" * 50)
        
        for scenario in scenarios:
            print(f"\n📋 {scenario['name']}")
            print(f"   {scenario['description']}")
            print(f"   ⚠️  {scenario['indicates']}")
        
        return True
```

#### **Técnicas de Evasão com TTL**

```python
#!/usr/bin/env python3
# ttl_evasion.py

class TTLEvasion:
    """Técnicas de evasão usando TTL"""
    
    @staticmethod
    def ttl_fragmentation(target):
        """Evitar detecção via fragmentação com TTL"""
        print("🔧 Técnica: Fragmentação com TTL")
        print("   Pacotes fragmentados podem ter TTL diferente")
        return True
    
    @staticmethod
    def ttl_spoofing(target):
        """Spoofing de TTL para evasão"""
        print("🔧 Técnica: Spoofing de TTL")
        print("   Modificar TTL para parecer de outro sistema")
        return True
    
    @staticmethod
    def ttl_scanning(target, ports):
        """Escaneamento com TTL baixo para evitar detecção"""
        print("🔧 Técnica: Escaneamento com TTL baixo")
        print("   TTL=1 limita escopo ao segmento local")
        return True
```

***

### 🛠️ **Ferramentas e Análise**

#### **Comandos para Análise de TTL**

```bash
# Ping com análise de TTL
ping -c 4 google.com
# Saída: ttl=117 (inicial 128 - 11 saltos)

# Traceroute padrão (usa TTL progressivo)
traceroute google.com

# Traceroute ICMP (TTL incremental)
traceroute -I google.com

# Traceroute TCP (TTL incremental)
traceroute -T -p 80 google.com

# Análise de TTL com hping3
hping3 --icmp --ttl 64 google.com

# Captura de pacotes com análise TTL
tcpdump -i eth0 -n -v 'ip[8] == 64'
```

#### **Script de Análise de TTL**

```python
#!/usr/bin/env python3
# ttl_analyzer.py

import subprocess
import re
import sys

class TTLAnalyzer:
    """Analisador de TTL para fingerprinting e diagnóstico"""
    
    def __init__(self, target):
        self.target = target
        self.results = {}
    
    def ping_analysis(self, count=4):
        """Analisar TTL de respostas ping"""
        print(f"[*] Analisando TTL para {self.target}")
        
        result = subprocess.run(
            ['ping', '-c', str(count), self.target],
            capture_output=True,
            text=True
        )
        
        ttls = []
        for line in result.stdout.split('\n'):
            match = re.search(r'ttl=(\d+)', line, re.IGNORECASE)
            if match:
                ttls.append(int(match.group(1)))
        
        if ttls:
            self.results['ttl'] = {
                'values': ttls,
                'min': min(ttls),
                'max': max(ttls),
                'avg': sum(ttls) / len(ttls)
            }
            
            print(f"  TTLs observados: {ttls}")
            print(f"  TTL médio: {self.results['ttl']['avg']:.1f}")
            
            return self.results['ttl']
        
        return None
    
    def guess_initial_ttl(self):
        """Estimar TTL inicial baseado nos valores observados"""
        if 'ttl' not in self.results:
            return None
        
        observed = self.results['ttl']['avg']
        
        # Possíveis valores iniciais
        initial_candidates = [64, 128, 255]
        distances = []
        
        for initial in initial_candidates:
            diff = abs(initial - observed)
            distances.append({'initial': initial, 'distance': diff})
        
        best = min(distances, key=lambda x: x['distance'])
        
        print(f"\n📊 Estimativa de TTL inicial: {best['initial']}")
        print(f"   Saltos estimados: {best['initial'] - observed:.0f}")
        
        return best
    
    def detect_os(self):
        """Detectar SO baseado no TTL"""
        if 'ttl' not in self.results:
            return None
        
        from ttl_fingerprint import TTLFingerprint
        observed = self.results['ttl']['avg']
        
        candidates = TTLFingerprint.guess_os_from_ttl(int(observed))
        
        print(f"\n💻 Possíveis sistemas operacionais:")
        for candidate in candidates[:3]:
            print(f"   - {candidate}")
        
        return candidates
    
    def run_analysis(self):
        """Executar análise completa"""
        print("=" * 50)
        print("🔍 ANÁLISE DE TTL")
        print("=" * 50)
        
        self.ping_analysis()
        self.guess_initial_ttl()
        self.detect_os()
        
        return self.results

# Uso
if __name__ == "__main__":
    target = sys.argv[1] if len(sys.argv) > 1 else "8.8.8.8"
    analyzer = TTLAnalyzer(target)
    analyzer.run_analysis()
```

#### **Wireshark Filters para TTL**

```bash
# Filtros de captura
ip.ttl == 64           # Pacotes com TTL 64
ip.ttl < 10            # TTL baixo (próximo da origem)
ip.ttl > 250           # TTL alto (origem próxima)

# Filtros de exibição
ip.ttl == 1            # Pacotes que expirarão no próximo salto
ip.ttl in {64 128 255} # Valores comuns de TTL inicial
```

***

### 🛡️ **Mitigações e Considerações**

#### **TTL Security (GTSM - Generalized TTL Security Mechanism)**

```yaml
GTSM (RFC 5082):
  - Protege contra ataques de spoofing
  - Verifica TTL de pacotes recebidos
  - Requer TTL=255 para eBGP multihop
  - Pacotes com TTL diferente são descartados

Configuração (Cisco IOS):
  router bgp 65000
   neighbor 192.168.1.2 ttl-security hops 1

Configuração (Linux):
  sysctl -w net.ipv4.conf.all.accept_redirects=0
  sysctl -w net.ipv4.conf.all.secure_redirects=0
```

#### **Considerações de Segurança**

```yaml
Riscos relacionados ao TTL:
  ✅ Permite OS fingerprinting
  ✅ Permite mapeamento de rede (traceroute)
  ✅ Pode ser usado para evasão de firewalls
  ✅ Pode indicar presença de load balancers

Mitigações:
  - Configurar firewalls para normalizar TTL
  - Implementar GTSM para protocolos críticos
  - Monitorar anomalias de TTL
  - Limitar informações de ICMP Time Exceeded
```

***

### 📋 **Checklists**

#### **Checklist para Administradores**

* [ ] Configurar TTL adequado para serviços críticos
* [ ] Implementar GTSM para protocolos de roteamento
* [ ] Monitorar anomalias de TTL nos logs
* [ ] Configurar firewalls para normalizar TTL quando necessário

#### **Checklist para Pentesters**

* [ ] Coletar TTL de respostas ICMP
* [ ] Estimar TTL inicial para fingerprinting
* [ ] Usar traceroute para mapear rede
* [ ] Testar técnicas de evasão com TTL
* [ ] Documentar sistemas identificados

***

### 📊 **Conclusão e Boas Práticas**

#### **Resumo Técnico**

```yaml
TTL (Time To Live):
  ✅ Campo de 8 bits no cabeçalho IP
  ✅ Funciona como contador de saltos
  ✅ Evita roteamento infinito
  ✅ Base para traceroute

Uso em pentesting:
  - OS Fingerprinting (valores iniciais)
  - Mapeamento de rede (traceroute)
  - Detecção de firewalls
  - Técnicas de evasão

Limitações:
  - Pode ser manipulado por firewalls
  - Roteadores podem ter comportamento diferente
  - Valores podem ser spoofados
```

#### **Valores de TTL por Sistema Operacional**

| Sistema Operacional | TTL Inicial | Observação           |
| ------------------- | ----------- | -------------------- |
| **Windows**         | 128         | 10, 8, 7, XP, Server |
| **Linux**           | 64          | Kernel 2.6, 3.x, 4.x |
| **macOS**           | 64          | Todas versões        |
| **FreeBSD**         | 64          | -                    |
| **Solaris**         | 255         | Versões 10 e 11      |
| **AIX**             | 255         | -                    |
| **Cisco IOS**       | 255         | Roteadores           |
| **Android**         | 64          | -                    |
| **iOS**             | 64          | iPhone/iPad          |


---

# 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/protocolos-de-roteamento/ttl-time-to-live.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.
