Security Token Integration for downloading API generated Backup Files

internex

Registered
Apr 26, 2012
4
0
51
cPanel Access Level
Root Administrator
Hello!

I generate full backups via API (Fileman::fullbackup). After that I list the backups via Backups::listfullbackups.
Everything works fine. Now I want to make the backup-tar-file downloadable.
I have the correct link:
https://{$hostname}:2083/download?file=backup-4.24.2012_15-06-11_account.tar.gz

But the problem is, our cPanel has Security Tokens activated (WHM -> Tweak Settings -> Security -> Security Tokens = ON)
When I deaktivate this setting, the download works fine.. without it - it failes. Unfortunately, for security reasons I am not allowed to deaktivate this setting...

I tried to solve it with cURL:
PHP:
	$whmusername = "account";
	$whmpassword = "****";
	$download_url = "https://".$hostname.":2083/download";
	
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
	curl_setopt($curl, CURLOPT_HEADER,0);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
	$header[0] = "Authorization: Basic " . base64_encode($whmusername.":".$whmpassword) . "\n\r";
	curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
	curl_setopt($curl, CURLOPT_URL, $download_url);
	curl_setopt($curl, CURLOPT_POSTFIELDS, "file=backup-4.24.2012_15-06-11_account.tar.gz");
	$result = curl_exec($curl);
	curl_close($curl);
But I just get "1" as feedback.. :-/
Can please someone give me a hint on how to do that?

Best regards, Harald
 

KostonConsulting

Well-Known Member
Verifed Vendor
Jun 17, 2010
255
1
68
San Francisco, CA
cPanel Access Level
Root Administrator
cPanel security tokens are essentially a session identifier for each unique customer session. In order to get a valid security token, you'll need to start a session by logging into cPanel remotely, and scraping for the security token. You can gather the security token like so:

Code:
   $download_url = "https://".$hostname.":2083/login/";

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($curl, CURLOPT_HEADER,0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($curl, CURLOPT_URL, $download_url);
    curl_setopt($curl, CURLOPT_POSTFIELDS, "user=$cpanelusername&pass=$whmpassword");
    $result = curl_exec($curl);
    curl_close($curl);

    $parts = explode( 'URL=', $result);
    $session_parts = explode( '/frontend/', $parts[1]);
    $token = $session_parts[0];
    echo $token;
Then, simply append it to your url:

Code:
$download_url = "https://".$hostname.":2083" . $token . "/download";
You should note that this is quick and dirty code and does not validate that there is a valid security token. You should check the $token variable to make sure it's a valid cPanel Security Token and set it to an empty string if it is not (to cover both servers that use tokens and ones that do not).