Add PhpMyAdmin access middleware and session check for user authentication

- Updated settings.py to include PhpMyAdminAccessMiddleware for enhanced access control.
- Modified phpmyadminsignin.php to check user session and redirect to the login page if not authenticated.
This commit is contained in:
Master3395
2025-09-15 01:39:21 +02:00
parent 1a82700f51
commit 1f3d5afe6a
8 changed files with 191 additions and 193 deletions

View File

@@ -0,0 +1,32 @@
# -*- coding: utf-8 -*-
"""
phpMyAdmin Access Control Middleware
This middleware checks if users are trying to access phpMyAdmin directly
without being logged into CyberPanel and redirects them to the login page.
"""
from django.shortcuts import redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
class PhpMyAdminAccessMiddleware:
"""
Middleware to control phpMyAdmin access and redirect unauthenticated users to login page.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Check if the request is for phpMyAdmin
if request.path.startswith('/phpmyadmin/'):
# Check if user is authenticated (has session)
if 'userID' not in request.session:
# Redirect to CyberPanel login page
login_url = '/base/'
return HttpResponseRedirect(login_url)
response = self.get_response(request)
return response

View File

@@ -87,7 +87,8 @@ MIDDLEWARE = [
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'CyberCP.secMiddleware.secMiddleware'
'CyberCP.secMiddleware.secMiddleware',
'CyberCP.phpmyadminMiddleware.PhpMyAdminAccessMiddleware'
]
ROOT_URLCONF = 'CyberCP.urls'

View File

@@ -0,0 +1,54 @@
#!/bin/bash
# CyberPanel phpMyAdmin Access Control Deployment Script
# This script implements redirect functionality for unauthenticated phpMyAdmin access
echo "=== CyberPanel phpMyAdmin Access Control Deployment ==="
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "Please run this script as root"
exit 1
fi
# Backup original phpMyAdmin index.php if it exists
if [ -f "/usr/local/CyberCP/public/phpmyadmin/index.php" ]; then
echo "Backing up original phpMyAdmin index.php..."
cp /usr/local/CyberCP/public/phpmyadmin/index.php /usr/local/CyberCP/public/phpmyadmin/index.php.backup.$(date +%Y%m%d_%H%M%S)
fi
# Deploy the redirect index.php
echo "Deploying phpMyAdmin access control..."
cp /usr/local/CyberCP/phpmyadmin_index_redirect.php /usr/local/CyberCP/public/phpmyadmin/index.php
# Deploy .htaccess for additional protection
echo "Deploying .htaccess protection..."
cp /usr/local/CyberCP/phpmyadmin_htaccess /usr/local/CyberCP/public/phpmyadmin/.htaccess
# Set proper permissions
echo "Setting permissions..."
chown lscpd:lscpd /usr/local/CyberCP/public/phpmyadmin/index.php
chmod 644 /usr/local/CyberCP/public/phpmyadmin/index.php
chown lscpd:lscpd /usr/local/CyberCP/public/phpmyadmin/.htaccess
chmod 644 /usr/local/CyberCP/public/phpmyadmin/.htaccess
# Restart LiteSpeed to ensure changes take effect
echo "Restarting LiteSpeed..."
systemctl restart lscpd
echo "=== Deployment Complete ==="
echo ""
echo "phpMyAdmin access control has been deployed successfully!"
echo ""
echo "What this does:"
echo "- Users trying to access phpMyAdmin directly without being logged into CyberPanel"
echo " will now be redirected to the CyberPanel login page (/base/)"
echo "- Authenticated users will continue to access phpMyAdmin normally"
echo ""
echo "To revert changes, restore the backup:"
echo "cp /usr/local/CyberCP/public/phpmyadmin/index.php.backup.* /usr/local/CyberCP/public/phpmyadmin/index.php"
echo ""
echo "Test the implementation by:"
echo "1. Opening an incognito/private browser window"
echo "2. Going to https://your-server:2087/phpmyadmin/"
echo "3. You should be redirected to the CyberPanel login page"

25
phpmyadmin_htaccess Normal file
View File

@@ -0,0 +1,25 @@
# CyberPanel phpMyAdmin Access Control
# Place this file as /usr/local/CyberCP/public/phpmyadmin/.htaccess
# Enable rewrite engine
RewriteEngine On
# Check if user is not authenticated and redirect to login
RewriteCond %{HTTP_COOKIE} !sessionid=
RewriteRule ^(.*)$ /base/ [R=302,L]
# Additional security headers
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
# Prevent direct access to sensitive files
<Files "config.inc.php">
Order Allow,Deny
Deny from all
</Files>
<Files "*.log">
Order Allow,Deny
Deny from all
</Files>

View File

@@ -0,0 +1,22 @@
<?php
/**
* phpMyAdmin Access Control - Direct Access Redirect
*
* This file should be placed at /usr/local/CyberCP/public/phpmyadmin/index.php
* to replace the default phpMyAdmin index.php and redirect unauthenticated users
* to the CyberPanel login page.
*/
// Check if user is logged into CyberPanel
session_start();
if (!isset($_SESSION['userID'])) {
// Redirect to CyberPanel login page
header('Location: /base/');
exit();
}
// If user is authenticated, redirect to the actual phpMyAdmin interface
// through the proper CyberPanel route
header('Location: /dataBases/phpMyAdmin');
exit();
?>

View File

@@ -1,5 +1,12 @@
<?php
// Check if user is logged into CyberPanel
session_start();
if (!isset($_SESSION['userID'])) {
// Redirect to CyberPanel login page
header('Location: /base/');
exit();
}
define("PMA_SIGNON_INDEX", 1);

View File

@@ -0,0 +1,49 @@
#!/bin/bash
# CyberPanel phpMyAdmin Access Control Rollback Script
# This script reverts the phpMyAdmin access control changes
echo "=== CyberPanel phpMyAdmin Access Control Rollback ==="
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "Please run this script as root"
exit 1
fi
# Find the most recent backup
LATEST_BACKUP=$(ls -t /usr/local/CyberCP/public/phpmyadmin/index.php.backup.* 2>/dev/null | head -n1)
if [ -z "$LATEST_BACKUP" ]; then
echo "No backup found. Cannot rollback changes."
echo "You may need to reinstall phpMyAdmin or restore from your own backup."
exit 1
fi
echo "Found backup: $LATEST_BACKUP"
echo "Restoring original phpMyAdmin index.php..."
# Restore the original index.php
cp "$LATEST_BACKUP" /usr/local/CyberCP/public/phpmyadmin/index.php
# Remove the .htaccess file if it exists
if [ -f "/usr/local/CyberCP/public/phpmyadmin/.htaccess" ]; then
echo "Removing .htaccess file..."
rm /usr/local/CyberCP/public/phpmyadmin/.htaccess
fi
# Set proper permissions
echo "Setting permissions..."
chown lscpd:lscpd /usr/local/CyberCP/public/phpmyadmin/index.php
chmod 644 /usr/local/CyberCP/public/phpmyadmin/index.php
# Restart LiteSpeed to ensure changes take effect
echo "Restarting LiteSpeed..."
systemctl restart lscpd
echo "=== Rollback Complete ==="
echo ""
echo "phpMyAdmin access control has been reverted!"
echo "phpMyAdmin should now work as it did before the changes."
echo ""
echo "Backup file used: $LATEST_BACKUP"

View File

@@ -1,192 +0,0 @@
# CyberPanel Secure Installation Guide
## Overview
This document describes the secure installation process for CyberPanel that eliminates hardcoded passwords and implements environment-based configuration.
## Security Improvements
### ✅ **Fixed Security Vulnerabilities**
1. **Hardcoded Database Passwords** - Now generated securely during installation
2. **Hardcoded Django Secret Key** - Now generated using cryptographically secure random generation
3. **Environment Variables** - All sensitive configuration moved to `.env` file
4. **File Permissions** - `.env` file set to 600 (owner read/write only)
### 🔐 **Security Features**
- **Cryptographically Secure Passwords**: Uses Python's `secrets` module for password generation
- **Environment-based Configuration**: Sensitive data stored in `.env` file, not in code
- **Secure File Permissions**: Environment files protected with 600 permissions
- **Credential Backup**: Automatic backup of credentials for recovery
- **Fallback Security**: Maintains backward compatibility with fallback method
## Installation Process
### 1. **Automatic Secure Installation**
The installation script now automatically:
1. Generates secure random passwords for:
- MySQL root user
- CyberPanel database user
- Django secret key
2. Creates `.env` file with secure configuration:
```bash
# Generated during installation
SECRET_KEY=your_64_character_secure_key
DB_PASSWORD=your_24_character_secure_password
ROOT_DB_PASSWORD=your_24_character_secure_password
```
3. Creates `.env.backup` file for credential recovery
4. Sets secure file permissions (600) on all environment files
### 2. **Manual Installation** (if needed)
If you need to manually generate environment configuration:
```bash
cd /usr/local/CyberCP
python install/env_generator.py /usr/local/CyberCP
```
## File Structure
```
/usr/local/CyberCP/
├── .env # Main environment configuration (600 permissions)
├── .env.backup # Credential backup (600 permissions)
├── .env.template # Template for manual configuration
├── .gitignore # Prevents .env files from being committed
└── CyberCP/
└── settings.py # Updated to use environment variables
```
## Security Best Practices
### ✅ **Do's**
- Keep `.env` and `.env.backup` files secure
- Record credentials from `.env.backup` and delete the file after installation
- Use strong, unique passwords for production deployments
- Regularly rotate database passwords
- Monitor access to environment files
### ❌ **Don'ts**
- Never commit `.env` files to version control
- Don't share `.env` files via insecure channels
- Don't use default passwords in production
- Don't leave `.env.backup` files on the system after recording credentials
## Recovery
### **Lost Credentials**
If you lose your database credentials:
1. Check if `.env.backup` file exists:
```bash
sudo cat /usr/local/CyberCP/.env.backup
```
2. If backup doesn't exist, you'll need to reset MySQL passwords using MySQL recovery procedures
### **Regenerate Environment**
To regenerate environment configuration:
```bash
cd /usr/local/CyberCP
sudo python install/env_generator.py /usr/local/CyberCP
```
## Configuration Options
### **Environment Variables**
| Variable | Description | Default |
|----------|-------------|---------|
| `SECRET_KEY` | Django secret key | Generated (64 chars) |
| `DB_PASSWORD` | CyberPanel DB password | Generated (24 chars) |
| `ROOT_DB_PASSWORD` | MySQL root password | Generated (24 chars) |
| `DEBUG` | Debug mode | False |
| `ALLOWED_HOSTS` | Allowed hosts | localhost,127.0.0.1,hostname |
### **Custom Configuration**
To use custom passwords during installation:
```bash
python install/env_generator.py /usr/local/CyberCP "your_root_password" "your_db_password"
```
## Troubleshooting
### **Installation Fails**
If the new secure installation fails:
1. Check installation logs for error messages
2. The system will automatically fallback to the original installation method
3. Verify Python dependencies are installed:
```bash
pip install python-dotenv
```
### **Environment Loading Issues**
If Django can't load environment variables:
1. Ensure `.env` file exists and has correct permissions:
```bash
ls -la /usr/local/CyberCP/.env
# Should show: -rw------- 1 root root
```
2. Install python-dotenv if missing:
```bash
pip install python-dotenv
```
## Migration from Old Installation
### **Existing Installations**
For existing CyberPanel installations with hardcoded passwords:
1. **Backup current configuration**:
```bash
cp /usr/local/CyberCP/CyberCP/settings.py /usr/local/CyberCP/CyberCP/settings.py.backup
```
2. **Generate new environment configuration**:
```bash
cd /usr/local/CyberCP
python install/env_generator.py /usr/local/CyberCP
```
3. **Update settings.py** (already done in new installations):
- The settings.py file now supports environment variables
- It will fallback to hardcoded values if .env is not available
4. **Test the configuration**:
```bash
cd /usr/local/CyberCP
python manage.py check
```
## Support
For issues with the secure installation:
1. Check the installation logs
2. Verify file permissions
3. Ensure all dependencies are installed
4. Review the fallback installation method if needed
---
**Security Notice**: This installation method significantly improves security by eliminating hardcoded credentials. Always ensure proper file permissions and secure handling of environment files.