Compare commits

..

No commits in common. "b536316a84755b624fcd144f6075586491bd3a2d" and "d5bdb1bade0cf52b2b4e0e4571eb203fef810d30" have entirely different histories.

14 changed files with 1840 additions and 2428 deletions

13
bin/console Executable file → Normal file
View File

@ -26,13 +26,11 @@ require dirname(path: __DIR__) . '/vendor/autoload.php';
$shortOpts = 'v::'; // version
$shortOpts = 'q::'; // version
$shortOpts .= "V::"; // verbose
$shortOpts .= "h::"; // help
$longOpts = [
'version::',
'quiet::',
'verbose::',
'help::'
];
@ -49,13 +47,6 @@ 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 {
@ -65,8 +56,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, quiet: $quiet);
$app->runCommand(arguments: $arguments);
$app = new BindAPI(verbose: $verbose );
$app->runCommand(argumentsCount: count(value: $arguments), arguments: $arguments);
} catch (DependencyException|NotFoundException|Exception $e) {
echo $e->getMessage() . PHP_EOL;

View File

@ -8,12 +8,8 @@ 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;
@ -25,10 +21,11 @@ class BindAPI
private Logger $logger;
private Container $container;
/**
* @throws Exception
* @throws \Exception
*/
public function __construct($verbose = false, $quiet = false)
public function __construct($verbose = false)
{
// init the logger
$dateFormat = "Y:m:d H:i:s";
@ -37,9 +34,9 @@ class BindAPI
$debug = (new ConfigController)->getConfig(configKey: 'debug');
if ($debug) {
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/bindAPI.log', level: Level::Debug);
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/bindAPI.log', level: Logger::DEBUG);
} else {
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/bindAPI.log', level: Level::Info);
$stream = new StreamHandler(stream: dirname(path: __DIR__, levels: 2) . '/bindAPI.log', level: Logger::INFO);
}
$stream->setFormatter(formatter: $formatter);
@ -51,7 +48,6 @@ 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),
@ -69,8 +65,8 @@ class BindAPI
/**
* @throws DependencyException
* @throws NotFoundException
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
public function runCommand(array $arguments): void
{
@ -81,8 +77,8 @@ class BindAPI
/**
* @throws DependencyException
* @throws NotFoundException
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
public function handleRequest(string $requestMethod, array $uri): void
{

View File

@ -11,13 +11,8 @@ 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;
@ -27,10 +22,7 @@ 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;
@ -43,7 +35,6 @@ if (php_sapi_name() !== 'cli') {
class CLIController
{
private array $arguments;
private CommandGroupContainer $commandGroupContainer;
/**
* @throws Exception
@ -57,159 +48,9 @@ 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
@ -235,6 +76,8 @@ class CLIController
}
// TODO encrypt the password in the config file, key in config
function runCommand(array $arguments): void
{
if (count($arguments) < 1) {
@ -253,7 +96,16 @@ class CLIController
}
$this->arguments = $this->parseArguments(arguments: $arguments);
$this->commandGroupContainer->run(command: $command, subcommand: $subcommand);
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)
};
}
@ -264,15 +116,6 @@ 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;
@ -280,9 +123,33 @@ 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: ' . COLOR_WHITE . '<mandatory> {optional}' . 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;
$this->commandGroupContainer->printCommands();
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;
echo COLOR_YELLOW . "dyndns" . COLOR_WHITE . " handle dyndns entries" . PHP_EOL;
echo COLOR_GREEN . "\t dyndns:list" . PHP_EOL;
@ -299,6 +166,21 @@ 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
{
@ -317,7 +199,7 @@ class CLIController
/**
*/
public function handleCheckPermissions(): void
function handleCheckPermissions(): void
{
$this->logger->debug(message: "handleCheckPermissions()");
@ -333,23 +215,6 @@ 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) {
@ -457,7 +322,7 @@ class CLIController
/**
* @param Panel $panel
* @param \App\Entity\Panel $panel
*
* @return void
*/
@ -465,10 +330,7 @@ class CLIController
{
$this->logger->debug(message: "checkSinglePanel()");
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);
echo COLOR_DEFAULT . 'KeyHelp-Panel: ' . COLOR_YELLOW . $panel->getName();
if ($this->configController->getConfig(configKey: 'verbose')) {
if (empty($panel->getA())) {
@ -476,7 +338,7 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $decryptedKey,
apiKey: $panel->getApikey(),
command: '/server',
serverType: 'panel');
} else {
@ -484,7 +346,7 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
apiKey: $decryptedKey,
apiKey: $panel->getApikey(),
command: '/server',
serverType: 'panel');
}
@ -506,8 +368,8 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $decryptedKey,
command: 'domains?sort=domain&subdomains=false',
apiKey: $panel->getApikey(),
command: 'domains?sort=domain',
serverType: 'panel'
);
} else {
@ -515,8 +377,8 @@ class CLIController
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
apiKey: $decryptedKey,
command: 'domains?sort=domain&subdomains=false',
apiKey: $panel->getApikey(),
command: 'domains?sort=domain',
serverType: 'panel');
}
@ -532,89 +394,30 @@ class CLIController
}
$maxDomainNameLength = 0;
$tmpDomainList = [];
$mapper = new JsonMapper();
$tmpDomainlist = [];
if (count($domains) > 0) {
foreach ($domains as $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 ($this->isValidSecondLevelDomain(domainName: $domain->domain, panel: $panel->getName(), parent: $domain->id_parent_domain)) {
$tmpDomainlist[] = $domain;
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->getDomain(), length: $maxDomainNameLength);
if (!$domain->isSubdomain()) {
$this->checkNS(domainName: $domain->getDomain(), panel: $panel);
foreach ($tmpDomainlist as $domain) {
echo COLOR_DEFAULT . " Domain: " . COLOR_YELLOW . str_pad(string: $domain->domain, length: $maxDomainNameLength);
$this->checkNS(domainName: $domain->domain, 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
{
@ -646,7 +449,7 @@ class CLIController
/**
* @param String $domainName
* @param Panel $panel
* @param \App\Entity\Panel $panel
*
* @return void
*/
@ -759,7 +562,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)
};
}
@ -792,15 +595,14 @@ class CLIController
exit(0);
}
$apikey = $this->arguments['apikey'] ?? '';
$self = $this->arguments['self'] ?? 'no';
$self = intval(value: $this->arguments['self'] ?? 0);
if ($this->panelRepository->findByName(name: $name)) {
echo "Panel: $name already exists." . PHP_EOL;
exit(1);
} else {
$panel = new Panel(name: $name, a: $a, aaaa: $aaaa, passphrase: $apikey, self: $self);
$result = $this->panelRepository->insert(panel: $panel);
$result = $this->panelRepository->insert(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey, self: $self);
echo "Panel $name has been created with id $result" . PHP_EOL;
exit(0);
}
@ -818,15 +620,20 @@ 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[] = $panel->getApikeyPrefix();
$row[] = ucfirst(string: $panel->getSelf());
$row[] = $token;
if ($panel->getSelf() == 1) {
$row[] = 'Yes';
} else {
$row[] = 'No';
}
$table->addRow(data: $row);
}
$table->setPadding(value: 2);
@ -850,7 +657,12 @@ class CLIController
$a = $this->arguments['a'] ?? '';
$aaaa = $this->arguments['aaaa'] ?? '';
$apikey = $this->arguments['apikey'] ?? '';
$self = $this->arguments['self'] ?? '';
$self = intval(value: $this->arguments['self'] ?? 0);
// a workaround for 0 being equal to false …
if ($self == 0) {
$self = -1;
}
if ($id == 0) {
echo 'An ID is required' . PHP_EOL;
@ -860,13 +672,8 @@ class CLIController
echo "Panel with ID : $id doesn't exist." . PHP_EOL;
exit(1);
}
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;
if ($this->panelRepository->update(id: $id, name: $name, a: $a, aaaa: $aaaa, apikey: $apikey, self: $self) !== false) {
echo 'Panel has been updated' . PHP_EOL;
} else {
echo 'Error while updating domain server.' . PHP_EOL;
}
@ -898,7 +705,7 @@ class CLIController
/**
*/
function handleApiPing(string $type): void
function handleAPIPing(string $type): void
{
$this->logger->debug(message: "handleApiPing()");
@ -918,7 +725,7 @@ class CLIController
$error = true;
}
} else {
if (!$this->configController->getConfig(configKey: 'quiet')) {
if ($this->configController->getConfig(configKey: 'verbose')) {
echo "Unknown $type ID $id" . PHP_EOL;
}
$error = true;
@ -935,13 +742,10 @@ class CLIController
}
}
}
if (!$this->configController->getConfig(configKey: 'quiet')) {
if ($this->configController->getConfig(configKey: 'verbose')) {
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);
@ -967,15 +771,13 @@ class CLIController
}
/**
* @param Panel|Nameserver $server
* @param \App\Entity\Panel|\App\Entity\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') {
@ -988,16 +790,12 @@ class CLIController
$maxAAAA = $this->panelRepository->getLongestEntry(field: 'aaaa');
}
if (!$this->configController->getConfig(configKey: 'quiet')) {
if ($this->configController->getConfig(configKey: 'verbose')) {
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) . ' ';
}
@ -1005,17 +803,14 @@ class CLIController
requestType: 'GET',
serverName: $server->getName(),
versionIP: 4,
apiKey: $decryptedKey,
apiKey: $server->getApikey(),
command: 'ping',
serverType: $type)) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
if ($result['data'] == 'pong') {
echo ' ' . COLOR_GREEN . $result['data'];
} else {
echo COLOR_BLUE . ' skip' . COLOR_DEFAULT;
if ($this->configController->getConfig(configKey: 'verbose')) {
echo ' ' . $result['data'];
}
if ($result['data'] == 'pong') {
echo COLOR_GREEN . $result['data'];
} else {
echo COLOR_BLUE . 'skip';
}
}
} else {
@ -1024,7 +819,6 @@ 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) . ' ';
}
@ -1032,33 +826,24 @@ class CLIController
requestType: 'GET',
serverName: $server->getName(),
versionIP: 6,
apiKey: $decryptedKey,
apiKey: $server->getApikey(),
command: 'ping',
serverType: $type)) {
if (!$this->configController->getConfig(configKey: 'quiet')) {
if ($result['data'] == 'pong') {
echo ' ' . COLOR_GREEN . $result['data'];
} else {
echo COLOR_BLUE . ' skip' . COLOR_DEFAULT;
if ($this->configController->getConfig(configKey: 'verbose')) {
echo ' ' . $result['data'];
}
if ($result['data'] == 'pong') {
echo COLOR_GREEN . $result['data'];
} else {
echo COLOR_BLUE . $result['data']; // TODO 'skip';
}
}
} else {
$error = true;
}
}
try {
sodium_memzero(string: $decryptedKey);
} catch (SodiumException $e) {
die($e->getMessage() . PHP_EOL);
if ($this->configController->getConfig(configKey: 'verbose')) {
echo PHP_EOL;
}
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo COLOR_DEFAULT . PHP_EOL;
}
return !$error;
return $error;
}
/**
@ -1084,27 +869,9 @@ class CLIController
{
$name = $this->arguments['name'] ?? '';
$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;
$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;
exit(0);
}
@ -1122,7 +889,7 @@ class CLIController
$row = [];
$row[] = $key->getID();
$row[] = $key->getName();
$row[] = $key->getApikeyPrefix();
$row[] = $key->getApiTokenPrefix();
$table->addRow(data: $row);
}
$table->setPadding(value: 2);
@ -1138,24 +905,24 @@ class CLIController
*/
function handleApikeysUpdate(): void
{
$id = intval(value: $this->arguments[1]) ?? 0;
// TODO check for use of id instead of number, mind for all occurences
$id = $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 (!$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) {
if ($this->apikeyRepository->update(id: intval(value: $id), name: $name) !== false) {
echo 'Apikey has been updated' . PHP_EOL;
} else {
echo 'Error while updating apikey.' . PHP_EOL;
@ -1193,7 +960,6 @@ class CLIController
match ($subcommand) {
'list' => $this->handleDomainsList(),
'refresh' => $this->handleDomainsRefresh(),
'update' => $this->handleDomainsUpdate(),
'delete' => $this->handleDomainsDelete(),
default => $this->unknownSubcommand(subcommand: $subcommand)
};
@ -1311,7 +1077,7 @@ class CLIController
if ($this->configController->getConfig(configKey: 'verbose')) {
echo "DynDNS host " . COLOR_YELLOW . $name . COLOR_DEFAULT . "will be created.". PHP_EOL;
// insert in db
$dyndnsHost = new DynDNS(name: $name);
$dyndnsHost = new DynDNS();
$dyndnsHost->setName($name);
}
}
@ -1359,7 +1125,8 @@ class CLIController
exit(1);
}
$panel = $this->arguments['panel'] ?? '';
$arguments = $this->parseArguments();
$panel = $arguments['panel'] ?? '';
if (empty($panel)) {
echo 'You need to supply the panel name.' . PHP_EOL;
@ -1392,9 +1159,11 @@ class CLIController
exit(1);
}
$arguments = $this->parseArguments();
$id = intval(value: $this->arguments[1] ?? 0);
$name = $this->arguments['name'] ?? '';
$panelName = $this->arguments['panel'] ?? '';
$name = $arguments['name'] ?? '';
$panelName = $arguments['panel'] ?? '';
if ($id == 0) {
echo 'An ID is required' . PHP_EOL;
@ -1504,27 +1273,23 @@ class CLIController
exit(1);
}
$arguments = $this->parseArguments();
$a = $this->arguments['a'] ?? '';
$aaaa = $this->arguments['aaaa'] ?? '';
$a = $arguments['a'] ?? '';
$aaaa = $arguments['aaaa'] ?? '';
if (empty($a) && empty($aaaa)) {
echo 'At least one IP address is required.' . PHP_EOL;
exit(0);
}
$apikey = $this->arguments['apikey'] ?? '';
if (empty($apikey)) {
echo 'An API key is required.' . PHP_EOL;
exit(0);
}
$apikey = $arguments['apikey'] ?? '';
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, passphrase: $apikey);
$nameserver = new Nameserver(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey);
$result = $this->nameserverRepository->insert(nameserver: $nameserver);
echo 'Nameserver ' . COLOR_YELLOW . $name . COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . PHP_EOL;
echo "Nameserver $name has been created with id $result" . PHP_EOL;
exit(0);
}
}
@ -1542,11 +1307,12 @@ 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[] = $nameserver->getApikeyPrefix();
$row[] = $token;
$table->addRow(data: $row);
}
$table->setPadding(value: 2);
@ -1563,11 +1329,13 @@ class CLIController
*/
function handleNameserversUpdate(): void
{
$arguments = $this->parseArguments();
$id = $this->arguments[1] ?? 0;
$name = $this->arguments['name'] ?? '';
$a = $this->arguments['a'] ?? '';
$aaaa = $this->arguments['aaaa'] ?? '';
$apikey = $this->arguments['apikey'] ?? '';
$name = $arguments['name'] ?? '';
$a = $arguments['a'] ?? '';
$aaaa = $arguments['aaaa'] ?? '';
$apikey = $arguments['apikey'] ?? '';
if ($id == 0) {
echo 'An ID is required.' . PHP_EOL;
@ -1577,14 +1345,7 @@ class CLIController
echo 'Nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . " doesn't exist." . PHP_EOL;
exit(1);
}
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) {
if ($this->nameserverRepository->update(id: intval(value: $id), name: $name, a: $a, aaaa: $aaaa, apikey: $apikey) !== false) {
echo 'Nameserver ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been updated.' . PHP_EOL;
} else {
echo 'Error while updating nameserver ' . COLOR_YELLOW . $id . '.' . PHP_EOL;
@ -1719,27 +1480,26 @@ 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;
try {
$key = sodium_bin2hex(string: sodium_crypto_secretbox_keygen());
echo 'Suggested new key : "' . COLOR_YELLOW . $key . COLOR_DEFAULT . '".' . 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;
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
@ -1747,17 +1507,15 @@ class CLIController
$this->logger->debug(message: "handleDomainsRefresh()");
// TODO create getSelf()
$panels = $this->panelRepository->findAll();
$panel = $this->panelRepository->findByName(name: 'keyhelp.lab.24unix.net');
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&subdomains=false',
command: 'domains?sort=domain',
serverType: 'panel'
);
} else {
@ -1766,7 +1524,7 @@ class CLIController
serverName: $panel->getName(),
versionIP: 4,
apiKey: $panel->getApikey(),
command: 'domains?sort=domain&subdomains=false',
command: 'domains?sort=domain',
serverType: 'panel');
}
@ -1781,24 +1539,30 @@ 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' . COLOR_DEFAULT . PHP_EOL;
echo COLOR_GREEN . ' OK';
} 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;
}
}
$this->domainController->updateSlaveZones();
echo PHP_EOL;
}
}

