# ServerManager

Web-based Linux Server Management Platform — manage multiple servers via SSH from a web interface.

## Features

- **SSH Management** — Connect to Linux servers via SSH (password or key-based auth)
- **Web Terminal** — Interactive terminal in the browser with command history
- **Dashboard** — Real-time CPU, RAM, Disk, Load Average monitoring
- **Server Admin** — Reboot, shutdown, restart services, view processes, system logs
- **Multi-Role Auth** — Super Admin, Administrator, Operator roles
- **AES-256 Encryption** — SSH credentials encrypted with master key stored outside DB
- **Audit Trail** — Complete logging of all actions with credential access tracking
- **REST API** — Full API with Bearer token authentication
- **Responsive UI** — Dark theme, collapsible sidebar, professional dashboard design

## Tech Stack

| Layer       | Technology                        |
|------------|-----------------------------------|
| Backend     | PHP 8.3, MVC Architecture         |
| Database    | MySQL 8 / MariaDB 10.5+           |
| SSH Library | phpseclib 3.0                     |
| Frontend    | HTML5, CSS3, JavaScript ES6+      |
| Auth        | Argon2id password hashing         |
| Encryption  | AES-256-CBC (OpenSSL)             |
| Dependencies| Composer, vlucas/phpdotenv        |

## System Requirements

- Ubuntu Server 22.04+ or 24.04+
- PHP 8.3+ with extensions: pdo_mysql, openssl, mbstring, json, curl, zip, gd
- MySQL 8.0+ or MariaDB 10.5+
- Nginx (recommended) or Apache
- Composer 2.x
- Root/sudo access for initial setup

## Quick Install (Ubuntu)

```bash
# Clone the repository
git clone https://github.com/your-org/servermanager.git /var/www/servermanager
cd /var/www/servermanager

# Run the installer (requires sudo)
sudo bash install.sh
```

## Manual Installation

### 1. System Dependencies

```bash
sudo apt update
sudo apt install -y nginx mysql-server php8.3 php8.3-fpm \
    php8.3-mysql php8.3-mbstring php8.3-xml php8.3-curl \
    php8.3-zip php8.3-gd php8.3-openssl composer unzip git
```

### 2. Database Setup

```bash
sudo mysql -e "CREATE DATABASE servermanager CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
sudo mysql -e "CREATE USER 'servermanager'@'localhost' IDENTIFIED BY 'strong_password';"
sudo mysql -e "GRANT ALL PRIVILEGES ON servermanager.* TO 'servermanager'@'localhost';"
sudo mysql servermanager < database/migrations/001_initial_schema.sql
```

### 3. Application Setup

```bash
cd /var/www/servermanager

# Copy and configure environment
cp .env.example .env
nano .env  # Edit database credentials and URL

# Generate master encryption key
sudo php bin/generate-key.php
# Or manually: openssl rand -hex 32 | sudo tee /etc/servermanager/master.key
sudo chmod 600 /etc/servermanager/master.key
sudo chown www-data:www-data /etc/servermanager/master.key

# Install dependencies
composer install --no-dev --optimize-autoloader

# Set permissions
sudo chown -R www-data:www-data .
sudo chmod -R 755 .
sudo mkdir -p logs storage/ssh_keys
sudo chmod -R 770 logs storage
sudo chmod 700 storage/ssh_keys
```

### 4. Nginx Configuration

```nginx
server {
    listen 80;
    server_name your-domain.com;
    root /var/www/servermanager/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\. { deny all; }
    location ~* \.(env|log|json|lock|key)$ { deny all; }
}
```

### 5. Cron Job for Monitoring

```bash
# Add to crontab (runs every minute)
sudo crontab -u www-data -e

# Add line:
* * * * * php /var/www/servermanager/bin/monitor.php >> /var/www/servermanager/logs/cron.log 2>&1
```

### 6. Start Services

```bash
sudo systemctl restart php8.3-fpm nginx mysql
```

## Default Credentials

| Field    | Value     |
|----------|-----------|
| Username | `admin`   |
| Password | `Admin@123` |

**Change this password immediately after first login!**

## Security Architecture

### Credential Encryption
- SSH passwords and private keys are encrypted with **AES-256-CBC**
- Master encryption key stored **outside the database** at `/etc/servermanager/master.key`
- If DB is compromised, SSH credentials remain safe without the master key
- Every credential access is logged in the audit trail

### Audit Logging
All credential accesses are logged:
- SSH connection tests
- Terminal command execution
- System info/process/log viewing
- Server actions (reboot, shutdown, service restart)

### Other Security Measures
- Password hashing with **Argon2id**
- CSRF protection on all forms
- XSS prevention (output escaping)
- Rate limiting on login endpoints
- Secure session configuration (HTTP Only, SameSite)
- Input validation on all endpoints
- API authentication via Bearer tokens
- File access restrictions via Nginx

## Project Structure

