
Intrusion Detection System (IDS) नेटवर्क या system पर नज़र रखता है और संदिग्ध गतिविधि पर alert देता है। यह हमला रोकता नहीं (वह IPS का काम है), पर समय पर चेतावनी देता है। Python से एक basic host-based IDS बनाया जा सकता है।
IDS के प्रकार
- NIDS (Network IDS): नेटवर्क traffic देखता है — Snort, Suricata, Zeek।
- HIDS (Host IDS): एक मशीन की files, processes और logs देखता है — OSSEC, Wazuh।
- Signature-based: ज्ञात attack patterns से मिलाता है — तेज़, पर नए हमले छूट सकते हैं।
- Anomaly-based: सामान्य व्यवहार से हटने पर alert देता है — नए हमले पकड़ सकता है, पर false positive ज़्यादा।
1. Log monitoring
Linux में authentication की जानकारी /var/log/auth.log में रहती है। बार-बार fail हो रहे logins attack का संकेत हो सकते हैं:
from collections import Counter
import re
fails = Counter()
with open("/var/log/auth.log", errors="ignore") as f:
for line in f:
if "Failed password" in line:
ip = re.search(r"from (\d+\.\d+\.\d+\.\d+)", line)
if ip:
fails[ip.group(1)] += 1
for ip, count in fails.most_common(5):
print(ip, count)
अगर किसी एक IP से 10 से ज़्यादा failures हैं, तो वह brute force की कोशिश हो सकती है।
2. File integrity monitoring
अहम फ़ाइलों का hash याद रखें; बदल जाए तो alert:
import hashlib, os
def digest(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).hexdigest()
watch = ["/etc/passwd", "/etc/hosts"]
for p in watch:
if os.path.exists(p):
print(p, digest(p)[:16])
असली IDS इस baseline को सेव करके नियमित रूप से तुलना करता है — जैसे AIDE या Tripwire करते हैं।
3. Simple network alert
Scapy से packets पढ़कर असामान्य ports या बहुत ज़्यादा connections पकड़े जा सकते हैं:
from scapy.all import sniff
def check(pkt):
if pkt.haslayer("TCP") and pkt["TCP"].dport == 23:
print("Telnet attempt from", pkt["IP"].src)
sniff(prn=check, store=0, count=20)
यह छोटा उदाहरण बताता है कि IDS का core क्या है — packet पढ़ना, नियम लगाना और alert देना। Production में signature rules और rate limiting ज़रूरी होती है।
False positive कम करने के तरीके
- Threshold तय करें — एक-दो बार नहीं, बार-बार होने पर alert।
- Known अच्छे IP (backup server, monitoring) को allowlist करें।
- Alert को severity में बाँटें — सब कुछ critical नहीं होता।
- हर alert में समय, source, destination और rule लिखें।
- IDS alert देता है, block नहीं करता
- HIDS host की files/logs, NIDS network traffic देखता है
- Signature तेज़, anomaly नए हमलों के लिए
- Threshold और allowlist से false positive कम होते हैं
अपनी lab VM में auth.log पढ़कर "Failed password" वाली पंक्तियाँ गिनें और top 3 IP लिखें। अगर लॉग खाली है, तो जान-बूझकर एक गलत SSH login करके देखें।