bindAPI/src/Controller/DomainController.php

388 lines
12 KiB
PHP

<?php declare(strict_types=1);
namespace App\Controller;
use App\Entity\Domain;
use App\Repository\DomainRepository;
use App\Repository\NameserverRepository;
use App\Repository\PanelRepository;
use App\Service\ApiClient;
use App\Utilities\Colors;
use Monolog\Logger;
error_reporting(error_level: E_ALL);
// TODO check include "/etc/bind/local.zones";
/**
*
*/
class DomainController
{
public string $localZoneFile;
public string $localZonesDir;
public string $namedConfLocalFile;
private string $zoneCachePath;
public function __construct(
private readonly NameserverRepository $nameserverRepository,
private readonly ApiClient $checkController,
private readonly DomainRepository $domainRepository,
private readonly PanelRepository $panelRepository,
private readonly ConfigController $configController,
private readonly Logger $logger,
private readonly bool $quiet
)
{
$this->localZoneFile = '/etc/bind/local.zones';
$this->localZonesDir = '/etc/bind/zones/';
$this->namedConfLocalFile = '/etc/bind/named.conf.local';
$this->zoneCachePath = '/var/cache/bind/';
}
function createIncludeFile(): void
{
$this->logger->debug(message: "createIncludeFile()");
$domains = $this->domainRepository->findAll();
$oFile = fopen(filename: $this->localZoneFile, mode: 'w');
foreach ($domains as $domain) {
if (!$this->isMasterZone(domain: $domain)) {
fputs(stream: $oFile, data: 'include "' . $this->localZonesDir . $domain->getName() . '";' . PHP_EOL);
}
}
fclose(stream: $oFile);
exec(command: '/usr/bin/named-checkconf', output: $output, result_code: $resultCode);
if ($resultCode != 0) {
echo 'There was an error:' . PHP_EOL;
foreach ($output as $line) {
echo $line . PHP_EOL;
}
echo 'You need to fix the error before the configuration can be activated.' . PHP_EOL;
exit(1);
}
exec(command: '/usr/sbin/rndc reload');
}
function updateSlaveZones(): void
{
$this->logger->debug(message: 'update slave zones');
$existingZones = glob(pattern: $this->localZonesDir . '*');
$domains = $this->domainRepository->findAll();
$longestEntry = $this->domainRepository->getLongestEntry(field: 'name');
$self = $this->panelRepository->getSelf();
foreach ($domains as $domain) {
$zoneFile = $this->localZonesDir . $domain->getName();
if (!$this->quiet) {
echo ' ' . Colors::YELLOW . str_pad(string: $domain->getName(), length: $longestEntry + 1, pad_string: " ", pad_type: STR_PAD_RIGHT) ;
}
if (strcmp(string1: $self->getName(), string2: $domain->getPanel()) !== 0) {
if (!file_exists(filename: $zoneFile)) {
if (!$this->quiet) {
echo Colors::GREEN . ' OK' . Colors::DEFAULT . PHP_EOL;
}
$this->createSlaveZoneFile(domain: $domain);
} else {
if (($key = array_search(needle: $zoneFile, haystack: $existingZones)) !== false) {
if (isset($existingZones[$key])) {
unset($existingZones[$key]);
}
} else {
echo 'missing value: ' . $zoneFile;
}
if (!$this->quiet) {
echo Colors::DEFAULT . 'Zone already exists.' . PHP_EOL;
}
}
} else {
if (!$this->quiet) {
echo Colors::DEFAULT . 'We are master for ' . Colors::YELLOW . $domain->getName() . PHP_EOL;
}
}
}
// remove stale zones
foreach ($existingZones as $zone) {
if (!$this->quiet) {
echo 'Removing stale zone: ' . Colors::YELLOW . $zone . Colors::DEFAULT . PHP_EOL;
}
echo $zone . PHP_EOL;
unlink(filename: $zone);
}
$semaphore = $this->localZonesDir . 'zones.flag';
if (file_exists(filename: $semaphore)) {
unlink(filename: $semaphore);
$this->createIncludeFile();
}
}
function deleteOnNameservers(Domain $domain): void
{
$this->logger->debug(message: "deleteOnNameserver()");
$nameservers = $this->nameserverRepository->findAll();
foreach ($nameservers as $nameserver) {
$body = [
'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);
} else {
$this->checkController->sendCommand(
requestType: 'DELETE',
serverName: $nameserver->getName(),
versionIP: 4,
apiKey: $nameserver->getApikey(),
command: 'delete',
serverType: 'nameserver',
body: $body);
}
}
}
/**
* @param Domain $domain
*
* @return void
*/
function deleteZone(Domain $domain): void
{
$this->logger->debug(message: "deleteZone()");
$zoneFile = $this->localZonesDir . $domain->getName();
if (file_exists(filename: "$zoneFile")) {
unlink(filename: $zoneFile);
}
$this->createIncludeFile();
$this->deleteOnNameservers(domain: $domain);
}
function checkPermissions($impersonatedUserId = null): bool
{
$this->logger->debug(message: "checkPermissions()");
$setupIsValid = true;
if (!$this->quiet) {
echo 'Checking permissions...' . PHP_EOL;
}
if ($impersonatedUserId) {
$uid = $impersonatedUserId;
} else {
$uid = posix_geteuid();
}
if (!$this->quiet) {
echo "UID:\t" . Colors::YELLOW . $uid . PHP_EOL;
}
$pwuid = posix_getpwuid(user_id: $uid);
$name = $pwuid['name'];
if (!$this->quiet) {
echo Colors::DEFAULT . "Name:\t" . Colors::YELLOW . $name . PHP_EOL;
}
if (!$bindGroup = posix_getgrnam(name: 'bind')) {
$bindGroup = [];
}
$members = $bindGroup['members'] ?? [];
if (in_array(needle: $name, haystack: $members)) {
if (!$this->quiet) {
echo "\t$name" . Colors::DEFAULT . ' is in group ' . Colors::YELLOW . 'bind' . PHP_EOL;
}
} else {
$setupIsValid = false;
if (!$this->quiet) {
echo Colors::RED . "\t$name needs to be in group " . Colors::YELLOW . 'bind' . Colors::DEFAULT . '!' . PHP_EOL;
}
}
if (!$this->quiet) {
echo Colors::DEFAULT . 'Checking ' . Colors::YELLOW . $this->localZoneFile . PHP_EOL;
}
$localZoneFilePermissions = @fileperms(filename: $this->localZoneFile);
if ($localZoneFilePermissions & 0x0010) {
if (!$this->quiet) {
echo Colors::DEFAULT . "\t✅ Group has write access." . PHP_EOL;
}
} else {
$setupIsValid = false;
if (!$this->quiet) {
echo Colors::RED . "\t❌Group needs write permission!" . Colors::DEFAULT . PHP_EOL;
}
}
if (!$this->quiet) {
echo 'Checking ' . Colors::YELLOW . $this->namedConfLocalFile . PHP_EOL;
}
if (file_exists(filename: $this->namedConfLocalFile) && $namedConfLocal = file_get_contents(filename: $this->namedConfLocalFile)) {
if (!str_contains(haystack: $namedConfLocal, needle: $this->localZoneFile)) {
$setupIsValid = false;
if (!$this->quiet) {
echo "\t$this->localZoneFile" . Colors::RED . ' needs to be included in ' . Colors::YELLOW . $this->namedConfLocalFile . PHP_EOL;
}
} else {
if (!$this->quiet) {
echo "\t$this->localZoneFile" . Colors::DEFAULT . ' is included in ' . Colors::YELLOW . $this->namedConfLocalFile . PHP_EOL;
}
}
} else {
$setupIsValid = false;
if (!$this->quiet) {
echo "\t❌ No access to '$this->namedConfLocalFile' . Please check permissions" . PHP_EOL;
}
}
if (!$this->quiet) {
echo Colors::DEFAULT . 'Checking directory: ' . Colors::YELLOW . $this->localZonesDir . PHP_EOL;
}
$localZoneDirPermissions = @fileperms(filename: $this->localZonesDir);
if ($localZoneDirPermissions & 0x0010) {
if (!$this->quiet) {
echo "\t✅ Group has write access." . PHP_EOL;
}
} else {
$setupIsValid = false;
if (!$this->quiet) {
echo Colors::RED . "\t❌Group needs write permission!" . PHP_EOL;
}
}
return $setupIsValid;
}
/**
* @return void
*/
function checkDomains(): void
{
if (!file_exists(filename: $this->localZoneFile)) {
if (!$this->quiet) {
echo Colors::DEFAULT . 'Local Zone file ' . Colors::YELLOW . $this->localZoneFile . Colors::DEFAULT . ' does not exist.' . PHP_EOL;
}
exit(1);
}
$localZones = file_get_contents(filename: $this->localZoneFile);
$maxNameLength = $this->domainRepository->getLongestEntry(field: 'name');
$domains = $this->domainRepository->findAll();
foreach ($domains as $domain) {
$idString = '(' . $domain->getId() . ') ';
if (!$this->quiet) {
echo Colors::YELLOW .
str_pad(string: $domain->getName(), length: $maxNameLength + 1)
. Colors::DEFAULT
. str_pad(string: $idString, length: 7, pad_type: STR_PAD_LEFT);
}
$hasError = false;
if ($this->isMasterZone(domain: $domain)) {
if (!$this->quiet) {
echo Colors::GREEN . 'Master Zone';
}
} else {
if (!str_contains(haystack: $localZones, needle: $domain->getName())) {
if (!$this->quiet) {
echo Colors::RED . 'is missing in ' . Colors::YELLOW . $this->localZoneFile . Colors::DEFAULT;
}
$hasError = true;
} else {
if (!$this->quiet) {
echo Colors::GREEN . 'OK';
}
}
$zoneFile = $this->localZonesDir . $domain->getName();
if (!file_exists(filename: $zoneFile)) {
echo ' Missing zone file for ' . Colors::YELLOW . $zoneFile . Colors::DEFAULT;
$hasError = true;
}
if ($hasError) {
echo " Update zone (Domain) to create it.";
}
}
if (!$this->quiet) {
echo Colors::DEFAULT . PHP_EOL;
}
}
}
/**
* @param Domain $domain
*
* @return void
*/
public function createSlaveZoneFile(Domain $domain): bool
{
touch(filename: $this->localZonesDir . 'zones.flag');
$domainName = $domain->getName();
$this->logger->info(message: "createZoneFile($domainName)");
// check if we're a master zone
if ($this->isMasterZone(domain: $domain)) {
//echo 'We are zone master for ' . $domainName . PHP_EOL;
return true;
}
if ($zoneFile = fopen(filename: $this->localZonesDir . $domainName, mode: 'w')) {
$panelName = $domain->getPanel();
if (!$panel = $this->panelRepository->findByName(name: $panelName)) {
if (!$this->quiet) {
echo "Error: Panel $panelName doesn't exist." . PHP_EOL;
}
return false;
}
$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);
if (!empty($a)) {
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};" . PHP_EOL);
fputs(stream: $zoneFile, data: "};" . PHP_EOL);
return true;
} else {
if (!$this->quiet) {
echo Colors::RED . ' Error: ' . Colors::DEFAULT . 'unable to create ' . Colors::YELLOW . $this->localZonesDir . $domainName . Colors::DEFAULT . PHP_EOL;
}
return false;
}
}
public function isMasterZone(Domain $domain): bool
{
if (file_exists(filename: '/etc/bind/keyhelp_domains/' . $domain->getName())) {
return true;
} else {
return false;
}
}
}