Kodax

CTF - تحديات الاختراق — الاختراق الأخلاقي

CTF - Capture The Flag

ما هو CTF؟

مسابقات أمنية لحل تحديات واستخراج "flags".

أنواع CTF

Jeopardy Style

- فئات متعددة

- كل تحدٍ له نقاط

- حل = flag = نقاط

Attack-Defense

- فريقان أو أكثر

- دافع واهجم في نفس الوقت

- أصعب وأكثر واقعية

King of the Hill

- السيطرة على خادم

- البقاء مسيطراً أطول وقت

فئات التحديات

Web

- SQL Injection

- XSS

- Authentication bypass

- SSRF

Crypto

- فك تشفير

- كسر خوارزميات

- تحليل تشفيري

Pwn (Binary Exploitation)

- Buffer overflow

- Format string

- ROP chains

Reverse Engineering

- تحليل برامج

- فهم كود بدون مصدر

- كسر حماية

Forensics

- تحليل ملفات

- استرجاع بيانات

- تحليل ذاكرة

Misc

- متنوعة

- تفكير خارج الصندوق

منصات CTF

للمبتدئين

- PicoCTF: الأفضل للبداية

- TryHackMe: مسارات تعليمية

- HackTheBox Starting Point: تحديات سهلة

للمتوسطين

- HackTheBox: آلات وتحديات

- VulnHub: آلات محلية

- PortSwigger: ثغرات الويب

للمتقدمين

- CTFtime: مسابقات عالمية

- Pwnable.kr/tw: Binary exploitation

- Root-Me: تنوع كبير

# أدوات CTF الأساسية
import base64
import binascii
import hashlib
from itertools import cycle

class CTFToolkit:
    """
    أدوات أساسية لحل تحديات CTF
    """
    
    # ===== Encoding/Decoding =====
    
    @staticmethod
    def base64_decode(encoded):
        """فك Base64"""
        try:
            return base64.b64decode(encoded).decode()
        except:
            return base64.b64decode(encoded)
    
    @staticmethod
    def base64_encode(data):
        """ترميز Base64"""
        if isinstance(data, str):
            data = data.encode()
        return base64.b64encode(data).decode()
    
    @staticmethod
    def hex_to_ascii(hex_string):
        """تحويل Hex لنص"""
        hex_string = hex_string.replace(" ", "").replace("0x", "")
        return binascii.unhexlify(hex_string).decode()
    
    @staticmethod
    def ascii_to_hex(text):
        """تحويل نص لـ Hex"""
        return binascii.hexlify(text.encode()).decode()
    
    @staticmethod
    def binary_to_ascii(binary):
        """تحويل Binary لنص"""
        binary = binary.replace(" ", "")
        return ''.join(chr(int(binary[i:i+8], 2)) for i in range(0, len(binary), 8))
    
    # ===== Crypto =====
    
    @staticmethod
    def caesar_decrypt(ciphertext, shift=None):
        """فك Caesar cipher"""
        results = []
        
        shifts = [shift] if shift else range(26)
        
        for s in shifts:
            decrypted = ""
            for char in ciphertext:
                if char.isalpha():
                    ascii_offset = ord('A') if char.isupper() else ord('a')
                    decrypted += chr((ord(char) - ascii_offset - s) % 26 + ascii_offset)
                else:
                    decrypted += char
            results.append((s, decrypted))
        
        return results
    
    @staticmethod
    def xor_decrypt(ciphertext, key):
        """فك XOR"""
        if isinstance(ciphertext, str):
            ciphertext = ciphertext.encode()
        if isinstance(key, str):
            key = key.encode()
        
        return bytes([c ^ k for c, k in zip(ciphertext, cycle(key))])
    
    @staticmethod
    def rot13(text):
        """ROT13"""
        result = ""
        for char in text:
            if char.isalpha():
                ascii_offset = ord('A') if char.isupper() else ord('a')
                result += chr((ord(char) - ascii_offset + 13) % 26 + ascii_offset)
            else:
                result += char
        return result
    
    # ===== Hashing =====
    
    @staticmethod
    def hash_identify(hash_value):
        """تحديد نوع الهاش"""
        length = len(hash_value)
        
        hash_types = {
            32: ["MD5", "NTLM"],
            40: ["SHA-1"],
            64: ["SHA-256"],
            128: ["SHA-512"],
        }
        
        return hash_types.get(length, ["Unknown"])
    
    @staticmethod
    def hash_text(text, algorithm='md5'):
        """حساب هاش"""
        algorithms = {
            'md5': hashlib.md5,
            'sha1': hashlib.sha1,
            'sha256': hashlib.sha256,
            'sha512': hashlib.sha512,
        }
        
        hasher = algorithms.get(algorithm, hashlib.md5)
        return hasher(text.encode()).hexdigest()
    
    # ===== String Analysis =====
    
    @staticmethod
    def find_flag(text, pattern="flag{"):
        """البحث عن flag"""
        import re
        patterns = [
            r'flag\{[^}]+\}',
            r'FLAG\{[^}]+\}',
            r'ctf\{[^}]+\}',
            r'CTF\{[^}]+\}',
            r'picoCTF\{[^}]+\}',
        ]
        
        for p in patterns:
            matches = re.findall(p, text, re.IGNORECASE)
            if matches:
                return matches
        return None
    
    @staticmethod
    def extract_strings(data, min_length=4):
        """استخراج النصوص من بيانات"""
        import re
        strings = re.findall(b'[\x20-\x7e]{%d,}' % min_length, data)
        return [s.decode() for s in strings]


# ===== أمثلة على حل تحديات =====
toolkit = CTFToolkit()

print("🎯 CTF Toolkit Demo")
print("=" * 50)

# Base64
print("\n📝 Base64:")
encoded = "ZmxhZ3t0aGlzX2lzX2FfZmxhZ30="
print(f"  Encoded: {encoded}")
print(f"  Decoded: {toolkit.base64_decode(encoded)}")

# Hex
print("\n📝 Hex:")
hex_str = "666c61677b6865785f69735f66756e7d"
print(f"  Hex: {hex_str}")
print(f"  ASCII: {toolkit.hex_to_ascii(hex_str)}")

# Caesar
print("\n📝 Caesar Cipher:")
cipher = "msj{fljxfw_nx_jfxd}"
print(f"  Cipher: {cipher}")
results = toolkit.caesar_decrypt(cipher)
for shift, plain in results[:5]:
    if "flag" in plain.lower():
        print(f"  ✅ Shift {shift}: {plain}")
        break

# ROT13
print("\n📝 ROT13:")
rot = "synt{ebg13_vf_fvzcyr}"
print(f"  ROT13: {rot}")
print(f"  Plain: {toolkit.rot13(rot)}")

# Hash identification
print("\n📝 Hash Identification:")
hashes = [
    "5d41402abc4b2a76b9719d911017c592",
    "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
    "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
]
for h in hashes:
    print(f"  {h[:20]}... → {toolkit.hash_identify(h)}")

# Finding flags
print("\n📝 Flag Extraction:")
text = "The answer is hidden here: flag{y0u_f0und_m3} somewhere in this text."
flags = toolkit.find_flag(text)
print(f"  Found: {flags}")
اختبر فهمك