Compare commits

..

No commits in common. "ea6e99e4be35f9c7fe55036f91fc163a7e7d1fcb" and "1b183fe626f584ab5bc022a009659c7c6cc33d4d" have entirely different histories.

6 changed files with 142 additions and 383 deletions

View File

@ -24,7 +24,7 @@ The CLI is used to perform configuration and some checks:
* check
- Permissions: The API needs to be able to access some files and create new ones
- Panels: This checks one or all panels if every nameserver is aware of all domains
- Domain: Check is all support files for domains on this NS are existing
- Domain: TODO
* panels
- List: List all panels which are configured on this server
- Create: Adds a new panel to the configuration

View File

@ -2,10 +2,10 @@
"openapi": "3.0.2",
"info": {
"title": "bindAPI",
"version": "0.0.2",
"version": "0.0.1",
"description": "TODO …",
"contact": {
"name": "Micha Espey",
"name": "micha Espey",
"email": "tracer@24unix.net"
}
},
@ -31,9 +31,6 @@
{
"name": "Server"
},
{
"name": "DNS"
},
{
"name": "Domains"
}
@ -69,45 +66,6 @@
]
}
},
"/dyndns/{hostname}": {
"get": {
"tags": [
"DNS"
],
"summary": "Updated a DynDNS host.",
"description": "Updates a predefined custom DNS entry.",
"operationId": "updateDynDNS",
"parameters": [
{
"name": "hostname",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"$ref": "#/components/requestBodies/dyndns-put"
},
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "API key is missing or invalid."
},
"404": {
"description": "Domain not found."
}
},
"security": [
{
"Authorization": []
}
]
}
},
"/domains": {
"get": {
"tags": [
@ -292,20 +250,6 @@
}
},
"requestBodies": {
"dyndns-put": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/dyndns"
},
"example": {
"a": "1.2.3.4",
"aaaa": "1bad::babe"
}
}
}
},
"domain-post": {
"required": true,
"content": {
@ -450,20 +394,6 @@
}
}
},
"dyndns": {
"type": "object",
"properties": {
"a": {
"type": "string",
"example": "1.2.3.4"
},
"aaaa": {
"type": "string",
"example": "1bad::babe"
}
}
},
"domain": {
"description": "Representation of a domain.\n",
"type": "object",

View File

@ -28,11 +28,13 @@ class ApiController
{
$error = false;
$curl = curl_init();
try {
match ($serverType) {
'panel' => curl_setopt(handle: $curl, option: CURLOPT_URL, value: "https://$serverName/api/v2/" . $command),
'nameserver' => curl_setopt(handle: $curl, option: CURLOPT_URL, value: "https://$serverName/api/" . $command)
};
} catch (UnhandledMatchError) {
echo 'Unhandled match: ' . $serverType;
@ -54,10 +56,6 @@ class ApiController
curl_setopt(handle: $curl, option: CURLOPT_POST, value: true);
curl_setopt(handle: $curl, option: CURLOPT_POSTFIELDS, value: $body);
}
if ($requestType == "PUT") {
curl_setopt(handle: $curl, option: CURLOPT_CUSTOMREQUEST, value: 'PUT');
curl_setopt(handle: $curl, option: CURLOPT_POSTFIELDS, value: json_encode(value: $body));
}
curl_setopt(handle: $curl, option: CURLOPT_CUSTOMREQUEST, value: $requestType);
@ -77,9 +75,6 @@ class ApiController
$result = $resultJSON;
}
break;
case 400:
$result = $resultJSON;
break;
case 401:
$result = 'Missing or wrong API Key';
break;

View File

@ -24,7 +24,7 @@ class DomainController
private string $keyhelpNamedCond;
public function __construct(private NameserverRepository $nameserverRepository, private ApiController $checkController, private DomainRepository $domainRepository, private PanelRepository $panelRepository, private array $config, private Logger $log)
public function __construct(private NameserverRepository $nameserverRepository, private ApiController $checkController, private DomainRepository $domainRepository, private PanelRepository $panelRepository, private array $config, private Logger $log)
{
if ($this->config['debug']) {
@ -35,10 +35,11 @@ class DomainController
$this->localZonesDir = '/etc/bind/zones/';
$this->namedConfLocalFile = '/etc/bind/named.conf.local';
$this->zoneCachePath = '/var/cache/bind/';
$this->keyhelpNamedCond = '/etc/bind/named.conf.keyhelp';
$this-> keyhelpNamedCond = '/etc/bind/named.conf.keyhelp';
}
function createIncludeFile()
{
if ($this->config['debug']) {
@ -108,15 +109,15 @@ class DomainController
echo 'Checking permission:' . PHP_EOL . PHP_EOL;
$uid = posix_geteuid();
print("UID:\t" . COLOR_YELLOW . $uid . PHP_EOL);
print("UID:\t$uid" . PHP_EOL);
$pwuid = posix_getpwuid(user_id: $uid);
$name = $pwuid['name'];
echo COLOR_DEFAULT . "Name:\t" . COLOR_YELLOW . $name . PHP_EOL;
print("Name:\t$name" . PHP_EOL);
$bindGroup = posix_getgrnam(name: 'bind');
$members = $bindGroup['members'];
if (in_array(needle: $name, haystack: $members)) {
echo "\t$name" . COLOR_DEFAULT . ' is in group ' . COLOR_YELLOW . 'bind' . PHP_EOL;
echo "\t$name is in group 'bind" . PHP_EOL;
} else {
echo "\t$name needs to be in group $bindGroup!" . PHP_EOL;
@ -125,7 +126,7 @@ class DomainController
echo 'Checking file: ' . $this->localZoneFile . PHP_EOL;
$localZoneFilePermissions = fileperms(filename: $this->localZoneFile);
if ($localZoneFilePermissions & 0x0010) {
echo "\t✅ Group has write access." . PHP_EOL;
echo "\t✅ Group has write access . " . PHP_EOL;
} else {
echo "\t❌Group needs write permission!" . PHP_EOL;
}
@ -144,7 +145,7 @@ class DomainController
echo 'Checking directory: ' . $this->localZonesDir . PHP_EOL;
$localZoneDirPermissions = fileperms(filename: $this->localZonesDir);
if ($localZoneDirPermissions & 0x0010) {
echo "\t✅ Group has write access." . PHP_EOL;
echo "\t✅ Group has write access . " . PHP_EOL;
} else {
echo "\t❌Group needs write permission!" . PHP_EOL;
}
@ -152,37 +153,47 @@ class DomainController
/**
* @return void
* @return array|bool
*/
function checkDomains(): void
function checkDomains(): array|bool
{
$localZones = file_get_contents(filename: $this->localZoneFile);
$maxNameLength = $this->domainRepository->getLongestEntry(field: 'name');
$domains = $this->domainRepository->findAll();
foreach ($domains as $domain) {
echo COLOR_YELLOW . str_pad(string: $domain->getName(), length: $maxNameLength + 1) . COLOR_DEFAULT;
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;
} else {
echo $domain->getName() . ' exists in ' . COLOR_YELLOW . $this->localZoneFile;
}
$zoneFile = $this->localZonesDir . $domain->getName();
if (!file_exists(filename: $zoneFile)) {
echo "Missing zone file for $zoneFile . Update zone to create it";
}
return true;
/*
$domains = $this->findAll();
if ($namedConfLocal = file_get_contents(filename: $this->namedConfLocalFile)) {
if (!str_contains(haystack: $namedConfLocal, needle: $this->localZoneFile)) {
return "$this->localZoneFile needs to be included in $this->namedConfLocalFile . ";
}
echo COLOR_DEFAULT . PHP_EOL;
} else {
return "No access to '$this->namedConfLocalFile' . Please check permissions";
}
if (!fileperms($this->localZoneFile)) {
return "No access to $this->localZoneFile . Please check permissions . ";
}
$localZones = file_get_contents($this->localZoneFile);
foreach($domains as $domain) {
if(!str_contains($localZones, $domain['name'])) {
$errors[] = $domain['name'] . " is missing in '$this->localZoneFile'";
}
$zoneFile = $this->localZonesDir . $domain['name'];
if (!file_exists($zoneFile)) {
$errors[] = "Missing zone file for $zoneFile . Update zone to create it";
}
}
if (empty($errors)) {
return true;
} else {
return $errors;
}
*/
}
@ -226,12 +237,5 @@ class DomainController
$this->createIncludeFile();
}
private function isMasterZone(Domain $domain): bool
{
if (file_exists(filename: '/etc/bind/keyhelp_domains/' . $domain->getName())) {
return true;
} else {
return false;
}
}
}

View File

@ -7,12 +7,12 @@ error_reporting(error_level: E_ALL);
use App\Entity\Domain;
use App\Repository\ApikeyRepository;
use App\Repository\DomainRepository;
use App\Repository\PanelRepository;
use DI\Container;
use DI\ContainerBuilder;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use OpenApi\Generator;
use UnhandledMatchError;
use function DI\autowire;
use OpenApi\Attributes as OAT;
@ -50,17 +50,14 @@ class RequestController
{
private Logger $log;
private ApiController $apiController;
private ApikeyRepository $apikeyRepository;
private DomainController $domainController;
private DomainRepository $domainRepository;
private PanelRepository $panelRepository;
private ApikeyRepository $apikeyRepository;
private Container $container;
private string $header;
private array $result;
private string $status;
private string $message;
/**
* @param array $config
@ -98,11 +95,10 @@ class RequestController
]);
$this->container = $containerBuilder->build();
$this->apiController = $this->container->get(name: ApiController::class);
$this->apikeyRepository = $this->container->get(name: ApikeyRepository::class);
$this->domainController = $this->container->get(name: DomainController::class);
$this->domainRepository = $this->container->get(name: DomainRepository::class);
$this->panelRepository = $this->container->get(name: PanelRepository::class);
$this->apikeyRepository = $this->container->get(name: ApikeyRepository::class);
}
/**
@ -135,7 +131,7 @@ class RequestController
description: 'Domain not found.'
)]
)]
private function handleAllDomainsGetRequest(): void
public function handleAllDomainsGetRequest(): void
{
$domains = $this->domainRepository->findAll();
$resultDomain = [];
@ -150,41 +146,6 @@ class RequestController
$this->result = $resultDomain;
}
/**
*/
private function handlePing()
{
if ($this->checkPassword()) {
$this->header = '200 OK';
$this->status = json_encode(value: ['response' => 'pong']);
} else {
$this->header = '401 Unauthorized';
$this->status = json_encode(value: ['message' => 'API key is missing or invalid']);
}
}
/**
* @return void
*/
private function handleDomains(): void
{
if ($this->checkPassword()) {
try {
match ($this->requestMethod) {
'GET' => $this->handleDomainsGetRequest(),
'POST' => $this->handleDomainsPostRequest(),
'PUT' => $this->handleDomainsPutRequest(),
'DELETE' => $this->handleDomainsDeleteRequest()
};
} catch (UnhandledMatchError) {
$this->header = '400 Bad Request';
$this->status = '400 Bad Request';
$this->message = "unknown request method: $this->requestMethod";
}
}
}
/**
* @OA\Tag(name = "Server")
@ -228,69 +189,90 @@ class RequestController
* @return void
*/
#[
OAT\Get(
path : '/domains/{name}',
operationId: 'getSingleDomain',
description: 'Returns information of a single domain specified by its domain name.',
summary : 'Returns a single domain.',
security : [
],
tags : ['Domains'],
parameters : [
new OAT\Parameter(name: 'name', in: 'path', required: true, schema: new OAT\Schema(type: 'string')),
],
responses : [
new OAT\Response(
response : 200,
description: 'OK'
),
new OAT\Response(
response : 401,
description: 'API key is missing or invalid.'
),
new OAT\Response(
response : 404,
description: 'Domain not found.'
)]
)]
#[OAT\Get(
path : '/domains/{name}',
operationId: 'getSingleDomain',
description: 'Returns information of a single domain specified by its domain name.',
summary : 'Returns a single domain.',
security : [
],
tags : ['Domains'],
parameters : [
new OAT\Parameter(name: 'name', in: 'path', required: true, schema: new OAT\Schema(type: 'string')),
],
responses : [
new OAT\Response(
response : 200,
description: 'OK'
),
new OAT\Response(
response : 401,
description: 'API key is missing or invalid.'
),
new OAT\Response(
response : 404,
description: 'Domain not found.'
)]
)]
public function processRequest()
{
$command = $this->uri[2];
if (empty($command) || !(($command == 'domains') || ($command == 'ping') || ($command == 'apidoc') || ($command == 'dyndns'))) {
if (empty($command) || !(($command == 'domains') || ($command == 'ping') || ($command == 'apidoc'))) {
$this->header = '404 Not Found';
$this->status = "404 Not Found";
$this->message = "Endpoint not found.";
} else {
try {
match ($command) {
'apidoc' => $this->apiDoc(),
'dyndns' => $this->handleDynDNS(),
'ping' => $this->handlePing(),
'domains' => $this->handleDomains(),
};
} catch (UnhandledMatchError) {
$this->header = '404 Bad Request';
$this->status = '404 Bad Request';
$this->message = 'Unknown path: ' . $command;
if ($command == 'apidoc') {
$openapi = Generator::scan(sources: [__DIR__ . 'RequestController.php']);
$this->status = 'openapi';
$this->result[] = $openapi->toJson();
} else {
if ($this->checkPassword()) {
if ($this->uri[2] == "ping") {
$this->header = '200 OK';
$this->status = 'pong';
} else {
try {
match ($this->requestMethod) {
'GET' => $this->handleDomainGetRequest(),
'POST' => $this->handleDomainPostRequest(),
'PUT' => $this->handleDomainPutRequest(),
'DELETE' => $this->handleDomainDeleteRequest()
};
} catch (UnhandledMatchError) {
$this->header = '400 Bad Request';
$this->status = '400 Bad Request';
$this->message = "unknown request method: $this->requestMethod";
}
}
}
}
if (!empty($this->header)) {
header(header: $_SERVER['SERVER_PROTOCOL'] . ' ' . $this->header);
}
if (!empty($this->result)) {
if (!empty($this->status) && $this->status == 'openapi') {
header(header: 'Content-Type: application/json');
echo $this->result[0];
} else {
echo json_encode(value: $this->result);
}
} else {
if (!empty($this->status) && $this->status == 'pong') {
echo json_encode(value: [
'response' => $this->status
]);
} else {
echo json_encode(value: [
'status' => $this->status ?? "Error: No status",
'message' => $this->message ?? "Error: No message."
]);
}
}
}
if (!empty($this->header)) {
header(header: $_SERVER['SERVER_PROTOCOL'] . ' ' . $this->header);
}
if (!empty($this->result)) {
echo json_encode(value: $this->result);
} elseif (!empty($this->status)) {
echo $this->status;
} else {
echo json_encode(value: [
'status' => $this->status ?? "Error: No status",
'message' => $this->message ?? "Error: No message."
]);
}
}
@ -298,7 +280,7 @@ class RequestController
/**
* @return bool
*/
private function checkPassword(): bool
public function checkPassword(): bool
{
$headers = array_change_key_case(array: getallheaders(), case: CASE_UPPER);
$apiKey = $headers['X-API-KEY'] ?? '';
@ -328,15 +310,12 @@ class RequestController
return true;
}
/**
* @return void
*/
private function handleDomainsGetRequest(): void
public function handleDomainGetRequest(): void
{
$name = $this->uri[3] ?? '';
if ($name == 'name') {
if ($this->uri[3] == 'name') {
if ($result = $this->domainRepository->findByName(name: $this->uri[4])) {
$domain = [
'id' => $result->getId(),
@ -350,10 +329,10 @@ class RequestController
$this->message = "The specified domain was not found.";
}
} else {
if (empty($name)) {
if (empty($this->uri[3])) {
$this->handleAllDomainsGetRequest();
} else {
$id = intval(value: $name);
$id = intval(value: $this->uri['3']);
if ($id > 0) {
if ($result = $this->domainRepository->findById(id: $id)) {
$domain = [
@ -381,7 +360,7 @@ class RequestController
/**
* @return void
*/
private function handleDomainsPostRequest(): void
public function handleDomainPostRequest(): void
{
$name = $_POST['name'] ?? '';
$panel = $_POST['panel'] ?? '';
@ -419,12 +398,12 @@ class RequestController
/**
* @return void
*/
private function handleDomainsPutRequest(): void
public function handleDomainPutRequest(): void
{
$putData = fopen(filename: 'php://input', mode: 'r');
$data = fread(stream: $putData, length: 8192);
$data = fread(stream: $putData, length: 512);
$params = explode(separator: '&', string: $data);
foreach ($params as $param) {
[$key, $value] = explode(separator: '=', string: $param);
$put[$key] = $value;
@ -456,7 +435,8 @@ class RequestController
/**
* @return void
*/
private function handleDomainsDeleteRequest(): void
public
function handleDomainDeleteRequest(): void
{
$deleteData = fopen(filename: 'php://input', mode: 'r');
$data = fread(stream: $deleteData, length: 512);
@ -488,154 +468,4 @@ class RequestController
}
}
private function apiDoc()
{
//TODO forward to apidoc …
}
/**
* @param String $host
*
* @return string
*/
private function getDomain(String $host): string
{
$host = strtolower(string: trim(string: $host));
$count = substr_count(haystack: $host, needle: '.');
if ($count == 2){
if (strlen(string: explode(separator: '.', string: $host)[1]) > 3) {
$host = explode(separator: '.', string: $host, limit: 2)[1];
}
} else if ($count > 2) {
$host = $this->getDomain(host: explode(separator: '.', string: $host, limit: 2)[1]);
}
return $host;
}
private function handleDynDNS()
{
if ($this->checkPassword()) {
$host = $this->uri[3] ?? '';
if (empty($host)) {
$this->header = '400 Bad Request';
$this->status = '400 Bad Request';
} else {
$a = $_POST['a'] ?? '';
$aaaa = $_POST['aaaa'] ?? '';
if (empty($a) && empty($aaaa)) {
$address = $_SERVER['REMOTE_ADDR'];
if (filter_var(value: $address, filter: FILTER_VALIDATE_IP, options: FILTER_FLAG_IPV6)) {
$aaaa = $address;
} else {
$a = $address;
}
}
$domainName = $this->getDomain(host: $host);
$hostName = str_replace(search: '.' . $domainName, replace: '', subject: $host);
$domain = $this->domainRepository->findByName(name: $domainName);
$panel = $this->panelRepository->findByName(name: $domain->getPanel());
if (!empty($panel->getAaaa())) {
$domainData = $this->apiController->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $panel->getApikey(),
command: 'domains/name/' . $domainName,
serverType: 'panel');
} else {
$domainData = $this->apiController->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
apiKey: $panel->getApikey(),
command: 'domains/name/' . $domainName,
serverType: 'panel');
}
$domainDecodedData = json_decode(json: $domainData['data']);
$domainID = $domainDecodedData->id;
if (!empty($panel->getAaaa())) {
$dnsData = $this->apiController->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $panel->getApikey(),
command: 'dns/' . $domainID,
serverType: 'panel');
} else {
$dnsData = $this->apiController->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
apiKey: $panel->getApikey(),
command: 'dns/' . $domainID,
serverType: 'panel');
}
$dnsDataDecoded = json_decode(json: $dnsData['data']);
$soa = $dnsDataDecoded->records->soa;
$others = $dnsDataDecoded->records->other;
$updateHost = function(object $host) use ($hostName, $a, $aaaa) {
if ($host->host == $hostName) {
if ($host->type == 'A') {
if (!empty($a)) {
$host->value = $a;
}
} else {
if (!empty($aaaa)) {
$host->value = $aaaa;
}
}
}
};
array_map(callback: $updateHost, array: $others);
$newDnsData = json_encode(value: [
'records' => [
'soa' => $soa,
'other' => $others
]
]);
if (!empty($panel->getAaaa())) {
$result = $this->apiController->sendCommand(
requestType: 'PUT',
serverName: $panel->getName(),
versionIP: 6,
apiKey: $panel->getApikey(),
command: 'dns/' . $domainID,
serverType: 'panel',
body: json_decode(json: $newDnsData, associative: true)
);
} else {
$result = $this->apiController->sendCommand(
requestType: 'PUT',
serverName: $panel->getName(),
versionIP: 4,
apiKey: $panel->getApikey(),
command: 'dns/' . $domainID,
serverType: 'panel',
body: json_decode(json: $newDnsData, associative: true)
);
}
if ($result['header'] == 200) {
$this->header = '200 OK';
$this->status = json_encode(value: ['message' => 'Domain successfully updated']);
}
}
}
}
}

View File

@ -82,7 +82,7 @@ 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']);
return new Panel(name: $result['name'], a: $result['a'], aaaa: $result['aaaa']);
} else {
return false;
}