check for php-curl installed when cron_letsencrypt runs; format source
Signed-off-by: Michael Kaufmann (d00p) <d00p@froxlor.org>
This commit is contained in:
@@ -28,10 +28,13 @@
|
||||
// and modified to work without files and integrate in Froxlor
|
||||
class lescript
|
||||
{
|
||||
|
||||
public $license = 'https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf';
|
||||
|
||||
private $logger;
|
||||
|
||||
private $client;
|
||||
|
||||
private $accountKey;
|
||||
|
||||
public function __construct($logger)
|
||||
@@ -62,22 +65,23 @@ class lescript
|
||||
$upd_stmt = Database::prepare("
|
||||
UPDATE `" . TABLE_PANEL_CUSTOMERS . "` SET `lepublickey` = :public, `leprivatekey` = :private WHERE `customerid` = :customerid;
|
||||
");
|
||||
Database::pexecute($upd_stmt, array('public' => $keys['public'], 'private' => $keys['private'], 'customerid' => $certrow['customerid']));
|
||||
Database::pexecute($upd_stmt, array(
|
||||
'public' => $keys['public'],
|
||||
'private' => $keys['private'],
|
||||
'customerid' => $certrow['customerid']
|
||||
));
|
||||
}
|
||||
$this->accountKey = $keys['private'];
|
||||
$this->postNewReg();
|
||||
$this->log('New account certificate registered');
|
||||
|
||||
} else {
|
||||
|
||||
$this->log('Account already registered. Continuing.');
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public function signDomains(array $domains, $domainkey = null, $csr = null)
|
||||
{
|
||||
|
||||
if (! $this->accountKey) {
|
||||
throw new \RuntimeException("Account not initiated");
|
||||
}
|
||||
@@ -97,10 +101,13 @@ class lescript
|
||||
|
||||
$this->log("Requesting challenge for $domain");
|
||||
|
||||
$response = $this->signedRequest(
|
||||
"/acme/new-authz",
|
||||
array("resource" => "new-authz", "identifier" => array("type" => "dns", "value" => $domain))
|
||||
);
|
||||
$response = $this->signedRequest("/acme/new-authz", array(
|
||||
"resource" => "new-authz",
|
||||
"identifier" => array(
|
||||
"type" => "dns",
|
||||
"value" => $domain
|
||||
)
|
||||
));
|
||||
|
||||
// if response is not an array but a string, it's most likely a server-error, e.g.
|
||||
// <HTML><HEAD><TITLE>Error</TITLE></HEAD><BODY>An error occurred while processing your request.
|
||||
@@ -114,13 +121,15 @@ class lescript
|
||||
}
|
||||
|
||||
// choose http-01 challenge only
|
||||
$challenge = array_reduce($response['challenges'], function($v, $w) { return $v ? $v : ($w['type'] == 'http-01' ? $w : false); });
|
||||
if(!$challenge) throw new RuntimeException("HTTP Challenge for $domain is not available. Whole response: ".json_encode($response));
|
||||
$challenge = array_reduce($response['challenges'], function ($v, $w) {
|
||||
return $v ? $v : ($w['type'] == 'http-01' ? $w : false);
|
||||
});
|
||||
if (! $challenge)
|
||||
throw new RuntimeException("HTTP Challenge for $domain is not available. Whole response: " . json_encode($response));
|
||||
|
||||
$this->log("Got challenge token for $domain");
|
||||
$location = $this->client->getLastLocation();
|
||||
|
||||
|
||||
// 2. saving authentication token for web verification
|
||||
// ---------------------------------------------------
|
||||
|
||||
@@ -136,8 +145,8 @@ class lescript
|
||||
"e" => Base64UrlSafeEncoder::encode($accountKeyDetails["rsa"]["e"]),
|
||||
"kty" => "RSA",
|
||||
"n" => Base64UrlSafeEncoder::encode($accountKeyDetails["rsa"]["n"])
|
||||
|
||||
);
|
||||
)
|
||||
;
|
||||
$payload = $challenge['token'] . '.' . Base64UrlSafeEncoder::encode(hash('sha256', json_encode($header), true));
|
||||
|
||||
file_put_contents($tokenPath, $payload);
|
||||
@@ -165,15 +174,12 @@ class lescript
|
||||
$this->log("Sending request to challenge");
|
||||
|
||||
// send request to challenge
|
||||
$result = $this->signedRequest(
|
||||
$challenge['uri'],
|
||||
array(
|
||||
$result = $this->signedRequest($challenge['uri'], array(
|
||||
"resource" => "challenge",
|
||||
"type" => "http-01",
|
||||
"keyAuthorization" => $payload,
|
||||
"token" => $challenge['token']
|
||||
)
|
||||
);
|
||||
));
|
||||
|
||||
// waiting loop
|
||||
// we wait for a maximum of 30 seconds to avoid endless loops
|
||||
@@ -192,7 +198,6 @@ class lescript
|
||||
}
|
||||
|
||||
$result = $this->client->get($location);
|
||||
|
||||
} while (! $ended && $count < 30);
|
||||
|
||||
$this->log("Verification ended with status: ${result['status']}");
|
||||
@@ -218,10 +223,10 @@ class lescript
|
||||
}
|
||||
|
||||
// request certificates creation
|
||||
$result = $this->signedRequest(
|
||||
"/acme/new-cert",
|
||||
array('resource' => 'new-cert', 'csr' => $csr)
|
||||
);
|
||||
$result = $this->signedRequest("/acme/new-cert", array(
|
||||
'resource' => 'new-cert',
|
||||
'csr' => $csr
|
||||
));
|
||||
if ($this->client->getLastCode() !== 201) {
|
||||
throw new \RuntimeException("Invalid response code: " . $this->client->getLastCode() . ", " . json_encode($result));
|
||||
}
|
||||
@@ -238,13 +243,12 @@ class lescript
|
||||
|
||||
$this->log("Certificate generation pending, sleeping 1s");
|
||||
sleep(1);
|
||||
|
||||
} else if ($this->client->getLastCode() == 200) {
|
||||
} else
|
||||
if ($this->client->getLastCode() == 200) {
|
||||
|
||||
$this->log("Got certificate! YAY!");
|
||||
$certificates[] = $this->parsePemFromBody($result);
|
||||
|
||||
|
||||
foreach ($this->client->getLastLinks() as $link) {
|
||||
$this->log("Requesting chained cert at $link");
|
||||
$result = $this->client->get($link);
|
||||
@@ -255,18 +259,24 @@ class lescript
|
||||
} else {
|
||||
|
||||
throw new \RuntimeException("Can't get certificate: HTTP code " . $this->client->getLastCode());
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if(empty($certificates)) throw new \RuntimeException('No certificates generated');
|
||||
if (empty($certificates))
|
||||
throw new \RuntimeException('No certificates generated');
|
||||
|
||||
$fullchain = implode("\n", $certificates);
|
||||
$crt = array_shift($certificates);
|
||||
$chain = implode("\n", $certificates);
|
||||
|
||||
$this->log("Done, returning new certificates and key");
|
||||
return array('fullchain' => $fullchain, 'crt' => $crt, 'chain' => $chain, 'key' => $domainkey, 'csr' => $csr);
|
||||
return array(
|
||||
'fullchain' => $fullchain,
|
||||
'crt' => $crt,
|
||||
'chain' => $chain,
|
||||
'key' => $domainkey,
|
||||
'csr' => $csr
|
||||
);
|
||||
}
|
||||
|
||||
private function parsePemFromBody($body)
|
||||
@@ -279,23 +289,24 @@ class lescript
|
||||
{
|
||||
$this->log('Sending registration to letsencrypt server');
|
||||
|
||||
return $this->signedRequest(
|
||||
'/acme/new-reg',
|
||||
array('resource' => 'new-reg', 'agreement' => $this->license)
|
||||
);
|
||||
return $this->signedRequest('/acme/new-reg', array(
|
||||
'resource' => 'new-reg',
|
||||
'agreement' => $this->license
|
||||
));
|
||||
}
|
||||
|
||||
private function generateCSR($privateKey, array $domains)
|
||||
{
|
||||
$domain = reset($domains);
|
||||
$san = implode(",", array_map(function ($dns) { return "DNS:" . $dns; }, $domains));
|
||||
$san = implode(",", array_map(function ($dns) {
|
||||
return "DNS:" . $dns;
|
||||
}, $domains));
|
||||
$tmpConf = tmpfile();
|
||||
$tmpConfMeta = stream_get_meta_data($tmpConf);
|
||||
$tmpConfPath = $tmpConfMeta["uri"];
|
||||
|
||||
// workaround to get SAN working
|
||||
fwrite($tmpConf,
|
||||
'HOME = .
|
||||
fwrite($tmpConf, 'HOME = .
|
||||
RANDFILE = $ENV::HOME/.rnd
|
||||
[ req ]
|
||||
default_bits = ' . Settings::Get('system.letsencryptkeysize') . '
|
||||
@@ -309,21 +320,18 @@ basicConstraints = CA:FALSE
|
||||
subjectAltName = ' . $san . '
|
||||
keyUsage = nonRepudiation, digitalSignature, keyEncipherment');
|
||||
|
||||
$csr = openssl_csr_new(
|
||||
array(
|
||||
$csr = openssl_csr_new(array(
|
||||
"CN" => $domain,
|
||||
"ST" => Settings::Get('system.letsencryptstate'),
|
||||
"C" => Settings::Get('system.letsencryptcountrycode'),
|
||||
"O" => "Unknown",
|
||||
),
|
||||
$privateKey,
|
||||
array(
|
||||
"O" => "Unknown"
|
||||
), $privateKey, array(
|
||||
"config" => $tmpConfPath,
|
||||
"digest_alg" => "sha256"
|
||||
)
|
||||
);
|
||||
));
|
||||
|
||||
if (!$csr) throw new \RuntimeException("CSR couldn't be generated! ".openssl_error_string());
|
||||
if (! $csr)
|
||||
throw new \RuntimeException("CSR couldn't be generated! " . openssl_error_string());
|
||||
|
||||
openssl_csr_export($csr, $csr);
|
||||
fclose($tmpConf);
|
||||
@@ -337,7 +345,7 @@ keyUsage = nonRepudiation, digitalSignature, keyEncipherment');
|
||||
{
|
||||
$res = openssl_pkey_new(array(
|
||||
"private_key_type" => OPENSSL_KEYTYPE_RSA,
|
||||
"private_key_bits" => (int)Settings::Get('system.letsencryptkeysize'),
|
||||
"private_key_bits" => (int) Settings::Get('system.letsencryptkeysize')
|
||||
));
|
||||
|
||||
if (! openssl_pkey_export($res, $privateKey)) {
|
||||
@@ -346,7 +354,10 @@ keyUsage = nonRepudiation, digitalSignature, keyEncipherment');
|
||||
|
||||
$details = openssl_pkey_get_details($res);
|
||||
|
||||
return array('private' => $privateKey, 'public' => $details['key']);
|
||||
return array(
|
||||
'private' => $privateKey,
|
||||
'public' => $details['key']
|
||||
);
|
||||
}
|
||||
|
||||
private function signedRequest($uri, array $payload)
|
||||
@@ -359,14 +370,13 @@ keyUsage = nonRepudiation, digitalSignature, keyEncipherment');
|
||||
"jwk" => array(
|
||||
"kty" => "RSA",
|
||||
"n" => Base64UrlSafeEncoder::encode($details["rsa"]["n"]),
|
||||
"e" => Base64UrlSafeEncoder::encode($details["rsa"]["e"]),
|
||||
"e" => Base64UrlSafeEncoder::encode($details["rsa"]["e"])
|
||||
)
|
||||
);
|
||||
|
||||
$protected = $header;
|
||||
$protected["nonce"] = $this->client->getLastNonce();
|
||||
|
||||
|
||||
$payload64 = Base64UrlSafeEncoder::encode(str_replace('\\/', '/', json_encode($payload)));
|
||||
$protected64 = Base64UrlSafeEncoder::encode(json_encode($protected));
|
||||
|
||||
@@ -394,7 +404,9 @@ keyUsage = nonRepudiation, digitalSignature, keyEncipherment');
|
||||
|
||||
class Client
|
||||
{
|
||||
|
||||
private $lastCode;
|
||||
|
||||
private $lastHeader;
|
||||
|
||||
private $base;
|
||||
@@ -406,7 +418,10 @@ class Client
|
||||
|
||||
private function curl($method, $url, $data = null)
|
||||
{
|
||||
$headers = array('Accept: application/json', 'Content-Type: application/json');
|
||||
$headers = array(
|
||||
'Accept: application/json',
|
||||
'Content-Type: application/json'
|
||||
);
|
||||
$handle = curl_init();
|
||||
curl_setopt($handle, CURLOPT_URL, preg_match('~^http~', $url) ? $url : $this->base . $url);
|
||||
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
|
||||
@@ -485,6 +500,7 @@ class Client
|
||||
|
||||
class Base64UrlSafeEncoder
|
||||
{
|
||||
|
||||
public static function encode($input)
|
||||
{
|
||||
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
<?php if (!defined('MASTER_CRONJOB')) die('You cannot access this file directly!');
|
||||
<?php
|
||||
|
||||
if (! defined('MASTER_CRONJOB'))
|
||||
die('You cannot access this file directly!');
|
||||
|
||||
/**
|
||||
* This file is part of the Froxlor project.
|
||||
@@ -20,6 +23,11 @@
|
||||
|
||||
$cronlog->logAction(CRON_ACTION, LOG_INFO, "Updating Let's Encrypt certificates");
|
||||
|
||||
if (! extension_loaded('curl')) {
|
||||
$cronlog->logAction(CRON_ACTION, LOG_ERR, "Let's Encrypt requires the php cURL extension to be installed.");
|
||||
exit;
|
||||
}
|
||||
|
||||
$certificates_stmt = Database::query("
|
||||
SELECT domssl.`id`, domssl.`domainid`, domssl.expirationdate, domssl.`ssl_cert_file`, domssl.`ssl_key_file`, domssl.`ssl_ca_file`, domssl.`ssl_csr_file`, dom.`domain`, dom.`iswildcarddomain`, dom.`wwwserveralias`,
|
||||
dom.`documentroot`, dom.`id` as 'domainid', dom.`ssl_redirect`, cust.`leprivatekey`, cust.`lepublickey`, cust.customerid, cust.loginname
|
||||
@@ -37,14 +45,15 @@ $upddom_stmt = Database::prepare("
|
||||
|
||||
$changedetected = 0;
|
||||
$certrows = $certificates_stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
foreach($certrows AS $certrow) {
|
||||
foreach ($certrows as $certrow) {
|
||||
|
||||
// set logger to corresponding loginname for the log to appear in the users system-log
|
||||
$cronlog = FroxlorLogger::getInstanceOf(array('loginname' => $certrow['loginname']));
|
||||
$cronlog = FroxlorLogger::getInstanceOf(array(
|
||||
'loginname' => $certrow['loginname']
|
||||
));
|
||||
|
||||
// Only renew let's encrypt certificate if no broken ssl_redirect is enabled
|
||||
if ($certrow['ssl_redirect'] != 2)
|
||||
{
|
||||
if ($certrow['ssl_redirect'] != 2) {
|
||||
$cronlog->logAction(CRON_ACTION, LOG_DEBUG, "Updating " . $certrow['domain']);
|
||||
|
||||
if ($certrow['ssl_cert_file']) {
|
||||
@@ -60,7 +69,9 @@ foreach($certrows AS $certrow) {
|
||||
}
|
||||
} else {
|
||||
$cronlog->logAction(CRON_ACTION, LOG_DEBUG, "letsencrypt generating new key / SAN for " . $certrow['domain']);
|
||||
$domains = array($certrow['domain']);
|
||||
$domains = array(
|
||||
$certrow['domain']
|
||||
);
|
||||
// Add www.<domain> for SAN
|
||||
if ($certrow['wwwserveralias'] == 1) {
|
||||
$domains[] = 'www.' . $certrow['domain'];
|
||||
@@ -90,20 +101,17 @@ foreach($certrows AS $certrow) {
|
||||
'chain' => $return['chain'],
|
||||
'csr' => $return['csr'],
|
||||
'expirationdate' => date('Y-m-d H:i:s', $newcert['validTo_time_t'])
|
||||
)
|
||||
);
|
||||
));
|
||||
|
||||
if ($certrow['ssl_redirect'] == 3) {
|
||||
Database::pexecute($upddom_stmt, array(
|
||||
'domainid' => $certrow['domainid']
|
||||
)
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
$cronlog->logAction(CRON_ACTION, LOG_INFO, "Updated Let's Encrypt certificate for " . $certrow['domain']);
|
||||
|
||||
$changedetected = 1;
|
||||
|
||||
} catch (Exception $e) {
|
||||
$cronlog->logAction(CRON_ACTION, LOG_ERR, "Could not get Let's Encrypt certificate for " . $certrow['domain'] . ": " . $e->getMessage());
|
||||
}
|
||||
@@ -119,5 +127,7 @@ if ($changedetected) {
|
||||
}
|
||||
|
||||
// reset logger
|
||||
$cronlog = FroxlorLogger::getInstanceOf(array('loginname' => 'cronjob'));
|
||||
$cronlog = FroxlorLogger::getInstanceOf(array(
|
||||
'loginname' => 'cronjob'
|
||||
));
|
||||
$cronlog->logAction(CRON_ACTION, LOG_INFO, "Let's Encrypt certificates have been updated");
|
||||
|
||||
Reference in New Issue
Block a user