Compare commits

..

7 Commits

Author SHA1 Message Date
tracer ea6e99e4be fixed missing apikey
Signed-off-by: tracer <tracer@24unix.net>
2022-03-01 16:44:56 +01:00
tracer 412e35cb02 added /dyndns endpoint
Signed-off-by: tracer <tracer@24unix.net>
2022-03-01 16:44:32 +01:00
tracer a92c445725 modified PUT options
Signed-off-by: tracer <tracer@24unix.net>
2022-03-01 16:44:07 +01:00
tracer 77808f84cf finished check domains
Signed-off-by: tracer <tracer@24unix.net>
2022-03-01 16:43:48 +01:00
tracer 7cc0f5d9f0 remove unneeded variable
Signed-off-by: tracer <tracer@24unix.net>
2022-03-01 16:43:17 +01:00
tracer 7a15d82a3a added endpoint /dyndns
Signed-off-by: tracer <tracer@24unix.net>
2022-03-01 16:42:34 +01:00
tracer 055431627a updated domain description
Signed-off-by: tracer <tracer@24unix.net>
2022-03-01 16:41:31 +01:00
6 changed files with 381 additions and 140 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: TODO
- Domain: Check is all support files for domains on this NS are existing
* 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.1",
"version": "0.0.2",
"description": "TODO …",
"contact": {
"name": "micha Espey",
"name": "Micha Espey",
"email": "tracer@24unix.net"
}
},
@ -31,6 +31,9 @@
{
"name": "Server"
},
{
"name": "DNS"
},
{
"name": "Domains"
}
@ -66,6 +69,45 @@
]
}
},
"/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": [
@ -250,6 +292,20 @@
}
},
"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": {
@ -394,6 +450,20 @@
}
}
},
"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