View File

@ -1,68 +0,0 @@
<?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

@ -1,68 +0,0 @@
<?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

@ -1,73 +0,0 @@
<?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, bool $quiet = false) {
public function __construct(bool $verbose = false) {
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json.local";
if (!file_exists(filename: $configFile)) {
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json";
@ -41,11 +41,6 @@ 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,30 +98,16 @@ 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 Domain $domain
* @param \App\Entity\Domain $domain
*
* @return void
*/
@ -244,34 +230,25 @@ class DomainController
$domains = $this->domainRepository->findAll();
foreach ($domains as $domain) {
$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);
echo COLOR_YELLOW . str_pad(string: $domain->getName(), length: $maxNameLength + 1) . COLOR_DEFAULT;
$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;
$hasError = true;
} else {
echo COLOR_GREEN . 'OK';
echo $domain->getName() . ' exists in ' . COLOR_YELLOW . $this->localZoneFile;
}
$zoneFile = $this->localZonesDir . $domain->getName();
if (!file_exists(filename: $zoneFile)) {
echo ' Missing zone file for ' . COLOR_YELLOW . $zoneFile . COLOR_DEFAULT;
$hasError = true;
echo "Missing zone file for $zoneFile . Update zone to create it";
}
}
if ($hasError) {
echo " Update zone (Domain) to create it.";
}
}
echo COLOR_DEFAULT . PHP_EOL;
}
@ -279,7 +256,7 @@ class DomainController
/**
* @param Domain $domain
* @param \App\Entity\Domain $domain
*
* @return void
*/
@ -290,11 +267,11 @@ class DomainController
// check if we're a master zone
if ($this->isMasterZone(domain: $domain)) {
//echo 'We are zone master for ' . $domainName . PHP_EOL;
return;
echo 'We are zone master for ' . $domainName . PHP_EOL;
exit(1);
}
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;
@ -302,18 +279,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,13 +20,11 @@ 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: $binKey));
$cipher = base64_encode(string: $nonce . sodium_crypto_secretbox(message: $message, nonce: $nonce, key: $key));
sodium_memzero(string: $message);
sodium_memzero(string: $key);
sodium_memzero(string: $binKey);
return $cipher;
}
@ -41,23 +39,19 @@ 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 payload.');
throw new Exception(message: 'Decoding broken. Wrong key?');
}
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: $binKey);
$plain = sodium_crypto_secretbox_open(ciphertext: $ciphertext, nonce: $nonce, key: $key);
if ($plain === false) {
throw new Exception(message: ' Incorrect key.');
throw new Exception(message: 'The message was tampered with in transit');
}
sodium_memzero(string: $ciphertext);
sodium_memzero(string: $key);

