-
Notifications
You must be signed in to change notification settings - Fork 1
459 lines (417 loc) · 24.3 KB
/
community_ip_report.yml
File metadata and controls
459 lines (417 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
name: Community IP Report
on:
issues:
types: [opened, reopened]
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
permissions:
contents: write
issues: write
actions: read
packages: none
pull-requests: none
security-events: none
concurrency:
group: netshield-seen-db-writers
cancel-in-progress: false
jobs:
process-report:
# Nur Issues mit dem Label "community-report" verarbeiten
if: contains(github.event.issue.labels.*.name, 'community-report')
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout Repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: true
- name: Restore seen_db Cache
# FIX: actions/cache/restore statt actions/cache verwenden.
# actions/cache löst automatisch einen Post-Job-Save aus und speichert
# dabei die noch UNBEREINIGTE seen_db. Der explizite Save-Step weiter
# unten ist die einzige korrekte Schreibquelle nach der Verarbeitung.
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: seen_db.json
# FIX #3: Key enthält issue-Nummer statt run-id.
# Bei gleichzeitigen Community-Reports (verschiedene Issues) schreibt jeder
# Run in einen eigenen Cache-Slot. Der restore-keys-Prefix holt trotzdem
# immer den neuesten globalen Stand (combined, confidence etc.).
key: netshield-seen-db-community-${{ github.event.issue.number }}-${{ github.run_id }}
restore-keys: |
netshield-seen-db-community-${{ github.event.issue.number }}-
netshield-seen-db-v2-
netshield-seen-db-v1-
netshield-seen-db-
- name: Process Community Report
env:
ISSUE_BODY: ${{ github.event.issue.body }}
ISSUE_NUMBER: ${{ github.event.issue.number }}
ISSUE_USER: ${{ github.event.issue.user.login }}
run: |
# FIX RACE1: Neuesten Stand holen bevor community_reports_log.txt gelesen
# wird. Ohne diesen Pull würde bei gleichzeitigen Issues desselben Users
# der Rate-Limit-Check auf veralteten Checkout-Daten basieren und beide
# Runs kämen durch (je nach GitHub-Scheduling-Zeitfenster ~30s Überlappung).
# FIX RACE2: merge-Fehler explizit behandeln. Das frühere `|| true`
# verschluckte Fehler still – wenn fast-forward fehlschlug, las Python
# danach veraltete Daten ohne es zu merken. Jetzt: bei Fehler warnen,
# aber trotzdem fortsetzen (Community-Report ist nicht kritisch genug
# für einen harten Abbruch).
git fetch origin ${GITHUB_REF_NAME}
if ! git merge --ff-only origin/${GITHUB_REF_NAME} 2>/dev/null; then
echo "::warning file=community_ip_report.yml::git merge --ff-only fehlgeschlagen – Rate-Limit-Check basiert auf lokalem Checkout-Stand"
echo "WARNUNG: Merge fehlgeschlagen, arbeite mit lokalem Stand weiter"
fi
python3 << 'EOF'
import sys as _sys; _sys.path.insert(0, "scripts")
from netshield_common import (
load_whitelist, load_fp_set, is_in_fp_set,
is_valid_public_ipv4, is_valid_public_cidr,
is_protected_entry, is_whitelisted,
parse_entries as _parse_entries, calculate_confidence,
safe_get_date, parse_date, sort_ips, write_ip_list,
write_text_atomic, write_json_atomic,
fetch_url, check_local_feed_age,
IPV4_RE, CIDR_RE, TIMESTAMP_RE,
)
# Init: Whitelist + FP-Set laden
load_whitelist()
load_fp_set()
import ipaddress, json, os, re, sys
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
now_day = now.strftime("%Y-%m-%d")
now_str = now.strftime("%Y-%m-%d %H:%M UTC")
issue_body = os.environ.get("ISSUE_BODY", "")
issue_number = os.environ.get("ISSUE_NUMBER", "?")
reporter = os.environ.get("ISSUE_USER", "unknown")
DB_FILE = "seen_db.json"
REPORT_FILE = "community_reports_log.txt"
RESULT_FILE = "community_result.txt"
# ── Schutzmechanismus: max. 5 Reports pro User pro Tag ─────────────
MAX_REPORTS_PER_USER = 5
today_count = 0
if os.path.exists(REPORT_FILE):
_date_re = re.compile(r"^\d{4}-\d{2}-\d{2}$")
with open(REPORT_FILE) as f:
for line in f:
# FIX #13: Datum-Format validieren bevor verglichen wird.
# Verhindert Bypass durch korrupte Log-Zeilen ohne gültiges Datum.
parts = line.split(" | ")
if len(parts) >= 3:
line_date = parts[0].strip()
line_user = parts[2].strip()
# Sicherheitscheck: line_date muss exakt YYYY-MM-DD sein
if (not _date_re.match(line_date)):
continue
if line_date == now_day and line_user == f"user={reporter}" and "ACCEPTED" in line:
today_count += 1
if today_count >= MAX_REPORTS_PER_USER:
write_text_atomic(RESULT_FILE, f"RATE_LIMITED|{reporter}|{today_count}")
print(f"Rate-Limit erreicht für {reporter}: {today_count} Reports heute")
sys.exit(0)
# ── IP aus Issue-Body extrahieren ──────────────────────────────────
# Issue Template Feld: "### IP Address\n\n1.2.3.4"
ip = None
match = re.search(r"###\s*IP Address\s*\n+\s*([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})", issue_body)
if match:
ip = match.group(1).strip()
else:
# Fallback: erste IP im Body suchen
fallback = re.search(r'\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b', issue_body)
if fallback:
ip = fallback.group(1)
if not ip:
write_text_atomic(RESULT_FILE, "NO_IP_FOUND||")
print("Keine IP im Issue gefunden")
sys.exit(0)
# ── IP validieren ─────────────────────────────────────────────────
# FIX SSOT3: Whitelist aus whitelist.json laden (Single Source of Truth)
# statt hardcoded DNS_WHITELIST und PROTECTED_CIDRS.
# Synchron mit update_combined_blacklist und false_positive_checker.
try:
with open(".github/workflows/whitelist.json", encoding="utf-8") as _wl_f:
_WHITELIST_ENTRIES = json.load(_wl_f)["entries"]
except Exception as _wl_err:
# Community-Report ist nicht kritisch genug für harten Abbruch –
# ohne Whitelist aber unsicher → IP ablehnen und User informieren.
print(f"FEHLER: whitelist.json nicht ladbar: {_wl_err}")
write_text_atomic(RESULT_FILE, f"INTERNAL_ERROR|{ip}|whitelist.json nicht ladbar")
sys.exit(0)
_whitelist_networks = []
for _wl_entry in _WHITELIST_ENTRIES:
try:
_whitelist_networks.append(ipaddress.ip_network(_wl_entry, strict=False))
except Exception as _suppressed:
print(f"WARN: suppressed Exception: {_suppressed}", file=sys.stderr)
# is_valid_public_ipv4() → importiert aus netshield_common
if not is_valid_public_ipv4(ip):
write_text_atomic(RESULT_FILE, f"INVALID_IP|{ip}|")
print(f"Ungültige IP: {ip}")
sys.exit(0)
# ── FIX FP1: False-Positive-Check gegen false_positives_set.json ──
# Verhindert dass Community-Reports bekannte legitime IPs (CDN, DNS,
# Mail-Provider) in die seen_db eintragen.
# FP-Set wurde oben via load_fp_set() bereits in netshield_common
# geladen; is_in_fp_set() prüft gegen die globalen Strukturen.
# Frühere lokale Re-Implementierung von _is_fp() entfernt.
if is_in_fp_set(ip):
write_text_atomic(RESULT_FILE, f"INVALID_IP|{ip}|")
print(f"IP {ip} ist auf der False-Positive-Liste – abgelehnt")
sys.exit(0)
# ── Angriffs-Typ aus Issue extrahieren ────────────────────────────
attack_match = re.search(r"###\s*Attack Type\s*\n+\s*(.+)", issue_body)
attack_type = attack_match.group(1).strip() if attack_match else "Unknown"
# Sanitize: nur ASCII-Buchstaben, Ziffern, Leerzeichen, Bindestrich, Slash und Unterstrich.
# FIX: \w durch [a-zA-Z0-9_] ersetzt – \w erlaubt auch Unicode-Zeichen die
# die Markdown-Tabelle im Issue-Kommentar visuell brechen können.
attack_type = re.sub(r"[^a-zA-Z0-9_ \-/]", "", attack_type)[:80].strip() or "Unknown"
# ── seen_db laden ─────────────────────────────────────────────────
db = {}
if os.path.exists(DB_FILE):
try:
with open(DB_FILE) as f:
db = json.load(f)
print(f"seen_db geladen: {len(db)} IPs")
except Exception:
db = {}
# ── IP in seen_db eintragen / aktualisieren ───────────────────────
action = ""
HQ_COMMUNITY_THRESHOLD = 3
if ip in db:
# IP existiert bereits → community-Flag erhöhen
try:
if not isinstance(db[ip], dict):
raise TypeError(f"db[{ip}] ist kein dict: {type(db[ip])}")
prev_last = db[ip].get("last", "2000-01-01")
community_count = db[ip].get("community", 0) + 1
db[ip]["community"] = community_count
db[ip]["today_count"] = db[ip].get("today_count", 0)
# "last" NUR setzen wenn HQ-Schwelle erreicht (analog zu combined: nur HQ setzt last)
# Einzelne Community-Meldungen sind kein HQ-Feed und dürfen die
# 180-Tage-Lebenszeit-Uhr nicht zurücksetzen.
if community_count >= HQ_COMMUNITY_THRESHOLD:
db[ip]["hq"] = True
db[ip]["today_hq"] = True
if prev_last != now_day:
db[ip]["days_seen"] = db[ip].get("days_seen", 0) + 1
db[ip]["last"] = now_day # HQ-Promotion → last darf gesetzt werden
print(f"IP {ip} auf HQ=True gesetzt (community={community_count} >= {HQ_COMMUNITY_THRESHOLD})")
else:
db[ip]["today_hq"] = db[ip].get("hq", False)
# last bleibt unverändert – Community < 3 ist kein HQ-Beweis
action = "UPDATED"
print(f"IP {ip} bereits bekannt – community={community_count}, hq={db[ip].get('hq', False)}")
except Exception as _corrupt:
print(f"WARN: Korrupter seen_db-Eintrag {ip}, wird neu angelegt: {_corrupt}", file=sys.stderr)
# Korrupten Eintrag durch frischen ersetzen
db[ip] = {
"first": now_day,
"last": "2000-01-01",
"hq": False,
"community": 1,
"feeds": ["community_report"],
"hq_feed_names": [],
"hq_feeds": 0,
"today_count": 1,
"today_hq": False,
"days_seen": 0,
}
action = "REPLACED_CORRUPT"
else:
# Neue IP → eintragen ohne last (noch keine HQ-Bestätigung)
db[ip] = {
"first": now_day,
"last": "2000-01-01", # kein HQ → last nicht setzen
"hq": False,
"community": 1,
"feeds": ["community_report"],
"hq_feed_names": [], # FIX: Schema-Konsistenz mit update_combined_blacklist
"hq_feeds": 0,
"today_count": 1,
"today_hq": False,
"days_seen": 0,
}
action = "NEW"
print(f"Neue IP {ip} als Community-Report eingetragen (Watchlist, last=2000-01-01)")
# ── seen_db speichern ─────────────────────────────────────────────
# FIX ATOMIC: write_json_atomic statt open("w")+json.dump – bei
# Runner-Kill bleibt die seen_db.json komplett alt oder komplett neu.
# Halb geschriebene JSON würde vom naechsten Run als korrupt erkannt
# → db={} → Leerungsschutz → Inkonsistenz mit Log-Eintrag
# (Log sagt ACCEPTED, seen_db hätte die IP stillschweigend verloren).
write_json_atomic(DB_FILE, db, separators=(",", ":"))
# ── Log-Eintrag ───────────────────────────────────────────────────
# allow-nonatomic: append-only Log, siehe FIX RACE2 unten (Zeile ~306)
with open(REPORT_FILE, "a", encoding="utf-8") as f:
f.write(f"{now_day} | issue=#{issue_number} | user={reporter} | ip={ip} | type={attack_type} | action={action} | ACCEPTED\n")
# ── community_reported_ips.txt pflegen ──────────────────────────
# FIX CACHE-LOSS: Community-IPs werden in eine committete Datei
# geschrieben, die update_combined_blacklist als LOCAL_FEED einliest.
#
# FIX RACE2: Append-only statt Read-Modify-Write.
# Vorher: Datei komplett neu geschrieben → bei zwei parallelen
# Community-Reports (verschiedene Issues) gewinnt nur der spätere
# Push. Der frühere Run verliert seine neue IP still durch
# `rebase -X theirs`. Jetzt: nur neue IP anhängen wenn nicht
# bereits vorhanden. Git kann Appends an verschiedene Dateistellen
# beim Rebase automatisch mergen → kein Datenverlust.
#
# Stale-Bereinigung wird NICHT mehr hier durchgeführt – das
# übernimmt update_combined_blacklist über WATCHLIST_EXPIRY_DAYS
# (30 Tage) beim nächsten Lauf. Community-Report soll nur
# hinzufügen, nie entfernen.
COMMUNITY_IPS_FILE = "community_reported_ips.txt"
community_existing = set()
if os.path.exists(COMMUNITY_IPS_FILE):
with open(COMMUNITY_IPS_FILE, encoding="utf-8") as _cf:
community_existing = {
l.strip() for l in _cf
if l.strip() and not l.startswith("#")
}
if ip not in community_existing:
# Datei existiert noch nicht → Header + IP atomar schreiben
if not os.path.exists(COMMUNITY_IPS_FILE):
# FIX ATOMIC: einmalige Header-Erstellung atomar.
# NB: die Append-Operation weiter unten (Zeile ~337) bleibt
# bewusst non-atomar – Git kann Appends an verschiedene
# Dateistellen beim Rebase automatisch mergen (FIX RACE2),
# deshalb kein write_text_atomic dort.
write_text_atomic(
COMMUNITY_IPS_FILE,
"# NETSHIELD Community Reported IPs\n"
f"# Aktualisiert: {now_str}\n"
"# Quelle: GitHub Issues (community-report Label)\n\n"
f"{ip}\n"
)
else:
# Append-only: neue IP ans Ende anfügen
# allow-nonatomic: FIX RACE2 – Git mergt Appends bei Rebase automatisch
with open(COMMUNITY_IPS_FILE, "a", encoding="utf-8") as _cf:
_cf.write(f"{ip}\n")
print(f"community_reported_ips.txt: IP {ip} hinzugefügt (append-only, {action})")
else:
print(f"community_reported_ips.txt: IP {ip} bereits vorhanden ({action})")
# ── Ergebnis für nächsten Step speichern ──────────────────────────
write_text_atomic(RESULT_FILE, f"{action}|{ip}|{attack_type}")
print(f"Fertig: {action} – IP {ip} ({attack_type})")
EOF
- name: Save seen_db Cache
if: always() # FIX: auch bei unbehandelter Exception den Cache speichern (verhindert Inkonsistenz: Log sagt ACCEPTED, seen_db verliert die IP)
# FIX: actions/cache/save statt actions/cache – verhindert doppelten
# Save (Restore-Step nutzt jetzt actions/cache/restore ohne Post-Job-Hook).
uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: seen_db.json
# FIX #3: Eindeutiger Slot pro Issue → keine gegenseitige Überschreibung
# bei parallelen Community-Reports.
key: netshield-seen-db-community-${{ github.event.issue.number }}-${{ github.run_id }}
- name: Commit Log
if: always() # FIX: auch bei exit(0) (RATE_LIMITED, NO_IP_FOUND etc.) den Log committen
env:
ISSUE_NUMBER: ${{ github.event.issue.number }}
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add community_reports_log.txt community_reported_ips.txt 2>/dev/null || true
if git diff --staged --quiet; then
echo "Keine Änderungen"
else
# FIX RACE5: Append-only Dateien VOR commit sichern, dann
# reset --hard auf Upstream + Re-Apply der eigenen Appends.
#
# Vorher (FIX RACE3): rebase -X theirs + Diff-Buffer in /tmp/.
# Problem: Bei git rebase bedeutet -X theirs das GEGENTEIL von
# git merge -X theirs – es behält den eigenen Commit und verwirft
# den Upstream. Der Fallback-Zweig (else nach rebase) wird nie
# erreicht, weil -X theirs Konflikte still „löst" → der gesamte
# RACE3-Schutz war toter Code, Remote-Appends gingen verloren.
#
# Neues Pattern: Explizit Upstream übernehmen (reset --hard),
# eigene Appends deterministisch darauf aufbauen (mit Dedup).
git diff HEAD -- community_reports_log.txt | grep '^+[^+]' | sed 's/^+//' > /tmp/local_log_appends.txt 2>/dev/null || true
git diff HEAD -- community_reported_ips.txt | grep '^+[^+]' | sed 's/^+//' > /tmp/local_ip_appends.txt 2>/dev/null || true
git commit -m "Community Report #${ISSUE_NUMBER}: $(date -u '+%Y-%m-%d %H:%M') UTC"
for attempt in 1 2 3 4 5; do
echo "Push-Versuch $attempt..."
git fetch origin ${GITHUB_REF_NAME}
# Reset auf Upstream-Stand – übernimmt alle Remote-Änderungen
git reset --hard origin/${GITHUB_REF_NAME}
# Gesicherte Appends deterministisch wieder anfügen (mit Dedup)
if [ -s /tmp/local_log_appends.txt ]; then
while IFS= read -r line; do
grep -qxF "$line" community_reports_log.txt 2>/dev/null || echo "$line" >> community_reports_log.txt
done < /tmp/local_log_appends.txt
fi
if [ -s /tmp/local_ip_appends.txt ]; then
while IFS= read -r ip; do
grep -qxF "$ip" community_reported_ips.txt 2>/dev/null || echo "$ip" >> community_reported_ips.txt
done < /tmp/local_ip_appends.txt
fi
git add community_reports_log.txt community_reported_ips.txt 2>/dev/null || true
if git diff --staged --quiet; then
echo "Keine neuen Änderungen nach Reset+Re-Apply"
exit 0
fi
git commit -m "Community Report #${ISSUE_NUMBER}: $(date -u '+%Y-%m-%d %H:%M') UTC"
if git push origin HEAD:${GITHUB_REF_NAME}; then
echo "Push erfolgreich (Versuch $attempt)"
exit 0
fi
sleep $((attempt * 3))
done
echo "FEHLER: Push nach 5 Versuchen fehlgeschlagen"
exit 1
fi
- name: Post Issue Comment & Close
# FIX CRASH1: if: always() damit der User auch bei unbehandelter Python-
# Exception eine Rückmeldung im Issue erhält. Ohne diesen Guard bleibt
# das Issue kommentarlos offen wenn der Python-Step crasht.
if: always()
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v7
with:
script: |
const fs = require('fs');
// FIX CRASH1: Wenn Python-Step crashte bevor community_result.txt
// geschrieben wurde, Fallback-Kommentar posten statt selbst zu crashen.
let result = 'INTERNAL_ERROR||';
try {
result = fs.readFileSync('community_result.txt', 'utf8').trim();
} catch (e) {
console.log('community_result.txt nicht vorhanden – Python-Step vermutlich gecrasht');
}
const [status, ip, attackType] = result.split('|');
let comment = '';
let shouldClose = true;
if (status === 'NEW') {
comment = `## ✅ Report Received\n\nThank you for your report!\n\n| Field | Value |\n|---|---|\n| **IP** | \`${ip}\` |\n| **Attack Type** | ${attackType} |\n| **Status** | Added to Watchlist |\n| **Next Step** | IP will be promoted to Blacklist when confirmed by other feeds |\n\n> 🔄 The next automated run will include this IP in the analysis.`;
} else if (status === 'UPDATED') {
comment = `## ✅ Report Confirmed\n\nThis IP was already in our database. Your report strengthens the confidence score.\n\n| Field | Value |\n|---|---|\n| **IP** | \`${ip}\` |\n| **Attack Type** | ${attackType} |\n| **Status** | Confirmation recorded – confidence score increased |\n\n> ⚡ Once this IP has been reported by **3 independent users**, it will be promoted to the **Active Blacklist (Stufe 2)** automatically.`;
} else if (status === 'INVALID_IP') {
comment = `## ❌ Invalid IP Address\n\nThe IP address \`${ip}\` could not be processed:\n- It may be a private, reserved, or protected IP\n- Please check the format and try again\n\nIf you believe this is an error, please open a new issue with a valid public IPv4 address.`;
shouldClose = false;
} else if (status === 'RATE_LIMITED') {
comment = `## ⚠️ Rate Limit Reached\n\nYou have submitted too many reports today. Please try again tomorrow.\n\n> Maximum: 5 reports per user per day`;
shouldClose = false;
} else if (status === 'NO_IP_FOUND') {
comment = `## ❌ No IP Address Found\n\nWe could not extract an IP address from your report.\n\nPlease use the **Issue Template** and fill in the IP Address field correctly.`;
shouldClose = false;
} else if (status === 'INTERNAL_ERROR') {
comment = `## ⚠️ Internal Error\n\nAn unexpected error occurred while processing your report. The maintainers have been notified via the workflow logs.\n\nPlease try again later or open a new issue if the problem persists.`;
shouldClose = false;
}
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: comment
});
if (shouldClose) {
await github.rest.issues.update({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
state: 'closed'
});
}