Kodax

أساسيات الشبكات للأمن — أساسيات الأمن السيبراني

أساسيات الشبكات للأمن

نموذج OSI

7 طبقات للاتصال:

1. Physical (فيزيائية)

2. Data Link (ربط البيانات)

3. Network (الشبكة) - IP

4. Transport (النقل) - TCP/UDP

5. Session (الجلسة)

6. Presentation (العرض)

7. Application (التطبيق) - HTTP

بروتوكولات مهمة

TCP vs UDP

- TCP: موثوق، مرتب (HTTP, SSH)

- UDP: سريع، غير موثوق (DNS, VoIP)

المنافذ الشائعة

- 80: HTTP

- 443: HTTPS

- 22: SSH

- 21: FTP

- 3389: RDP

- 3306: MySQL

أدوات الفحص

- nmap: فحص المنافذ

- Wireshark: تحليل الحزم

- netstat: الاتصالات الحالية

import socket
import struct

class NetworkTools:
    """
    أدوات شبكية للأمن السيبراني
    """
    
    @staticmethod
    def port_scan(target, ports=[21, 22, 23, 25, 53, 80, 443, 3306, 3389, 8080]):
        """
        فحص المنافذ (Port Scanner بسيط)
        ⚠️ للاستخدام على أنظمتك فقط!
        """
        results = {
            "target": target,
            "open_ports": [],
            "closed_ports": []
        }
        
        port_services = {
            21: "FTP",
            22: "SSH",
            23: "Telnet",
            25: "SMTP",
            53: "DNS",
            80: "HTTP",
            443: "HTTPS",
            3306: "MySQL",
            3389: "RDP",
            8080: "HTTP-Proxy"
        }
        
        for port in ports:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            
            try:
                result = sock.connect_ex((target, port))
                if result == 0:
                    service = port_services.get(port, "Unknown")
                    results["open_ports"].append({
                        "port": port,
                        "service": service,
                        "status": "OPEN"
                    })
                else:
                    results["closed_ports"].append(port)
            except:
                pass
            finally:
                sock.close()
        
        return results
    
    @staticmethod
    def get_local_ip():
        """الحصول على IP المحلي"""
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except:
            return "127.0.0.1"
    
    @staticmethod
    def dns_lookup(domain):
        """استعلام DNS"""
        results = {
            "domain": domain,
            "records": {}
        }
        
        try:
            # A Record
            results["records"]["A"] = socket.gethostbyname(domain)
            
            # All records
            results["records"]["ALL"] = socket.gethostbyname_ex(domain)
            
        except socket.gaierror as e:
            results["error"] = str(e)
        
        return results
    
    @staticmethod
    def check_connection(host, port, timeout=5):
        """فحص اتصال TCP"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(timeout)
            result = sock.connect_ex((host, port))
            sock.close()
            
            return {
                "host": host,
                "port": port,
                "reachable": result == 0,
                "status": "متصل ✅" if result == 0 else "غير متصل ❌"
            }
        except Exception as e:
            return {
                "host": host,
                "port": port,
                "reachable": False,
                "error": str(e)
            }
    
    @staticmethod
    def analyze_packet_header(data):
        """
        تحليل رأس حزمة IP (للتعليم)
        """
        if len(data) < 20:
            return {"error": "البيانات قصيرة جداً"}
        
        # فك رأس IP
        version_ihl = data[0]
        version = version_ihl >> 4
        ihl = version_ihl & 0xF
        
        ttl = data[8]
        protocol = data[9]
        
        src_ip = ".".join(map(str, data[12:16]))
        dst_ip = ".".join(map(str, data[16:20]))
        
        protocols = {1: "ICMP", 6: "TCP", 17: "UDP"}
        
        return {
            "version": version,
            "header_length": ihl * 4,
            "ttl": ttl,
            "protocol": protocols.get(protocol, f"Unknown ({protocol})"),
            "source_ip": src_ip,
            "destination_ip": dst_ip
        }

# اختبار
tools = NetworkTools()

# IP المحلي
print(f"IP المحلي: {tools.get_local_ip()}")

# DNS lookup
dns = tools.dns_lookup("google.com")
print(f"\nDNS لـ google.com:")
print(f"  IP: {dns['records'].get('A', 'N/A')}")

# فحص اتصال
conn = tools.check_connection("google.com", 443)
print(f"\nفحص اتصال google.com:443")
print(f"  {conn['status']}")

# ⚠️ فحص المنافذ - للاستخدام على أنظمتك فقط!
# result = tools.port_scan("localhost")
# print(result)
اختبر فهمك