# Security Guide

EasyStream implements comprehensive security measures to protect against common web application vulnerabilities and ensure data integrity.

## Security Framework Overview

### Core Security Classes
- `VSecurity` - Input validation and sanitization
- `VAuth` - Authentication management
- `VRBAC` - Role-based access control
- `VIPTracker` - IP monitoring and blocking
- `VFingerprint` - Browser fingerprinting
- `VLogger` - Security event logging

## Input Validation and Sanitization

### Safe Input Handling
Always use the security wrapper functions for user input:

```php
// GET parameters
$id = get_param('id', 'int');
$email = get_param('email', 'email');
$filename = get_param('file', 'filename');

// POST parameters
$username = post_param('username', 'alphanum');
$content = post_param('content', 'text');
$url = post_param('url', 'url');
```

### Validation Types
- `int` - Integer values only
- `email` - Valid email addresses
- `url` - Valid URLs
- `alpha` - Alphabetic characters only
- `alphanum` - Alphanumeric characters
- `slug` - URL-safe slugs
- `filename` - Safe filenames
- `boolean` - Boolean values
- `text` - General text with XSS protection

### Custom Validation
```php
$input = VSecurity::validateInput($value, [
    'type' => 'custom',
    'pattern' => '/^[A-Z0-9]{6,12}$/',
    'min_length' => 6,
    'max_length' => 12
]);
```

## Output Escaping

### HTML Context
```php
echo secure_output($user_content);
```

### JavaScript Context
```php
echo '<script>var data = ' . secure_js($data) . ';</script>';
```

### URL Context
```php
echo '<a href="' . secure_url($url) . '">Link</a>';
```

## CSRF Protection

### Form Protection
```php
// In templates
{csrf_field('form_action')}

// In PHP
echo csrf_field('form_action');
```

### Validation
```php
if (!validate_csrf('form_action')) {
    throw new SecurityException('CSRF token validation failed');
}
```

## Authentication System

### Password Security
- Minimum 8 characters
- Bcrypt/Argon2 hashing
- Salt generation
- Password strength validation

```php
// Password hashing
$hash = VAuth::hashPassword($password);

// Password verification
if (VAuth::verifyPassword($password, $hash)) {
    // Login successful
}
```

### Session Management
- Secure session configuration
- Session regeneration on login
- Automatic session timeout
- Session hijacking protection

```php
// Start secure session
VAuth::startSecureSession();

// Regenerate session ID
VAuth::regenerateSession();

// Destroy session
VAuth::destroySession();
```

### Multi-Factor Authentication
```php
// Generate TOTP secret
$secret = VAuth::generateTOTPSecret();

// Verify TOTP code
if (VAuth::verifyTOTP($code, $secret)) {
    // MFA successful
}
```

## Authorization (RBAC)

### Role Management
```php
// Check user role
if (VRBAC::hasRole($userId, 'admin')) {
    // Admin access
}

// Check specific permission
if (VRBAC::hasPermission($userId, 'video.delete')) {
    // Can delete videos
}
```

### Resource-Level Permissions
```php
// Check resource access
if (VRBAC::canAccess($userId, 'video', $videoId, 'edit')) {
    // Can edit this specific video
}
```

## Rate Limiting

### Implementation
```php
// Check rate limit
if (!check_rate_limit('login_' . $ip, 5, 300)) {
    throw new SecurityException('Too many login attempts');
}

// Custom rate limiting
if (!VSecurity::checkRateLimit($key, $maxAttempts, $windowSeconds)) {
    // Rate limit exceeded
}
```

### Common Rate Limits
- Login attempts: 5 per 5 minutes
- API requests: 100 per hour
- File uploads: 10 per hour
- Password resets: 3 per hour

## File Upload Security

### Validation
```php
$result = validate_file_upload($_FILES['upload'], [
    'allowed_types' => ['image/jpeg', 'image/png', 'video/mp4'],
    'max_size' => 100 * 1024 * 1024, // 100MB
    'scan_content' => true
]);

if (!$result['valid']) {
    throw new SecurityException($result['error']);
}
```

### Security Measures
- MIME type validation
- File extension checking
- Content scanning
- Size limitations
- Virus scanning (if available)
- Secure file storage

## IP Tracking and Blocking

### Automatic Monitoring
```php
// Log user activity
VIPTracker::logActivity($ip, 'login_attempt', [
    'user_id' => $userId,
    'success' => $success
]);

// Check if IP is banned
if (VIPTracker::isBanned($ip)) {
    throw new SecurityException('IP address is banned');
}
```

### Manual IP Management
```php
// Ban IP address
VIPTracker::banIP($ip, 'Suspicious activity', 3600); // 1 hour

// Unban IP address
VIPTracker::unbanIP($ip);
```

## Browser Fingerprinting

