Kodax

تقسيم الشبكات (Network Segmentation) — أمن الشبكات

Network Segmentation

ما هو؟

تقسيم الشبكة الكبيرة لشبكات أصغر معزولة.

لماذا؟

- الأمان: المهاجم لا يصل لكل شيء

- الأداء: تقليل الـ Broadcast

- الامتثال: فصل البيانات الحساسة

- الإدارة: سهولة التحكم

طرق التقسيم

VLANs (Virtual LANs)

VLAN 10: الإدارة
VLAN 20: المحاسبة
VLAN 30: المطورين
VLAN 40: الضيوف

Subnets

192.168.10.0/24 - الإدارة
192.168.20.0/24 - المحاسبة
192.168.30.0/24 - المطورين
192.168.40.0/24 - الضيوف

Micro-segmentation

- تقسيم دقيق جداً

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

- Zero Trust

أفضل الممارسات

1. فصل حسب الوظيفة

- المستخدمين

- الخوادم

- الأجهزة IoT

- الضيوف

2. فصل حسب الحساسية

- البيانات السرية

- البيانات العادية

- البيانات العامة

3. Least Privilege

- السماح بما هو ضروري فقط

- Default Deny

مثال عملي

┌─────────────────────────────────────────────┐
│              Core Switch                     │
├─────────────┬─────────────┬─────────────────┤
│   VLAN 10   │   VLAN 20   │    VLAN 30      │
│   Servers   │    Users    │    Guests       │
│             │             │                 │
│ 10.0.10.0/24│ 10.0.20.0/24│  10.0.30.0/24  │
└─────────────┴─────────────┴─────────────────┘

القواعد:
- VLAN 20 → VLAN 10: فقط HTTP/HTTPS
- VLAN 30 → الإنترنت فقط
- VLAN 30 ✗ VLAN 10, 20
# محاكاة تقسيم الشبكات
from dataclasses import dataclass
from typing import List, Dict

@dataclass
class VLAN:
    id: int
    name: str
    subnet: str
    security_level: int
    hosts: List[str]

