T.ME/BIBIL_0DAY
CasperSecurity


Server : Apache/2
System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64
User : gositeme ( 1004)
PHP Version : 8.2.29
Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname
Directory :  /home/gositeme/domains/soundstudiopro.com/private_html/includes/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/gositeme/domains/soundstudiopro.com/private_html/includes/security.php
<?php
/**
 * SECURITY INCLUDE FILE
 * Include this at the top of all PHP files for basic security
 */

// Prevent direct access
if (!defined('SECURE_ACCESS')) {
    define('SECURE_ACCESS', true);
}

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Set security headers (only if headers not already sent)
if (!headers_sent()) {
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: DENY');
    header('X-XSS-Protection: 1; mode=block');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
    header('Permissions-Policy: geolocation=(), microphone=(), camera=()');
    // Content Security Policy - Prevents XSS attacks
    header('Content-Security-Policy: default-src \'self\'; script-src \'self\' \'unsafe-inline\' https://js.stripe.com https://checkout.stripe.com; style-src \'self\' \'unsafe-inline\' https://fonts.googleapis.com; img-src \'self\' data: https:; font-src \'self\' data: https://fonts.gstatic.com; connect-src \'self\' https://api.stripe.com https://checkout.stripe.com; frame-src https://js.stripe.com https://checkout.stripe.com;');
}

// Basic input validation functions
function validateInteger($value, $min = null, $max = null) {
    $int = filter_var($value, FILTER_VALIDATE_INT);
    if ($int === false) return null;
    if ($min !== null && $int < $min) return null;
    if ($max !== null && $int > $max) return null;
    return $int;
}

function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : null;
}

function sanitizeString($string, $maxLength = 255) {
    $string = trim($string);
    $string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
    return strlen($string) > $maxLength ? substr($string, 0, $maxLength) : $string;
}

// CSRF Protection
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validateCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Session security
function secureSession() {
    // Set session timeout (24 hours - very long timeout for better user experience while maintaining security)
    $session_timeout = 86400; // 24 hours in seconds
    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $session_timeout)) {
        session_unset();
        session_destroy();
        header('Location: /auth/login.php?timeout=1');
        exit;
    }
    $_SESSION['last_activity'] = time();
    
    // Regenerate session ID periodically to prevent session fixation
    if (!isset($_SESSION['created'])) {
        $_SESSION['created'] = time();
    } else if (time() - $_SESSION['created'] > 3600) {
        // Regenerate session ID every hour
        session_regenerate_id(true);
        $_SESSION['created'] = time();
    }
}

// Helper function to update session activity - call this on all authenticated pages
function updateSessionActivity() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    $_SESSION['last_activity'] = time();
}

// Rate limiting
function checkRateLimit($action, $limit = 10, $window = 60) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $key = "rate_limit_{$action}_{$ip}";
    
    if (!isset($_SESSION[$key])) {
        $_SESSION[$key] = ['count' => 0, 'reset_time' => time() + $window];
    }
    
    if (time() > $_SESSION[$key]['reset_time']) {
        $_SESSION[$key] = ['count' => 0, 'reset_time' => time() + $window];
    }
    
    if ($_SESSION[$key]['count'] >= $limit) {
        return false;
    }
    
    $_SESSION[$key]['count']++;
    return true;
}

