Compare commits

...

17 Commits

Author SHA1 Message Date
tracer b536316a84 initial commit 2022-09-27 19:49:16 +02:00
tracer f614837729 initial commit 2022-09-27 19:41:35 +02:00
tracer e9d777ab24 initial commit 2022-09-27 19:38:01 +02:00
tracer 61ec6aaaa5 refactored command registration 2022-09-27 19:13:28 +02:00
tracer 4c80ba1543 added encryption 2022-09-22 19:31:38 +02:00
tracer be6402b4a3 removed a stale blank line ^^ 2022-09-22 19:30:45 +02:00
tracer 8f5a57ee54 made all methods use objects instead of single parameters 2022-09-22 19:11:04 +02:00
tracer 51b9e67ea9 added encryption, constructor property promotion 2022-09-22 18:57:10 +02:00
tracer 8ec1a2942d added password encryption 2022-09-22 18:54:54 +02:00
tracer 790176964d added corrected key import from config 2022-09-22 18:54:23 +02:00
tracer b2115a97a8 removed unused imports 2022-09-22 18:53:29 +02:00
tracer 3c09b4038d added encryption support 2022-09-21 16:02:42 +02:00
tracer 3bc232ef0b fixed a handling bug 2022-09-21 16:01:44 +02:00
tracer cd5361c65b refactored zone deletion 2022-09-21 16:01:14 +02:00
tracer f81b0451b4 added quiet option 2022-09-21 16:00:16 +02:00
tracer 9474a9ebef added quiet option 2022-09-21 15:59:09 +02:00
tracer ccb3479568 added quiet option 2022-09-21 15:58:48 +02:00
14 changed files with 2483 additions and 1895 deletions

13
bin/console Normal file → Executable file
View File

