Step 4: Security Report چالش 4 از جلسهی 36، سخت
قدم چهارم: همه را کنار هم بگذار. تابع report(events, locked, alerts, corrupted) بنویس که دقیقاً این خطها را چاپ کند: === SECURITY REPORT ===، events: 8، fails: 6، locked users: admin، alerts: 1، هر هشدار با دو فاصله در ابتدا ( ALERT: user admin had 5 fails in 60 s from 10.0.0.5)، corrupted files: notes.txt، restored: 1، و در آخر status: ATTACK DETECTED, FILES RESTORED (اگر هشداری نبود status: all quiet). اسمها را با ", ".join(...) بچسبان.
import hashlib
LOG = '''
1700000000 LOGIN FAIL user=admin ip=10.0.0.5
1700000008 LOGIN FAIL user=admin ip=10.0.0.5
1700000015 LOGIN FAIL user=admin ip=10.0.0.5
1700000022 LOGIN OK user=sara ip=10.0.0.7
1700000030 LOGIN FAIL user=admin ip=10.0.0.5
1700000041 LOGIN FAIL user=admin ip=10.0.0.5
1700000055 LOGIN FAIL user=omid ip=10.0.0.9
1700000120 LOGIN OK user=admin ip=10.0.0.5
'''.strip()
FILES = {
"notes.txt": "homework due friday",
"scores.json": '{"ali": 10, "sara": 12}',
"readme.md": "# my project",
}
BACKUP = {
"notes.txt": "homework due monday",
"scores.json": '{"ali": 10, "sara": 12}',
"readme.md": "# my project",
}
GOOD = {
"notes.txt": "2d3d75188476b84575fe19587e770d728bb49229bfa365fea4fcf5fbe7a0862c",
"scores.json": "ee55c4e6b774e375fb3acefa25559b3d907e0aab41166761b901494fc0413575",
"readme.md": "559de0bee74861c64b5d1af95b8618042d5b7ca30dcf9850953c2f7758f430b2",
}
def parse_log(text):
events = []
for line in text.splitlines():
parts = line.split()
events.append({"ts": int(parts[0]), "result": parts[2],
"user": parts[3].split("=")[1], "ip": parts[4].split("=")[1]})
return events
def brute_force(events):
fails = [e for e in events if e["result"] == "FAIL"]
locked = set()
alerts = []
for e in fails:
same = [f for f in fails if f["user"] == e["user"] and e["ts"] <= f["ts"] < e["ts"] + 60]
if len(same) >= 5 and e["user"] not in locked:
locked.add(e["user"])
alerts.append(f"ALERT: user {e['user']} had {len(same)} fails in 60 s from {e['ip']}")
return locked, alerts
def check_files(files, good, backup):
corrupted = []
for name in list(files):
if hashlib.sha256(files[name].encode()).hexdigest() != good[name]:
corrupted.append(name)
files[name] = backup[name]
return corrupted
def report(events, locked, alerts, corrupted):
# print the report lines described in the task
pass
events = parse_log(LOG)
locked, alerts = brute_force(events)
corrupted = check_files(FILES, GOOD, BACKUP)
report(events, locked, alerts, corrupted)
راهنما و جواب این چالش · برگشت به درس جلسهی 36: پروژه: نگهبان کوچک · چالش بعدی: Startup Path Audit
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال