Skip to content

feat: manage certificate policy #4833

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
May 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions lib/Controller/AdminController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use OCA\Libresign\Handler\CertificateEngine\IEngineHandler;
use OCA\Libresign\Helper\ConfigureCheckHelper;
use OCA\Libresign\ResponseDefinitions;
use OCA\Libresign\Service\CertificatePolicyService;
use OCA\Libresign\Service\Install\ConfigureCheckService;
use OCA\Libresign\Service\Install\InstallService;
use OCA\Libresign\Service\SignatureBackgroundService;
Expand All @@ -31,6 +32,7 @@
use OCP\IL10N;
use OCP\IRequest;
use OCP\ISession;
use UnexpectedValueException;

/**
* @psalm-import-type LibresignEngineHandler from ResponseDefinitions
Expand All @@ -51,6 +53,7 @@ public function __construct(
private IL10N $l10n,
protected ISession $session,
private SignatureBackgroundService $signatureBackgroundService,
private CertificatePolicyService $certificatePolicyService,
) {
parent::__construct(Application::APP_ID, $request);
$this->eventSource = $this->eventSourceFactory->create();
Expand Down Expand Up @@ -525,4 +528,101 @@ public function signerName(
);
}
}

/**
* Update certificate policy of this instance
*
* @return DataResponse<Http::STATUS_OK, array{status: 'success', CPS: string}, array{}>|DataResponse<Http::STATUS_UNPROCESSABLE_ENTITY, array{status: 'failure', message: string}, array{}>
*
* 200: OK
* 422: Not found
*/
#[ApiRoute(verb: 'POST', url: '/api/{apiVersion}/admin/certificate-policy', requirements: ['apiVersion' => '(v1)'])]
public function saveCertificatePolicy(): DataResponse {
$pdf = $this->request->getUploadedFile('pdf');
$phpFileUploadErrors = [
UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'),
UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'),
UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'),
UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'),
UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'),
UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'),
];
if (empty($pdf)) {
$error = $this->l10n->t('No file uploaded');
} elseif (!empty($pdf) && array_key_exists('error', $pdf) && $pdf['error'] !== UPLOAD_ERR_OK) {
$error = $phpFileUploadErrors[$pdf['error']];
}
if ($error !== null) {
return new DataResponse(
[
'message' => $error,
'status' => 'failure',
],
Http::STATUS_UNPROCESSABLE_ENTITY
);
}
try {
$cps = $this->certificatePolicyService->updateFile($pdf['tmp_name']);
} catch (UnexpectedValueException $e) {
return new DataResponse(
[
'message' => $e->getMessage(),
'status' => 'failure',
],
Http::STATUS_UNPROCESSABLE_ENTITY
);
}
return new DataResponse(
[
'CPS' => $cps,
'status' => 'success',
]
);
}

/**
* Delete certificate policy of this instance
*
* @return DataResponse<Http::STATUS_OK, array{}, array{}>
*
* 200: OK
* 404: Not found
*/
#[ApiRoute(verb: 'DELETE', url: '/api/{apiVersion}/admin/certificate-policy', requirements: ['apiVersion' => '(v1)'])]
public function deleteCertificatePolicy(): DataResponse {
$this->certificatePolicyService->deleteFile();
return new DataResponse();
}

/**
* Update OID
*
* @param string $oid OID is a unique numeric identifier for certificate policies in digital certificates.
* @return DataResponse<Http::STATUS_OK, array{status: 'success'}, array{}>|DataResponse<Http::STATUS_UNPROCESSABLE_ENTITY, array{status: 'failure', message: string}, array{}>
*
* 200: OK
* 422: Validation error
*/
#[ApiRoute(verb: 'POST', url: '/api/{apiVersion}/admin/certificate-policy/oid', requirements: ['apiVersion' => '(v1)'])]
public function updateOID(string $oid): DataResponse {
try {
$this->certificatePolicyService->updateOid($oid);
return new DataResponse(
[
'status' => 'success',
]
);
} catch (\Exception $e) {
return new DataResponse(
[
'message' => $e->getMessage(),
'status' => 'failure',
],
Http::STATUS_UNPROCESSABLE_ENTITY
);
}
}
}
55 changes: 55 additions & 0 deletions lib/Controller/CertificatePolicyController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Libresign\Controller;

use OCA\Libresign\AppInfo\Application;
use OCA\Libresign\Service\CertificatePolicyService;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\AnonRateLimit;
use OCP\AppFramework\Http\Attribute\FrontpageRoute;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\FileDisplayResponse;
use OCP\Files\NotFoundException;
use OCP\IRequest;

