Kodax

مراقبة الشبكات — أمن الشبكات

مراقبة الشبكات

لماذا المراقبة؟

- اكتشاف الهجمات

- تحليل الأداء

- حل المشاكل

- الامتثال للوائح

أدوات المراقبة

Wireshark

- تحليل الحزم (Packet Analysis)

- التقاط كل حركة الشبكة

- فلاتر قوية

tcpdump

- سطر الأوامر

- خفيف وسريع

tcpdump -i eth0 port 80

Netflow/sFlow

- إحصائيات تدفق البيانات

- لا يلتقط المحتوى

SNMP

- Simple Network Management Protocol

- مراقبة الأجهزة

Nagios/Zabbix

- مراقبة البنية التحتية

- تنبيهات تلقائية

ما نراقب؟

حركة المرور

- البروتوكولات المستخدمة

- حجم البيانات

- مصادر ووجهات

الأداء

- Latency (التأخير)

- Bandwidth usage

- Packet loss

الأمان

- محاولات اتصال مشبوهة

- حركة غير عادية

- بروتوكولات غير متوقعة

فلاتر Wireshark المفيدة

# HTTP فقط
http

# IP محدد
ip.addr == 192.168.1.1

# TCP port
tcp.port == 443

# DNS queries
dns

# بدون ARP
!arp

# HTTP POST
http.request.method == "POST"

# كلمات مرور (خطير!)
http contains "password"
# أدوات مراقبة الشبكة
import socket
import struct
import time
from collections import defaultdict

class NetworkMonitor:
    """
    مراقب شبكة بسيط للتعليم
    """
    
    def __init__(self):
        self.connections = defaultdict(int)
        self.protocols = defaultdict(int)
        self.bytes_transferred = 0
    
    def analyze_packet(self, raw_data):
        """
        تحليل حزمة IP
        """
        # استخراج معلومات أساسية من IP header
        version_ihl = raw_data[0]
        version = version_ihl >> 4
        ihl = (version_ihl & 0xF) * 4
        
        ttl = raw_data[8]
        protocol = raw_data[9]
        
        src_ip = ".".join(map(str, raw_data[12:16]))
        dst_ip = ".".join(map(str, raw_data[16:20]))
        
        # تحديد البروتوكول
        protocol_names = {
            1: "ICMP",
            6: "TCP",
            17: "UDP"
        }
        protocol_name = protocol_names.get(protocol, f"Unknown({protocol})")
        
        return {
            "version": version,
            "header_length": ihl,
            "ttl": ttl,
            "protocol": protocol_name,
            "src_ip": src_ip,
            "dst_ip": dst_ip
        }
    
    def parse_tcp_header(self, raw_data, ip_header_length):
        """
        استخراج معلومات TCP
        """
        tcp_header = raw_data[ip_header_length:ip_header_length+20]
        
        src_port = struct.unpack('!H', tcp_header[0:2])[0]
        dst_port = struct.unpack('!H', tcp_header[2:4])[0]
        
        return {
            "src_port": src_port,
            "dst_port": dst_port
        }
    
    def detect_suspicious_activity(self, packet_info):
        """
        اكتشاف نشاط مشبوه
        """
        alerts = []
        
        # فحص المنافذ المشبوهة
        suspicious_ports = [4444, 5555, 6666, 31337, 12345]
        
        if 'src_port' in packet_info:
            if packet_info['src_port'] in suspicious_ports:
                alerts.append(f"⚠️ منفذ مصدر مشبوه: {packet_info['src_port']}")
            if packet_info['dst_port'] in suspicious_ports:
                alerts.append(f"⚠️ منفذ وجهة مشبوه: {packet_info['dst_port']}")
        
        return alerts
    
    def get_common_ports(self, port):
        """
        تحديد الخدمة من المنفذ
        """
        services = {
            20: "FTP-data", 21: "FTP", 22: "SSH", 23: "Telnet",
            25: "SMTP", 53: "DNS", 80: "HTTP", 110: "POP3",
            143: "IMAP", 443: "HTTPS", 993: "IMAPS", 995: "POP3S",
            3306: "MySQL", 3389: "RDP", 5432: "PostgreSQL",
            6379: "Redis", 27017: "MongoDB"
        }
        return services.get(port, f"Unknown({port})")
    
    def generate_traffic_report(self, duration_seconds=10):
        """
        توليد تقرير حركة المرور (محاكاة)
        """
        print(f"\n📊 تقرير حركة المرور")
        print("=" * 50)
        
        # بيانات محاكاة
        traffic_data = [
            {"proto": "TCP", "src": "192.168.1.100", "dst": "93.184.216.34", "port": 443, "bytes": 15000},
            {"proto": "TCP", "src": "192.168.1.100", "dst": "142.250.185.78", "port": 443, "bytes": 25000},
            {"proto": "UDP", "src": "192.168.1.100", "dst": "8.8.8.8", "port": 53, "bytes": 500},
            {"proto": "TCP", "src": "192.168.1.100", "dst": "151.101.1.140", "port": 443, "bytes": 8000},
            {"proto": "TCP", "src": "10.0.0.50", "dst": "192.168.1.100", "port": 22, "bytes": 2000},
        ]
        
        print(f"\n{'البروتوكول':<10} {'المصدر':<18} {'الوجهة':<18} {'المنفذ':<8} {'الحجم'}")
        print("-" * 70)
        
        total_bytes = 0
        for t in traffic_data:
            service = self.get_common_ports(t['port'])
            print(f"{t['proto']:<10} {t['src']:<18} {t['dst']:<18} {service:<8} {t['bytes']} bytes")
            total_bytes += t['bytes']
        
        print("-" * 70)
        print(f"{'الإجمالي:':<56} {total_bytes} bytes")
        
        # تحليل البروتوكولات
        print("\n📈 توزيع البروتوكولات:")
        proto_count = defaultdict(int)
        for t in traffic_data:
            proto_count[t['proto']] += 1
        
        for proto, count in proto_count.items():
            pct = (count / len(traffic_data)) * 100
            bar = "█" * int(pct / 5)
            print(f"  {proto}: {bar} {pct:.0f}%")
    
    def show_live_traffic(self, duration=5):
        """
        عرض حركة المرور الحية (محاكاة)
        """
        print(f"\n🔴 مراقبة حركة المرور (محاكاة)")
        print("=" * 50)
        print("اضغط Ctrl+C للإيقاف\n")
        
        simulated_packets = [
            "TCP 192.168.1.100:52341 → 93.184.216.34:443 [SYN]",
            "TCP 93.184.216.34:443 → 192.168.1.100:52341 [SYN,ACK]",
            "TCP 192.168.1.100:52341 → 93.184.216.34:443 [ACK]",
            "TCP 192.168.1.100:52341 → 93.184.216.34:443 [PSH,ACK] len=517",
            "UDP 192.168.1.100:54321 → 8.8.8.8:53 DNS Query A google.com",
            "UDP 8.8.8.8:53 → 192.168.1.100:54321 DNS Response 142.250.185.78",
        ]
        
        try:
            for i, packet in enumerate(simulated_packets):
                time.sleep(0.5)
                timestamp = time.strftime("%H:%M:%S")
                print(f"[{timestamp}] {packet}")
        except KeyboardInterrupt:
            print("\n⏹️ تم الإيقاف")


# تشغيل
monitor = NetworkMonitor()
monitor.generate_traffic_report()
# monitor.show_live_traffic()
اختبر فهمك