```
ServerManager/
├── bin/
│   ├── monitor.php           # CLI: collect metrics
│   └── generate-key.php      # CLI: generate master key
├── config/
│   └── config.php            # App configuration
├── database/
│   └── migrations/
│       └── 001_initial_schema.sql
├── logs/                     # Application logs (runtime)
├── public/
│   ├── index.php             # Front controller
│   ├── .htaccess
│   └── assets/
│       ├── css/style.css
│       └── js/app.js
├── routes/
│   └── web.php               # Route definitions
├── src/
│   ├── Controllers/          # MVC Controllers
│   │   ├── AuthController.php
│   │   ├── DashboardController.php
│   │   ├── ServerController.php
│   │   ├── TerminalController.php
│   │   ├── AdminController.php
│   │   └── ApiController.php
│   ├── Core/                 # Framework core
│   │   ├── App.php           # Application bootstrap
│   │   ├── Database.php      # PDO wrapper (Singleton)
│   │   ├── Encryption.php    # AES-256 encryption
│   │   ├── Logger.php        # PSR-like logging
│   │   ├── Router.php        # HTTP router
│   │   ├── Security.php      # CSRF, XSS, password hashing
│   │   ├── Session.php       # Session management
│   │   ├── Validator.php     # Input validation
│   │   └── View.php          # Template engine
│   ├── Helpers/
│   │   └── functions.php     # Global helper functions
│   ├── Middleware/
│   │   ├── AuthMiddleware.php
│   │   ├── CSRFMiddleware.php
│   │   ├── RateLimitMiddleware.php
│   │   └── RoleMiddleware.php
│   ├── Models/
│   │   ├── User.php
│   │   ├── Server.php
│   │   └── CommandHistory.php
│   └── Services/
│       ├── SSHService.php    # SSH connection management
│       ├── MonitoringService.php
│       └── AuditService.php
├── storage/
│   └── ssh_keys/             # SSH key storage (restricted)
├── views/                    # Templates
│   ├── layouts/
│   │   ├── main.php
│   │   └── auth.php
│   ├── auth/
│   │   ├── login.php
│   │   └── profile.php
│   ├── dashboard/
│   │   └── index.php
│   ├── servers/
│   │   ├── index.php
│   │   ├── create.php
│   │   ├── edit.php
│   │   ├── show.php
│   │   ├── processes.php
│   │   ├── system_info.php
│   │   └── logs.php
│   ├── terminal/
│   │   └── index.php
│   ├── admin/
│   │   ├── users.php
│   │   ├── audit.php
│   │   └── security.php
│   └── errors/
│       └── 500.php
├── .env.example
├── .gitignore
├── composer.json
├── install.sh
└── README.md
```

## API Reference

### Authentication
All API requests require a Bearer token:
```
Authorization: Bearer YOUR_API_TOKEN
```

### Endpoints

| Method   | Endpoint                    | Description                |
|----------|-----------------------------|----------------------------|
| `GET`    | `/api/status`               | Application status + stats |
| `GET`    | `/api/servers`              | List all servers           |
| `POST`   | `/api/servers`              | Add a new server           |
| `GET`    | `/api/servers/:id`          | Server details + metrics   |
| `PUT`    | `/api/servers/:id`          | Update server              |
| `DELETE` | `/api/servers/:id`          | Delete server              |
| `GET`    | `/api/servers/:id/metrics`  | Historical metrics         |
| `POST`   | `/api/servers/:id/execute`  | Execute remote command     |
| `GET`    | `/api/users`                | List users (admin only)    |
| `GET`    | `/api/refresh-metrics`      | Refresh all metrics        |

### Example: Execute Command via API

```bash
curl -X POST https://your-domain.com/api/servers/1/execute \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"command": "uptime"}'
```

## Maintenance

### Logs
- Application: `logs/app-YYYY-MM-DD.log`
- Errors: `logs/error-YYYY-MM-DD.log`
- Cron: `logs/cron.log`

### Monitoring
The cron job runs every minute to collect metrics. Check:
```bash
sudo crontab -u www-data -l
tail -f /var/www/servermanager/logs/cron.log
```

### Backup
```bash
# Database
mysqldump servermanager > backup_$(date +%Y%m%d).sql

# Master key (CRITICAL!)
sudo cp /etc/servermanager/master.key /secure/backup/location/

# Application files
tar -czf servermanager_backup.tar.gz /var/www/servermanager
```

## HTTPS Setup

```bash
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com
```

### Auto-renewal
```bash
sudo crontab -e
# Add: 0 0 1 * * certbot renew --quiet
```

## Troubleshooting

### Cannot connect to servers
- Verify SSH credentials in server configuration
- Test connection from command line: `ssh user@host -p port`
- Check firewall rules on target server
- Verify the master encryption key is correct

### Blank page / 500 error
```bash
# Enable debug mode temporarily
sudo nano /var/www/servermanager/.env
# Set: APP_DEBUG=true

# Check logs
tail -f /var/www/servermanager/logs/error-*.log
```

### Database connection issues
```bash
# Verify MySQL is running
sudo systemctl status mysql

# Test connection
mysql -u servermanager -p servermanager -e "SELECT 1"
```

## License

MIT License. See LICENSE file for details.