@ -26,11 +26,13 @@ require dirname(path: __DIR__) . '/vendor/autoload.php';
$shortOpts = 'v::'; // version
$shortOpts = 'q::'; // version
$shortOpts .= "V::"; // verbose
$shortOpts .= "h::"; // help
$longOpts = [
'version::',
'quiet::',
'verbose::',
'help::'
];
@ -47,6 +49,13 @@ if (array_key_exists(key: 'h', array: $options) || array_key_exists(key: 'help',
exit(0);
}
if (array_key_exists(key: 'q', array: $options) || array_key_exists(key: 'quiet', array: $options)) {
$quiet = true;
} else {
$quiet = false;
}
if (array_key_exists(key: 'V', array: $options) || array_key_exists(key: 'verbose', array: $options)) {
$verbose = true;
} else {
@ -56,8 +65,8 @@ if (array_key_exists(key: 'V', array: $options) || array_key_exists(key: 'verbos
$arguments = array_slice(array: $argv, offset: $restIndex);
try {
$app = new BindAPI(verbose: $verbose );
$app->runCommand(argumentsCount: count(value: $arguments), arguments: $arguments);
$app = new BindAPI(verbose: $verbose, quiet: $quiet);
$app->runCommand(arguments: $arguments);
} catch (DependencyException|NotFoundException|Exception $e) {
echo $e->getMessage() . PHP_EOL;

View File

@ -8,8 +8,12 @@ use App\Repository\DomainRepository;
use App\Repository\DynDNSRepository;
use DI\Container;
use DI\ContainerBuilder;
use DI\DependencyException;
use DI\NotFoundException;
use Exception;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Level;
use Monolog\Logger;
use function DI\autowire;
@ -21,11 +25,10 @@ class BindAPI
private Logger $logger;
private Container $container;
/**
* @throws \Exception
* @throws Exception
*/
public function __construct($verbose = false)
public function __construct($verbose = false, $quiet = false)
{
// init the logger
$dateFormat = "Y:m:d H:i:s";
@ -34,9 +37,9 @@ class BindAPI
$debug = (new ConfigController)->getConfig(configKey: 'debug');
if ($debug) {
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/bindAPI.log', level: Logger::DEBUG);
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/bindAPI.log', level: Level::Debug);
} else {
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/bindAPI.log', level: Logger::INFO);
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/bindAPI.log', level: Level::Info);
}
$stream->setFormatter(formatter: $formatter);
@ -48,6 +51,7 @@ class BindAPI
$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions([
ConfigController::class => autowire()
->constructorParameter(parameter: 'quiet', value: $quiet)
->constructorParameter(parameter: 'verbose', value: $verbose),
CLIController::class => autowire()
->constructorParameter(parameter: 'logger', value: $this->logger),
@ -65,8 +69,8 @@ class BindAPI
/**
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
* @throws DependencyException
* @throws NotFoundException
*/
public function runCommand(array $arguments): void
{
@ -77,8 +81,8 @@ class BindAPI
/**
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
* @throws DependencyException
* @throws NotFoundException
*/
public function handleRequest(string $requestMethod, array $uri): void
{

View File

@ -11,8 +11,13 @@ define(constant_name: 'COLOR_BLUE', value: "\033[34m");
define(constant_name: 'COLOR_WHITE', value: "\033[37m");
define(constant_name: 'COLOR_DEFAULT', value: "\033[39m");
use App\Controller\Commands\Command;
use App\Controller\Commands\CommandGroup;
use App\Controller\Commands\CommandGroupContainer;
use App\Entity\Apikey;
use App\Entity\Domain;
use App\Entity\DynDNS;
use App\Entity\KeyHelp\KeyHelpDomain;
use App\Entity\Nameserver;
use App\Entity\Panel;
use App\Repository\ApikeyRepository;
@ -22,7 +27,10 @@ use App\Repository\NameserverRepository;
use App\Repository\PanelRepository;
use Arubacao\TldChecker\Validator;
use Exception;
use JsonMapper;
use JsonMapper_Exception;
use LucidFrame\Console\ConsoleTable;
use SodiumException;
if (php_sapi_name() !== 'cli') {
exit;
@ -35,6 +43,7 @@ if (php_sapi_name() !== 'cli') {
class CLIController
{
private array $arguments;
private CommandGroupContainer $commandGroupContainer;
/**
* @throws Exception
@ -48,9 +57,159 @@ class CLIController
private readonly NameserverRepository $nameserverRepository,
private readonly PanelRepository $panelRepository,
private readonly ConfigController $configController,
private readonly EncryptionController $encryptionController,
private $logger)
{
$this->checkSetup();
$this->commandGroupContainer = (new CommandGroupContainer())
->add(commandGroup: (new CommandGroup(name: 'check', description: 'health checks the system can perform'))
->addCommand(command: new Command(
name: 'permissions',
callback: function () {
$this->handleCheckPermissions();
},
description: 'health checks the system can perform'))
->addCommand(command: new Command(
name: 'panels',
callback: function () {
$this->handleCheckPanels();
},
optionalParameters: ['ID', 'fix=xes']))
->addCommand(command: new Command(
name: 'domains',
callback: function () {
$this->handleCheckDomains();
}))
->addCommand(command: new Command(
name: 'showincludes',
callback: function () {
$this->handleCheckShowIncludes();
},
description: 'Shows needed setting on panels'))
->addCommand(command: new Command(
name: 'generatekey',
callback: function () {
$this->handleCheckGenerateKey();
},
description: 'Generates a a new key for encryption'))
->addCommand(command: new Command(
name: 'setup',
callback: function () {
$this->handleCheckSetup();
},
mandatoryParameters: ['username'],
description: 'Adapt filesystem permissions (requires elaborated permissions)'))
->addCommand(command: new Command(
name: 'version',
callback: function () {
$this->handleChecksVersion();
},
optionalParameters: ['major:minor:patch'],
description: 'Read or set the bindApi version in the database')))
->add(commandGroup: (new CommandGroup(name: 'panels', description: 'all KeyHelp systems configured'))
->addCommand(command: new Command(
name: 'list',
callback: function () {
$this->handlePanelsList();
}))
->addCommand(command: new Command(
name: 'create',
callback: function () {
$this->handlePanelsCreate();
},
mandatoryParameters: ['name'],
optionalParameters: ['A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>']))
->addCommand(command: new Command(
name: 'update',
callback: function () {
$this->handlePanelsUpdate();
},
mandatoryParameters: ['ID'],
optionalParameters: ['name=<name>', 'A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>']))
->addCommand(command: new Command(
name: 'delete',
callback: function () {
$this->handlePanelsDelete();
},
mandatoryParameters: ['ID']))
->addCommand(command: new Command(
name: 'apiping',
callback: function () {
$this->handleApiPing();
},
optionalParameters: ['ID'])))
->add(commandGroup: (new CommandGroup(name: 'nameservers', description: 'available nameservers'))
->addCommand(command: new Command(
name: 'list',
callback: function () {
$this->handleNameserversList();
}))
->addCommand(command: new Command(
name: 'create',
callback: function () {
$this->handleNameserversCreate();
},
mandatoryParameters: ['name'],
optionalParameters: ['A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>']))
->addCommand(command: new Command(
name: 'update',
callback: function () {
$this->handleNameserversUpdate();
},
mandatoryParameters: ['ID'],
optionalParameters: ['name=<name>', 'A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>']))
->addCommand(command: new Command(
name: 'delete',
callback: function () {
$this->handleNameserversDelete();
},
mandatoryParameters: ['ID']))
->addCommand(command: new Command(
name: 'apiping',
callback: function () {
$this->handleApiPing();
},
optionalParameters: ['ID'])))
->add(commandGroup: (new CommandGroup(name: 'domains', description: 'configured domains'))
->addCommand(command: new Command(
name: 'list',
callback: function () {
$this->handleDomainsList();
}))
->addCommand(command: new Command(
name: 'refresh',
callback: function () {
$this->handleDomainsRefresh();
},
mandatoryParameters: ['name'],
optionalParameters: ['A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>'])))
->add(commandGroup: (new CommandGroup(name: 'dyndns', description: 'handle DynDNS entries'))
->addCommand(command: new Command(
name: 'list',
callback: function () {
$this->handleDynDnsList();
}))
->addCommand(command: new Command(
name: 'create',
callback: function () {
$this->handlePanelsCreate();
},
mandatoryParameters: ['hostname.example.com', 'password'],
description: 'FQDN within a domain where this server is master'))
->addCommand(command: new Command(
name: 'update',
callback: function () {
$this->handlePanelsUpdate();
},
mandatoryParameters: ['ID'],
optionalParameters: ['name=<name>', 'A=<IPv4>', 'AAAA=<IPv6>', 'apikey=<API-Key>']))
->addCommand(command: new Command(
name: 'delete',
callback: function () {
$this->handlePanelsDelete();
},
mandatoryParameters: ['ID'])));
}
function checkSetup(): void
@ -76,8 +235,6 @@ class CLIController
}
// TODO encrypt the password in the config file, key in config
function runCommand(array $arguments): void
{
if (count($arguments) < 1) {
@ -96,16 +253,7 @@ class CLIController
}
$this->arguments = $this->parseArguments(arguments: $arguments);
match ($command) {
'check' => $this->handleChecks(subcommand: $subcommand),
'panels' => $this->handlePanels(subcommand: $subcommand),
'apikeys' => $this->handleApiKeys(subcommand: $subcommand),
'domains' => $this->handleDomains(subcommand: $subcommand),
'dyndns' => $this->handleDynDns(subcommand: $subcommand),
'nameservers' => $this->handleNameservers(subcommand: $subcommand),
default => $this->unknownCommand(command: $command)
};
$this->commandGroupContainer->run(command: $command, subcommand: $subcommand);
}
@ -116,6 +264,15 @@ class CLIController
{
$this->logger->debug(message: "showUsage()");
$debug = $this->configController->getConfig(configKey: 'debug');
echo 'bindAPI version: todo (env: todo) ';
if ($debug) {
echo 'true';
} else {
echo 'false';
}
echo COLOR_DEFAULT . ')' . PHP_EOL;
echo COLOR_YELLOW . 'Usage:' . PHP_EOL;
echo COLOR_DEFAULT . "\t./bin/console {options} {arguments}" . PHP_EOL . PHP_EOL;
@ -123,33 +280,9 @@ class CLIController
echo COLOR_GREEN . "\t-v, --version\t\t" . COLOR_DEFAULT . "Display the version of the API" . PHP_EOL;
echo COLOR_GREEN . "\t-V, --verbose\t\t" . COLOR_DEFAULT . "All :lists command are auto-verbose" . PHP_EOL . PHP_EOL;
echo COLOR_YELLOW . 'Arguments:' . PHP_EOL;
echo COLOR_YELLOW . "check" . COLOR_WHITE . "\t health checks the system can perform" . PHP_EOL;
echo COLOR_GREEN . "\t check:permissions" . PHP_EOL;
echo COLOR_GREEN . "\t check:panels {ID} {fix=yes}" . PHP_EOL;
echo COLOR_GREEN . "\t check:domains" . PHP_EOL;
echo COLOR_GREEN . "\t check:showincludes" . COLOR_WHITE . " Shows needed setting on panels" . PHP_EOL;
echo COLOR_GREEN . "\t check:generatekey" . COLOR_WHITE . " Generates a key for encryption" . PHP_EOL;
echo COLOR_GREEN . "\t check:setup <username>" . COLOR_WHITE . " Adapt filesystem permissions (requires elaborated permissions)" . PHP_EOL;
echo COLOR_YELLOW . 'Arguments: ' . COLOR_WHITE . '<mandatory> {optional}' . PHP_EOL;
echo COLOR_YELLOW . "panels" . COLOR_WHITE . "\t all KeyHelp systems configured" . PHP_EOL;
echo COLOR_GREEN . "\t panels:list" . PHP_EOL;
echo COLOR_GREEN . "\t panels:create <name> {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t panels:update <ID> {name=<name>} {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t panels:delete <ID>" . PHP_EOL;
echo COLOR_GREEN . "\t panels:apiping {<ID>}" . PHP_EOL;
echo COLOR_YELLOW . "nameservers" . COLOR_WHITE . " available nameservers" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:list" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:create <name> {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:update <ID> {name=<name>} {A=<IPv4>} {AAAA=<IPv6>} {apikey=<API-Key>}" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:delete <ID>" . PHP_EOL;
echo COLOR_GREEN . "\t nameservers:apiping {<ID>}" . PHP_EOL;
echo COLOR_YELLOW . "domains" . COLOR_WHITE . " configured domains" . PHP_EOL;
echo COLOR_GREEN . "\t domains:list" . PHP_EOL;
echo COLOR_GREEN . "\t domains:refresh" . PHP_EOL;
$this->commandGroupContainer->printCommands();
echo COLOR_YELLOW . "dyndns" . COLOR_WHITE . " handle dyndns entries" . PHP_EOL;
echo COLOR_GREEN . "\t dyndns:list" . PHP_EOL;
@ -166,21 +299,6 @@ class CLIController
echo PHP_EOL . "\033[39me.g. ./bin/console apikeys:list" . PHP_EOL;
}
function handleChecks(string $subcommand): void
{
$this->logger->debug(message: "handleChecks()");
match ($subcommand) {
'permissions' => $this->handleCheckPermissions(),
'panels' => $this->handleCheckPanels(),
'domains' => $this->handleCheckDomains(),
'showincludes' => $this->handleCheckShowIncludes(),
'generatekey' => $this->handleCheckGenerateKey(),
'setup' => $this->handleCheckSetup(),
default => $this->unknownSubcommand(subcommand: $subcommand)
};
}
function unknownCommand(string $command): void
{
@ -199,7 +317,7 @@ class CLIController
/**
*/
function handleCheckPermissions(): void
public function handleCheckPermissions(): void
{
$this->logger->debug(message: "handleCheckPermissions()");
@ -215,6 +333,23 @@ class CLIController
}
/*
public function handleCheckPermissions(): void
{
$this->logger->debug(message: "handleCheckPermissions()");
if (!$this->domainController->checkPermissions()) {
if ($this->configController->getConfig(configKey: 'verbose')) {
echo PHP_EOL . COLOR_DEFAULT;
echo 'Missing permissions, please run ' . COLOR_YELLOW . './bin/console check:setup' . COLOR_DEFAULT . ' as root or with sudo.' . PHP_EOL;
}
exit(1);
} else {
exit(0);
}
}
*/
function handleCheckSetup(): void
{
if (count($this->arguments) < 2) {
@ -322,7 +457,7 @@ class CLIController
/**
* @param \App\Entity\Panel $panel
* @param Panel $panel
*
* @return void
*/
@ -330,7 +465,10 @@ class CLIController
{
$this->logger->debug(message: "checkSinglePanel()");
echo COLOR_DEFAULT . 'KeyHelp-Panel: ' . COLOR_YELLOW . $panel->getName();
echo COLOR_DEFAULT . 'KeyHelp-Panel: ' . COLOR_YELLOW . $panel->getName() . COLOR_DEFAULT;
$encryptionKey = $this->configController->getConfig(configKey: 'encryptionKey');
$decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $panel->getApikey(), key: $encryptionKey);
if ($this->configController->getConfig(configKey: 'verbose')) {
if (empty($panel->getA())) {
@ -338,7 +476,7 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $panel->getApikey(),
apiKey: $decryptedKey,
command: '/server',
serverType: 'panel');
} else {
@ -346,7 +484,7 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
apiKey: $panel->getApikey(),
apiKey: $decryptedKey,
command: '/server',
serverType: 'panel');
}
@ -368,8 +506,8 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $panel->getApikey(),
command: 'domains?sort=domain',
apiKey: $decryptedKey,
command: 'domains?sort=domain&subdomains=false',
serverType: 'panel'
);
} else {
@ -377,8 +515,8 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
apiKey: $panel->getApikey(),
command: 'domains?sort=domain',
apiKey: $decryptedKey,
command: 'domains?sort=domain&subdomains=false',
serverType: 'panel');
}
@ -394,30 +532,89 @@ class CLIController
}
$maxDomainNameLength = 0;
$tmpDomainlist = [];
$tmpDomainList = [];
$mapper = new JsonMapper();
if (count($domains) > 0) {
foreach ($domains as $domain) {
if ($this->isValidSecondLevelDomain(domainName: $domain->domain, panel: $panel->getName(), parent: $domain->id_parent_domain)) {
$tmpDomainlist[] = $domain;
$mapper->bExceptionOnUndefinedProperty = true;
$mapper->bStrictNullTypes = false;
try {
$domainObject = $mapper->map(json: $domain, object: new KeyHelpDomain());
} catch (JsonMapper_Exception $e) {
die($e->getMessage() . PHP_EOL);
}
$tmpDomainList[] = $domainObject;
if (strlen(string: $domain->domain) > $maxDomainNameLength) {
$maxDomainNameLength = strlen(string: $domain->domain);
}
}
}
}
$domainCount = 0;
foreach ($tmpDomainlist as $domain) {
echo COLOR_DEFAULT . " Domain: " . COLOR_YELLOW . str_pad(string: $domain->domain, length: $maxDomainNameLength);
$this->checkNS(domainName: $domain->domain, panel: $panel);
foreach ($tmpDomainList as $domain) {
echo COLOR_DEFAULT . " Domain: " . COLOR_YELLOW . str_pad(string: $domain->getDomain(), length: $maxDomainNameLength);
if (!$domain->isSubdomain()) {
$this->checkNS(domainName: $domain->getDomain(), panel: $panel);
$domainCount++;
}
}
if ($domainCount == 0) {
echo 'No second level domains found.' . COLOR_DEFAULT . PHP_EOL;
}
echo PHP_EOL;
try {
sodium_memzero(string: $decryptedKey);
} catch (SodiumException $e) {
die($e->getMessage() . PHP_EOL);
}
}
function isSubDomain(Domain $domain): bool
{
$this->logger->debug(message: "isSubDomain()");
// valid second level domain
if (!Validator::endsWithTld(value: $domain)) {
return false;
}
$domainParts = explode(separator: '.', string: $domain->getName());
$reversedParts = array_reverse(array: $domainParts);
$testDomain = '';
$foundDomain = '';
foreach ($reversedParts as $part) {
if ($testDomain) {
$testDomain = $part . '.' . $testDomain;
} else {
$testDomain = $part;
}
if ($this->domainRepository->findByName(name: $testDomain)) {
$foundDomain = $testDomain;
echo $part . PHP_EOL;
}
}
echo "fould domain ***" . $foundDomain . PHP_EOL;
/*
// system domain
if (str_contains(haystack: $domainName, needle: $panel)) {
return false;
}
// no second level domain
if (substr_count(haystack: $domainName, needle: '.') > 1) {
return false;
}
*/
return true;
}
function isValidSecondLevelDomain(string $domainName, string $panel, int $parent): bool
{
@ -449,7 +646,7 @@ class CLIController
/**
* @param String $domainName
* @param \App\Entity\Panel $panel
* @param Panel $panel
*
* @return void
*/
@ -562,7 +759,7 @@ class CLIController
'list' => $this->handlePanelsList(),
'update' => $this->handlePanelsUpdate(),
'delete' => $this->handlePanelsDelete(),
'apiping' => $this->handleAPIPing(type: 'panel'),
'apiping' => $this->handleApiPing(type: 'panel'),
default => $this->unknownSubcommand(subcommand: $subcommand)
};
}
@ -595,14 +792,15 @@ class CLIController
exit(0);
}
$apikey = $this->arguments['apikey'] ?? '';
$self = intval(value: $this->arguments['self'] ?? 0);
$self = $this->arguments['self'] ?? 'no';
if ($this->panelRepository->findByName(name: $name)) {
echo "Panel: $name already exists." . PHP_EOL;
exit(1);
} else {
$result = $this->panelRepository->insert(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey, self: $self);
$panel = new Panel(name: $name, a: $a, aaaa: $aaaa, passphrase: $apikey, self: $self);
$result = $this->panelRepository->insert(panel: $panel);
echo "Panel $name has been created with id $result" . PHP_EOL;
exit(0);
}
@ -620,20 +818,15 @@ class CLIController
echo 'All available panels:' . PHP_EOL;
$table = new ConsoleTable();
$table->setHeaders(content: ['ID', 'Name', 'A', 'AAAA', 'API Key (Prefix)', 'This Panel']);
foreach ($panels as $panel) {
$row = [];
$token = strtok(string: $panel->getApikey(), token: '.');
$row[] = $panel->getID();
$row[] = $panel->getName();
$row[] = $panel->getA();
$row[] = $panel->getAaaa();
$row[] = $token;
if ($panel->getSelf() == 1) {
$row[] = 'Yes';
} else {
$row[] = 'No';
}
$row[] = $panel->getApikeyPrefix();
$row[] = ucfirst(string: $panel->getSelf());
$table->addRow(data: $row);
}
$table->setPadding(value: 2);
@ -657,12 +850,7 @@ class CLIController
$a = $this->arguments['a'] ?? '';
$aaaa = $this->arguments['aaaa'] ?? '';
$apikey = $this->arguments['apikey'] ?? '';
$self = intval(value: $this->arguments['self'] ?? 0);
// a workaround for 0 being equal to false …
if ($self == 0) {
$self = -1;
}
$self = $this->arguments['self'] ?? '';
if ($id == 0) {
echo 'An ID is required' . PHP_EOL;
@ -672,8 +860,13 @@ class CLIController
echo "Panel with ID : $id doesn't exist." . PHP_EOL;
exit(1);
}
if ($this->panelRepository->update(id: $id, name: $name, a: $a, aaaa: $aaaa, apikey: $apikey, self: $self) !== false) {
echo 'Panel has been updated' . PHP_EOL;
if ($apikey) {
$panel = new Panel(name: $name, id: $id, a: $a, aaaa: $aaaa, passphrase: $apikey, self: $self);
} else {
$panel = new Panel(name: $name, id: $id, a: $a, aaaa: $aaaa, self: $self);
}
if ($this->panelRepository->update(panel: $panel) !== false) {
echo 'Panel ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been updated' . PHP_EOL;
} else {
echo 'Error while updating domain server.' . PHP_EOL;
}
@ -705,7 +898,7 @@ class CLIController
/**
*/
function handleAPIPing(string $type): void
function handleApiPing(string $type): void
{
$this->logger->debug(message: "handleApiPing()");
@ -725,7 +918,7 @@ class CLIController
$error = true;
}
} else {
if ($this->configController->getConfig(configKey: 'verbose')) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo "Unknown $type ID $id" . PHP_EOL;
}
$error = true;
@ -742,10 +935,13 @@ class CLIController
}
}
}
if ($this->configController->getConfig(configKey: 'verbose')) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo PHP_EOL;
}
if ($error) {
if (!$this->configController->getConfig(configKey: 'verbose')) {
echo 'There were errors, run command with -V (or -verbose) to see the errors.' . PHP_EOL;
}
exit(1);
} else {
exit(0);
@ -771,13 +967,15 @@ class CLIController
}
/**
* @param \App\Entity\Panel|\App\Entity\Nameserver $server
* @param Panel|Nameserver $server
* @param String $type
*
* @return bool
*/
public function checkPing(Panel|Nameserver $server, string $type): bool
{
$this->logger->debug(message: "handleApiPing() - server, type: " . $server->getName() . ', ' . $type);
$error = false;
if ($type == 'nameserver') {
@ -790,12 +988,16 @@ class CLIController
$maxAAAA = $this->panelRepository->getLongestEntry(field: 'aaaa');
}
if ($this->configController->getConfig(configKey: 'verbose')) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo COLOR_YELLOW . str_pad(string: $server->getName(), length: $maxName);
}
$encryptionKey = $this->configController->getConfig(configKey: 'encryptionKey');
$decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $server->getApikey(), key: $encryptionKey);
$a = $server->getA() ?? '';
if (!empty($a)) {
$this->logger->debug("check a");
if ($this->configController->getConfig(configKey: 'verbose')) {
echo COLOR_DEFAULT . ' ' . str_pad(string: $a, length: $maxA, pad_type: STR_PAD_LEFT) . ' ';
}
@ -803,14 +1005,17 @@ class CLIController
requestType: 'GET',
serverName: $server->getName(),
versionIP: 4,
apiKey: $server->getApikey(),
apiKey: $decryptedKey,
command: 'ping',
serverType: $type)) {
if ($this->configController->getConfig(configKey: 'verbose')) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
if ($result['data'] == 'pong') {
echo COLOR_GREEN . $result['data'];
echo ' ' . COLOR_GREEN . $result['data'];
} else {
echo COLOR_BLUE . 'skip';
echo COLOR_BLUE . ' skip' . COLOR_DEFAULT;
if ($this->configController->getConfig(configKey: 'verbose')) {
echo ' ' . $result['data'];
}
}
}
} else {
@ -819,6 +1024,7 @@ class CLIController
}
$aaaa = $server->getAaaa() ?? '';
if (!empty($aaaa)) {
$this->logger->debug("check aaaa");
if ($this->configController->getConfig(configKey: 'verbose')) {
echo COLOR_DEFAULT . ' ' . str_pad(string: $aaaa, length: $maxAAAA, pad_type: STR_PAD_LEFT) . ' ';
}
@ -826,24 +1032,33 @@ class CLIController
requestType: 'GET',
serverName: $server->getName(),
versionIP: 6,
apiKey: $server->getApikey(),
apiKey: $decryptedKey,
command: 'ping',
serverType: $type)) {
if ($this->configController->getConfig(configKey: 'verbose')) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
if ($result['data'] == 'pong') {
echo COLOR_GREEN . $result['data'];
echo ' ' . COLOR_GREEN . $result['data'];
} else {
echo COLOR_BLUE . $result['data']; // TODO 'skip';
echo COLOR_BLUE . ' skip' . COLOR_DEFAULT;
if ($this->configController->getConfig(configKey: 'verbose')) {
echo ' ' . $result['data'];
}
}
}
} else {
$error = true;
}
}
if ($this->configController->getConfig(configKey: 'verbose')) {
echo PHP_EOL;
try {
sodium_memzero(string: $decryptedKey);
} catch (SodiumException $e) {
die($e->getMessage() . PHP_EOL);
}
return $error;
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo COLOR_DEFAULT . PHP_EOL;
}
return !$error;
}
/**
@ -869,9 +1084,27 @@ class CLIController
{
$name = $this->arguments['name'] ?? '';
$result = $this->apikeyRepository->create(name: $name);
echo 'API key ' . COLOR_YELLOW . $result['row'] . COLOR_DEFAULT . ' has been generated. Store it in a save place, it cannot be recovered.' . PHP_EOL;
echo "\033[32m\t" . $result['tokenPrefix'] . '.' . $result['key'] . PHP_EOL;
$apiKeyPrefix = uniqid();
try {
$apikeyRand = bin2hex(string: random_bytes(length: 24));
} catch (Exception $e) {
die($e->getMessage() . PHP_EOL);
}
$passphrase = password_hash(password: $apiKeyPrefix . '.' . $apikeyRand, algo: PASSWORD_ARGON2ID);
$apikey = new Apikey(name: $name, apikeyPrefix: $apiKeyPrefix, passphrase: $passphrase);
$result = $this->apikeyRepository->insert(apikey: $apikey);
if ($name) {
echo 'API key ' . COLOR_YELLOW . $name . COLOR_DEFAULT;
} else {
echo 'Unnamed API key ';
}
echo ' with ID ' . COLOR_YELLOW . $result . COLOR_DEFAULT . ' has been generated. Store it in a safe place, it cannot be recovered.' . PHP_EOL;
echo COLOR_YELLOW . $apiKeyPrefix . '.' . $apikeyRand . COLOR_DEFAULT . PHP_EOL;
exit(0);
}
@ -889,7 +1122,7 @@ class CLIController
$row = [];
$row[] = $key->getID();
$row[] = $key->getName();
$row[] = $key->getApiTokenPrefix();
$row[] = $key->getApikeyPrefix();
$table->addRow(data: $row);
}
$table->setPadding(value: 2);
@ -905,24 +1138,24 @@ class CLIController
*/
function handleApikeysUpdate(): void
{
// TODO check for use of id instead of number, mind for all occurences
$id = $this->arguments[1] ?? 0;
$id = intval(value: $this->arguments[1]) ?? 0;
$name = $this->arguments['name'] ?? '';
if ($id == 0) {
echo 'An ID is required' . PHP_EOL;
exit(1);
}
if (empty($name)) {
echo 'You need to supply the new name.' . PHP_EOL;
exit(1);
}
if (!$this->apikeyRepository->findByID(id: intval(value: $id))) {
echo "Apikeys with ID : $id doesn't exist." . PHP_EOL;
exit(1);
}
if ($this->apikeyRepository->update(id: intval(value: $id), name: $name) !== false) {
if (!$name) {
echo 'You need tu supply a name.' . PHP_EOL;
exit(1);
}
$apikey = new Apikey(id: $id, name: $name);
if ($this->apikeyRepository->update(apikey: $apikey) !== false) {
echo 'Apikey has been updated' . PHP_EOL;
} else {
echo 'Error while updating apikey.' . PHP_EOL;
@ -960,6 +1193,7 @@ class CLIController
match ($subcommand) {
'list' => $this->handleDomainsList(),
'refresh' => $this->handleDomainsRefresh(),
'update' => $this->handleDomainsUpdate(),
'delete' => $this->handleDomainsDelete(),
default => $this->unknownSubcommand(subcommand: $subcommand)
};
@ -1070,14 +1304,14 @@ class CLIController
if ($this->dynDNSRepository->findByName(name: $name)) {
if ($this->configController->getConfig(configKey: 'verbose')) {
echo "DynDNS host " . COLOR_YELLOW . $name . COLOR_DEFAULT . "already exists.". PHP_EOL;
echo "DynDNS host " . COLOR_YELLOW . $name . COLOR_DEFAULT . "already exists." . PHP_EOL;
exit(0);
}
} else {
if ($this->configController->getConfig(configKey: 'verbose')) {
echo "DynDNS host " . COLOR_YELLOW . $name . COLOR_DEFAULT . "will be created.". PHP_EOL;
echo "DynDNS host " . COLOR_YELLOW . $name . COLOR_DEFAULT . "will be created." . PHP_EOL;
// insert in db
$dyndnsHost = new DynDNS();
$dyndnsHost = new DynDNS(name: $name);
$dyndnsHost->setName($name);
}
}
@ -1125,8 +1359,7 @@ class CLIController
exit(1);
}
$arguments = $this->parseArguments();
$panel = $arguments['panel'] ?? '';
$panel = $this->arguments['panel'] ?? '';
if (empty($panel)) {
echo 'You need to supply the panel name.' . PHP_EOL;
@ -1159,11 +1392,9 @@ class CLIController
exit(1);
}
$arguments = $this->parseArguments();
$id = intval(value: $this->arguments[1] ?? 0);
$name = $arguments['name'] ?? '';
$panelName = $arguments['panel'] ?? '';
$name = $this->arguments['name'] ?? '';
$panelName = $this->arguments['panel'] ?? '';
if ($id == 0) {
echo 'An ID is required' . PHP_EOL;
@ -1273,23 +1504,27 @@ class CLIController
exit(1);
}
$arguments = $this->parseArguments();
$a = $arguments['a'] ?? '';
$aaaa = $arguments['aaaa'] ?? '';
$a = $this->arguments['a'] ?? '';
$aaaa = $this->arguments['aaaa'] ?? '';
if (empty($a) && empty($aaaa)) {
echo 'At least one IP address is required.' . PHP_EOL;
exit(0);
}
$apikey = $arguments['apikey'] ?? '';
$apikey = $this->arguments['apikey'] ?? '';
if (empty($apikey)) {
echo 'An API key is required.' . PHP_EOL;
exit(0);
}
if ($this->nameserverRepository->findByName(name: $name)) {
echo "Nameserver: $name already exists." . PHP_EOL;
exit(1);
} else {
$nameserver = new Nameserver(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey);
$nameserver = new Nameserver(name: $name, a: $a, aaaa: $aaaa, passphrase: $apikey);
$result = $this->nameserverRepository->insert(nameserver: $nameserver);
echo "Nameserver $name has been created with id $result" . PHP_EOL;
echo 'Nameserver ' . COLOR_YELLOW . $name . COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . PHP_EOL;
exit(0);
}
}
@ -1307,12 +1542,11 @@ class CLIController
$table->setHeaders(content: ['ID', 'Name', 'A', 'AAAA', 'API Key']);
foreach ($nameservers as $nameserver) {
$row = [];
$token = strtok(string: $nameserver->getApiKey(), token: '.');
$row[] = $nameserver->getId();
$row[] = $nameserver->getName();
$row[] = $nameserver->getA();
$row[] = $nameserver->getAaaa();
$row[] = $token;
$row[] = $nameserver->getApikeyPrefix();
$table->addRow(data: $row);
}
$table->setPadding(value: 2);
@ -1329,13 +1563,11 @@ class CLIController
*/
function handleNameserversUpdate(): void
{
$arguments = $this->parseArguments();
$id = $this->arguments[1] ?? 0;
$name = $arguments['name'] ?? '';
$a = $arguments['a'] ?? '';
$aaaa = $arguments['aaaa'] ?? '';
$apikey = $arguments['apikey'] ?? '';
$name = $this->arguments['name'] ?? '';
$a = $this->arguments['a'] ?? '';
$aaaa = $this->arguments['aaaa'] ?? '';
$apikey = $this->arguments['apikey'] ?? '';
if ($id == 0) {
echo 'An ID is required.' . PHP_EOL;
@ -1345,7 +1577,14 @@ class CLIController
echo 'Nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . " doesn't exist." . PHP_EOL;
exit(1);
}
if ($this->nameserverRepository->update(id: intval(value: $id), name: $name, a: $a, aaaa: $aaaa, apikey: $apikey) !== false) {
if ($apikey) {
$nameserver = new Nameserver(name: $name, id: intval(value: $id), a: $a, aaaa: $aaaa, passphrase: $apikey);
} else {
$nameserver = new Nameserver(name: $name, id: intval(value: $id), a: $a, aaaa: $aaaa);
}
if ($this->nameserverRepository->update(nameserver: $nameserver) !== false) {
echo 'Nameserver ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been updated.' . PHP_EOL;
} else {
echo 'Error while updating nameserver ' . COLOR_YELLOW . $id . '.' . PHP_EOL;
@ -1480,26 +1719,27 @@ class CLIController
exit(0);
}
private
function handleCheckGenerateKey(): void
/**
*/
private function handleCheckGenerateKey(): void
{
echo 'This generates a fresh encryption key.' . PHP_EOL;
echo 'Copy it to config.json.' . PHP_EOL;
echo 'Note: You must update all API-Keys for panels and nameservers after changing the key!' . PHP_EOL;
$cStrong = false;
$bytes = null;
while (!$cStrong) {
$bytes = openssl_random_pseudo_bytes(length: 18, strong_result: $cStrong);
}
$hex = bin2hex(string: $bytes);
echo 'Suggested new key : ' . COLOR_YELLOW . $hex . COLOR_DEFAULT . '.' . PHP_EOL;
try {
$key = sodium_bin2hex(string: sodium_crypto_secretbox_keygen());
echo 'Suggested new key : "' . COLOR_YELLOW . $key . COLOR_DEFAULT . '".' . PHP_EOL;
echo PHP_EOL;
exit(0);
} catch (SodiumException $e) {
die($e->getMessage() . PHP_EOL);
}
private
function handleDomainsRefresh(): void
}
private function handleDomainsRefresh(): void
{
// TODO check for self in check:permissions
@ -1507,15 +1747,17 @@ class CLIController
$this->logger->debug(message: "handleDomainsRefresh()");
// TODO create getSelf()
$panel = $this->panelRepository->findByName(name: 'keyhelp.lab.24unix.net');
$panels = $this->panelRepository->findAll();
foreach ($panels as $panel) {
echo COLOR_DEFAULT . 'Checking panel ' . COLOR_YELLOW . $panel->getName() . COLOR_DEFAULT . PHP_EOL;
if (empty($panel->getA())) {
$result = $this->apiController->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $panel->getApikey(),
command: 'domains?sort=domain',
command: 'domains?sort=domain&subdomains=false',
serverType: 'panel'
);
} else {
@ -1524,7 +1766,7 @@ class CLIController
serverName: $panel->getName(),
versionIP: 4,
apiKey: $panel->getApikey(),
command: 'domains?sort=domain',
command: 'domains?sort=domain&subdomains=false',
serverType: 'panel');
}
@ -1539,30 +1781,24 @@ class CLIController
exit(1);
}
// TODO remove stale domains
$domainCount = 0;
if (count($domains) > 0) {
foreach ($domains as $domain) {
if ($this->isValidSecondLevelDomain(domainName: $domain->domain, panel: $panel->getName(), parent: $domain->id_parent_domain)) {
$domainCount++;
echo COLOR_YELLOW . $domain->domain;
echo COLOR_YELLOW . ' ' . $domain->domain;
if ($this->domainRepository->findByName(name: $domain->domain)) {
echo COLOR_GREEN . ' OK';
echo COLOR_GREEN . ' OK' . COLOR_DEFAULT . PHP_EOL;
} else {
$newDomain = new Domain(name: $domain->domain, panel: $panel->getName());
$result = $this->domainRepository->insert(domain: $newDomain);
echo COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . '.' . PHP_EOL;
}
echo PHP_EOL;
}
}
}
if ($domainCount == 0) {
echo 'No second level domains found.' . COLOR_DEFAULT . PHP_EOL;
}
echo PHP_EOL;
}
$this->domainController->updateSlaveZones();
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace App\Controller\Commands;
use Closure;
/**
*
*/
class Command
{
public function __construct(
private readonly string $name,
private readonly Closure $callback,
private readonly array $mandatoryParameters = [],
private readonly array $optionalParameters = [],
private readonly string $description = ''
)
{
// no body
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return array
*/
public function getMandatoryParameters(): array
{
return $this->mandatoryParameters;
}
/**
* @return array
*/
public function getOptionalParameters(): array
{
return $this->optionalParameters;
}
/**
* @return string|null
*/
public function getDescription(): ?string
{
return $this->description;
}
/**
* @return Closure
*/
public function getCallback(): Closure
{
return $this->callback;
}
public function exec(): void
{
call_user_func(callback: $this->callback);
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace App\Controller\Commands;
/**
*
*/
class CommandGroup
{
private array $commands = [];
public function __construct(private readonly string $name, private readonly string $description)
{
// no body
}
public function addCommand(Command $command): ?CommandGroup
{
$this->commands[] = $command;
return $this;
}
public function getName(): string
{
return $this->name;
}
public function printCommands(int $longestCommandLength): void
{
echo COLOR_YELLOW . str_pad(string: $this->name, length: $longestCommandLength + 1) . COLOR_WHITE . $this->description . COLOR_DEFAULT . PHP_EOL;
foreach ($this->commands as $command) {
echo COLOR_GREEN . str_pad(string: ' ', length: $longestCommandLength + 1, pad_type: STR_PAD_LEFT) . $this->name . ':' . $command->getName();
foreach ($command->getMandatoryParameters() as $parameter) {
echo ' <' . $parameter . '>';
}
foreach ($command->getOptionalParameters() as $parameter) {
echo ' {' . $parameter . '}';
}
echo COLOR_WHITE . ' ' . $command->getDescription();
echo COLOR_DEFAULT . PHP_EOL;
}
}
public function findCommandByName(string $command): ?Command
{
foreach ($this->commands as $currentCommand) {
if ($command === $currentCommand->getName()) {
return $currentCommand;
}
}
return null;
}
public function exec(string $subcommand): void
{
if ($command = $this->findCommandByName(command: $subcommand)) {
$command->exec();
} else {
echo COLOR_DEFAULT . 'Command ' . COLOR_YELLOW . $this->name . ':' . $subcommand . COLOR_DEFAULT . ' not found.' . PHP_EOL;
exit(1);
}
}
}

View File

@ -0,0 +1,73 @@
<?php
namespace App\Controller\Commands;
/**
*
*/
class CommandGroupContainer
{
private array $commandGroups = [];
public function addCommandGroup(CommandGroup $commandGroup): CommandGroupContainer
{
$this->commandGroups[] = $commandGroup;
return $this;
}
/**
* @return void
*/
public function printCommands(): void
{
$longestCommandLength = $this->getLongestCommandLength();
foreach ($this->commandGroups as $commandGroup) {
$commandGroup->printCommands($longestCommandLength);
}
}
/**
* @return int
*/
public function getLongestCommandLength(): int
{
$longest = 0;
foreach ($this->commandGroups as $group) {
$len = strlen(string: $group->getName());
if ($len > $longest) {
$longest = $len;
}
}
return $longest;
}
/**
* @param string $command
* @return ?CommandGroup
*/
private function findGroupByName(string $command): ?CommandGroup
{
foreach ($this->commandGroups as $group) {
if ($group->getName() === $command) {
return $group;
}
}
return null;
}
public function run(string $command, string $subcommand): void
{
if ($group = $this->findGroupByName(command: $command)) {
$group->exec(subcommand: $subcommand);
} else {
echo COLOR_DEFAULT . 'Unknown command ' . COLOR_YELLOW . $command . COLOR_DEFAULT . '.' . PHP_EOL;
exit(1);
}
}
}

View File

@ -9,7 +9,7 @@ class ConfigController
{
private array $config;
public function __construct(bool $verbose = false) {
public function __construct(bool $verbose = false, bool $quiet = false) {
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json.local";
if (!file_exists(filename: $configFile)) {
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json";
@ -41,6 +41,11 @@ class ConfigController
} else {
$this->config['verbose'] = false;
}
if ($quiet) {
$this->config['quiet'] = true;
} else {
$this->config['quiet'] = false;
}
}
public function getConfig(string $configKey): string {

View File

@ -98,16 +98,30 @@ class DomainController
'name' => $domain->getName()
];
if (!empty($nameserver->getAaaa())) {
$this->checkController->sendCommand(requestType: 'DELETE', serverName: $nameserver->getName(), versionIP: 6, apiKey: $nameserver->getApikey(), command: 'delete', serverType: 'nameserver', body: $body);
$this->checkController->sendCommand(
requestType: 'DELETE',
serverName: $nameserver->getName(),
versionIP: 6,
apiKey: $nameserver->getApikey(),
command: 'delete',
serverType: 'nameserver',
body: $body);
} else {
$this->checkController->sendCommand(requestType: 'DELETE', serverName: $nameserver->getName(), versionIP: 4, apiKey: $nameserver->getApikey(), command: 'delete', serverType: 'nameserver', body: $body);
$this->checkController->sendCommand(
requestType: 'DELETE',
serverName: $nameserver->getName(),
versionIP: 4,
apiKey: $nameserver->getApikey(),
command: 'delete',
serverType: 'nameserver',
body: $body);
}
}
}
/**
* @param \App\Entity\Domain $domain
* @param Domain $domain
*
* @return void
*/
@ -230,25 +244,34 @@ class DomainController
$domains = $this->domainRepository->findAll();
foreach ($domains as $domain) {
echo COLOR_YELLOW . str_pad(string: $domain->getName(), length: $maxNameLength + 1) . COLOR_DEFAULT;
$idString = '(' . strval(value: $domain->getId()) . ') ';
echo COLOR_YELLOW .
str_pad(string: $domain->getName(), length: $maxNameLength + 1)
. COLOR_DEFAULT
. str_pad(string: $idString, length: 7, pad_type: STR_PAD_LEFT);
$hasError = false;
if ($this->isMasterZone(domain: $domain)) {
echo 'Master Zone lies on this panel.';
} else {
if (!str_contains(haystack: $localZones, needle: $domain->getName())) {
echo COLOR_RED . ' is missing in ' . COLOR_YELLOW . $this->localZoneFile . COLOR_DEFAULT;
echo COLOR_RED . 'is missing in ' . COLOR_YELLOW . $this->localZoneFile . COLOR_DEFAULT;
$hasError = true;
} else {
echo $domain->getName() . ' exists in ' . COLOR_YELLOW . $this->localZoneFile;
echo COLOR_GREEN . 'OK';
}
$zoneFile = $this->localZonesDir . $domain->getName();
if (!file_exists(filename: $zoneFile)) {
echo "Missing zone file for $zoneFile . Update zone to create it";
}
echo ' Missing zone file for ' . COLOR_YELLOW . $zoneFile . COLOR_DEFAULT;
$hasError = true;
}
if ($hasError) {
echo " Update zone (Domain) to create it.";
}
}
echo COLOR_DEFAULT . PHP_EOL;
}
@ -256,7 +279,7 @@ class DomainController
/**
* @param \App\Entity\Domain $domain
* @param Domain $domain
*
* @return void
*/
@ -267,11 +290,11 @@ class DomainController
// check if we're a master zone
if ($this->isMasterZone(domain: $domain)) {
echo 'We are zone master for ' . $domainName . PHP_EOL;
exit(1);
//echo 'We are zone master for ' . $domainName . PHP_EOL;
return;
}
if ($zonefile = fopen(filename: $this->localZonesDir . $domainName, mode: 'w')) {
if ($zoneFile = fopen(filename: $this->localZonesDir . $domainName, mode: 'w')) {
$panelName = $domain->getPanel();
if (!$panel = $this->panelRepository->findByName(name: $panelName)) {
echo "Error: Panel $panelName doesn't exist." . PHP_EOL;
@ -279,18 +302,18 @@ class DomainController
}
$a = $panel->getA();
$aaaa = $panel->getAaaa();
fputs(stream: $zonefile, data: 'zone "' . $domainName . '"' . ' IN {' . PHP_EOL);
fputs(stream: $zonefile, data: "\ttype slave;" . PHP_EOL);
fputs(stream: $zonefile, data: "\tfile \"" . $this->zoneCachePath . $domainName . '.db";' . PHP_EOL);
fputs(stream: $zonefile, data: "\tmasters {" . PHP_EOL);
fputs(stream: $zoneFile, data: 'zone "' . $domainName . '"' . ' IN {' . PHP_EOL);
fputs(stream: $zoneFile, data: "\ttype slave;" . PHP_EOL);
fputs(stream: $zoneFile, data: "\tfile \"" . $this->zoneCachePath . $domainName . '.db";' . PHP_EOL);
fputs(stream: $zoneFile, data: "\tmasters {" . PHP_EOL);
if (!empty($a)) {
fputs(stream: $zonefile, data: "\t\t" . $a . ';' . PHP_EOL);
fputs(stream: $zoneFile, data: "\t\t" . $a . ';' . PHP_EOL);
}
if (!empty($aaaa)) {
fputs(stream: $zonefile, data: "\t\t" . $aaaa . ';' . PHP_EOL);
fputs(stream: $zoneFile, data: "\t\t" . $aaaa . ';' . PHP_EOL);
}
fputs(stream: $zonefile, data: "\t};" . PHP_EOL);
fputs(stream: $zonefile, data: "};" . PHP_EOL);
fputs(stream: $zoneFile, data: "\t};" . PHP_EOL);
fputs(stream: $zoneFile, data: "};" . PHP_EOL);
}
}

View File

@ -20,11 +20,13 @@ class EncryptionController
*/
function safeEncrypt(string $message, string $key): string
{
$binKey = sodium_hex2bin(string: $key);
$nonce = random_bytes(length: SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipher = base64_encode(string: $nonce . sodium_crypto_secretbox(message: $message, nonce: $nonce, key: $key));
$cipher = base64_encode(string: $nonce . sodium_crypto_secretbox(message: $message, nonce: $nonce, key: $binKey));
sodium_memzero(string: $message);
sodium_memzero(string: $key);
sodium_memzero(string: $binKey);
return $cipher;
}
@ -39,19 +41,23 @@ class EncryptionController
*/
function safeDecrypt(string $encrypted, string $key): string
{
$binKey = sodium_hex2bin(string: $key);
$decoded = base64_decode(string: $encrypted);
if ($decoded === false) {
throw new Exception(message: 'Decoding broken. Wrong key?');
throw new Exception(message: 'Decoding broken. Wrong payload.');
}
if (mb_strlen(string: $decoded, encoding: '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
throw new Exception(message: 'Decoding broken. Incomplete message.');
}
$nonce = mb_substr(string: $decoded, start: 0, length: SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, encoding: '8bit');
$ciphertext = mb_substr(string: $decoded, start: SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, length: null, encoding: '8bit');
$plain = sodium_crypto_secretbox_open(ciphertext: $ciphertext, nonce: $nonce, key: $key);
$plain = sodium_crypto_secretbox_open(ciphertext: $ciphertext, nonce: $nonce, key: $binKey);
if ($plain === false) {
throw new Exception(message: 'The message was tampered with in transit');
throw new Exception(message: ' Incorrect key.');
}
sodium_memzero(string: $ciphertext);
sodium_memzero(string: $key);

View File

@ -11,7 +11,6 @@ use App\Repository\DomainRepository;
use App\Repository\DynDNSRepository;
use App\Repository\PanelRepository;
use Monolog\Logger;
use OpenApi\Annotations as OA;
use OpenApi\Attributes as OAT;
use UnhandledMatchError;
@ -58,13 +57,13 @@ class RequestController
/**
* @param \App\Controller\ApiController $apiController
* @param \App\Repository\ApikeyRepository $apikeyRepository
* @param \App\Controller\DomainController $domainController
* @param \App\Repository\DomainRepository $domainRepository
* @param \App\Repository\DynDNSRepository $dynDNSRepository
* @param \App\Repository\PanelRepository $panelRepository
* @param \Monolog\Logger $logger
* @param ApiController $apiController
* @param ApikeyRepository $apikeyRepository
* @param DomainController $domainController
* @param DomainRepository $domainRepository
* @param DynDNSRepository $dynDNSRepository
* @param PanelRepository $panelRepository
* @param Logger $logger
*/
public function __construct(
private readonly ApiController $apiController,

View File

@ -2,22 +2,39 @@
namespace App\Entity;
use App\Controller\ConfigController;
use App\Controller\EncryptionController;
use Exception;
use SodiumException;
/**
*
*/
class Apikey
{
private int $id;
private string $name;
private string $apiTokenPrefix;
private string $apiToken;
public function __construct(string $name, string $apiTokenPrefix, string $apiToken, int $id = 0)
public function __construct(
private int $id = 0,
private string $name = '',
private string $apiTokenPrefix = '',
private string $apiToken = '',
private readonly string $passphrase = ''
)
{
$this->id = $id;
$this->name = $name;
$this->apiTokenPrefix = $apiTokenPrefix;
$this->apiToken = $apiToken;
if ($this->passphrase) {
$configController = new ConfigController();
$encryptionController = new EncryptionController();
$encryptionKey = $configController->getConfig(configKey: 'encryptionKey');
$this->apiTokenPrefix = strtok(string: $this->passphrase, token: '.');
try {
$this->apiToken = $encryptionController->safeEncrypt(message: $this->passphrase, key: $encryptionKey);
} catch (Exception|SodiumException $e) {
die($e->getMessage() . PHP_EOL);
}
}
}

View File

@ -2,7 +2,11 @@
namespace App\Entity;
use App\Controller\ConfigController;
use App\Controller\EncryptionController;
use Exception;
use OpenApi\Attributes as OAT;
use SodiumException;
/**
*
@ -11,24 +15,60 @@ use OpenApi\Attributes as OAT;
class Nameserver
{
private int $id;
private String $name;
private String $a;
private String $aaaa;
private String $apikey;
public function __construct(String $name, int $id = 0, String $a = '', String $aaaa = '', String $apikey = '')
/**
* @param string $name
* @param int $id
* @param string $a
* @param string $aaaa
* @param string $passphrase
* @param string $apikey
* @param string $apikeyPrefix
*/
public function __construct(
private string $name,
private int $id = 0,
private string $a = '',
private string $aaaa = '',
private readonly string $passphrase = '',
private string $apikey = '',
private string $apikeyPrefix = '')
{
$this->id = $id;
$this->name = $name;
$this->a = $a;
$this->aaaa = $aaaa;
$this->apikey = $apikey;
if ($this->passphrase) {
$configController = new ConfigController();
$encryptionController = new EncryptionController();
$encryptionKey = $configController->getConfig(configKey: 'encryptionKey');
[$this->apikeyPrefix] = explode(separator: '.', string: $this->passphrase);
try {
$this->apikey = $encryptionController->safeEncrypt(message: $this->passphrase, key: $encryptionKey);
} catch (Exception|SodiumException $e) {
die($e->getMessage() . PHP_EOL);
}
}
}
/**
* @return string
*/
public function getApikeyPrefix(): string
{
return $this->apikeyPrefix;
}
/**
* @param string $apikeyPrefix
*/
public function setApikeyPrefix(string $apikeyPrefix): void
{
$this->apikeyPrefix = $apikeyPrefix;
}
/**
* @return String
* @return string
*/
#[OAT\Property(type: 'string')]
public function getA(): string
@ -37,7 +77,7 @@ class Nameserver
}
/**
* @param String $a
* @param string $a
*/
public function setA(string $a): void
{
@ -45,7 +85,7 @@ class Nameserver
}
/**
* @return String
* @return string
*/
#[OAT\Property(type: 'string')]
public function getAaaa(): string
@ -54,7 +94,7 @@ class Nameserver
}
/**
* @param String $aaaa
* @param string $aaaa
*/
public function setAaaa(string $aaaa): void
{
@ -62,7 +102,7 @@ class Nameserver
}
/**
* @return String
* @return string
*/
#[OAT\Property(type: 'string')]
public function getApikey(): string
@ -71,7 +111,7 @@ class Nameserver
}
/**
* @param String $apikey
* @param string $apikey
*/
public function setApikey(string $apikey): void
{
@ -96,7 +136,7 @@ class Nameserver
}
/**
* @return String
* @return string
*/
#[OAT\Property(type: 'string')]
public function getName(): string
@ -105,11 +145,19 @@ class Nameserver
}
/**
* @param String $name
* @param string $name
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* @return string
*/
public function getPassphrase(): string
{
return $this->passphrase;
}
}

View File

@ -2,75 +2,76 @@
namespace App\Entity;
use App\Controller\ConfigController;
use App\Controller\EncryptionController;
use Exception;
use SodiumException;
/**
*
*/
class Panel
{
private int $id;
private String $name;
private String $a;
private String $aaaa;
private String $apikey;
private int $self;
/**
* @param String $name
* @param string $name
* @param int $id
* @param String $a
* @param String $aaaa
* @param String $apikey
* @param int $self
* @param string $a
* @param string $aaaa
* @param string $passphrase
* @param string $apikey
* @param string $apikeyPrefix
* @param string $self
*/
public function __construct(String $name, int $id = 0, String $a = '', String $aaaa = '', String $apikey = '', int $self = 0)
public function __construct(
private string $name,
private int $id = 0,
private string $a = '',
private string $aaaa = '',
private readonly string $passphrase = '',
private string $apikey = '',
private string $apikeyPrefix = '',
private string $self = 'no',
)
{
if ($this->passphrase) {
$configController = new ConfigController();
$encryptionController = new EncryptionController();
$encryptionKey = $configController->getConfig(configKey: 'encryptionKey');
$this->apikeyPrefix = strtok(string: $this->passphrase, token: '.');
try {
$this->apikey = $encryptionController->safeEncrypt(message: $this->passphrase, key: $encryptionKey);
} catch (Exception|SodiumException $e) {
die($e->getMessage() . PHP_EOL);
}
}
}
/**
* @return string
*/
public function getPassphrase(): string
{
return $this->passphrase;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*/
public function setName(string $name): void
{
$this->id = $id;
$this->name = $name;
$this->a = $a;
$this->aaaa = $aaaa;
$this->apikey = $apikey;
$this->self = $self;
}
/**
* @return int
*/
public function getSelf(): int
{
return $this->self;
}
/**
* @param int $self
*/
public function setSelf(int $self): void
{
$this->self = $self;
}
/**
* @return String
*/
public function getA(): string
{
return $this->a;
}
/**
* @return String
*/
public function getAaaa(): string
{
return $this->aaaa;
}
/**
* @return String
*/
public function getApikey(): string
{
return $this->apikey;
}
/**
@ -90,33 +91,50 @@ class Panel
}
/**
* @return String
* @return string
*/
public function getName(): string
public function getA(): string
{
return $this->name;
return $this->a;
}
/**
* @param String $apikey
* @return string
*/
public function setApikey(string $apikey): void
public function getSelf(): string
{
$this->apikey = $apikey;
return $this->self;
}
/**
* @param string $self
*/
public function setSelf(string $self): void
{
$this->self = $self;
}
/**
* @param String $name
* @return string
*/
public function setName(string $name): void
public function getAaaa(): string
{
$this->name = $name;
return $this->aaaa;
}
/**
* @param String $a
* @return string
*/
public function getApikey(): string
{
return $this->apikey;
}
/**
* @param string $a
*/
public function setA(string $a): void
{
@ -124,11 +142,20 @@ class Panel
}
/**
* @param String $aaaa
* @param string $aaaa
*/
public function setAaaa(string $aaaa): void
{
$this->aaaa = $aaaa;
}
/**
* @return string
*/
public function getApikeyPrefix(): string
{
return $this->apikeyPrefix;
}
}

View File

@ -3,7 +3,6 @@
namespace App\Repository;
use App\Controller\DatabaseConnection;
use App\Entity\Domain;
use App\Entity\Panel;
use PDO;
use PDOException;
@ -14,39 +13,37 @@ use PDOException;
class PanelRepository
{
public function __construct(private readonly DatabaseConnection $databaseConnection)
{}
{
// no body
}
public function findSelf(): array
/**
* @return array|null
*/
public function findSelf(): ?array
{
$sql = "
SELECT id, name, a, aaaa, apikey, self
SELECT id, name, a, aaaa, apikey, apikey_prefix, self
FROM " . DatabaseConnection::TABLE_PANELS . "
WHERE self = 1";
$panels = [];
try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->execute();
while ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
$panel = new Panel(name: $result['name'], id: $result['id'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], self: $result['self']);
$panel = new Panel(name: $result['name'], id: $result['id'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], apikeyPrefix: $result['apikey_prefix'], self: $result['self']);
$panels[] = $panel;
}
return $panels;
} catch (PDOException $e) {
exit($e->getMessage());
}
}
/**
* @return array
*/
public function findAll(): array
public function findAll(): ?array
{
$panels = [];
$sql = "
SELECT id, name, a, aaaa, apikey, self
SELECT id, name, a, aaaa, apikey, apikey_prefix, self
FROM " . DatabaseConnection::TABLE_PANELS . "
ORDER BY name";
@ -54,7 +51,7 @@ class PanelRepository
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->execute();
while ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
$panel = new Panel(name: $result['name'], id: $result['id'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], self: $result['self']);
$panel = new Panel(name: $result['name'], id: $result['id'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], apikeyPrefix: $result['apikey_prefix'], self: $result['self']);
$panels[] = $panel;
}
return $panels;
@ -67,12 +64,12 @@ class PanelRepository
/**
* @param int $id
*
* @return null|\App\Entity\Panel
* @return null|Panel
*/
public function findByID(int $id): ?Panel
{
$sql = "
SELECT id, name, a, aaaa, apikey, self
SELECT id, name, a, aaaa, apikey, apikey_prefix, self
FROM . " . DatabaseConnection::TABLE_PANELS . "
WHERE id = :id";
@ -81,7 +78,7 @@ class PanelRepository
$statement->bindParam(param: ':id', var: $id);
$statement->execute();
if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
return new Panel(name: $result['name'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], self: $result['self']);
return new Panel(name: $result['name'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], apikeyPrefix: $result['apikey_prefix'], self: $result['self']);
} else {
return null;
}
@ -94,12 +91,12 @@ class PanelRepository
/**
* @param String $name
*
* @return \App\Entity\Panel|bool
* @return Panel|null
*/
public function findByName(string $name): Panel|bool
public function findByName(string $name): ?Panel
{
$sql = "
SELECT id, name, a, aaaa, apikey, self
SELECT id, name, a, aaaa, apikey, apikey_prefix, self
FROM " . DatabaseConnection::TABLE_PANELS . "
WHERE name = :name";
@ -108,9 +105,9 @@ class PanelRepository
$statement->bindParam(param: ':name', var: $name);
$statement->execute();
if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
return new Panel(name: $result['name'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], self: $result['self']);
return new Panel(name: $result['name'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], apikeyPrefix: $result['apikey_prefix'], self: $result['self']);
} else {
return false;
return null;
}
} catch (PDOException $e) {
exit($e->getMessage());
@ -119,18 +116,21 @@ class PanelRepository
/**
* @param String $name
* @param String $a
* @param String $aaaa
* @param String $apikey
*
* @return string|false
* @param Panel $panel
* @return int|null
*/
public function insert(string $name, string $a, string $aaaa, String $apikey, int $self): bool|string
public function insert(Panel $panel): ?int
{
$name = $panel->getName();
$a = $panel->getA();
$aaaa = $panel->getAaaa();
$apikey = $panel->getApikey();
$apikeyPrefix = $panel->getApikeyPrefix();
$self = $panel->getSelf();
$sql = "
INSERT INTO " . DatabaseConnection::TABLE_PANELS . " (name, a, aaaa, apikey, self)
VALUES (:name, :a, :aaaa, :apikey, :self)";
INSERT INTO " . DatabaseConnection::TABLE_PANELS . " (name, a, aaaa, apikey, apikey_prefix, self)
VALUES (:name, :a, :aaaa, :apikey, :prefix, :self)";
try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
@ -138,10 +138,11 @@ class PanelRepository
$statement->bindParam(param: ':a', var: $a);
$statement->bindParam(param: ':aaaa', var: $aaaa);
$statement->bindParam(param: ':apikey', var: $apikey);
$statement->bindParam(param: ':prefix', var: $apikeyPrefix);
$statement->bindParam(param: ':self', var: $self);
$statement->execute();
return $this->databaseConnection->getConnection()->lastInsertId();
return intval(value: $this->databaseConnection->getConnection()->lastInsertId());
} catch (PDOException $e) {
exit($e->getMessage());
}
@ -149,18 +150,22 @@ class PanelRepository
/**
* @param Int $id
* @param String $name
* @param String $a
* @param String $aaaa
* @param String $apikey
*
* @return false|int
* @param Panel $panel
* @return int|null
*/
public function update(int $id, string $name, string $a, string $aaaa, String $apikey, int $self): bool|int
public function update(Panel $panel): ?int
{
$id = $panel->getId();
$name = $panel->getName();
$a = $panel->getA();
$aaaa = $panel->getAaaa();
$apikey = $panel->getApikey();
$apikeyPrefix = $panel->getApikeyPrefix();
$passphrase = $panel->getPassphrase();
$current = $this->findByID(id: $id);
if (empty($name)) {
$name = $current->getName();
}
@ -170,25 +175,24 @@ class PanelRepository
if (empty($aaaa)) {
$aaaa = $current->getAaaa();
}
if (empty($apikey)) {
if (empty($passphrase)) {
$apikey = $current->getApikey();
$apikeyPrefix = $current->getApikeyPrefix();
}
if (empty($self)) {
echo "self is empty";
$self = $current->getSelf();
} else {
if ($self == -1) {
$self = 0;
}
}
$sql = "
UPDATE " . DatabaseConnection::TABLE_PANELS . " SET
name = :name,
a = :a,
aaaa = :aaaa,
apikey = :apikey,
apikey_prefix = :apikey_prefix,
self = :self
WHERE id = :id";
@ -199,13 +203,14 @@ class PanelRepository
$statement->bindParam(param: 'a', var: $a);
$statement->bindParam(param: 'aaaa', var: $aaaa);
$statement->bindParam(param: 'apikey', var: $apikey);
$statement->bindParam(param: 'apikey_prefix', var: $apikeyPrefix);
$statement->bindParam(param: 'self', var: $self);
$statement->execute();
return $statement->rowCount();
return intval(value: $statement->rowCount());
} catch (PDOException $e) {
echo $e->getMessage();
return false;
return null;
}
}
@ -213,9 +218,9 @@ class PanelRepository
/**
* @param $id
*
* @return int
* @return int|null
*/
public function delete($id): int
public function delete($id): ?int
{
$sql = "
DELETE FROM " . DatabaseConnection::TABLE_PANELS . "
@ -226,7 +231,7 @@ class PanelRepository
$statement->bindParam(param: 'id', var: $id);
$statement->execute();
return $statement->rowCount();
return intval(value: $statement->rowCount());
} catch (PDOException $e) {
exit($e->getMessage());
}
@ -236,9 +241,9 @@ class PanelRepository
/**
* @param String $field
*
* @return int
* @return int|null
*/
public function getLongestEntry(String $field): int
public function getLongestEntry(string $field): ?int
{
$sql = "
SELECT MAX(LENGTH(" . $field . ")) as length FROM " . DatabaseConnection::TABLE_PANELS;