@ -33,8 +33,6 @@ class ApiController
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;
@ -56,6 +54,10 @@ 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);
@ -75,6 +77,9 @@ 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,11 +35,10 @@ 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']) {
@ -109,15 +108,15 @@ class DomainController
echo 'Checking permission:' . PHP_EOL . PHP_EOL;
$uid = posix_geteuid();
print("UID:\t$uid" . PHP_EOL);
print("UID:\t" . COLOR_YELLOW . $uid . PHP_EOL);
$pwuid = posix_getpwuid(user_id: $uid);
$name = $pwuid['name'];
print("Name:\t$name" . PHP_EOL);
echo COLOR_DEFAULT . "Name:\t" . COLOR_YELLOW . $name . PHP_EOL;
$bindGroup = posix_getgrnam(name: 'bind');
$members = $bindGroup['members'];
if (in_array(needle: $name, haystack: $members)) {
echo "\t$name is in group 'bind" . PHP_EOL;
echo "\t$name" . COLOR_DEFAULT . ' is in group ' . COLOR_YELLOW . 'bind' . PHP_EOL;
} else {
echo "\t$name needs to be in group $bindGroup!" . PHP_EOL;
@ -126,7 +125,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;
}
@ -145,7 +144,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;
}
@ -153,47 +152,37 @@ class DomainController
/**
* @return array|bool
* @return void
*/
function checkDomains(): array|bool
function checkDomains(): void
{
$localZones = file_get_contents(filename: $this->localZoneFile);
$maxNameLength = $this->domainRepository->getLongestEntry(field: 'name');
$domains = $this->domainRepository->findAll();
return true;
/*
$domains = $this->findAll();
foreach ($domains as $domain) {
echo COLOR_YELLOW . str_pad(string: $domain->getName(), length: $maxNameLength + 1) . COLOR_DEFAULT;
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 . ";
}
} else {
return "No access to '$this->namedConfLocalFile' . Please check permissions";
}
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;
}
if (!fileperms($this->localZoneFile)) {
return "No access to $this->localZoneFile . Please check permissions . ";
}
$zoneFile = $this->localZonesDir . $domain->getName();
$localZones = file_get_contents($this->localZoneFile);
foreach($domains as $domain) {
if(!str_contains($localZones, $domain['name'])) {
$errors[] = $domain['name'] . " is missing in '$this->localZoneFile'";
if (!file_exists(filename: $zoneFile)) {
echo "Missing zone file for $zoneFile . Update zone to create it";
}
}
$zoneFile = $this->localZonesDir . $domain['name'];
if (!file_exists($zoneFile)) {
$errors[] = "Missing zone file for $zoneFile . Update zone to create it";
}
echo COLOR_DEFAULT . PHP_EOL;
}
if (empty($errors)) {
return true;
} else {
return $errors;
}
*/
}
@ -237,5 +226,12 @@ 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,15 +50,18 @@ class RequestController
{
private Logger $log;
private ApiController $apiController;
private ApikeyRepository $apikeyRepository;
private DomainController $domainController;
private DomainRepository $domainRepository;
private ApikeyRepository $apikeyRepository;
private PanelRepository $panelRepository;
private Container $container;
private string $header;
private array $result;
private string $status;
private string $message;
/**
* @param array $config
* @param String $requestMethod
@ -95,10 +98,11 @@ 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->apikeyRepository = $this->container->get(name: ApikeyRepository::class);
$this->panelRepository = $this->container->get(name: PanelRepository::class);
}
/**
@ -131,7 +135,7 @@ class RequestController
description: 'Domain not found.'
)]
)]
public function handleAllDomainsGetRequest(): void
private function handleAllDomainsGetRequest(): void
{
$domains = $this->domainRepository->findAll();
$resultDomain = [];
@ -146,6 +150,41 @@ 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")
@ -189,90 +228,69 @@ 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'))) {
if (empty($command) || !(($command == 'domains') || ($command == 'ping') || ($command == 'apidoc') || ($command == 'dyndns'))) {
$this->header = '404 Not Found';
$this->status = "404 Not Found";
$this->message = "Endpoint not found.";
} else {
if ($command == 'apidoc') {
$openapi = Generator::scan(sources: [__DIR__ . 'RequestController.php']);
$this->status = 'openapi';
$this->result[] = $openapi->toJson();
} else {
if ($this->checkPassword()) {
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 ($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->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->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."
]);
}
}
@ -280,7 +298,7 @@ class RequestController
/**
* @return bool
*/
public function checkPassword(): bool
private function checkPassword(): bool
{
$headers = array_change_key_case(array: getallheaders(), case: CASE_UPPER);
$apiKey = $headers['X-API-KEY'] ?? '';
@ -310,12 +328,15 @@ class RequestController
return true;
}
/**
* @return void
*/
public function handleDomainGetRequest(): void
private function handleDomainsGetRequest(): void
{
if ($this->uri[3] == 'name') {
$name = $this->uri[3] ?? '';
if ($name == 'name') {
if ($result = $this->domainRepository->findByName(name: $this->uri[4])) {
$domain = [
'id' => $result->getId(),
@ -329,10 +350,10 @@ class RequestController
$this->message = "The specified domain was not found.";
}
} else {
if (empty($this->uri[3])) {
if (empty($name)) {
$this->handleAllDomainsGetRequest();
} else {
$id = intval(value: $this->uri['3']);
$id = intval(value: $name);
if ($id > 0) {
if ($result = $this->domainRepository->findById(id: $id)) {
$domain = [
@ -360,7 +381,7 @@ class RequestController
/**
* @return void
*/
public function handleDomainPostRequest(): void
private function handleDomainsPostRequest(): void
{
$name = $_POST['name'] ?? '';
$panel = $_POST['panel'] ?? '';
@ -398,10 +419,10 @@ class RequestController
/**
* @return void
*/
public function handleDomainPutRequest(): void
private function handleDomainsPutRequest(): void
{
$putData = fopen(filename: 'php://input', mode: 'r');
$data = fread(stream: $putData, length: 512);
$data = fread(stream: $putData, length: 8192);
$params = explode(separator: '&', string: $data);
foreach ($params as $param) {
@ -435,8 +456,7 @@ class RequestController
/**
* @return void
*/
public
function handleDomainDeleteRequest(): void
private function handleDomainsDeleteRequest(): void
{
$deleteData = fopen(filename: 'php://input', mode: 'r');
$data = fread(stream: $deleteData, length: 512);
@ -468,4 +488,154 @@ 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']);
return new Panel(name: $result['name'], a: $result['a'], aaaa: $result['aaaa'], apikey: $result['apikey']);
} else {
return false;
}