Initial Commit
This commit is contained in:
12
src/Commands/Command.php
Normal file
12
src/Commands/Command.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace Kelunik\AcmeClient\Commands;
|
||||
|
||||
use Amp\Promise;
|
||||
use League\CLImate\Argument\Manager;
|
||||
|
||||
interface Command {
|
||||
public function execute(Manager $args): Promise;
|
||||
|
||||
public static function getDefinition(): array;
|
||||
}
|
||||
231
src/Commands/Issue.php
Normal file
231
src/Commands/Issue.php
Normal file
@@ -0,0 +1,231 @@
|
||||
<?php
|
||||
|
||||
namespace Kelunik\AcmeClient\Commands;
|
||||
|
||||
use Amp\Dns as dns;
|
||||
use Amp\Dns\Record;
|
||||
use Amp\Promise;
|
||||
use Generator;
|
||||
use Kelunik\Acme\AcmeClient;
|
||||
use Kelunik\Acme\AcmeException;
|
||||
use Kelunik\Acme\AcmeService;
|
||||
use Kelunik\Acme\KeyPair;
|
||||
use Kelunik\Acme\OpenSSLKeyGenerator;
|
||||
use League\CLImate\Argument\Manager;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use stdClass;
|
||||
use Throwable;
|
||||
use function Amp\all;
|
||||
use function Amp\any;
|
||||
use function Amp\resolve;
|
||||
|
||||
class Issue implements Command {
|
||||
private $logger;
|
||||
|
||||
public function __construct(LoggerInterface $logger) {
|
||||
$this->logger = $logger;
|
||||
}
|
||||
|
||||
public function execute(Manager $args): Promise {
|
||||
return resolve($this->doExecute($args));
|
||||
}
|
||||
|
||||
private function doExecute(Manager $args): Generator {
|
||||
if (posix_geteuid() !== 0) {
|
||||
throw new AcmeException("Please run this script as root!");
|
||||
}
|
||||
|
||||
$user = $args->get("user") ?? "www-data";
|
||||
|
||||
$server = $args->get("server");
|
||||
$protocol = substr($server, 0, strpos("://", $server));
|
||||
|
||||
if (!$protocol || $protocol === $server) {
|
||||
$server = "https://" . $server;
|
||||
} elseif ($protocol !== "https") {
|
||||
throw new \InvalidArgumentException("Invalid server protocol, only HTTPS supported");
|
||||
}
|
||||
|
||||
$domains = $args->get("domains");
|
||||
$domains = array_map("trim", explode(",", $domains));
|
||||
$this->checkDnsRecords($domains);
|
||||
|
||||
$keyPair = $this->checkRegistration($args);
|
||||
|
||||
$acme = new AcmeService(new AcmeClient($server, $keyPair), $keyPair);
|
||||
|
||||
foreach ($domains as $domain) {
|
||||
list($location, $challenges) = yield $acme->requestChallenges($domain);
|
||||
$goodChallenges = $this->findSuitableCombination($challenges);
|
||||
|
||||
if (empty($goodChallenges)) {
|
||||
throw new AcmeException("Couldn't find any combination of challenges which this server can solve!");
|
||||
}
|
||||
|
||||
$challenge = $challenges->challenges[reset($goodChallenges)];
|
||||
$token = $challenge->token;
|
||||
|
||||
if (!preg_match("#^[a-zA-Z0-9-_]+$#", $token)) {
|
||||
throw new AcmeException("Protocol Violation: Invalid Token!");
|
||||
}
|
||||
|
||||
$payload = $acme->generateHttp01Payload($token);
|
||||
|
||||
$docRoot = rtrim($args->get("path") ?? __DIR__ . "/../../data/public", "/\\");
|
||||
$path = $docRoot . "/.well-known/acme-challenge";
|
||||
|
||||
try {
|
||||
if (!file_exists($docRoot)) {
|
||||
throw new AcmeException("Document root doesn't exist: " . $docRoot);
|
||||
}
|
||||
|
||||
if (!file_exists($path) && !@mkdir($path, 0770, true)) {
|
||||
throw new AcmeException("Couldn't create public dir to serve the challenges: " . $path);
|
||||
}
|
||||
|
||||
if (!$userInfo = posix_getpwnam($user)) {
|
||||
throw new AcmeException("Unknown user: " . $user);
|
||||
}
|
||||
|
||||
chown($docRoot . "/.well-known", $userInfo["uid"]);
|
||||
chown($docRoot . "/.well-known/acme-challenge", $userInfo["uid"]);
|
||||
|
||||
file_put_contents("{$path}/{$token}", $payload);
|
||||
chown("{$path}/{$token}", $userInfo["uid"]);
|
||||
chmod("{$path}/{$token}", 0660);
|
||||
|
||||
yield $acme->selfVerify($domain, $token, $payload);
|
||||
yield $acme->answerChallenge($challenge->uri, $payload);
|
||||
yield $acme->pollForChallenge($location);
|
||||
|
||||
@unlink("{$path}/{$token}");
|
||||
} catch (Throwable $e) {
|
||||
// no finally because generators...
|
||||
@unlink("{$path}/{$token}");
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
$path = __DIR__ . "/../../data/live/" . reset($domains);
|
||||
|
||||
if (!file_exists($path) && !mkdir($path, 0700, true)) {
|
||||
throw new AcmeException("Couldn't create directory: {$path}");
|
||||
}
|
||||
|
||||
if (file_exists($path . "/private.pem") && file_exists($path . "/public.pem")) {
|
||||
$private = file_get_contents($path . "/private.pem");
|
||||
$public = file_get_contents($path . "/public.pem");
|
||||
|
||||
$domainKeys = new KeyPair($private, $public);
|
||||
} else {
|
||||
$domainKeys = (new OpenSSLKeyGenerator)->generate(2048);
|
||||
|
||||
file_put_contents($path . "/private.pem", $domainKeys->getPrivate());
|
||||
file_put_contents($path . "/public.pem", $domainKeys->getPublic());
|
||||
|
||||
chmod($path . "/private.pem", 0600);
|
||||
chmod($path . "/public.pem", 0600);
|
||||
}
|
||||
|
||||
$location = yield $acme->requestCertificate($domainKeys, $domains);
|
||||
$certificates = yield $acme->pollForCertificate($location);
|
||||
|
||||
file_put_contents($path . "/cert.pem", reset($certificates));
|
||||
file_put_contents($path . "/fullchain.pem", implode("\n", $certificates));
|
||||
|
||||
array_shift($certificates);
|
||||
file_put_contents($path . "/chain.pem", implode("\n", $certificates));
|
||||
}
|
||||
|
||||
private function checkDnsRecords($domains): Generator {
|
||||
$promises = [];
|
||||
|
||||
foreach ($domains as $domain) {
|
||||
$promises[$domain] = dns\resolve($domain, [
|
||||
"types" => Record::A,
|
||||
"hosts" => false,
|
||||
]);
|
||||
}
|
||||
|
||||
list($errors) = yield any($promises);
|
||||
|
||||
if (!empty($errors)) {
|
||||
throw new AcmeException("Couldn't resolve the following domains to an IPv4 record: " . implode(array_keys($errors)));
|
||||
}
|
||||
}
|
||||
|
||||
private function checkRegistration(Manager $args) {
|
||||
$server = $args->get("server");
|
||||
$protocol = substr($server, 0, strpos("://", $server));
|
||||
|
||||
if (!$protocol || $protocol === $server) {
|
||||
$server = "https://" . $server;
|
||||
} elseif ($protocol !== "https") {
|
||||
throw new \InvalidArgumentException("Invalid server protocol, only HTTPS supported");
|
||||
}
|
||||
|
||||
$identity = str_replace(["/", "%"], "-", substr($server, 8));
|
||||
|
||||
$path = __DIR__ . "/../../data/accounts";
|
||||
$pathPrivate = "{$path}/{$identity}.private.key";
|
||||
$pathPublic = "{$path}/{$identity}.public.key";
|
||||
|
||||
if (file_exists($pathPrivate) && file_exists($pathPublic)) {
|
||||
$private = file_get_contents($pathPrivate);
|
||||
$public = file_get_contents($pathPublic);
|
||||
|
||||
return new KeyPair($private, $public);
|
||||
}
|
||||
|
||||
throw new AcmeException("No registration found for server, please register first");
|
||||
}
|
||||
|
||||
private function findSuitableCombination(stdClass $response): array {
|
||||
$challenges = $response->challenges ?? [];
|
||||
$combinations = $response->combinations ?? [];
|
||||
$goodChallenges = [];
|
||||
|
||||
foreach ($challenges as $i => $challenge) {
|
||||
if ($challenge->type === "http-01") {
|
||||
$goodChallenges[] = $i;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($goodChallenges as $i => $challenge) {
|
||||
if (!in_array([$challenge], $combinations)) {
|
||||
unset($goodChallenges[$i]);
|
||||
}
|
||||
}
|
||||
|
||||
return $goodChallenges;
|
||||
}
|
||||
|
||||
public static function getDefinition(): array {
|
||||
return [
|
||||
"domains" => [
|
||||
"prefix" => "d",
|
||||
"longPrefix" => "domains",
|
||||
"description" => "Domains to request a certificate for.",
|
||||
"required" => true,
|
||||
],
|
||||
"server" => [
|
||||
"prefix" => "s",
|
||||
"longPrefix" => "server",
|
||||
"description" => "ACME server to use for authorization.",
|
||||
"required" => true,
|
||||
],
|
||||
"user" => [
|
||||
"prefix" => "s",
|
||||
"longPrefix" => "user",
|
||||
"description" => "User for the public directory.",
|
||||
"required" => false,
|
||||
],
|
||||
"path" => [
|
||||
"prefix" => "p",
|
||||
"longPrefix" => "path",
|
||||
"description" => "Path to the document root for ACME challenges.",
|
||||
"required" => false,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
116
src/Commands/Register.php
Normal file
116
src/Commands/Register.php
Normal file
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace Kelunik\AcmeClient\Commands;
|
||||
|
||||
use Amp\Dns\Record;
|
||||
use Amp\Dns\ResolutionException;
|
||||
use Amp\Promise;
|
||||
use Generator;
|
||||
use Kelunik\Acme\AcmeClient;
|
||||
use Kelunik\Acme\AcmeException;
|
||||
use Kelunik\Acme\AcmeService;
|
||||
use Kelunik\Acme\KeyPair;
|
||||
use Kelunik\Acme\OpenSSLKeyGenerator;
|
||||
use Kelunik\Acme\Registration;
|
||||
use League\CLImate\Argument\Manager;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use function Amp\File\exists;
|
||||
use function Amp\resolve;
|
||||
|
||||
class Register implements Command {
|
||||
private $logger;
|
||||
|
||||
public function __construct(LoggerInterface $logger) {
|
||||
$this->logger = $logger;
|
||||
}
|
||||
|
||||
public function execute(Manager $args): Promise {
|
||||
return resolve($this->doExecute($args));
|
||||
}
|
||||
|
||||
public function doExecute(Manager $args): Generator {
|
||||
if (posix_geteuid() !== 0) {
|
||||
throw new AcmeException("Please run this script as root!");
|
||||
}
|
||||
|
||||
$email = $args->get("email");
|
||||
yield resolve($this->checkEmail($email));
|
||||
|
||||
$server = $args->get("server");
|
||||
$protocol = substr($server, 0, strpos("://", $server));
|
||||
|
||||
if (!$protocol || $protocol === $server) {
|
||||
$server = "https://" . $server;
|
||||
} elseif ($protocol !== "https") {
|
||||
throw new \InvalidArgumentException("Invalid server protocol, only HTTPS supported");
|
||||
}
|
||||
|
||||
$identity = str_replace(["/", "%"], "-", substr($server, 8));
|
||||
|
||||
$path = __DIR__ . "/../../data/accounts";
|
||||
$pathPrivate = "{$path}/{$identity}.private.key";
|
||||
$pathPublic = "{$path}/{$identity}.public.key";
|
||||
|
||||
if ((yield exists($pathPrivate)) && (yield exists($pathPublic))) {
|
||||
$this->logger->info("Loading existing keys ...");
|
||||
|
||||
$private = file_get_contents($pathPrivate);
|
||||
$public = file_get_contents($pathPublic);
|
||||
|
||||
$keyPair = new KeyPair($private, $public);
|
||||
} else {
|
||||
$this->logger->info("Generating key keys ...");
|
||||
|
||||
$keyPair = (new OpenSSLKeyGenerator)->generate(4096);
|
||||
|
||||
if (!mkdir($path, 0700, true)) {
|
||||
throw new AcmeException("Couldn't create account directory");
|
||||
}
|
||||
|
||||
file_put_contents($pathPrivate, $keyPair->getPrivate());
|
||||
file_put_contents($pathPublic, $keyPair->getPublic());
|
||||
|
||||
chmod($pathPrivate, 600);
|
||||
chmod($pathPrivate, 600);
|
||||
}
|
||||
|
||||
$acme = new AcmeService(new AcmeClient($server, $keyPair), $keyPair);
|
||||
|
||||
$this->logger->info("Registering with ACME server " . substr($server, 8) . " ...");
|
||||
|
||||
/** @var Registration $registration */
|
||||
$registration = yield $acme->register($email);
|
||||
|
||||
$this->logger->notice("Registration successful with contact " . json_encode($registration->getContact()));
|
||||
}
|
||||
|
||||
private function checkEmail(string $email): Generator {
|
||||
$host = substr($email, strrpos($email, "@") + 1);
|
||||
|
||||
if (!$host) {
|
||||
throw new AcmeException("Invalid contact email: '{$email}'");
|
||||
}
|
||||
|
||||
try {
|
||||
yield \Amp\Dns\query($host, Record::MX);
|
||||
} catch (ResolutionException $e) {
|
||||
throw new AcmeException("No MX record defined for '{$host}'");
|
||||
}
|
||||
}
|
||||
|
||||
public static function getDefinition(): array {
|
||||
return [
|
||||
"server" => [
|
||||
"prefix" => "s",
|
||||
"longPrefix" => "server",
|
||||
"description" => "ACME server to register for.",
|
||||
"required" => true,
|
||||
],
|
||||
"email" => [
|
||||
"longPrefix" => "email",
|
||||
"description" => "Email to be notified about important account issues.",
|
||||
"required" => true,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
30
src/Commands/Revoke.php
Normal file
30
src/Commands/Revoke.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Kelunik\AcmeClient\Commands;
|
||||
|
||||
use Amp\Promise;
|
||||
use Kelunik\Acme\AcmeException;
|
||||
use League\CLImate\Argument\Manager;
|
||||
|
||||
class Revoke implements Command {
|
||||
public function execute(Manager $args): Promise {
|
||||
throw new AcmeException("Command not yet implemented!");
|
||||
}
|
||||
|
||||
public static function getDefinition(): array {
|
||||
return [
|
||||
"domains" => [
|
||||
"prefix" => "d",
|
||||
"longPrefix" => "domains",
|
||||
"description" => "Domains to request a certificate for.",
|
||||
"required" => true,
|
||||
],
|
||||
"server" => [
|
||||
"prefix" => "s",
|
||||
"longPrefix" => "server",
|
||||
"description" => "ACME server to use for authorization.",
|
||||
"required" => true,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
29
src/LoggerColorScheme.php
Normal file
29
src/LoggerColorScheme.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace Kelunik\AcmeClient;
|
||||
|
||||
use Bramus\Ansi\ControlSequences\EscapeSequences\Enums\SGR;
|
||||
use Bramus\Monolog\Formatter\ColorSchemes\ColorSchemeInterface;
|
||||
use Bramus\Monolog\Formatter\ColorSchemes\ColorSchemeTrait;
|
||||
use Monolog\Logger;
|
||||
|
||||
class LoggerColorScheme implements ColorSchemeInterface {
|
||||
use ColorSchemeTrait {
|
||||
ColorSchemeTrait::__construct as private __constructTrait;
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->__constructTrait();
|
||||
|
||||
$this->setColorizeArray([
|
||||
Logger::DEBUG => $this->ansi->color(SGR::COLOR_FG_WHITE)->get(),
|
||||
Logger::INFO => $this->ansi->color(SGR::COLOR_FG_WHITE_BRIGHT)->get(),
|
||||
Logger::NOTICE => $this->ansi->color(SGR::COLOR_FG_GREEN)->get(),
|
||||
Logger::WARNING => $this->ansi->color(SGR::COLOR_FG_YELLOW)->get(),
|
||||
Logger::ERROR => $this->ansi->color(SGR::COLOR_FG_RED)->get(),
|
||||
Logger::CRITICAL => $this->ansi->color(SGR::COLOR_FG_RED)->get(),
|
||||
Logger::ALERT => $this->ansi->color(SGR::COLOR_FG_RED)->get(),
|
||||
Logger::EMERGENCY => $this->ansi->color(SGR::COLOR_FG_RED)->get(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user