Firedog-dettagli-tecnici

Firedog – Advanced Firewall & Threat Detection insostituibile

Descrizione Prodotto

Firedog è un sistema di firewall avanzato host-based per Linux che ridefinisce la protezione perimetrale attraverso l’unione di policy restrittive, protezioni anti-attacco multi-layer e analisi intelligente del traffico bloccato. A differenza dei firewall tradizionali che si limitano a permettere/bloccare, Firedog implementa un approccio “defense-in-depth” con machine learning-based threat scoring che identifica pattern di attacco in tempo reale.

Costruito su iptables/nftables con policy DROP di default, Firedog protegge automaticamente contro le minacce più comuni: SYN flood, port scanning, SSH brute force, ICMP flood, packet spoofing e attacchi a livello applicativo. Ogni pacchetto bloccato viene loggato in formato PCAP per analisi forensi post-incident, mentre il threat intelligence engine assegna un risk score 0-100 a ogni IP sorgente per identificare attaccanti persistenti.

La gestione attraverso CLI Python user-friendly nasconde la complessità di iptables, permettendo anche a sysadmin non-esperti di configurare firewall enterprise-grade in minuti. Con integrazione nativa MicroSIEM e Sentinel Core (via Integration Pack), Firedog diventa il braccio armato di una strategia di difesa coordinata e automatizzata. È possibile anche usare la web-interface scritta in react e installare su macchine target remote e gestirne le feature per tutte le macchine debian in produzione. È possibile contribuire o scaricare firedog e firedog web-console su github a questo indirizzo.


Caratteristiche Principali

🛡️ Firewall Multi-Layer con Policy Restrittive

Policy DROP di Default:

La filosofia “deny-all, permit-by-exception” garantisce massima sicurezza:

bash

# Default policy (all chains)
iptables -P INPUT DROP      # Block all incoming traffic
iptables -P OUTPUT DROP     # Block all outgoing traffic  
iptables -P FORWARD DROP    # Block all forwarded traffic

# Solo traffico esplicitamente permesso passa

Perché DROP invece di REJECT:

  • DROP: Pacchetto silenziosamente scartato (attacker non sa se host esiste)
  • REJECT: Risponde con ICMP “port unreachable” (information disclosure)

Best practice security: DROP è preferibile per sistemi esposti Internet.

Connection Tracking (Stateful Firewall):

bash

# Allow established connections (responses to outgoing requests)
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow loopback (localhost communication)
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
```

**Connection states:**
- **NEW**: Primo pacchetto di nuova connessione
- **ESTABLISHED**: Connessione già stabilita
- **RELATED**: Connessione correlata (e.g. FTP data channel dopo control channel)
- **INVALID**: Pacchetto malformato o non tracciabile

**Chain Structure:**
```
INPUT chain (traffico in ingresso):
├─ Loopback accept (lo interface)
├─ Established/Related accept
├─ Anti-attack rules (rate limiting, flood protection)
├─ Whitelist rules (permitted IPs/ports)
├─ Logging (NFLOG per dropped packets)
└─ Default policy: DROP

OUTPUT chain (traffico in uscita):
├─ Loopback accept
├─ Established/Related accept
├─ Application rules (allow specific outbound)
├─ Logging (dropped outbound = suspicious)
└─ Default policy: DROP

FORWARD chain (routing/NAT):
├─ Connection tracking
├─ NAT rules (if gateway)
└─ Default policy: DROP

Dual Stack Support (IPv4 + IPv6):

Firedog protegge entrambi gli stack:

  • iptables per IPv4
  • ip6tables per IPv6 (parallel rules)

Critical: Molte organizzazioni dimenticano IPv6, lasciando backdoor. Firedog hardenizza entrambi di default.


🚨 Protezioni Anti-Attacco Integrate

1. SYN Flood Protection:

Attack vector: Attacker invia migliaia di SYN packets, esaurisce connection table del server.

Firedog mitigation:

bash

# Limit new TCP connections to 10/second per IP
iptables -A INPUT -p tcp --syn -m connlimit --connlimit-above 10 -j DROP

# Alternative: Limit using recent module
iptables -A INPUT -p tcp --syn -m recent --name syn_flood --set
iptables -A INPUT -p tcp --syn -m recent --name syn_flood --update --seconds 1 --hitcount 10 -j LOG --log-prefix "SYN_FLOOD: "
iptables -A INPUT -p tcp --syn -m recent --name syn_flood --update --seconds 1 --hitcount 10 -j DROP
```

**Threshold**: Max 10 nuove connessioni/secondo per IP. Se superato → DROP per 60 secondi.

**Log example**:
```
SYN_FLOOD: IN=eth0 SRC=203.0.113.50 DST=192.168.1.10 PROTO=TCP SPT=45123 DPT=80 SYN

2. Port Scan Detection:

Attack vector: Attacker scansiona porte per trovare servizi vulnerabili (nmap, masscan).

Firedog mitigation:

bash

# Detect port scanning: >15 different ports in 1 minute
iptables -A INPUT -m recent --name portscan --rcheck --seconds 60 --hitcount 15 -j LOG --log-prefix "PORT_SCAN: "
iptables -A INPUT -m recent --name portscan --rcheck --seconds 60 --hitcount 15 -j DROP

# Track port access attempts
iptables -A INPUT -m recent --name portscan --set -j ACCEPT

Detection logic:

  • Traccia IP che toccano porte diverse
  • Se >15 porte in 60 secondi → identificato come scan
  • Ban IP per 1 ora

Advanced: Pattern recognition identifica scan types:

  • Horizontal scan: Stesso port su IP multipli (worm)
  • Vertical scan: Porte multiple su stesso IP (reconnaissance)
  • Stealth scan: TCP flags anomali (Xmas, NULL, FIN scan)

3. SSH Brute Force Protection:

Attack vector: Automated login attempts con dictionary/credential stuffing.

Firedog mitigation:

bash

# Allow max 4 SSH connection attempts per minute
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --name ssh --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --name ssh --update --seconds 60 --hitcount 4 -j LOG --log-prefix "SSH_BRUTE: "
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --name ssh --update --seconds 60 --hitcount 4 -j DROP