// Admin access validation
function validateAdminAccess() {
    // Check if user is logged in
    if (!isset($_SESSION['user_id'])) {
        error_log("Unauthorized admin access attempt from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        header('Location: /auth/login.php');
        exit;
    }
    
    // Check if user has admin privileges in session
    if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
        // Check database for admin status
        try {
            require_once __DIR__ . '/../config/database.php';
            $pdo = getDBConnection();
            $stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $user = $stmt->fetch();
            
            if ($user && $user['is_admin']) {
                // Update session with admin status
                $_SESSION['is_admin'] = 1;
            } else {
                // Make the first user admin if no admin exists
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM users WHERE is_admin = 1");
                $admin_count = $stmt->fetch()['count'];
                
                if ($admin_count == 0) {
                    // Make current user admin
                    $stmt = $pdo->prepare("UPDATE users SET is_admin = 1 WHERE id = ?");
                    $stmt->execute([$_SESSION['user_id']]);
                    $_SESSION['is_admin'] = 1;
                } else {
                    error_log("Unauthorized admin access attempt from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
                    header('Location: /auth/login.php');
                    exit;
                }
            }
        } catch (Exception $e) {
            error_log("Database error in validateAdminAccess: " . $e->getMessage());
            header('Location: /auth/login.php');
            exit;
        }
    }
}

// Premium subscription access validation
function validatePremiumAccess($required_plan = 'starter') {
    // Check if user is logged in
    if (!isset($_SESSION['user_id'])) {
        error_log("Unauthorized premium access attempt from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        header('Location: /auth/login.php');
        exit;
    }
    
    // Get user's current plan from session or database
    $user_plan = $_SESSION['plan'] ?? 'free';
    
    // Define plan hierarchy (higher plans have access to lower plan features)
    $plan_hierarchy = [
        'free' => 0,
        'starter' => 1,
        'pro' => 2,
        'premium' => 3
    ];
    
    // Check if user's plan meets the required plan level
    $user_level = $plan_hierarchy[$user_plan] ?? 0;
    $required_level = $plan_hierarchy[$required_plan] ?? 0;
    
    if ($user_level < $required_level) {
        error_log("Premium access denied for user ID: " . $_SESSION['user_id'] . " (Plan: $user_plan, Required: $required_plan)");
        
        // Redirect to upgrade page with appropriate message
        $upgrade_url = '/account_settings.php?tab=subscription&upgrade=required';
        header('Location: ' . $upgrade_url);
        exit;
    }
    
    return true;
}

// File upload validation - Enhanced security
function validateFileUpload($file, $allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp'], $maxSize = 5242880) {
    // Check if file was uploaded
    if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
        return ['valid' => false, 'error' => 'Invalid file upload'];
    }
    
    // Check upload error
    if (isset($file['error']) && $file['error'] !== UPLOAD_ERR_OK) {
        $error_messages = [
            UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize directive',
            UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE directive',
            UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
            UPLOAD_ERR_NO_FILE => 'No file was uploaded',
            UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
            UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
            UPLOAD_ERR_EXTENSION => 'File upload stopped by extension'
        ];
        return ['valid' => false, 'error' => $error_messages[$file['error']] ?? 'Unknown upload error'];
    }
    
    // Check file size
    if ($file['size'] > $maxSize) {
        return ['valid' => false, 'error' => 'File size exceeds maximum allowed size'];
    }
    
    // Use finfo for MIME type detection (more secure than $_FILES['type'])
    if (!function_exists('finfo_open')) {
        return ['valid' => false, 'error' => 'File info extension not available'];
    }
    
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    // Map allowed types to MIME types
    $allowedMimes = [
        'image/jpeg' => ['jpg', 'jpeg'],
        'image/png' => ['png'],
        'image/gif' => ['gif'],
        'image/webp' => ['webp'],
        'audio/mpeg' => ['mp3'],
        'audio/wav' => ['wav'],
        'audio/mp4' => ['m4a'],
        'audio/ogg' => ['ogg']
    ];
    
    // Check if MIME type is allowed
    if (!isset($allowedMimes[$mimeType])) {
        return ['valid' => false, 'error' => 'Invalid file type. MIME type: ' . $mimeType];
    }
    
    // Validate extension matches MIME type
    $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($extension, $allowedMimes[$mimeType])) {
        return ['valid' => false, 'error' => 'File extension does not match file type'];
    }
    
    // Check if extension is in allowed types list
    if (!in_array($extension, $allowedTypes)) {
        return ['valid' => false, 'error' => 'File extension not allowed'];
    }
    
    // Sanitize filename - remove dangerous characters
    $originalFilename = pathinfo($file['name'], PATHINFO_FILENAME);
    $sanitizedFilename = preg_replace('/[^a-zA-Z0-9._-]/', '', $originalFilename);
    if (empty($sanitizedFilename)) {
        $sanitizedFilename = 'file_' . time();
    }
    $finalFilename = $sanitizedFilename . '.' . $extension;
    
    return [
        'valid' => true,
        'mime' => $mimeType,
        'extension' => $extension,
        'filename' => $finalFilename,
        'size' => $file['size']
    ];
}

// Secure error handling
function secureErrorHandler($errno, $errstr, $errfile, $errline) {
    error_log("Error [$errno]: $errstr in $errfile on line $errline");
    
    if (defined('DEBUG_MODE') && DEBUG_MODE) {
        return false;
    }
    
    return true;
}

// Initialize security
secureSession();
set_error_handler('secureErrorHandler');

CasperSecurity Mini