VK TECH LEARN
Home/Courses/Ethical Hacking/लेसन 13
Chapter 7 · Network Security और Defense

Python से Intrusion Detection System (IDS) बनाना

लेसन 13 / 20·~7 मिनट·by Vïnâý Kúshwâhå
Network diagram के ऊपर shield और monitoring graph
Network diagram के ऊपर shield और monitoring graph — Chapter 7: Network Security और Defense

Intrusion Detection System (IDS) नेटवर्क या system पर नज़र रखता है और संदिग्ध गतिविधि पर alert देता है। यह हमला रोकता नहीं (वह IPS का काम है), पर समय पर चेतावनी देता है। Python से एक basic host-based IDS बनाया जा सकता है।

IDS के प्रकार

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 कम करने के तरीके

याद रखें
  • IDS alert देता है, block नहीं करता
  • HIDS host की files/logs, NIDS network traffic देखता है
  • Signature तेज़, anomaly नए हमलों के लिए
  • Threshold और allowlist से false positive कम होते हैं
Practical — 10 मिनट

अपनी lab VM में auth.log पढ़कर "Failed password" वाली पंक्तियाँ गिनें और top 3 IP लिखें। अगर लॉग खाली है, तो जान-बूझकर एक गलत SSH login करके देखें।