Enhanced protection (integrazione con fail2ban-like):

  • Dopo 4 tentativi falliti → ban 1 ora
  • Dopo 3 ban → ban permanente (whitelist manual unban)
  • Logging IP + timestamp → forensic analysis

Best practice combination:

  • Firedog rate limiting
  • SSH key-only authentication (disable password)
  • Non-standard SSH port (e.g. 2222 invece 22)
  • VPN required per SSH access

4. ICMP Flood Protection (Ping Flood):

Attack vector: Overwhelm network con ICMP echo requests.

Firedog mitigation:

bash

# Allow max 5 ping per second
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 5/s --limit-burst 10 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-request -j LOG --log-prefix "ICMP_FLOOD: "
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

# Allow ICMP echo-reply, destination-unreachable, time-exceeded (necessary for network functions)
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT

Rationale: Ping utility per troubleshooting, ma flood è attacco. Limit rate mantiene utility, blocca abuse.


5. Invalid Packet Filtering:

Attack vectors: Packet malformati per bypass firewall o exploit kernel vulnerabilities.

Firedog protection:

bash

# Drop INVALID packets (malformed, corrupted)
iptables -A INPUT -m conntrack --ctstate INVALID -j LOG --log-prefix "INVALID_PKT: "
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP

# Drop NULL packets (no flags set - reconnaissance)
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j LOG --log-prefix "NULL_PKT: "
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

# Drop XMAS packets (all flags set - Nmap Xmas scan)
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j LOG --log-prefix "XMAS_PKT: "
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

# Drop FIN packets without ACK (invalid TCP handshake)
iptables -A INPUT -p tcp --tcp-flags FIN,ACK FIN -j LOG --log-prefix "FIN_SCAN: "
iptables -A INPUT -p tcp --tcp-flags FIN,ACK FIN -j DROP

# Drop packets with SYN and FIN set (invalid combination)
iptables -A INPUT -p tcp --tcp-flags SYN,FIN SYN,FIN -j LOG --log-prefix "SYN_FIN: "
iptables -A INPUT -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP

Protection rationale: Pacchetti legittimi non hanno mai queste combinazioni. Detection = attacco o misconfiguration.


6. Anti-Spoofing (Martian Packets):

Attack vector: IP source address spoofing (IP sorgente falso per eludere detection o DDoS reflection).

Firedog mitigation:

bash

# Drop packets with private IP as source from Internet
iptables -A INPUT -i eth0 -s 10.0.0.0/8 -j LOG --log-prefix "SPOOFED_10: "
iptables -A INPUT -i eth0 -s 10.0.0.0/8 -j DROP

iptables -A INPUT -i eth0 -s 172.16.0.0/12 -j LOG --log-prefix "SPOOFED_172: "
iptables -A INPUT -i eth0 -s 172.16.0.0/12 -j DROP

iptables -A INPUT -i eth0 -s 192.168.0.0/16 -j LOG --log-prefix "SPOOFED_192: "
iptables -A INPUT -i eth0 -s 192.168.0.0/16 -j DROP

# Drop packets with localhost IP from external interface
iptables -A INPUT -i eth0 -s 127.0.0.0/8 -j LOG --log-prefix "SPOOFED_LOCALHOST: "
iptables -A INPUT -i eth0 -s 127.0.0.0/8 -j DROP

# Drop packets with multicast source
iptables -A INPUT -s 224.0.0.0/4 -j LOG --log-prefix "SPOOFED_MULTICAST: "
iptables -A INPUT -s 224.0.0.0/4 -j DROP

# Enable reverse path filtering (kernel-level anti-spoofing)
echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter

Martian packets: Packets con IP impossibili (e.g. 192.168.x.x coming from Internet). Nome deriva da “Martians” (alieni) perché non dovrebbero esistere.


7. Fragment Attack Protection:

Attack vector: IP fragmentation per eludere IDS/firewall o exploit reassembly bugs.

Firedog mitigation:

bash

# Drop fragmented packets
iptables -A INPUT -f -j LOG --log-prefix "FRAGMENT: "
iptables -A INPUT -f -j DROP

# Kernel-level protection
echo 1 > /proc/sys/net/ipv4/ip_always_defrag  # Force defragmentation before firewall

Rationale: Fragmentation legittima è rara con modern MTU discovery. Bloccare frammenti = massima sicurezza con minimo impatto legittimo.


📝 Logging e Forensics PCAP

ULOGD2 Integration:

Firedog usa ulogd2 (Userspace Logging Daemon) per logging avanzato invece di syslog tradizionale.

Vantaggi ulogd2:

  • ✅ Output PCAP nativo (compatibile Wireshark/tcpdump)
  • ✅ Logging separato INPUT/OUTPUT (analysis granulare)
  • ✅ Performance superiore (kernel-space → userspace efficiente)
  • ✅ Plugin architecture (PCAP, MySQL, PostgreSQL, JSON, etc.)

Configurazione ulogd2:

ini

# /etc/ulogd.conf

# Stack for INPUT dropped packets
stack=log_input:NFLOG,base1:BASE,pcap1:PCAP

[log_input]
group=1
bind=0.0.0.0

[pcap1]
file="/var/log/ulogd/input_dropped.pcap"
sync=1  # Sync after each packet (prevents data loss on crash)

# Stack for OUTPUT dropped packets  
stack=log_output:NFLOG,base2:BASE,pcap2:PCAP

[log_output]
group=2
bind=0.0.0.0

[pcap2]
file="/var/log/ulogd/output_dropped.pcap"
sync=1

Iptables logging rules:

bash

# Log dropped INPUT packets to NFLOG group 1
iptables -A INPUT -j NFLOG --nflog-group 1 --nflog-prefix "INPUT_DROP" --nflog-threshold 50

# Log dropped OUTPUT packets to NFLOG group 2
iptables -A OUTPUT -j NFLOG --nflog-group 2 --nflog-prefix "OUTPUT_DROP" --nflog-threshold 50