View File

@ -11,6 +11,7 @@ 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;
@ -57,13 +58,13 @@ class RequestController
/**
* @param ApiController $apiController
* @param ApikeyRepository $apikeyRepository
* @param DomainController $domainController
* @param DomainRepository $domainRepository
* @param DynDNSRepository $dynDNSRepository
* @param PanelRepository $panelRepository
* @param Logger $logger
* @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
*/
public function __construct(
private readonly ApiController $apiController,

View File

@ -2,39 +2,22 @@
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(
private int $id = 0,
private string $name = '',
private string $apiTokenPrefix = '',
private string $apiToken = '',
private readonly string $passphrase = ''
)
public function __construct(string $name, string $apiTokenPrefix, string $apiToken, int $id = 0)
{
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);
}
}
$this->id = $id;
$this->name = $name;
$this->apiTokenPrefix = $apiTokenPrefix;
$this->apiToken = $apiToken;
}

View File

@ -2,11 +2,7 @@
namespace App\Entity;
use App\Controller\ConfigController;
use App\Controller\EncryptionController;
use Exception;
use OpenApi\Attributes as OAT;
use SodiumException;
/**
*
@ -15,60 +11,24 @@ use SodiumException;
class Nameserver
{
/**
* @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 = '')
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 = '')
{
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;
$this->id = $id;
$this->name = $name;
$this->a = $a;
$this->aaaa = $aaaa;
$this->apikey = $apikey;
}
/**
* @return string
* @return String
*/
#[OAT\Property(type: 'string')]
public function getA(): string
@ -77,7 +37,7 @@ class Nameserver
}
/**
* @param string $a
* @param String $a
*/
public function setA(string $a): void
{
@ -85,7 +45,7 @@ class Nameserver
}
/**
* @return string
* @return String
*/
#[OAT\Property(type: 'string')]
public function getAaaa(): string
@ -94,7 +54,7 @@ class Nameserver
}
/**
* @param string $aaaa
* @param String $aaaa
*/
public function setAaaa(string $aaaa): void
{
@ -102,7 +62,7 @@ class Nameserver
}
/**
* @return string
* @return String
*/
#[OAT\Property(type: 'string')]
public function getApikey(): string
@ -111,7 +71,7 @@ class Nameserver
}
/**
* @param string $apikey
* @param String $apikey
*/
public function setApikey(string $apikey): void
{
@ -136,7 +96,7 @@ class Nameserver
}
/**
* @return string
* @return String
*/
#[OAT\Property(type: 'string')]
public function getName(): string
@ -145,19 +105,11 @@ 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,76 +2,75 @@
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 $passphrase
* @param string $apikey
* @param string $apikeyPrefix
* @param string $self
* @param String $a
* @param String $aaaa
* @param String $apikey
* @param int $self
*/
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
public function __construct(String $name, int $id = 0, String $a = '', String $aaaa = '', String $apikey = '', int $self = 0)
{
$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;
}
/**
@ -91,50 +90,33 @@ class Panel
}
/**
* @return string
* @return String
*/
public function getA(): string
public function getName(): string
{
return $this->a;
return $this->name;
}
/**
* @return string
* @param String $apikey
*/
public function getSelf(): string
public function setApikey(string $apikey): void
{
return $this->self;
}
/**
* @param string $self
*/
public function setSelf(string $self): void
{
$this->self = $self;
$this->apikey = $apikey;
}
/**
* @return string
* @param String $name
*/
public function getAaaa(): string
public function setName(string $name): void
{
return $this->aaaa;
$this->name = $name;
}
/**
* @return string
*/
public function getApikey(): string
{
return $this->apikey;
}
/**
* @param string $a
* @param String $a
*/
public function setA(string $a): void
{
@ -142,20 +124,11 @@ 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,6 +3,7 @@
namespace App\Repository;
use App\Controller\DatabaseConnection;
use App\Entity\Domain;
use App\Entity\Panel;
use PDO;
use PDOException;
@ -13,37 +14,39 @@ use PDOException;
class PanelRepository
{
public function __construct(private readonly DatabaseConnection $databaseConnection)
{
// no body
}
{}
/**
* @return array|null
*/
public function findSelf(): ?array
public function findSelf(): array
{
$sql = "
SELECT id, name, a, aaaa, apikey, apikey_prefix, self
SELECT id, name, a, aaaa, apikey, 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'], apikeyPrefix: $result['apikey_prefix'], self: $result['self']);
$panel = new Panel(name: $result['name'], id: $result['id'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], self: $result['self']);
$panels[] = $panel;
}
return $panels;
} catch (PDOException $e) {
exit($e->getMessage());
}
public function findAll(): ?array
}
/**
* @return array
*/
public function findAll(): array
{
$panels = [];
$sql = "
SELECT id, name, a, aaaa, apikey, apikey_prefix, self
SELECT id, name, a, aaaa, apikey, self
FROM " . DatabaseConnection::TABLE_PANELS . "
ORDER BY name";
@ -51,7 +54,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'], apikeyPrefix: $result['apikey_prefix'], self: $result['self']);
$panel = new Panel(name: $result['name'], id: $result['id'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], self: $result['self']);
$panels[] = $panel;
}
return $panels;
@ -64,12 +67,12 @@ class PanelRepository
/**
* @param int $id
*
* @return null|Panel
* @return null|\App\Entity\Panel
*/
public function findByID(int $id): ?Panel
{
$sql = "
SELECT id, name, a, aaaa, apikey, apikey_prefix, self
SELECT id, name, a, aaaa, apikey, self
FROM . " . DatabaseConnection::TABLE_PANELS . "
WHERE id = :id";
@ -78,7 +81,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'], apikeyPrefix: $result['apikey_prefix'], self: $result['self']);
return new Panel(name: $result['name'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], self: $result['self']);
} else {
return null;
}
@ -91,12 +94,12 @@ class PanelRepository
/**
* @param String $name
*
* @return Panel|null
* @return \App\Entity\Panel|bool
*/
public function findByName(string $name): ?Panel
public function findByName(string $name): Panel|bool
{
$sql = "
SELECT id, name, a, aaaa, apikey, apikey_prefix, self
SELECT id, name, a, aaaa, apikey, self
FROM " . DatabaseConnection::TABLE_PANELS . "
WHERE name = :name";
@ -105,9 +108,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'], apikeyPrefix: $result['apikey_prefix'], self: $result['self']);
return new Panel(name: $result['name'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey'], self: $result['self']);
} else {
return null;
return false;
}
} catch (PDOException $e) {
exit($e->getMessage());
@ -116,21 +119,18 @@ class PanelRepository
/**
* @param Panel $panel
* @return int|null
* @param String $name
* @param String $a
* @param String $aaaa
* @param String $apikey
*
* @return string|false
*/
public function insert(Panel $panel): ?int
public function insert(string $name, string $a, string $aaaa, String $apikey, int $self): bool|string
{
$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, apikey_prefix, self)
VALUES (:name, :a, :aaaa, :apikey, :prefix, :self)";
INSERT INTO " . DatabaseConnection::TABLE_PANELS . " (name, a, aaaa, apikey, self)
VALUES (:name, :a, :aaaa, :apikey, :self)";
try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
@ -138,11 +138,10 @@ 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 intval(value: $this->databaseConnection->getConnection()->lastInsertId());
return $this->databaseConnection->getConnection()->lastInsertId();
} catch (PDOException $e) {
exit($e->getMessage());
}
@ -150,22 +149,18 @@ class PanelRepository
/**
* @param Panel $panel
* @return int|null
* @param Int $id
* @param String $name
* @param String $a
* @param String $aaaa
* @param String $apikey
*
* @return false|int
*/
public function update(Panel $panel): ?int
public function update(int $id, string $name, string $a, string $aaaa, String $apikey, int $self): bool|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();
}
@ -175,16 +170,18 @@ class PanelRepository
if (empty($aaaa)) {
$aaaa = $current->getAaaa();
}
if (empty($passphrase)) {
if (empty($apikey)) {
$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
@ -192,7 +189,6 @@ class PanelRepository
a = :a,
aaaa = :aaaa,
apikey = :apikey,
apikey_prefix = :apikey_prefix,
self = :self
WHERE id = :id";
@ -203,14 +199,13 @@ 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 intval(value: $statement->rowCount());
return $statement->rowCount();
} catch (PDOException $e) {
echo $e->getMessage();
return null;
return false;
}
}
@ -218,9 +213,9 @@ class PanelRepository
/**
* @param $id
*
* @return int|null
* @return int
*/
public function delete($id): ?int
public function delete($id): int
{
$sql = "
DELETE FROM " . DatabaseConnection::TABLE_PANELS . "
@ -231,7 +226,7 @@ class PanelRepository
$statement->bindParam(param: 'id', var: $id);
$statement->execute();
return intval(value: $statement->rowCount());
return $statement->rowCount();
} catch (PDOException $e) {
exit($e->getMessage());
}
@ -241,9 +236,9 @@ class PanelRepository
/**
* @param String $field
*
* @return int|null
* @return int
*/
public function getLongestEntry(string $field): ?int
public function getLongestEntry(String $field): int
{
$sql = "
SELECT MAX(LENGTH(" . $field . ")) as length FROM " . DatabaseConnection::TABLE_PANELS;