class CertificatePolicyController extends Controller {
public function __construct(
IRequest $request,
private CertificatePolicyService $certificatePolicyService,
) {
parent::__construct(Application::APP_ID, $request);
}

/**
* Certificate policy of this instance
*
* @return FileDisplayResponse<Http::STATUS_OK, array{Content-Disposition: 'inline; filename="certificate-policy.pdf"', Content-Type: 'application/pdf'}>|DataResponse<Http::STATUS_NOT_FOUND, array<empty>, array{}>
*
* 200: OK
* 404: Not found
*/
#[PublicPage]
#[NoCSRFRequired]
#[AnonRateLimit(limit: 10, period: 60)]
#[FrontpageRoute(verb: 'GET', url: '/certificate-policy.pdf')]
public function getCertificatePolicy(): FileDisplayResponse|DataResponse {
try {
$file = $this->certificatePolicyService->getFile();
return new FileDisplayResponse($file, Http::STATUS_OK, [
'Content-Disposition' => 'inline; filename="certificate-policy.pdf"',
'Content-Type' => 'application/pdf',
]);
} catch (NotFoundException $e) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}
}
}
25 changes: 25 additions & 0 deletions lib/Handler/CertificateEngine/AEngineHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use OCA\Libresign\Exception\InvalidPasswordException;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Helper\MagicGetterSetterTrait;
use OCA\Libresign\Service\CertificatePolicyService;
use OCP\Files\AppData\IAppDataFactory;
use OCP\Files\IAppData;
use OCP\Files\SimpleFS\ISimpleFolder;
Expand Down Expand Up @@ -71,6 +72,7 @@ public function __construct(
protected IAppDataFactory $appDataFactory,
protected IDateTimeFormatter $dateTimeFormatter,
protected ITempManager $tempManager,
protected CertificatePolicyService $certificatePolicyService,
) {
$this->appData = $appDataFactory->get('libresign');
}
Expand Down Expand Up @@ -291,6 +293,12 @@ public function setConfigPath(string $configPath): IEngineHandler {
if (!$configPath) {
$this->appConfig->deleteKey(Application::APP_ID, 'config_path');
} else {
if (!is_dir($configPath)) {
mkdir(
directory: $configPath,
recursive: true,
);
}
$this->appConfig->setValueString(Application::APP_ID, 'config_path', $configPath);
}
$this->configPath = $configPath;
Expand Down Expand Up @@ -341,6 +349,19 @@ public function configureCheck(): array {
throw new \Exception('Necessary to implement configureCheck method');
}

private function getCertificatePolicy(): array {
$return = ['policySection' => []];
$oid = $this->certificatePolicyService->getOid();
$cps = $this->certificatePolicyService->getCps();
if ($oid && $cps) {
$return['policySection'][] = [
'OID' => $oid,
'CPS' => $cps,
];
}
return $return;
}

public function toArray(): array {
$return = [
'configPath' => $this->getConfigPath(),
Expand All @@ -350,6 +371,10 @@ public function toArray(): array {
'names' => [],
],
];
$return = array_merge(
$return,
$this->getCertificatePolicy(),
);
$names = $this->getNames();
foreach ($names as $name => $value) {
$return['rootCert']['names'][] = [
Expand Down
7 changes: 4 additions & 3 deletions lib/Handler/CertificateEngine/CfsslHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Handler\CfsslServerHandler;
use OCA\Libresign\Helper\ConfigureCheckHelper;
use OCA\Libresign\Service\CertificatePolicyService;
use OCA\Libresign\Service\Install\InstallService;
use OCP\Files\AppData\IAppDataFactory;
use OCP\IAppConfig;
Expand All @@ -37,7 +38,6 @@ class CfsslHandler extends AEngineHandler implements IEngineHandler {
protected $client;
protected $cfsslUri;
private string $binary = '';
private CfsslServerHandler $cfsslServerHandler;

public function __construct(
protected IConfig $config,
Expand All @@ -46,10 +46,11 @@ public function __construct(
protected IAppDataFactory $appDataFactory,
protected IDateTimeFormatter $dateTimeFormatter,
protected ITempManager $tempManager,
protected CfsslServerHandler $cfsslServerHandler,
protected CertificatePolicyService $certificatePolicyService,
) {
parent::__construct($config, $appConfig, $appDataFactory, $dateTimeFormatter, $tempManager);
parent::__construct($config, $appConfig, $appDataFactory, $dateTimeFormatter, $tempManager, $certificatePolicyService);

$this->cfsslServerHandler = new CfsslServerHandler();
$this->cfsslServerHandler->configCallback(fn () => $this->getConfigPath());
}

Expand Down
60 changes: 55 additions & 5 deletions lib/Handler/CertificateEngine/OpenSslHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Helper\ConfigureCheckHelper;
use OCA\Libresign\Service\CertificatePolicyService;
use OCP\Files\AppData\IAppDataFactory;
use OCP\IAppConfig;
use OCP\IConfig;
Expand All @@ -30,8 +31,9 @@ public function __construct(
protected IAppDataFactory $appDataFactory,
protected IDateTimeFormatter $dateTimeFormatter,
protected ITempManager $tempManager,
protected CertificatePolicyService $certificatePolicyService,
) {
parent::__construct($config, $appConfig, $appDataFactory, $dateTimeFormatter, $tempManager);
parent::__construct($config, $appConfig, $appDataFactory, $dateTimeFormatter, $tempManager, $certificatePolicyService);
}

public function generateRootCert(
Expand All @@ -44,7 +46,8 @@ public function generateRootCert(
]);

$csr = openssl_csr_new($this->getCsrNames(), $privateKey, ['digest_alg' => 'sha256']);
$x509 = openssl_csr_sign($csr, null, $privateKey, $days = 365 * 5, ['digest_alg' => 'sha256']);
$options = $this->getRootCertOptions();
$x509 = openssl_csr_sign($csr, null, $privateKey, $days = 365 * 5, $options);

openssl_csr_export($csr, $csrout);
openssl_x509_export($x509, $certout);
Expand All @@ -57,6 +60,18 @@ public function generateRootCert(
return $pkeyout;
}

private function getRootCertOptions(): array {
$this->generateRootCertConfig();
$configPath = $this->getConfigPath();

$options = [
'digest_alg' => 'sha256',
'config' => $configPath . DIRECTORY_SEPARATOR . 'openssl.cnf',
'x509_extensions' => 'v3_ca',
];
return $options;
}

public function generateCertificate(): string {
$configPath = $this->getConfigPath();
$rootCertificate = file_get_contents($configPath . DIRECTORY_SEPARATOR . 'ca.pem');
Expand Down Expand Up @@ -105,10 +120,17 @@ private function getFilenameToLeafCert(): string {
'subjectAltName' => $this->getSubjectAltNames(),
'authorityKeyIdentifier' => 'keyid',
'subjectKeyIdentifier' => 'hash',
// @todo Implement a feature to define this PDF at Administration Settings
// 'certificatePolicies' => '<policyOID> CPS: http://url/with/policy/informations.pdf',
]
],
];
$oid = $this->certificatePolicyService->getOid();
$cps = $this->certificatePolicyService->getCps();
if ($oid && $cps) {
$config['v3_req']['certificatePolicies'] = '@policy_section';
$config['policy_section'] = [
'policyIdentifier' => $oid,
'CPS.1' => $cps,
];
}
if (empty($config['v3_req']['subjectAltName'])) {
unset($config['v3_req']['subjectAltName']);
}
Expand All @@ -117,6 +139,34 @@ private function getFilenameToLeafCert(): string {
return $temporaryFile;
}

private function generateRootCertConfig(): void {
// More information about x509v3: https://www.openssl.org/docs/manmaster/man5/x509v3_config.html
$config = [
'v3_ca' => [
'basicConstraints' => 'critical, CA:TRUE',
'keyUsage' => 'critical, digitalSignature, keyCertSign',
'extendedKeyUsage' => 'clientAuth, emailProtection',
'subjectAltName' => $this->getSubjectAltNames(),
'authorityKeyIdentifier' => 'keyid',
'subjectKeyIdentifier' => 'hash',
],
];
$oid = $this->certificatePolicyService->getOid();
$cps = $this->certificatePolicyService->getCps();
if ($oid && $cps) {
$config['v3_ca']['certificatePolicies'] = '@policy_section';
$config['policy_section'] = [
'policyIdentifier' => $oid,
'CPS.1' => $cps,
];
}
if (empty($config['v3_ca']['subjectAltName'])) {
unset($config['v3_ca']['subjectAltName']);
}
$iniContent = $this->arrayToIni($config);
$this->saveFile('openssl.cnf', $iniContent);
}

private function arrayToIni(array $config) {
$fileContent = '';
foreach ($config as $i => $v) {
Expand Down
Loading
Loading