NFLOG vs LOG:

  • LOG: Logging a syslog/dmesg (text-based, limited info)
  • NFLOG: Logging a userspace daemon (binary, full packet capture)

Threshold parameter: Batch 50 packets prima di flush (performance optimization).


Log Rotation con Logrotate:

Problem: File PCAP crescono rapidamente (GB/giorno su server busy).

Solution: Automatic rotation con compressione.

bash

# /etc/logrotate.d/firedog-pcap

/var/log/ulogd/*.pcap {
    daily                    # Rotate ogni giorno
    rotate 30                # Keep 30 giorni di log
    maxsize 1G               # Force rotate se file >1GB
    compress                 # Gzip compression (riduce ~80%)
    delaycompress            # Compress file precedente, non corrente
    notifempty               # Don't rotate se file vuoto
    create 0640 root adm     # Nuovo file permissions
    sharedscripts
    postrotate
        systemctl reload ulogd2 > /dev/null 2>&1 || true
    endscript
}

Retention policy configurabile:

  • Default: 30 giorni o 1GB (whatever comes first)
  • Compliance-heavy: 90-365 giorni (healthcare, finance)
  • High-traffic: 7 giorni con offload a cold storage (S3 Glacier)

Forensic Analysis:

Analisi manuale con tcpdump:

bash

# View PCAP in real-time
tcpdump -r /var/log/ulogd/input_dropped.pcap

# Filter by IP
tcpdump -r input_dropped.pcap src host 203.0.113.50

# Filter by port
tcpdump -r input_dropped.pcap dst port 22

# Extract specific timestamp
tcpdump -r input_dropped.pcap 'greater 2024-01-15 10:00:00 and less 2024-01-15 11:00:00'

# Count packets per IP
tcpdump -r input_dropped.pcap -n | awk '{print $3}' | cut -d. -f1-4 | sort | uniq -c | sort -rn

Analisi con Wireshark (GUI):

  • Open PCAP file
  • Filter syntax: ip.src == 203.0.113.50 && tcp.flags.syn == 1
  • Statistics → Conversations (see top talkers)
  • Statistics → Protocol Hierarchy (see attack types)

Export per SIEM:

bash

# Convert PCAP to JSON for SIEM ingestion
tshark -r input_dropped.pcap -T json > dropped_packets.json

# Upload to Elasticsearch
curl -X POST "localhost:9200/firedog-logs/_bulk" -H 'Content-Type: application/json' --data-binary @dropped_packets.json

🧠 Threat Intelligence & Analysis

Traffic Analyzer con ML-like Scoring:

Firedog include traffic-analyzer.py che analizza PCAP files e assegna threat score 0-100 a ogni IP sorgente.

Scoring Algorithm:

python

threat_score = (
    packet_volume_score +      # Volume anomalo
    port_diversity_score +     # Scansione porte multiple
    protocol_diversity_score + # Protocolli multipli (recon)
    critical_port_targeting +  # RDP, Telnet, MSSQL (honeypot signals)
    syn_flood_pattern +        # TCP SYN senza ACK
    known_malicious_ip         # Blacklist match
)

# Normalized 0-100

Fattori Dettagliati:

1. Packet Volume Score (0-25 punti):

python

packets_per_minute = total_packets / time_window_minutes

if packets_per_minute > 1000: score = 25      # Flood attack
elif packets_per_minute > 500: score = 20
elif packets_per_minute > 100: score = 15
elif packets_per_minute > 50: score = 10
else: score = 5

2. Port Diversity Score (0-30 punti):

python

unique_ports_targeted = len(set(destination_ports))

if unique_ports > 50: score = 30     # Comprehensive scan
elif unique_ports > 20: score = 25   # Port scan
elif unique_ports > 10: score = 18
elif unique_ports > 5: score = 10
else: score = 0  # Targeting specific service (legit possibile)

3. Critical Port Targeting (0-20 punti):

python

critical_ports = [23, 3389, 1433, 3306, 5432, 445, 139]  # Telnet, RDP, SQL, SMB
score = 0

for port in destination_ports:
    if port in critical_ports:
        score += 5  # Cap at 20

Rationale: Porte critiche sono raramente legit target, spesso honeypot indicators.

4. SYN Flood Pattern (0-15 punti):

python

syn_packets = count_packets_with_flag('SYN')
ack_packets = count_packets_with_flag('ACK')

syn_ack_ratio = syn_packets / (ack_packets + 1)  # +1 avoid division by zero

if syn_ack_ratio > 10: score = 15   # Quasi solo SYN = flood
elif syn_ack_ratio > 5: score = 10
elif syn_ack_ratio > 2: score = 5

5. Protocol Diversity (0-10 punti):

python

unique_protocols = set([pkt.protocol for pkt in packets])

if len(unique_protocols) > 5: score = 10  # TCP + UDP + ICMP + ... = recon
elif len(unique_protocols) > 3: score = 7
elif len(unique_protocols) > 1: score = 3
```

---

**Threat Classification:**

| Score Range | Level | Indicatori | Azione Raccomandata |
|-------------|-------|------------|---------------------|
| **90-100** | 🔴 **CRITICAL** | Flood attack confermato, scan massivo, exploit tentativi multipli | **Immediate ban** IP, investigate compromissione, check logs altri sistemi |
| **70-89** | 🟠 **HIGH** | Port scan aggressivo, targeting porte critiche, volume elevato | **Temporary ban** (1-24h), monitoraggio stretto, correlazione con IDS |
| **50-69** | 🟡 **MEDIUM** | Attività sospetta ma non definitiva, possibile recon fase iniziale | **Log & alert**, no ban automatico, review manuale |
| **30-49** | 🟢 **LOW** | Anomalia leggera, potrebbe essere legit (e.g. vulnerability scanner autorizzato) | **Monitoring only**, verifica se IP è interno o partner |
| **0-29** | ⚪ **MINIMAL** | Traffico normale bloccato per policy restrittive (e.g. servizio non permesso) | **No action**, log per troubleshooting |

---

**Attack Pattern Recognition:**

**Port Scan Patterns:**
```
Sequential scan: 80, 81, 82, 83, ... (tools: nmap -sS)
Random scan: 8080, 443, 22, 3389, ... (tools: masscan)
Specific scan: 22, 2222, 22222 (SSH variants hunting)
```

**SYN Flood Pattern:**
```
Characteristics:
- High volume SYN packets (>500/sec)
- Low ACK response
- Source port randomization
- Often spoofed source IP
```

**Service Attack Pattern:**
```
Targeting specific vulnerability:
- Repeated requests to same port (e.g. 445 SMB - EternalBlue)
- Payload signatures (exploit code patterns)
- Timing patterns (exploit retry logic)
```

---

**Reporting & Recommendations:**

**Analyzer Output:**
```
=== Threat Analysis Report ===
Period: 2024-01-15 10:00 - 11:00 (1 hour)
Total IPs analyzed: 247

🔴 CRITICAL Threats (3):
├─ 203.0.113.50 [Score: 95/100]
│  ├─ Packets: 15,234 (flood)
│  ├─ Ports scanned: 127
│  ├─ Critical ports targeted: RDP, Telnet, MSSQL
│  ├─ Pattern: Horizontal + Vertical scan
│  └─ ⚠️ RECOMMENDATION: Permanent ban, report to ISP abuse@

├─ 198.51.100.20 [Score: 92/100]
│  ├─ Packets: 8,912
│  ├─ SYN flood detected (SYN/ACK ratio: 15:1)
│  └─ ⚠️ RECOMMENDATION: Immediate ban + check for DDoS botnet

🟠 HIGH Threats (12):
├─ 192.0.2.100 [Score: 78/100]
│  ├─ SSH brute force (480 attempts/hour)
│  └─ ⚠️ RECOMMENDATION: Implement fail2ban, consider VPN-only SSH

[... truncated for brevity ...]

💡 Strategic Recommendations:
1. Top attacked port: 22 (SSH) - Consider non-standard port or VPN requirement
2. Geographic anomaly: 80% attacks from CN/RU - Consider geo-blocking
3. Attack time: Peak 03:00-05:00 UTC - Schedule maintenance outside this window

🎛️ Gestione CLI User-Friendly

Firewall Manager (firewall-manager.py):

Tool CLI Python che nasconde complessità iptables con interfaccia intuitiva.

Comandi Principali:

1. Listing Rules:

bash

# List all rules
firewall-manager --list

# List specific chain
firewall-manager --list INPUT
firewall-manager --list OUTPUT

# Output example:
INPUT Chain Rules:
[1] ACCEPT tcp dpt:22 src:192.168.1.0/24  # SSH da LAN
[2] ACCEPT tcp dpt:80                     # HTTP
[3] ACCEPT tcp dpt:443                    # HTTPS
[4] DROP   tcp dpt:23                     # Telnet blocked

2. Adding Rules:

bash

# Open porta TCP (INPUT)
sudo firewall-manager --add-input 8080

# Open porta UDP
sudo firewall-manager --add-input 53 --protocol udp

# Open porta con source IP restriction
sudo firewall-manager --add-input 22 --source 192.168.1.10 --comment "SSH admin only"

# Open porta con subnet
sudo firewall-manager --add-input 3306 --source 10.0.0.0/8 --comment "MySQL internal network"

# OUTPUT rules (allow outgoing)
sudo firewall-manager --add-output 587 --comment "SMTP submission"
sudo firewall-manager --add-output 443 --dest 203.0.113.50 --comment "API server"

Validation:

  • Port range check (1-65535)
  • IP address validation (CIDR notation supported)
  • Protocol validation (tcp/udp/icmp)
  • Duplicate detection (prevent duplicate rules)

3. Removing Rules:

bash

# List rules with numbers
firewall-manager --list INPUT

# Remove by rule number
sudo firewall-manager --remove INPUT 5

# Confirmation prompt:
Remove rule: ACCEPT tcp dpt:8080
Are you sure? (y/n): y
✓ Rule removed successfully

4. Statistics & Analysis:

bash

# Show firewall statistics
firewall-manager --stats

# Output:
Firewall Statistics:
├─ Rules active: 23 (INPUT), 15 (OUTPUT)
├─ Packets processed (24h): 1,234,567
├─ Packets dropped (24h): 45,123 (3.7%)
├─ Top dropped source IPs:
│  ├─ 203.0.113.50: 12,345 packets
│  ├─ 198.51.100.20: 8,912 packets
│  └─ 192.0.2.100: 3,456 packets
└─ Most attacked ports: 22 (SSH), 3389 (RDP), 23 (Telnet)

5. Threat Analysis:

bash

# Analyze traffic ultima ora
sudo firewall-manager --analyze

# Analyze specific time range (hours)
sudo firewall-manager --analyze 24  # Last 24 hours

# Show only high-severity threats (score >= 70)
sudo firewall-manager --threats 70

# Output:
🔴 CRITICAL Threats (score >= 80):
├─ 203.0.113.50 [Score: 95]
│  └─ Port scan + SYN flood detected
└─ Recommendation: Permanent ban

🟠 HIGH Threats (score 70-79):
├─ 198.51.100.20 [Score: 78]
│  └─ SSH brute force (480 attempts)

6. Backup & Restore:

bash

# Save current rules
sudo firewall-manager --save
# Saved to: /etc/firewall/iptables.rules

# Backup with timestamp
sudo firewall-manager --backup
# Saved to: /etc/firewall/backups/iptables-20240115-103045.rules

# Restore from backup
sudo firewall-manager --restore /etc/firewall/backups/iptables-20240115-103045.rules

# List available backups
firewall-manager --list-backups

7. Testing & Dry-Run:

bash

# Test rule without applying (dry-run)
firewall-manager --add-input 8080 --dry-run

# Output:
[DRY-RUN] Would execute:
iptables -A INPUT -p tcp --dport 8080 -j ACCEPT

# Validate current ruleset (syntax check)
firewall-manager --validate

🔐 OWASP/NIST Security Compliance

Defense in Depth:

Firedog implementa multiple layer di protezione:

  1. Network layer: Packet filtering (iptables)
  2. Transport layer: Connection tracking, rate limiting
  3. Application layer: Pattern recognition (exploit signatures)
  4. Logging layer: PCAP per forensics
  5. Intelligence layer: Threat scoring, anomaly detection

Se attacker bypassa un layer, altri layer ancora proteggono.


Fail Secure:

Policy DROP default garantisce che in caso di:

  • Regola errata
  • Crash firewall daemon
  • Misconfiguration

→ Sistema default blocca tutto (fail-safe) invece che permettere tutto (fail-open insicuro).


Least Privilege:

Solo traffico esplicitamente necessario è permesso:

  • No “allow all” rules
  • Ogni porta aperta deve avere justification
  • OUTPUT filtering (unusual ma important): previene data exfiltration, C2 communication

Audit & Logging:

PCAP logging completo permette:

  • Incident reconstruction
  • Compliance audit (PCI-DSS Req 10: logging)
  • Forensic analysis post-breach
  • Threat intelligence generation

Retention: Configurabile per compliance (e.g. PCI-DSS richiede 1 anno log retention).


Rate Limiting:

Protezione contro resource exhaustion:

  • Connection rate limiting (anti-flood)
  • Packet rate limiting (anti-DDoS)
  • Per-IP limits (prevent single source overwhelming)

Input Validation:

Firedog valida ogni pacchetto:

  • TCP flags validation (drop invalid combinations)
  • IP address validation (anti-spoofing)
  • Fragmentation validation (anti-evasion)
  • Protocol compliance (RFC-compliant packets only)

Casi d’Uso

Caso 1: E-commerce WordPress – Protezione Sito Esposto

Scenario:
Negozio online WordPress su VPS, 5000 visitatori/giorno. Subiscono 3-4 attacchi/settimana: brute force wp-admin, vulnerability scan, DDoS tentativi.

Before Firedog:

  • Solo firewall cloud provider (basic)
  • Attacchi saturano Apache (downtime)
  • Log access.log inutilizzabili (troppo rumore)
  • Plugin security WordPress inefficaci contro network attacks

Implementazione Firedog:

Day 1 – Deployment:

bash

# Install Firedog
curl -sSL https://firedog.dognet.tech/install.sh | sudo bash

# Apply web-server template
sudo firewall-init.sh --template web-server

# Rules applicate:
├─ Allow 80, 443 (HTTP/HTTPS)
├─ Allow 22 from admin IP only (SSH)
├─ Block 3389, 23, 445 (RDP, Telnet, SMB - not needed)
├─ Rate limiting: max 100 req/sec per IP
├─ SYN flood protection active
└─ Port scan detection active

Week 1 – Tuning:

  • Alert Slack quando threat score >70
  • Whitelist Cloudflare IPs (se usano CDN)
  • Ban automatico IP con score >90

Risultati dopo 1 mese:

  • Attack success rate: 100% → 0% (zero downtime da attacchi)
  • Apache load: -40% (traffico malevolo bloccato prima di raggiungere Apache)
  • Bandwidth saving: ~20GB/mese (attack traffic dropped)
  • Incident response time: 2 ore → 10 minuti (alert immediate + PCAP analysis)
  • False positive: <1% (legit users blocked – quick whitelist)

Specific attack blocked:

  • XMLrpc.php DDoS: 50k requests bloccate (WordPress vulnerability common)
  • wp-login.php brute force: 1200+ tentativi da botnet (SSH protection analog)
  • Vulnerability scanner: Nessus/Acunetix scan da competitor (port scan detection)

Caso 2: Startup SaaS – Protezione API Multi-Tenant

Scenario:
Startup SaaS B2B con API REST. 50 clienti corporate. API keys leak su GitHub → credential stuffing attack. 100k unauthorized API calls in 2 ore.

Problem:

  • Application-level rate limiting esiste ma tardivo (requests già processed)
  • Database overwhelmed (query per ogni auth check)
  • Legit customers impacted (slowdown generale)

Implementazione Firedog:

Emergency Response:

bash

# Block attacking IPs (identified from application logs)
for ip in $(cat /tmp/attacking_ips.txt); do
    sudo firewall-manager --add-input --source $ip --action DROP
done

# Rate limit API port aggressively
sudo iptables -A INPUT -p tcp --dport 8080 -m limit --limit 50/sec --limit-burst 100 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 8080 -j DROP

Attack mitigato in 5 minuti.

Long-term Solution:

  • Geo-blocking: API clients sono solo US/EU → block CN/RU/IN (where leak exploited)
bash
# Using ipset for efficient geo-blocking
sudo ipset create geoblock_cn hash:net
sudo ipset add geoblock_cn 1.0.0.0/8  # China CIDR blocks
# ... (add all China IP ranges)
sudo iptables -A INPUT -p tcp --dport 8080 -m set --match-set geoblock_cn src -j DROP
```

- **API key rotation enforcement**: Email clienti per rotate leaked keys
- **Firedog monitoring**: Alert se spike request da IP sconosciuto

**Risultati:**
- **Attack stopped**: 5 minuti (vs 2 ore senza Firedog)
- **Database load**: Reduced 80% (malicious requests never reach app)
- **Customer impact**: Minimized (only 5 min slowdown)
- **Reputation saved**: No public disclosure needed (handled internally)

Caso 3: Healthcare – Segmentazione Rete HIPAA

**Scenario:**
Clinica con EHR system. HIPAA compliance richiede network segmentation: DMZ, EHR network, Administrative network. Firedog su gateway server per enforcement.

**Network Topology:**
“`
Internet
│
[Firedog Gateway]
├─ DMZ (Web server, public-facing)
├─ EHR Network (Database, application servers – PHI data)
└─ Admin Network (Staff workstations)

Firedog Rules:

DMZ → EHR Network:

bash

# Allow ONLY web server to database (specific IP + port)
sudo firewall-manager --add-forward --source 10.0.1.10 --dest 10.0.2.5 --port 5432 --comment "Web to DB"

# Block everything else from DMZ to EHR
sudo iptables -A FORWARD -s 10.0.1.0/24 -d 10.0.2.0/24 -j DROP

Admin Network → EHR Network:

bash

# Allow admin workstations to EHR application (HTTPS only)
sudo firewall-manager --add-forward --source 10.0.3.0/24 --dest 10.0.2.10 --port 443

# Allow database admin access (restricted IP)
sudo firewall-manager --add-forward --source 10.0.3.50 --dest 10.0.2.5 --port 5432 --comment "DBA access"

Internet → DMZ:

bash

# Allow HTTPS only
sudo firewall-manager --add-input 443

# Block everything else (including SSH - use VPN)

Logging for HIPAA Audit:

  • Every FORWARD rule logs (audit trail)
  • PCAP retention 2 anni (HIPAA requirement)
  • Monthly review report generated automatically

Compliance Result:

  • HIPAA Security Rule §164.312(a)(1): Network segmentation enforced ✅
  • §164.312(b): Audit logs complete ✅
  • Penetration test: Attempted lateral movement from DMZ → EHR blocked ✅

Caso 4: Manufacturing – Protezione SCADA/ICS

Scenario:
Azienda manifatturiera con sistema SCADA (Industrial Control System) per linea produzione. SCADA network deve essere air-gapped ma ha connessione enterprise network per monitoring remoto.

Risk:

  • SCADA protocols (Modbus, OPC) non hanno security nativa
  • Ransomware su corporate network può propagare a SCADA
  • SCADA devices non patchabili (vendor EOL, uptime critico 99.9%)

Implementazione Firedog:

Firewall SCADA Gateway:

bash

# Whitelist ONLY: Engineering workstation → SCADA devices
sudo firewall-manager --add-forward --source 192.168.100.50 --dest 10.10.0.0/24 --comment "Engineer to SCADA"

# Whitelist: SCADA historian (monitoring) → Corporate DB (report)
sudo firewall-manager --add-forward --source 10.10.0.10 --dest 192.168.1.100 --port 1433

# DENY everything else (default policy)
# Especially: Block corporate workstations → SCADA (prevent ransomware spread)

Monitoring Alerts:

bash

# Alert if ANY non-whitelisted traffic attempts SCADA access
sudo firewall-manager --alert-on-drop --dest 10.10.0.0/24 --notify slack

Virtual Patching (SCADA Vulnerabilities):

  • SCADA PLC has critical vulnerability (CVE-2023-XXXX), no patch available (EOL device)
  • Firedog blocks exploit pattern:

bash

# Block specific exploit traffic pattern (identified by ICS-CERT advisory)
sudo iptables -A FORWARD -d 10.10.0.5 -m string --algo bm --hex-string '|504c4320...|' -j LOG --log-prefix "SCADA_EXPLOIT_ATTEMPT: "
sudo iptables -A FORWARD -d 10.10.0.5 -m string --algo bm --hex-string '|504c4320...|' -j DROP

Incident Response:

  • Corporate network infected con ransomware (WannaCry variant)
  • Ransomware attempts propagate via SMB
  • Firedog blocks: SMB (445) traffic corporate → SCADA
  • Result: SCADA network untouched, production continua
  • Downtime avoided: €500k/hour production loss

Compliance:

  • IEC 62443 (Industrial security standard): Network segmentation required ✅
  • NIS2 Directive (EU critical infrastructure): Protective measures documented ✅

Caso 5: Hosting Provider – Multi-Tenant Security

Scenario:
Hosting provider con 500 VPS clienti su stessa infrastruttura. Necessità isolamento tra tenant, protezione shared resources.

Challenge:

  • Alcuni clienti sono attack targets (high-profile)
  • DDoS su cliente A non deve impattare cliente B
  • Prevent lateral movement se cliente compromesso

Implementazione Firedog (su ogni VPS):

Automated Deployment:

bash

# Ansible playbook per deploy Firedog su 500 VPS
---
- hosts: all_vps
  tasks:
    - name: Install Firedog
      shell: curl -sSL https://firedog.dognet.tech/install.sh | bash
    
    - name: Apply base template
      command: firewall-init.sh --template vps-hosting
    
    - name: Configure tenant-specific rules
      template:
        src: firewall-rules.j2
        dest: /etc/firewall/custom_rules.conf
      vars:
        allowed_ports: "{{ tenant_allowed_ports }}"
        admin_ip: "{{ tenant_admin_ip }}"

Tenant Isolation:

bash

# Each VPS can ONLY communicate with:
# - Internet (outbound)
# - Hosting provider management network (inbound admin)
# - NO inter-VPS communication

# Block RFC1918 destinations (prevent lateral movement)
sudo iptables -A OUTPUT -d 10.0.0.0/8 -j DROP
sudo iptables -A OUTPUT -d 172.16.0.0/12 -j DROP
sudo iptables -A OUTPUT -d 192.168.0.0/16 -j DROP

# Exception: Allow DNS to hosting resolver
sudo iptables -I OUTPUT -d 10.0.0.53 -p udp --dport 53 -j ACCEPT

DDoS Protection per Tenant:

  • Firedog rate limiting per VPS
  • Se VPS riceve >10k pkt/sec → automatic upstream notification (BGP blackhole route)
  • PCAP captured per forensics

Centralized Monitoring:

  • Hosting provider dashboard: Real-time threat score tutti VPS
  • Alert se VPS compromesso (unusual outbound traffic pattern)
  • Automatic quarantine: Compromised VPS network isolated

Results:

  • Tenant satisfaction: +15% (improved security posture)
  • DDoS incidents: -70% (early detection + mitigation)
  • Support tickets: -30% (less “my VPS slow” – better noisy neighbor prevention)
  • Compliance: SOC 2 Type II audit passed (isolation controls documented)

FAQ – Firedog

Generale

Q: Firedog sostituisce firewall hardware (Fortinet, Palo Alto)?
A: No, Firedog è host-based firewall (gira sul server stesso), non perimetral firewall. Sono complementari:

  • Perimeter firewall: Prima linea difesa, filtra traffico entrante/uscente rete
  • Firedog: Seconda linea difesa, protegge singolo host anche se attacker bypassa perimeter

Defense-in-depth: Entrambi layer sono importanti.

Q: Funziona solo su Linux?
A: Attualmente sì (iptables/nftables sono Linux-specific).
Roadmap: Windows Firewall version (Q2 2026), macOS pf version (Q4 2026).

Q: Serve competenza Linux avanzata?
A: No, CLI Python (firewall-manager) nasconde complessità iptables. Comandi intuitivi:

bash

# Instead of:
iptables -A INPUT -p tcp --dport 8080 -j ACCEPT

# You write:
firewall-manager --add-input 8080

Curva apprendimento: 30 minuti per operations base, 2-3 ore per tuning avanzato.

Q: Quanto costa?
A: Licensing: Per server, non per traffico/regole/features.


Deployment & Configuration

Q: Quanto tempo serve per deploy?
A: Setup base: 15-30 minuti

bash

# 3 comandi:
curl -sSL https://firedog.dognet.tech/install.sh | sudo bash  # 5 min
sudo firewall-init.sh --template web-server                    # 2 min
sudo systemctl enable --now firedog                             # 1 min

Production-ready (con tuning): 2-4 ore (testing, whitelist, alert config).

Q: Posso testare senza impattare produzione?
A: Sì, dry-run mode:

bash

# Apply rules in LOG-only mode (no DROP)
sudo firewall-init.sh --template web-server --mode log-only

# Monitor logs for false positives (24-48h)
tail -f /var/log/firedog/blocked.log

# If looks good, activate blocking
sudo firewall-init.sh --template web-server --mode enforce

Q: Cosa succede se regola sbagliata mi locka fuori (SSH)?
A: Safety mechanisms:

  1. Auto-rollback: Se server unreachable dopo 5 min → automatic rollback
  2. Console access: Accesso fisico/IPMI bypassa firewall
  3. Rescue mode: Boot in rescue, disable firewall, fix rules

Best practice: SEMPRE testare su staging first, mantenere console access ready.

Q: Supporta template pre-configurati?
A: Sì, template per use case comuni:

  • web-server: Apache/Nginx (80, 443, 22)
  • database-server: MySQL/PostgreSQL (3306, 5432, 22)
  • mail-server: SMTP/IMAP/POP3 (25, 587, 143, 993, 110, 995)
  • vpn-gateway: OpenVPN/WireGuard (1194, 51820)
  • dns-server: BIND (53 UDP/TCP)
  • minimal: SSH only (22) – ultra-restrictive
  • custom: Build your own

Usage:

bash

sudo firewall-init.sh --template web-server

Q: Posso usare Firedog con firewall cloud provider (AWS Security Groups, Azure NSG)?
A: Sì, layered approach (recommended):

  • Cloud firewall: Primo layer, regole grossolane (e.g. allow 80/443 from 0.0.0.0/0)
  • Firedog: Secondo layer, regole fini (e.g. rate limiting, anti-brute-force)

Benefit: Se attacker bypassa cloud firewall (misconfiguration), Firedog still protects.


Protezioni & Threat Detection

Q: SYN flood protection è efficace contro DDoS?
A: Parzialmente:

  • ✅ Effective: Small/medium DDoS (<10Gbps), single-source attacks
  • ⚠️ Limited: Large DDoS (>10Gbps), distributed attacks (100k+ sources)

Per DDoS massive serve:

  • Upstream mitigation (ISP, Cloudflare, AWS Shield)
  • Anycast network
  • Scrubbing centers

Firedog protects: Application-layer dopo DDoS mitigation (L7 attacks che passano CDN).

Q: Quanti falsi positivi genera port scan detection?
A: Configurabile threshold:

  • Aggressive (>10 porte/min): ~5-10% false positive (vulnerability scanner legit)
  • Balanced (>15 porte/min): ~1-2% false positive (default)
  • Conservative (>30 porte/min): <1% false positive ma miss alcuni scan

Tuning: Dopo 1 settimana monitoring, adjust threshold per tuo ambiente.

Q: SSH brute force protection è meglio di fail2ban?
A: Simile ma integrato:

FeatureFiredogfail2ban
Rate limiting✅ Kernel-level (iptables)✅ Userspace (log parsing)
PerformanceFaster (no log parsing)Slower (regex su log)
IntegrationNative FiredogSeparate daemon
FlexibilityLimited (SSH, HTTP)High (any service)
RecommendedFiredog + fail2ban combofail2ban se solo tool

Best practice: Use both – Firedog per protection immediata, fail2ban per custom services.

Q: Threat score è accurato? Quanti falsi positivi?
A: Accuracy ~85-90% dopo tuning:

False Positives comuni:

  • Vulnerability scanner autorizzato (Nessus scan) → score 70+ (looks like attack)
    • Mitigation: Whitelist scanner IP
  • Load balancer health checks → high volume packets
    • Mitigation: Whitelist LB IP
  • Backup software → port scanning (looking for services to backup)
    • Mitigation: Whitelist backup server

Tuning: Dopo 2 settimane, false positive rate <5%.

Q: PCAP logging impatta performance?
A: Overhead ~2-5%:

  • CPU: +3-5% (ulogd2 processing)
  • Disk I/O: Depends on traffic volume (high traffic = high I/O)
  • RAM: +50-100MB (ulogd2 buffering)

Mitigation per high-traffic:

  • Use SSD (PCAP write-intensive)
  • Dedicate CPU core per ulogd2 (taskset)
  • Reduce logging verbosity (log only DROP, not all traffic)
  • Shorter retention (7 days instead 30)

Server ad alto traffico (>100Mbps sustained): Consider dedicated logging server (remote ulogd2).


Integration con Sentinel Suite

Q: Firedog comunica con MicroSIEM e Sentinel Core?
A: Sì, con Integration Pack:

Firedog → MicroSIEM:

  • Threat alerts forwarded to MicroSIEM dashboard
  • PCAP files accessible from MicroSIEM (per correlation)
  • Unified alerting (Slack notification con context da entrambi tool)

Sentinel Core → Firedog:

  • Critical vulnerability discovered → Firedog auto-block affected port
  • Exploit confirmed (da Intellidog) → Firedog create virtual patch rule

Firedog ↔ MicroSIEM Intellidog:

  • Intellidog analyze Firedog PCAP for exploit detection
  • Virtual patching orchestrated attraverso Firedog API

Q: Integration Pack è obbligatorio?
A: No, Firedog funziona standalone. Integration Pack è optional per automation cross-tool.

Q: Posso usare Firedog senza altri tool della suite?
A: Assolutamente sì. Firedog è fully functional independently. Integration è bonus, not requirement.


Compliance & Reporting

Q: Firedog aiuta con compliance PCI-DSS?
A: Sì, specificamente:

  • Requirement 1.2.1: Restrict inbound/outbound traffic ✅ (policy DROP)
  • Requirement 1.3: Prohibit direct public access between Internet and cardholder data ✅ (network segmentation)
  • Requirement 10.2: Implement automated audit trails ✅ (PCAP logging)

Gap: PCI-DSS richiede anche physical firewall. Firedog è complementary, not substitute.

Q: PCAP logs sono audit-ready?
A: Sì:

  • Timestamp NTP-synced (accurate timing)
  • Immutable (append-only, can’t modify past events)
  • Standard format (PCAP – universally readable)
  • Retention configurable (e.g. 1 anno per PCI-DSS)

Auditor può:

  • Open PCAP in Wireshark
  • Verify timestamp authenticity
  • Replay attack sequences

Q: Firedog genera report per compliance?
A: Roadmap v2.0 (Q3 2025): Automated compliance report generation.

Currently: Manual report via:

bash

# Generate summary
sudo traffic-analyzer --report --format pdf --output compliance-report.pdf

# Include:
# - Blocked attacks summary
# - Top threat sources
# - Protection efficacy metrics

Troubleshooting & Support

Q: Come debug se servizio legittimo è bloccato?
A: Troubleshooting steps:

Step 1: Check logs

bash

# View recent drops
sudo tail -100 /var/log/ulogd/input_dropped.log | grep <service_port>

Step 2: Temporary allow

bash

# Allow temporarily (1 hour)
sudo firewall-manager --add-input <port> --temporary 3600

Step 3: If works, make permanent

bash

sudo firewall-manager --add-input <port> --comment "Service X"

Q: Firedog blocca tutto dopo aggiornamento sistema, come fix?
A: Common cause: Kernel upgrade broke iptables modules.

Fix:

bash

# Reload modules
sudo modprobe ip_tables
sudo modprobe iptable_filter
sudo modprobe nf_conntrack

# Restart Firedog
sudo systemctl restart firedog

Q: PCAP files crescono troppo velocemente, come gestire?
A: Options:

1. Ridurre retention:

bash

# /etc/logrotate.d/firedog-pcap
rotate 7  # Instead of 30

2. Compress aggressively:

bash

compress
compresscmd /usr/bin/xz  # Better compression than gzip

3. Offload to cold storage:

bash

# Cron job: Upload to S3 Glacier dopo 7 giorni, delete local
0 2 * * * aws s3 cp /var/log/ulogd/*.pcap.7.gz s3://mybucket/firedog-logs/ && rm -f /var/log/ulogd/*.pcap.7.gz

4. Log only critical:

bash

# Don't log INFO-level drops, only HIGH/CRITICAL
# (requires custom ulogd2 config)

Q: Supporto include incident response?
A: Support tiers:

Standard (incluso):

  • Email support per configuration issues
  • Troubleshooting blocchi legittimi
  • False positive tuning advice

Premium (+€2.000/anno):

  • 24/7 phone support
  • Incident response guidance (not hands-on, ma advisory)
  • Custom rule development

Professional Services (€150/ora):

  • Hands-on incident response
  • PCAP forensic analysis
  • Post-incident remediation

Technical Deep Dive

Q: Differenza tra iptables e nftables?
A: nftables è successor moderno di iptables:

FeatureiptablesnftablesPerformanceGoodBetter (20-30% faster)SyntaxComplexSimpler, more consistentIPv4/IPv6Separate toolsUnifiedScriptingLimitedBetter (transaction-based)

Firedog support:

  • v1.x: iptables (maximum compatibility)
  • v2.0 (roadmap 2025): nftables support

Q: Posso usare Firedog con Docker containers?
A: Yes, con caveat:

Scenario 1: Firedog su host, protegge Docker:

bash

# Firedog rules si applicano PRIMA di Docker iptables manipulation
# Works, but Docker potrebbe bypass alcune rules

Scenario 2: Firedog in container (non consigliato):

bash

# Container non ha accesso privilegiato a iptables host
# Needs --privileged flag (security risk)

Best practice: Firedog su host, + container-specific firewall (e.g. network policy in Kubernetes).

Q: Firedog scala per >1Gbps traffic?
A: Limitations:

  • iptables/nftables sono software firewall (CPU-bound)
  • Typical performance: ~5-10Gbps su high-end server (16 core, 3GHz+)
  • Bottleneck: Connection tracking table (default 65536 entries)

Optimization per high traffic:

bash

# Increase connection tracking table
echo 262144 > /proc/sys/net/netfilter/nf_conntrack_max

# Reduce connection tracking timeout (free entries faster)
echo 60 > /proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established

# Dedicate CPU cores to network interrupts (IRQ affinity)

For >10Gbps: Hardware firewall (FPGA-based) o XDP (eXpress Data Path) – roadmap Firedog v3.0.

Q: Supporta IPv6?
A: Sì, full dual-stack:

bash

# All Firedog rules applied to both IPv4 and IPv6
firewall-manager --add-input 80  # Applies to both iptables and ip6tables

IPv6-specific considerations:

  • ICMPv6 must be partially allowed (Neighbor Discovery Protocol)
  • IPv6 address notation (::1, fe80::/10, etc.)

Q: API disponibile per automation?
A: Roadmap v2.0 (Q2 2025): REST API per:

  • Add/remove rules programmatically
  • Query threat score
  • Retrieve PCAP via API (per SIEM integration)

Currently: CLI scripting:

bash

# Ansible example
- name: Open port 8080
  command: firewall-manager --add-input 8080

CONTATTACI

Contatta il team vendite

ItalianoitItalianoItaliano