
Strumento di monitoraggio di rete che mappa le connessioni processo-rete, identifica i provider cloud e rileva attività di beaconing
Strumento di monitoraggio di rete che mappa le connessioni processo-rete, identifica i provider cloud e genera regole firewall. Agente leggero per la raccolta, server per l'aggregazione, parser per l'analisi.
Panoramica tra macchine — confronto versioni OS, rilevamento IP condivisi, candidati beaconing tra tutti gli host:

Dettaglio per host — avvisi critici (SO EOL, nc.exe in beaconing verso IP sconosciuto):

Dettaglio per host — avviso (candidato beacon segnalato):

Dettaglio per host — pulito (nessuna anomalia):

cargo build --release
# Raccolta semplice
cargo run --release -- collect --duration-seconds 300
# Con DNS lookups
cargo run --release -- collect --duration-seconds 300 --enable-dns
# Con compressione e crittografia
cargo run --release -- collect \
--duration-seconds 300 \
--compress \
--encrypt-key "your-secret-password"
# Genera tutti i report
cargo run --release -- parse \
--input connections.jsonl \
--process-summary processes.json \
--cloud-analysis cloud.json \
--firewall-rules-iptables firewall.sh \
--database-export network.sql
# Ricerca proprietà offline con database ASN locale (nessuna chiamata di rete)
cargo run --release -- parse \
--input connections.jsonl \
--cloud-analysis cloud.json \
--asn-db ip2asn-v4.tsv
# Ricerca ARIN live con cache persistente (le riesecuzioni saltano gli IP già consultati)
cargo run --release -- parse \
--input connections.jsonl \
--cloud-analysis cloud.json \
--arin-lookup \
--arin-cache arin_cache.json
# Analisi rapida di 5 minuti
cargo run --release -- monitor \
--duration-seconds 300 \
--output-dir ./analysis \
--full-analysis
Il binario agent è un obiettivo di distribuzione minimo, senza flag. Tutta la configurazione viene incorporata nel binario al momento della compilazione tramite variabili d'ambiente — posizionalo su un target ed eseguilo senza argomenti.
AGENT_SERVER="http://10.0.1.5:8080/upload" \
AGENT_KEY="labkey123" \
AGENT_INTERVAL="5" \
AGENT_BATCH="200" \
AGENT_DURATION="0" \
AGENT_DNS="false" \
AGENT_ENCRYPT_KEY="mysecretpassword" \
cargo build --release --bin agent
Il binario risultante in target/release/agent non ha dipendenze esterne e non richiede flag:
./agent
| Variabile | Default | Descrizione |
|---|---|---|
AGENT_SERVER | http://localhost:8080/upload | URL dell'endpoint di upload |
AGENT_KEY | (nessuno) | Valore dell'header X-API-Key |
AGENT_INTERVAL | 5 | Intervallo di polling dei socket in secondi |
AGENT_BATCH | 200 | Record per batch di upload |
AGENT_DURATION | 0 | Durata di esecuzione in secondi (0 = esegui per sempre) |
AGENT_DNS | false | Risolvi IP in hostname |
AGENT_ESTABLISHED | true | Solo connessioni ESTABLISHED |
AGENT_LOCAL_COPY | false | Mantieni una copia locale .jsonl insieme agli upload |
AGENT_COMPRESS | false | Comprimi con Gzip prima dell'upload |
AGENT_ENCRYPT_KEY | (nessuno) | Crittografia AES-256-GCM del payload (password o chiave hex di 64 caratteri) |
AGENT_UA | (default reqwest) | Header HTTP User-Agent |
AGENT_SERVER="https://collector.internal/upload" \
AGENT_KEY="prod-api-key" \
AGENT_DURATION="0" \
AGENT_INTERVAL="30" \
AGENT_COMPRESS="true" \
AGENT_ENCRYPT_KEY="$(cat /etc/gibson/key)" \
cargo build --release --bin agent
cargo run --release -- collect \
--duration-seconds 3600 \
--interval-seconds 10 \
--compress \
--encrypt-key "your-32-char-hex-key-or-password" \
--upload-url "https://your-server.com/api/upload" \
--api-key "your-api-key" \
--batch-size 50 \
--delete-after-upload
cargo run --release -- collect \
--duration-seconds 86400 \
--interval-seconds 30 \
--output connections_daily.jsonl \
--enable-dns \
--compress
Il parser supporta due percorsi mutuamente esclusivi per identificare chi possiede IP non associati:
| Metodo | Flag | Velocità | Rete | Ideale per |
|---|---|---|---|---|
| Database ASN locale | --asn-db | Immediato | Nessuna | Analisi ripetute, ambienti air-gapped |
| ARIN RDAP live | --arin-lookup | Lento (per IP) | Sì | Ricerche occasionali, nessun database locale disponibile |
Scarica il database ip2asn (aggiorna settimanalmente):
curl -O https://iptoasn.com/data/ip2asn-v4.tsv.gz && gunzip ip2asn-v4.tsv.gz
Quando viene fornito --asn-db, --arin-lookup viene ignorato. Usa --arin-cache per persistere i risultati ARIN su disco così le riesecuzioni saltano gli IP già consultati.
# Analisi con focus sul rilevamento cloud
cargo run --release -- parse \
--input connections.jsonl \
--cloud-analysis cloud_report.json \
--min-connections 5 \
--whitelist-processes "chrome,firefox,safari,edge"
Crea collector_server.py:
from flask import Flask, request, jsonify
import os
import json
import base64
from datetime import datetime
from Crypto.Cipher import AES
import gzip
app = Flask(__name__)
# Configurazione
UPLOAD_DIR = "./collected_data"
API_KEY = "your-secure-api-key"
ENCRYPTION_KEY = bytes.fromhex("your-32-byte-hex-key") # Opzionale
os.makedirs(UPLOAD_DIR, exist_ok=True)
def decrypt_data(encrypted_data, key):
"""Decifra dati criptati AES-256-GCM"""
decoded = base64.b64decode(encrypted_data)
nonce = decoded[:12]
ciphertext = decoded[12:]
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
plaintext = cipher.decrypt_and_verify(ciphertext[:-16], ciphertext[-16:])
return plaintext
@app.route('/api/upload', methods=['POST'])
def upload():
# Verifica API key
if request.headers.get('X-API-Key') != API_KEY:
return jsonify({"error": "Invalid API key"}), 401
try:
data = request.get_data()
# Se i dati sono codificati in base64 (criptati)
if data.startswith(b'eyJ'): # JSON inizia con {
# Non criptato, analizza direttamente
batch = json.loads(data)
else:
# Dati criptati
decrypted = decrypt_data(data, ENCRYPTION_KEY)
batch = json.loads(decrypted)
# Salva su file
hostname = batch.get('hostname', 'unknown')
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f"{UPLOAD_DIR}/{hostname}_{timestamp}.json"
with open(filename, 'w') as f:
json.dump(batch, f)
return jsonify({"status": "success", "file": filename}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, ssl_context='adhoc') # Usa SSL adeguato in produzione
Esegui con:
pip install flask pycryptodome
python collector_server.py
Crea /etc/nginx/sites-available/collector:
server {
listen 443 ssl;
server_name collector.yourcompany.com;
ssl_certificate /etc/ssl/certs/your-cert.pem;
ssl_certificate_key /etc/ssl/private/your-key.pem;
client_max_body_size 100M;
location /upload {
# Validazione API key
if ($http_x_api_key != "your-secure-api-key") {
return 403;
}
# Salva file caricati
client_body_in_file_only on;
client_body_temp_path /var/uploads/;
# Passa allo script di elaborazione
proxy_pass http://localhost:8080;
proxy_set_header X-File $request_body_file;
}
}
// index.js per AWS Lambda
const AWS = require('aws-sdk');
const crypto = require('crypto');
const s3 = new AWS.S3();
const BUCKET_NAME = 'your-network-data-bucket';
const API_KEY = process.env.API_KEY;
const ENCRYPTION_KEY = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');
exports.handler = async (event) => {
// Verifica API key
if (event.headers['X-API-Key'] !== API_KEY) {
return {
statusCode: 401,
body: JSON.stringify({ error: 'Invalid API key' })
};
}
try {
let data = event.body;
// Decifra se necessario
if (!data.startsWith('{')) {
// Dati criptati
const encrypted = Buffer.from(data, 'base64');
const nonce = encrypted.slice(0, 12);
const ciphertext = encrypted.slice(12);
const decipher = crypto.createDecipheriv('aes-256-gcm', ENCRYPTION_KEY, nonce);
const decrypted = Buffer.concat([
decipher.update(ciphertext.slice(0, -16)),
decipher.final()
]);
data = decrypted.toString();
}
const batch = JSON.parse(data);
const key = `${batch.hostname}/${Date.now()}_${batch.batch_id}.json`;
await s3.putObject({
Bucket: BUCKET_NAME,
Key: key,
Body: data,
ContentType: 'application/json'
}).promise();
return {
statusCode: 200,
body: JSON.stringify({ status: 'success', key })
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: error.message })
};
}
};
Distribuisci collettori sui sistemi chiave:
# Endpoint Windows
gibson.exe collect --duration-seconds 3600 --upload-url https://sec.company.com/upload --api-key KEY
# Server Linux
./gibson collect --duration-seconds 7200 --compress --upload-url https://sec.company.com/upload
Usa un servizio systemd su Linux:
# /etc/systemd/system/network-monitor.service
[Unit]
Description=Monitor Connessioni di Rete
After=network.target
[Service]
Type=simple
User=monitor
ExecStart=/opt/monitor/gibson collect \
--duration-seconds 3600 \
--compress \
--encrypt-key ${ENCRYPT_KEY} \
--upload-url https://collector.internal/upload \
--api-key ${API_KEY}
Restart=always
[Install]
WantedBy=multi-user.target
FROM rust:1.75 as builder
WORKDIR /app
COPY . .
RUN cargo build --release
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates
COPY --from=builder /app/target/release/gibson /usr/local/bin/
CMD ["gibson", "collect", "--duration-seconds", "3600", "--upload-url", "${UPLOAD_URL}"]
{
"process_name": "chrome",
"pid": 1234,
"total_connections": 45,
"unique_remote_ips": ["1.2.3.4", "5.6.7.8"],
"cloud_providers": {
"AWS": {
"connection_count": 12,
"services": {"CloudFront": 8, "S3": 4}
}
},
"risk_score": 0.5
}
{
"AWS": {
"provider": "AWS",
"unique_ips": ["52.84.1.2", "54.230.3.4"],
"unique_domains": ["d1234.cloudfront.net"],
"services": {"CloudFront": 15, "S3": 3},
"total_connections": 18
}
}
# Regole firewall generate
# ALLOW: Provider Cloud Noti
iptables -A OUTPUT -p tcp -d 52.84.0.0/14 -j ACCEPT -m comment --comment "chrome towards AWS"
iptables -A OUTPUT -p tcp -d 104.16.0.0/12 -j ACCEPT -m comment --comment "firefox towards Cloudflare"
--interval-seconds 30 per monitoraggio a lungo termine--enable-dns flag)MIT
Pull request benvenute.