### Fingerprint Generation
```php
// Generate fingerprint
$fingerprint = VFingerprint::generateFingerprint($_SERVER, $_POST);

// Track fingerprint
VFingerprint::trackFingerprint($fingerprint, $userId);
```

### Threat Detection
```php
// Check for suspicious fingerprints
if (VFingerprint::isBanned($fingerprint)) {
    // Handle banned fingerprint
}

// Detect fingerprint anomalies
$risk = VFingerprint::calculateRiskScore($fingerprint);
if ($risk > 0.8) {
    // High risk - additional verification required
}
```

## Security Headers

### HTTP Security Headers
```php
// Set in Caddy configuration or PHP
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
header('Content-Security-Policy: default-src \'self\'');
```

## Database Security

### Query Protection
```php
// Always use prepared statements
$result = $db->execute("SELECT * FROM users WHERE id = ?", [$userId]);

// Validate table/field names
$table = VDatabase::validateTableName($table);
$field = VDatabase::validateFieldName($field);
```

### Connection Security
- Use dedicated database user with minimal privileges
- Enable SSL/TLS for database connections
- Regular password rotation
- Connection pooling with limits

## Logging and Monitoring

### Security Event Logging
```php
// Log security events
VLogger::security('Failed login attempt', [
    'ip' => $ip,
    'username' => $username,
    'user_agent' => $_SERVER['HTTP_USER_AGENT']
]);

// Log admin actions
VLogger::admin('User deleted', [
    'admin_id' => $adminId,
    'target_user_id' => $userId
]);
```

### Log Analysis
- Monitor failed login attempts
- Track privilege escalation attempts
- Detect unusual access patterns
- Alert on security threshold breaches

## Vulnerability Prevention

### SQL Injection
- Use prepared statements exclusively
- Validate all input parameters
- Escape dynamic table/field names
- Limit database user privileges

### XSS Prevention
- Escape all output by default
- Use Content Security Policy
- Validate and sanitize rich text input
- Implement proper encoding for different contexts

### CSRF Protection
- Use anti-CSRF tokens for all forms
- Validate tokens on server side
- Implement SameSite cookie attributes
- Use double-submit cookie pattern for AJAX

### Directory Traversal
- Validate file paths
- Use whitelisted directories
- Implement proper access controls
- Sanitize filename inputs

## Security Testing

### Automated Testing
```bash
# Run security tests
./run-tests.sh --filter=Security

# Run specific security test
phpunit tests/Security/AuthSecurityTest.php
```

### Manual Testing Checklist
- [ ] Input validation on all forms
- [ ] CSRF protection on state-changing operations
- [ ] Authentication bypass attempts
- [ ] Authorization escalation tests
- [ ] File upload security validation
- [ ] SQL injection testing
- [ ] XSS payload testing

## Incident Response

### Security Incident Handling
1. **Detection** - Monitor logs and alerts
2. **Analysis** - Investigate the incident
3. **Containment** - Limit damage and exposure
4. **Eradication** - Remove the threat
5. **Recovery** - Restore normal operations
6. **Lessons Learned** - Improve security measures

### Emergency Procedures
```php
// Emergency IP ban
VIPTracker::emergencyBan($ip, 'Security incident');

// Disable user account
VAuth::disableUser($userId, 'Security breach');

// Clear all sessions
VAuth::clearAllSessions();
```

## Security Configuration

### Environment Variables
```bash
# Security settings
SECURITY_LEVEL=high
CSRF_PROTECTION=enabled
RATE_LIMITING=enabled
IP_TRACKING=enabled
FINGERPRINTING=enabled

# Session security
SESSION_SECURE=true
SESSION_HTTPONLY=true
SESSION_SAMESITE=strict
```

### Database Configuration
```sql
-- Create security-focused database user
CREATE USER 'easystream_app'@'%' IDENTIFIED BY 'strong_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON easystream.* TO 'easystream_app'@'%';
FLUSH PRIVILEGES;
```

## Compliance and Standards

### Security Standards
- OWASP Top 10 compliance
- PCI DSS requirements (if handling payments)
- GDPR data protection requirements
- SOC 2 Type II controls

### Regular Security Tasks
- [ ] Security dependency updates
- [ ] Vulnerability scanning
- [ ] Penetration testing
- [ ] Security code reviews
- [ ] Access control audits
- [ ] Log analysis and monitoring

## Security Resources

### Documentation
- [OWASP Security Guide](https://owasp.org/)
- [PHP Security Best Practices](https://www.php.net/manual/en/security.php)
- [Web Application Security Testing](https://owasp.org/www-project-web-security-testing-guide/)

### Tools
- Static analysis: PHPStan, Psalm
- Dependency scanning: Composer audit
- Vulnerability scanning: OWASP ZAP
- Code review: SonarQube