class NetworkSegmentation:
    """
    محاكاة تقسيم الشبكات
    """
    
    def __init__(self):
        self.vlans: Dict[int, VLAN] = {}
        self.acl_rules = []
    
    def create_vlan(self, vlan_id, name, subnet, security_level):
        """إنشاء VLAN"""
        self.vlans[vlan_id] = VLAN(
            id=vlan_id,
            name=name,
            subnet=subnet,
            security_level=security_level,
            hosts=[]
        )
        print(f"✅ VLAN {vlan_id} ({name}) created: {subnet}")
    
    def add_host(self, vlan_id, hostname, ip):
        """إضافة جهاز لـ VLAN"""
        if vlan_id in self.vlans:
            self.vlans[vlan_id].hosts.append({"name": hostname, "ip": ip})
            print(f"  📦 {hostname} ({ip}) → VLAN {vlan_id}")
    
    def add_acl(self, src_vlan, dst_vlan, ports, action="ALLOW"):
        """إضافة قاعدة ACL"""
        self.acl_rules.append({
            "src": src_vlan,
            "dst": dst_vlan,
            "ports": ports,
            "action": action
        })
        
        ports_str = ", ".join(map(str, ports)) if ports else "ALL"
        emoji = "✅" if action == "ALLOW" else "❌"
        print(f"{emoji} ACL: VLAN{src_vlan} → VLAN{dst_vlan} [{ports_str}]")
    
    def check_communication(self, src_vlan, dst_vlan, port):
        """فحص إمكانية الاتصال"""
        print(f"\n🔍 Check: VLAN{src_vlan} → VLAN{dst_vlan}:{port}")
        
        # نفس الـ VLAN
        if src_vlan == dst_vlan:
            print("  ✅ Same VLAN - Allowed")
            return True
        
        # فحص ACL
        for rule in self.acl_rules:
            if rule["src"] == src_vlan and rule["dst"] == dst_vlan:
                if rule["action"] == "DENY":
                    print(f"  ❌ Blocked by ACL")
                    return False
                if port in rule["ports"] or not rule["ports"]:
                    print(f"  ✅ Allowed by ACL")
                    return True
        
        print("  ❌ Default Deny")
        return False
    
    def visualize(self):
        """عرض الشبكة"""
        print("\n" + "=" * 60)
        print("  🌐 Network Segmentation Map")
        print("=" * 60)
        
        # ترتيب حسب Security Level
        sorted_vlans = sorted(self.vlans.values(), 
                             key=lambda v: v.security_level, 
                             reverse=True)
        
        for vlan in sorted_vlans:
            sec_bar = "🔒" * (vlan.security_level // 20)
            print(f"""
┌{'─' * 50}┐
│ VLAN {vlan.id}: {vlan.name:<20} Security: {sec_bar:<10}
│ Subnet: {vlan.subnet:<40}
│ Hosts:""")
            for host in vlan.hosts:
                print(f"│   • {host['name']:<15} {host['ip']}")
            print(f"└{'─' * 50}┘")
    
    def security_assessment(self):
        """تقييم أمني"""
        print("\n🔒 Security Assessment")
        print("=" * 60)
        
        findings = []
        
        # فحص VLANs بدون ACL
        vlan_ids = set(self.vlans.keys())
        protected_vlans = set()
        
        for rule in self.acl_rules:
            protected_vlans.add(rule["dst"])
        
        unprotected = vlan_ids - protected_vlans
        if unprotected:
            for v in unprotected:
                findings.append(f"⚠️ VLAN {v} ({self.vlans[v].name}) has no inbound ACLs")
        
        # فحص Guest VLAN
        for vlan in self.vlans.values():
            if "guest" in vlan.name.lower():
                # هل Guest معزول؟
                can_reach_internal = False
                for rule in self.acl_rules:
                    if rule["src"] == vlan.id and rule["action"] == "ALLOW":
                        if self.vlans[rule["dst"]].security_level > 50:
                            can_reach_internal = True
                            findings.append(
                                f"🔴 Guest VLAN can reach high-security VLAN {rule['dst']}"
                            )
                
                if not can_reach_internal:
                    print(f"  ✅ Guest VLAN {vlan.id} properly isolated")
        
        if findings:
            print("\n  Issues Found:")
            for f in findings:
                print(f"    {f}")
        else:
            print("\n  ✅ No major issues found")
        
        return findings
    
    def generate_config(self):
        """توليد Config تقريبي"""
        print("\n📝 Sample Switch Configuration")
        print("=" * 60)
        
        config = []
        config.append("! VLAN Configuration")
        
        for vlan in self.vlans.values():
            config.append(f"vlan {vlan.id}")
            config.append(f"  name {vlan.name}")
        
        config.append("")
        config.append("! ACL Configuration")
        
        for i, rule in enumerate(self.acl_rules, 1):
            action = "permit" if rule["action"] == "ALLOW" else "deny"
            ports = ",".join(map(str, rule["ports"])) if rule["ports"] else "any"
            config.append(
                f"access-list {i} {action} vlan{rule['src']} vlan{rule['dst']} eq {ports}"
            )
        
        print("\n".join(config))


# ===== تشغيل المحاكاة =====
net = NetworkSegmentation()

# إنشاء VLANs
print("📌 Creating VLANs...")
net.create_vlan(10, "Servers", "10.0.10.0/24", 100)
net.create_vlan(20, "Finance", "10.0.20.0/24", 80)
net.create_vlan(30, "Users", "10.0.30.0/24", 60)
net.create_vlan(40, "Guests", "10.0.40.0/24", 20)

# إضافة أجهزة
print("\n📦 Adding Hosts...")
net.add_host(10, "web-server", "10.0.10.10")
net.add_host(10, "db-server", "10.0.10.20")
net.add_host(20, "finance-pc1", "10.0.20.10")
net.add_host(30, "user-pc1", "10.0.30.10")
net.add_host(40, "guest-laptop", "10.0.40.10")

# إضافة ACLs
print("\n🔒 Adding ACL Rules...")
net.add_acl(30, 10, [80, 443])  # Users → Servers (Web only)
net.add_acl(20, 10, [80, 443, 3306])  # Finance → Servers (Web + DB)
net.add_acl(40, 10, [], "DENY")  # Guests ✗ Servers
net.add_acl(40, 20, [], "DENY")  # Guests ✗ Finance
net.add_acl(40, 30, [], "DENY")  # Guests ✗ Users

# عرض الشبكة
net.visualize()

# فحص الاتصالات
net.check_communication(30, 10, 80)   # User → Server:HTTP
net.check_communication(40, 10, 80)   # Guest → Server (blocked)
net.check_communication(20, 10, 3306) # Finance → DB

# تقييم أمني
net.security_assessment()
اختبر فهمك