• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

LibreSign / libresign / 24933268096

25 Apr 2026 02:38PM UTC coverage: 56.474%. First build
24933268096

Pull #7605

github

web-flow
Merge 514ae2c6d into 7922186b4
Pull Request #7605: fix: allow signing for legacy certificates missing CRL metadata (fixes #7597)

12 of 14 new or added lines in 1 file covered. (85.71%)

10568 of 18713 relevant lines covered (56.47%)

6.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

67.93
/lib/Handler/CertificateEngine/AEngineHandler.php
1
<?php
2

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

9
namespace OCA\Libresign\Handler\CertificateEngine;
10

11
use OCA\Libresign\AppInfo\Application;
12
use OCA\Libresign\Enum\CrlValidationStatus;
13
use OCA\Libresign\Exception\EmptyCertificateException;
14
use OCA\Libresign\Exception\InvalidPasswordException;
15
use OCA\Libresign\Exception\LibresignException;
16
use OCA\Libresign\Helper\ConfigureCheckHelper;
17
use OCA\Libresign\Helper\MagicGetterSetterTrait;
18
use OCA\Libresign\Service\CaIdentifierService;
19
use OCA\Libresign\Service\CertificatePolicyService;
20
use OCA\Libresign\Service\Crl\CrlRevocationChecker;
21
use OCP\Files\AppData\IAppDataFactory;
22
use OCP\Files\IAppData;
23
use OCP\Files\SimpleFS\ISimpleFolder;
24
use OCP\IAppConfig;
25
use OCP\IConfig;
26
use OCP\IDateTimeFormatter;
27
use OCP\ITempManager;
28
use OCP\IURLGenerator;
29
use OpenSSLAsymmetricKey;
30
use OpenSSLCertificate;
31
use Psr\Log\LoggerInterface;
32
use ReflectionClass;
33

34
/**
35
 * @method IEngineHandler setPassword(string $password)
36
 * @method string getPassword()
37
 * @method IEngineHandler setCommonName(string $commonName)
38
 * @method string getCommonName()
39
 * @method IEngineHandler setHosts(array $hosts)
40
 * @method array getHosts()
41
 * @method IEngineHandler setFriendlyName(string $friendlyName)
42
 * @method string getFriendlyName()
43
 * @method IEngineHandler setCountry(string $country)
44
 * @method string getCountry()
45
 * @method IEngineHandler setState(string $state)
46
 * @method string getState()
47
 * @method IEngineHandler setLocality(string $locality)
48
 * @method string getLocality()
49
 * @method IEngineHandler setOrganization(string $organization)
50
 * @method string getOrganization()
51
 * @method IEngineHandler setOrganizationalUnit(array $organizationalUnit)
52
 * @method array getOrganizationalUnit()
53
 * @method IEngineHandler setUID(string $UID)
54
 * @method string getName()
55
 */
56
abstract class AEngineHandler implements IEngineHandler {
57
        use MagicGetterSetterTrait;
58
        use OrderCertificatesTrait;
59

60
        protected string $commonName = '';
61
        protected array $hosts = [];
62
        protected string $friendlyName = '';
63
        protected string $country = '';
64
        protected string $state = '';
65
        protected string $locality = '';
66
        protected string $organization = '';
67
        protected array $organizationalUnit = [];
68
        protected string $UID = '';
69
        private ?int $leafExpiryOverrideInDays = null;
70
        protected string $password = '';
71
        protected string $configPath = '';
72
        protected string $engine = '';
73
        protected string $certificate = '';
74
        protected string $currentCaId = '';
75
        protected IAppData $appData;
76

77
        public function __construct(
78
                protected IConfig $config,
79
                protected IAppConfig $appConfig,
80
                protected IAppDataFactory $appDataFactory,
81
                protected IDateTimeFormatter $dateTimeFormatter,
82
                protected ITempManager $tempManager,
83
                protected CertificatePolicyService $certificatePolicyService,
84
                protected IURLGenerator $urlGenerator,
85
                protected CaIdentifierService $caIdentifierService,
86
                protected LoggerInterface $logger,
87
                private CrlRevocationChecker $crlRevocationChecker,
88
        ) {
89
                $this->appData = $appDataFactory->get('libresign');
153✔
90
        }
91

92
        protected function exportToPkcs12(
93
                OpenSSLCertificate|string $certificate,
94
                OpenSSLAsymmetricKey|OpenSSLCertificate|string $privateKey,
95
                array $options = [],
96
        ): string {
97
                if (empty($certificate) || empty($privateKey)) {
8✔
98
                        throw new EmptyCertificateException();
×
99
                }
100
                $certContent = null;
8✔
101
                try {
102
                        openssl_pkcs12_export(
8✔
103
                                $certificate,
8✔
104
                                $certContent,
8✔
105
                                $privateKey,
8✔
106
                                $this->getPassword(),
8✔
107
                                $options,
8✔
108
                        );
8✔
109
                        if (!$certContent) {
8✔
110
                                throw new \Exception();
8✔
111
                        }
112
                } catch (\Throwable) {
×
113
                        throw new LibresignException('Error while creating certificate file', 500);
×
114
                }
115

116
                return $certContent;
8✔
117
        }
118

119
        #[\Override]
120
        public function updatePassword(string $certificate, string $currentPrivateKey, string $newPrivateKey): string {
121
                if (empty($certificate) || empty($currentPrivateKey) || empty($newPrivateKey)) {
×
122
                        throw new EmptyCertificateException();
×
123
                }
124
                $certContent = $this->opensslPkcs12Read($certificate, $currentPrivateKey);
×
125
                $this->setPassword($newPrivateKey);
×
126
                $certContent = self::exportToPkcs12($certContent['cert'], $certContent['pkey']);
×
127
                return $certContent;
×
128
        }
129

130
        #[\Override]
131
        public function readCertificate(string $certificate, string $privateKey): array {
132
                if (empty($certificate) || empty($privateKey)) {
10✔
133
                        throw new EmptyCertificateException();
1✔
134
                }
135
                $certContent = $this->opensslPkcs12Read($certificate, $privateKey);
9✔
136

137
                $return = $this->parseX509($certContent['cert']);
7✔
138
                if (isset($certContent['extracerts'])) {
7✔
139
                        foreach ($certContent['extracerts'] as $extraCert) {
7✔
140
                                $return['extracerts'][] = $this->parseX509($extraCert);
7✔
141
                        }
142
                        $return['extracerts'] = $this->orderCertificates($return['extracerts']);
7✔
143
                }
144
                return $return;
7✔
145
        }
146

147
        public function getCaId(): string {
148
                $caId = $this->caIdentifierService->getCaId();
68✔
149
                if (empty($caId)) {
68✔
150
                        $this->appConfig->clearCache(true);
4✔
151
                        $caId = $this->caIdentifierService->getCaId() ?: $this->caIdentifierService->generateCaId($this->getName());
4✔
152
                }
153
                return $caId;
68✔
154
        }
155

156
        #[\Override]
157
        public function parseCertificate(string $certificate): array {
158
                return $this->parseX509($certificate);
3✔
159
        }
160

161
        private function parseX509(string $x509): array {
162
                $parsed = openssl_x509_parse(openssl_x509_read($x509));
10✔
163

164
                $return = self::convertArrayToUtf8($parsed);
10✔
165

166
                foreach (['subject', 'issuer'] as $actor) {
10✔
167
                        foreach ($return[$actor] as $part => $value) {
10✔
168
                                if (is_string($value) && str_contains($value, ', ')) {
10✔
169
                                        $return[$actor][$part] = explode(', ', $value);
3✔
170
                                } else {
171
                                        $return[$actor][$part] = $value;
10✔
172
                                }
173
                        }
174
                }
175

176
                $return['valid_from'] = $this->dateTimeFormatter->formatDateTime($parsed['validFrom_time_t']);
10✔
177
                $return['valid_to'] = $this->dateTimeFormatter->formatDateTime($parsed['validTo_time_t']);
10✔
178

179
                $this->addCrlValidationInfo($return, $x509);
10✔
180

181
                return $return;
10✔
182
        }
183

184
        private function addCrlValidationInfo(array &$certData, string $certPem): void {
185
                if (isset($certData['extensions']['crlDistributionPoints'])) {
10✔
186
                        preg_match_all('/URI:([^\s,\n]+)/', $certData['extensions']['crlDistributionPoints'], $matches);
9✔
187
                        $extractedUrls = $matches[1] ?? [];
9✔
188

189
                        $certData['crl_urls'] = $extractedUrls;
9✔
190
                        $crlDetails = $this->crlRevocationChecker->validate($extractedUrls, $certPem);
9✔
191
                        $certData['crl_validation'] = $crlDetails['status'];
9✔
192
                        if (!empty($crlDetails['revoked_at'])) {
9✔
NEW
193
                                $certData['crl_revoked_at'] = $crlDetails['revoked_at'];
×
194
                        }
195
                } else {
196
                        $externalValidationEnabled = $this->appConfig->getValueBool(Application::APP_ID, 'crl_external_validation_enabled', true);
2✔
197
                        $certData['crl_validation'] = $externalValidationEnabled
2✔
198
                                ? CrlValidationStatus::MISSING
2✔
NEW
199
                                : CrlValidationStatus::DISABLED;
×
200
                        $certData['crl_urls'] = [];
2✔
201
                }
202
        }
203

204
        private static function convertArrayToUtf8($array) {
205
                foreach ($array as $key => $value) {
10✔
206
                        if (is_array($value)) {
10✔
207
                                $array[$key] = self::convertArrayToUtf8($value);
10✔
208
                        } elseif (is_string($value)) {
10✔
209
                                $array[$key] = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
10✔
210
                        }
211
                }
212
                return $array;
10✔
213
        }
214

215
        public function opensslPkcs12Read(string &$certificate, string $privateKey): array {
216
                openssl_pkcs12_read($certificate, $certContent, $privateKey);
9✔
217
                if (!empty($certContent)) {
9✔
218
                        return $certContent;
7✔
219
                }
220
                /**
221
                 * Reference:
222
                 *
223
                 * https://github.com/php/php-src/issues/12128
224
                 * https://www.php.net/manual/en/function.openssl-pkcs12-read.php#128992
225
                 */
226
                $msg = openssl_error_string();
2✔
227
                if ($msg === 'error:0308010C:digital envelope routines::unsupported') {
2✔
228
                        $tempPassword = $this->tempManager->getTemporaryFile();
×
229
                        $tempEncriptedOriginal = $this->tempManager->getTemporaryFile();
×
230
                        $tempEncriptedRepacked = $this->tempManager->getTemporaryFile();
×
231
                        $tempDecrypted = $this->tempManager->getTemporaryFile();
×
232
                        file_put_contents($tempPassword, $privateKey);
×
233
                        file_put_contents($tempEncriptedOriginal, $certificate);
×
234
                        shell_exec(<<<REPACK_COMMAND
×
235
                                cat $tempPassword | openssl pkcs12 -legacy -in $tempEncriptedOriginal -nodes -out $tempDecrypted -passin stdin &&
×
236
                                cat $tempPassword | openssl pkcs12 -in $tempDecrypted -export -out $tempEncriptedRepacked -passout stdin
×
237
                                REPACK_COMMAND
×
238
                        );
×
239
                        $certificateRepacked = file_get_contents($tempEncriptedRepacked);
×
240
                        openssl_pkcs12_read($certificateRepacked, $certContent, $privateKey);
×
241
                        if (!empty($certContent)) {
×
242
                                $certificate = $certificateRepacked;
×
243
                                return $certContent;
×
244
                        }
245
                }
246
                throw new InvalidPasswordException();
2✔
247
        }
248

249
        /**
250
         * @param (int|string) $name
251
         *
252
         * @psalm-param array-key $name
253
         */
254
        public function translateToLong($name): string {
255
                return match ($name) {
3✔
256
                        'CN' => 'CommonName',
×
257
                        'C' => 'Country',
3✔
258
                        'ST' => 'State',
×
259
                        'L' => 'Locality',
×
260
                        'O' => 'Organization',
3✔
261
                        'OU' => 'OrganizationalUnit',
2✔
262
                        'UID' => 'UserIdentifier',
×
263
                        default => '',
3✔
264
                };
3✔
265
        }
266

267
        #[\Override]
268
        public function setEngine(string $engine): void {
269
                $this->appConfig->setValueString(Application::APP_ID, 'certificate_engine', $engine);
16✔
270
                $this->engine = $engine;
16✔
271
                $this->configureIdentifyMethodsForEngine($engine);
16✔
272
        }
273

274
        /**
275
         * Configure identification methods based on the certificate engine.
276
         *
277
         * When the engine is set to 'none', only the 'account' identification method
278
         * is allowed. This is because:
279
         * - The 'none' engine doesn't generate digital certificates
280
         * - Without certificates, only basic password authentication is viable
281
         * - The 'account' method ensures users authenticate with their Nextcloud credentials
282
         *
283
         * For other engines (openssl, cfssl, java), the identification methods remain
284
         * unchanged to preserve existing configurations.
285
         *
286
         * @param string $engine The certificate engine name (i.e. 'none', 'openssl', 'cfssl')
287
         */
288
        private function configureIdentifyMethodsForEngine(string $engine): void {
289
                if ($engine !== 'none') {
16✔
290
                        return;
10✔
291
                }
292

293
                $config = [[
6✔
294
                        'name' => 'account',
6✔
295
                        'enabled' => true,
6✔
296
                        'mandatory' => true,
6✔
297
                ]];
6✔
298
                $this->appConfig->setValueArray(Application::APP_ID, 'identify_methods', $config);
6✔
299
        }
300

301
        #[\Override]
302
        public function getEngine(): string {
303
                if ($this->engine) {
3✔
304
                        return $this->engine;
3✔
305
                }
306
                $this->engine = $this->appConfig->getValueString(Application::APP_ID, 'certificate_engine', 'openssl');
×
307
                return $this->engine;
×
308
        }
309

310
        #[\Override]
311
        public function populateInstance(array $rootCert): IEngineHandler {
312
                if (empty($rootCert)) {
24✔
313
                        $rootCert = $this->appConfig->getValueArray(Application::APP_ID, 'rootCert');
24✔
314
                }
315
                if (!$rootCert) {
24✔
316
                        return $this;
24✔
317
                }
318
                if (!empty($rootCert['names'])) {
×
319
                        foreach ($rootCert['names'] as $id => $customName) {
×
320
                                $longCustomName = $this->translateToLong($id);
×
321
                                // Prevent to save a property that don't exists
322
                                if (!property_exists($this, lcfirst($longCustomName))) {
×
323
                                        continue;
×
324
                                }
325
                                $this->{'set' . ucfirst($longCustomName)}($customName['value']);
×
326
                        }
327
                }
328
                if (!$this->getCommonName()) {
×
329
                        $this->setCommonName($rootCert['commonName']);
×
330
                }
331
                return $this;
×
332
        }
333

334
        #[\Override]
335
        public function getCurrentConfigPath(): string {
336
                if ($this->configPath) {
78✔
337
                        return $this->configPath;
72✔
338
                }
339

340
                $customConfigPath = $this->appConfig->getValueString(Application::APP_ID, 'config_path');
68✔
341
                if ($customConfigPath && is_dir($customConfigPath)) {
68✔
342
                        $this->configPath = $customConfigPath;
10✔
343
                        return $this->configPath;
10✔
344
                }
345

346
                $this->configPath = $this->initializePkiConfigPath();
68✔
347
                if (!empty($this->configPath)) {
68✔
348
                        $this->appConfig->setValueString(Application::APP_ID, 'config_path', $this->configPath);
68✔
349
                }
350
                return $this->configPath;
68✔
351
        }
352

353
        #[\Override]
354
        public function getConfigPathByParams(string $instanceId, int $generation): string {
355
                $engineName = $this->getName();
20✔
356

357
                $pkiDirName = $this->caIdentifierService->generatePkiDirectoryNameFromParams($instanceId, $generation, $engineName);
20✔
358
                $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
20✔
359
                $systemInstanceId = $this->config->getSystemValue('instanceid');
20✔
360
                $pkiPath = $dataDir . '/appdata_' . $systemInstanceId . '/libresign/' . $pkiDirName;
20✔
361

362
                if (!is_dir($pkiPath)) {
20✔
363
                        throw new \RuntimeException("Config path does not exist for instanceId: {$instanceId}, generation: {$generation}");
2✔
364
                }
365

366
                return $pkiPath;
18✔
367
        }
368

369
        private function initializePkiConfigPath(): string {
370
                $caId = $this->getCaId();
68✔
371
                if (empty($caId)) {
68✔
372
                        return '';
×
373
                }
374
                $pkiDirName = $this->caIdentifierService->generatePkiDirectoryName($caId);
68✔
375
                $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
68✔
376
                $systemInstanceId = $this->config->getSystemValue('instanceid');
68✔
377
                $pkiPath = $dataDir . '/appdata_' . $systemInstanceId . '/libresign/' . $pkiDirName;
68✔
378

379
                if (!is_dir($pkiPath)) {
68✔
380
                        $this->createDirectoryWithCorrectOwnership($pkiPath);
68✔
381
                }
382

383
                return $pkiPath;
68✔
384
        }
385

386
        private function createDirectoryWithCorrectOwnership(string $path): void {
387
                $ownerInfo = $this->getFilesOwnerInfo();
68✔
388
                $fullCommand = 'mkdir -p ' . escapeshellarg($path);
68✔
389

390
                if (posix_getuid() !== $ownerInfo['uid']) {
68✔
391
                        $fullCommand = 'runuser -u ' . $ownerInfo['name'] . ' -- ' . $fullCommand;
×
392
                }
393

394
                exec($fullCommand);
68✔
395
        }
396

397
        private function getFilesOwnerInfo(): array {
398
                $currentFile = realpath(__DIR__);
68✔
399
                $owner = fileowner($currentFile);
68✔
400
                if ($owner === false) {
68✔
401
                        throw new \RuntimeException('Unable to get file information');
×
402
                }
403
                $ownerInfo = posix_getpwuid($owner);
68✔
404
                if ($ownerInfo === false) {
68✔
405
                        throw new \RuntimeException('Unable to get file owner information');
×
406
                }
407

408
                return $ownerInfo;
68✔
409
        }
410

411
        /**
412
         * @todo check a best solution to don't use reflection
413
         */
414
        private function getInternalPathOfFolder(ISimpleFolder $node): string {
415
                $reflection = new \ReflectionClass($node);
×
416
                $reflectionProperty = $reflection->getProperty('folder');
×
417
                $folder = $reflectionProperty->getValue($node);
×
418
                $path = $folder->getInternalPath();
×
419
                return $path;
×
420
        }
421

422
        #[\Override]
423
        public function setConfigPath(string $configPath): IEngineHandler {
424
                if (!$configPath) {
8✔
425
                        $this->appConfig->deleteKey(Application::APP_ID, 'config_path');
×
426
                } else {
427
                        if (!is_dir($configPath)) {
8✔
428
                                mkdir(
×
429
                                        directory: $configPath,
×
430
                                        recursive: true,
×
431
                                );
×
432
                        }
433
                        $this->appConfig->setValueString(Application::APP_ID, 'config_path', $configPath);
8✔
434
                }
435
                $this->configPath = $configPath;
8✔
436
                return $this;
8✔
437
        }
438

439
        public function getName(): string {
440
                $reflect = new ReflectionClass($this);
24✔
441
                $className = $reflect->getShortName();
24✔
442
                $name = strtolower(substr($className, 0, -7));
24✔
443
                return $name;
24✔
444
        }
445

446
        protected function getNames(): array {
447
                $names = [
74✔
448
                        'C' => $this->getCountry(),
74✔
449
                        'ST' => $this->getState(),
74✔
450
                        'L' => $this->getLocality(),
74✔
451
                        'O' => $this->getOrganization(),
74✔
452
                        'OU' => $this->getOrganizationalUnit(),
74✔
453
                ];
74✔
454
                if ($uid = $this->getUID()) {
74✔
455
                        $names['UID'] = $uid;
×
456
                }
457
                $names = array_filter($names, fn ($v) => !empty($v));
74✔
458
                return $names;
74✔
459
        }
460

461
        public function getUID(): string {
462
                return str_replace(' ', '+', $this->UID);
74✔
463
        }
464

465
        #[\Override]
466
        public function getLeafExpiryInDays(): int {
467
                if ($this->leafExpiryOverrideInDays !== null) {
27✔
468
                        return $this->leafExpiryOverrideInDays;
×
469
                }
470
                $exp = $this->appConfig->getValueInt(Application::APP_ID, 'expiry_in_days', 365);
27✔
471
                return $exp > 0 ? $exp : 365;
27✔
472
        }
473

474
        #[\Override]
475
        public function setLeafExpiryOverrideInDays(?int $days): self {
476
                $this->leafExpiryOverrideInDays = ($days !== null && $days > 0) ? $days : null;
×
477
                return $this;
×
478
        }
479

480
        #[\Override]
481
        public function getCaExpiryInDays(): int {
482
                $exp = $this->appConfig->getValueInt(Application::APP_ID, 'ca_expiry_in_days', 3650); // 10 years
62✔
483
                return $exp > 0 ? $exp : 3650;
62✔
484
        }
485

486
        private function getCertificatePolicy(): array {
487
                $return = ['policySection' => []];
11✔
488
                $oid = $this->certificatePolicyService->getOid();
11✔
489
                $cps = $this->certificatePolicyService->getCps();
11✔
490
                if ($oid && $cps) {
11✔
491
                        $return['policySection'][] = [
×
492
                                'OID' => $oid,
×
493
                                'CPS' => $cps,
×
494
                        ];
×
495
                }
496
                return $return;
11✔
497
        }
498

499
        abstract protected function getConfigureCheckResourceName(): string;
500

501
        abstract protected function getCertificateRegenerationTip(): string;
502

503
        abstract protected function getEngineSpecificChecks(): array;
504

505
        abstract protected function getSetupSuccessMessage(): string;
506

507
        abstract protected function getSetupErrorMessage(): string;
508

509
        abstract protected function getSetupErrorTip(): string;
510

511
        #[\Override]
512
        public function configureCheck(): array {
513
                $checks = $this->getEngineSpecificChecks();
8✔
514

515
                if (!$this->isSetupOk()) {
8✔
516
                        return array_merge($checks, [
1✔
517
                                (new ConfigureCheckHelper())
1✔
518
                                        ->setErrorMessage($this->getSetupErrorMessage())
1✔
519
                                        ->setResource($this->getConfigureCheckResourceName())
1✔
520
                                        ->setTip($this->getSetupErrorTip())
1✔
521
                        ]);
1✔
522
                }
523

524
                $checks[] = (new ConfigureCheckHelper())
7✔
525
                        ->setSuccessMessage($this->getSetupSuccessMessage())
7✔
526
                        ->setResource($this->getConfigureCheckResourceName());
7✔
527

528
                $modernFeaturesCheck = $this->checkRootCertificateModernFeatures();
7✔
529
                if ($modernFeaturesCheck) {
7✔
530
                        $checks[] = $modernFeaturesCheck;
7✔
531
                }
532

533
                $expiryCheck = $this->checkRootCertificateExpiry();
7✔
534
                if ($expiryCheck) {
7✔
535
                        $checks[] = $expiryCheck;
5✔
536
                }
537

538
                return $checks;
7✔
539
        }
540

541
        protected function checkRootCertificateModernFeatures(): ?ConfigureCheckHelper {
542
                $configPath = $this->getCurrentConfigPath();
7✔
543
                $caCertPath = $configPath . DIRECTORY_SEPARATOR . 'ca.pem';
7✔
544

545
                try {
546
                        $certContent = file_get_contents($caCertPath);
7✔
547
                        if (!$certContent) {
7✔
548
                                return (new ConfigureCheckHelper())
×
549
                                        ->setErrorMessage('Failed to read root certificate file')
×
550
                                        ->setResource($this->getConfigureCheckResourceName())
×
551
                                        ->setTip('Check file permissions and disk space');
×
552
                        }
553

554
                        $x509Resource = openssl_x509_read($certContent);
7✔
555
                        if (!$x509Resource) {
7✔
556
                                return (new ConfigureCheckHelper())
×
557
                                        ->setErrorMessage('Failed to parse root certificate')
×
558
                                        ->setResource($this->getConfigureCheckResourceName())
×
559
                                        ->setTip('Root certificate file may be corrupted or invalid');
×
560
                        }
561

562
                        $parsed = openssl_x509_parse($x509Resource);
7✔
563
                        if (!$parsed) {
7✔
564
                                return (new ConfigureCheckHelper())
×
565
                                        ->setErrorMessage('Failed to extract root certificate information')
×
566
                                        ->setResource($this->getConfigureCheckResourceName())
×
567
                                        ->setTip('Root certificate may be in an unsupported format');
×
568
                        }
569

570
                        $criticalIssues = [];
7✔
571
                        $minorIssues = [];
7✔
572

573
                        if (isset($parsed['serialNumber'])) {
7✔
574
                                $serialNumber = $parsed['serialNumber'];
7✔
575
                                $serialDecimal = hexdec($serialNumber);
7✔
576
                                if ($serialDecimal <= 1) {
7✔
577
                                        $minorIssues[] = 'Serial number is simple (zero or one)';
×
578
                                }
579
                        } else {
580
                                $criticalIssues[] = 'Serial number is missing';
×
581
                        }
582

583
                        $missingExtensions = [];
7✔
584
                        if (!isset($parsed['extensions']['subjectKeyIdentifier'])) {
7✔
585
                                $missingExtensions[] = 'Subject Key Identifier (SKI)';
×
586
                        }
587

588
                        $isSelfSigned = (isset($parsed['issuer']) && isset($parsed['subject'])
7✔
589
                                                        && $parsed['issuer'] === $parsed['subject']);
7✔
590

591
                        /**
592
                         * @todo workarround for missing AKI at certificates generated by CFSSL.
593
                         *
594
                         * CFSSL does not add Authority Key Identifier (AKI) to self-signed root certificates.
595
                         */
596
                        if (!$isSelfSigned && !isset($parsed['extensions']['authorityKeyIdentifier'])) {
7✔
597
                                $missingExtensions[] = 'Authority Key Identifier (AKI)';
×
598
                        }
599

600
                        if (!isset($parsed['extensions']['crlDistributionPoints'])) {
7✔
601
                                $missingExtensions[] = 'CRL Distribution Points';
×
602
                        }
603

604
                        if (!empty($missingExtensions)) {
7✔
605
                                $extensionsList = implode(', ', $missingExtensions);
×
606
                                $minorIssues[] = "Missing modern extensions: {$extensionsList}";
×
607
                        }
608

609
                        $hasLibresignCaUuid = $this->validateLibresignCaUuidInCertificate($parsed);
7✔
610
                        if (!$hasLibresignCaUuid) {
7✔
611
                                $minorIssues[] = 'LibreSign CA UUID not found in Organizational Unit';
7✔
612
                        }
613

614
                        if (!empty($criticalIssues)) {
7✔
615
                                $issuesList = implode(', ', $criticalIssues);
×
616
                                return (new ConfigureCheckHelper())
×
617
                                        ->setErrorMessage("Root certificate has critical issues: {$issuesList}")
×
618
                                        ->setResource($this->getConfigureCheckResourceName())
×
619
                                        ->setTip($this->getCertificateRegenerationTip());
×
620
                        }
621

622
                        if (!empty($minorIssues)) {
7✔
623
                                $issuesList = implode(', ', $minorIssues);
7✔
624
                                return (new ConfigureCheckHelper())
7✔
625
                                        ->setInfoMessage("Root certificate could benefit from modern features: {$issuesList}")
7✔
626
                                        ->setResource($this->getConfigureCheckResourceName())
7✔
627
                                        ->setTip($this->getCertificateRegenerationTip() . ' (recommended but not required)');
7✔
628
                        }
629

630
                        return null;
×
631

632
                } catch (\Exception $e) {
×
633
                        return (new ConfigureCheckHelper())
×
634
                                ->setErrorMessage('Failed to analyze root certificate: ' . $e->getMessage())
×
635
                                ->setResource($this->getConfigureCheckResourceName())
×
636
                                ->setTip('Check if the root certificate file is valid');
×
637
                }
638
        }
639

640
        private function validateLibresignCaUuidInCertificate(array $parsed): bool {
641
                if (!isset($parsed['subject']['OU'])) {
7✔
642
                        return false;
7✔
643
                }
644

645
                $instanceId = $this->getLibreSignInstanceId();
×
646
                if (empty($instanceId)) {
×
647
                        return false;
×
648
                }
649

650
                $organizationalUnits = $parsed['subject']['OU'];
×
651

652
                if (is_string($organizationalUnits)) {
×
653
                        if (str_contains($organizationalUnits, ', ')) {
×
654
                                $organizationalUnits = explode(', ', $organizationalUnits);
×
655
                        } else {
656
                                $organizationalUnits = [$organizationalUnits];
×
657
                        }
658
                }
659

660
                foreach ($organizationalUnits as $ou) {
×
661
                        $ou = trim($ou);
×
662
                        if ($this->caIdentifierService->isValidCaId($ou, $instanceId)) {
×
663
                                return true;
×
664
                        }
665
                }
666

667
                return false;
×
668
        }
669

670
        private function getLibreSignInstanceId(): string {
671
                $instanceId = $this->appConfig->getValueString(Application::APP_ID, 'instance_id', '');
×
672
                if (strlen($instanceId) === 10) {
×
673
                        return $instanceId;
×
674
                }
675
                return '';
×
676
        }
677

678
        private function calculateRemainingDays(int $validToTimestamp): int {
679
                $secondsPerDay = 60 * 60 * 24;
27✔
680
                $remainingSeconds = $validToTimestamp - time();
27✔
681
                return (int)ceil($remainingSeconds / $secondsPerDay);
27✔
682
        }
683

684
        protected function checkRootCertificateExpiry(): ?ConfigureCheckHelper {
685
                $configPath = $this->getCurrentConfigPath();
7✔
686
                $caCertPath = $configPath . DIRECTORY_SEPARATOR . 'ca.pem';
7✔
687

688
                if (!file_exists($caCertPath)) {
7✔
689
                        return null;
×
690
                }
691

692
                $certContent = file_get_contents($caCertPath);
7✔
693
                if (!$certContent) {
7✔
694
                        return null;
×
695
                }
696

697
                $x509Resource = openssl_x509_read($certContent);
7✔
698
                if (!$x509Resource) {
7✔
699
                        return null;
×
700
                }
701

702
                $parsed = openssl_x509_parse($x509Resource);
7✔
703
                if (!$parsed) {
7✔
704
                        return null;
×
705
                }
706

707
                $remainingDays = $this->calculateRemainingDays($parsed['validTo_time_t']);
7✔
708
                $leafExpiryDays = $this->getLeafExpiryInDays();
7✔
709

710
                if ($remainingDays < 0) {
7✔
711
                        return (new ConfigureCheckHelper())
×
712
                                ->setErrorMessage('Root certificate has expired')
×
713
                                ->setResource($this->getConfigureCheckResourceName())
×
714
                                ->setTip($this->getCertificateRegenerationTip() . ' URGENT: Certificate is expired!');
×
715
                }
716

717
                if ($remainingDays <= 7) {
7✔
718
                        return (new ConfigureCheckHelper())
2✔
719
                                ->setErrorMessage("Root certificate expires in {$remainingDays} days")
2✔
720
                                ->setResource($this->getConfigureCheckResourceName())
2✔
721
                                ->setTip($this->getCertificateRegenerationTip() . ' URGENT: Renew immediately!');
2✔
722
                }
723

724
                if ($remainingDays <= 30) {
5✔
725
                        return (new ConfigureCheckHelper())
1✔
726
                                ->setErrorMessage("Root certificate expires in {$remainingDays} days")
1✔
727
                                ->setResource($this->getConfigureCheckResourceName())
1✔
728
                                ->setTip($this->getCertificateRegenerationTip() . ' Renewal recommended soon.');
1✔
729
                }
730

731
                if ($remainingDays <= $leafExpiryDays) {
4✔
732
                        return (new ConfigureCheckHelper())
2✔
733
                                ->setInfoMessage("Root certificate expires in {$remainingDays} days (leaf validity: {$leafExpiryDays} days)")
2✔
734
                                ->setResource($this->getConfigureCheckResourceName())
2✔
735
                                ->setTip('Root certificate should be renewed to ensure it can sign CRLs for all issued leaf certificates.');
2✔
736
                }
737

738
                return null;
2✔
739
        }
740

741
        #[\Override]
742
        public function toArray(): array {
743
                $generated = $this->isSetupOk();
11✔
744
                $return = [
11✔
745
                        'configPath' => $this->getConfigPathForApi($generated),
11✔
746
                        'generated' => $generated,
11✔
747
                        'rootCert' => [
11✔
748
                                'commonName' => $this->getCommonName(),
11✔
749
                                'names' => [],
11✔
750
                        ],
11✔
751
                ];
11✔
752
                $return = array_merge(
11✔
753
                        $return,
11✔
754
                        $this->getCertificatePolicy(),
11✔
755
                );
11✔
756
                $names = $this->getNames();
11✔
757
                foreach ($names as $name => $value) {
11✔
758
                        $return['rootCert']['names'][] = [
6✔
759
                                'id' => $name,
6✔
760
                                'value' => $this->filterNameValue($name, $value, $generated),
6✔
761
                        ];
6✔
762
                }
763
                return $return;
11✔
764
        }
765

766
        private function getConfigPathForApi(bool $generated): string {
767
                return $generated ? $this->getCurrentConfigPath() : '';
11✔
768
        }
769

770
        private function filterNameValue(string $name, mixed $value, bool $generated): mixed {
771
                if ($name === 'OU' && is_array($value) && !$generated) {
6✔
772
                        $filtered = $this->removeCaIdFromOrganizationalUnit($value);
3✔
773
                        return empty($filtered) ? null : $filtered;
3✔
774
                }
775
                return $value;
6✔
776
        }
777

778
        private function removeCaIdFromOrganizationalUnit(array $organizationalUnits): array {
779
                $filtered = array_filter(
3✔
780
                        $organizationalUnits,
3✔
781
                        fn ($item) => !str_starts_with($item, 'libresign-ca-id:')
3✔
782
                );
3✔
783
                return array_values($filtered);
3✔
784
        }
785

786
        protected function getCrlDistributionUrl(): string {
787
                $caIdParsed = $this->caIdentifierService->getCaIdParsed();
63✔
788
                return $this->urlGenerator->linkToRouteAbsolute('libresign.crl.getRevocationList', [
63✔
789
                        'instanceId' => $caIdParsed['instanceId'],
63✔
790
                        'generation' => $caIdParsed['generation'],
63✔
791
                        'engineType' => $caIdParsed['engineType'],
63✔
792
                ]);
63✔
793
        }
794

795
        #[\Override]
796
        public function generateCrlDer(array $revokedCertificates, string $instanceId, int $generation, int $crlNumber): string {
797
                $configPath = $this->getConfigPathByParams($instanceId, $generation);
20✔
798
                $issuer = $this->loadCaIssuer($configPath);
18✔
799
                $signedCrl = $this->createAndSignCrl($issuer, $revokedCertificates, $crlNumber);
18✔
800
                $crlDerData = $this->saveCrlToDer($signedCrl, $configPath);
18✔
801

802
                return $crlDerData;
18✔
803
        }
804

805
        private function loadCaIssuer(string $configPath): \phpseclib3\File\X509 {
806
                $caCertPath = $configPath . DIRECTORY_SEPARATOR . 'ca.pem';
18✔
807
                $caKeyPath = $configPath . DIRECTORY_SEPARATOR . 'ca-key.pem';
18✔
808

809
                if (!file_exists($caCertPath) || !file_exists($caKeyPath)) {
18✔
810
                        $this->logger->error('CA certificate or private key not found', ['caCertPath' => $caCertPath, 'caKeyPath' => $caKeyPath]);
×
811
                        throw new \RuntimeException('CA certificate or private key not found. Run: occ libresign:configure:openssl');
×
812
                }
813

814
                $caCert = file_get_contents($caCertPath);
18✔
815
                $caKey = file_get_contents($caKeyPath);
18✔
816

817
                if (!$caCert || !$caKey) {
18✔
818
                        $this->logger->error('Failed to read CA certificate or private key', ['caCertPath' => $caCertPath, 'caKeyPath' => $caKeyPath]);
×
819
                        throw new \RuntimeException('Failed to read CA certificate or private key');
×
820
                }
821

822
                $issuer = new \phpseclib3\File\X509();
18✔
823
                $issuer->loadX509($caCert);
18✔
824
                $caPrivateKey = \phpseclib3\Crypt\PublicKeyLoader::load($caKey);
18✔
825

826
                if (!$caPrivateKey instanceof \phpseclib3\Crypt\Common\PrivateKey) {
18✔
827
                        $this->logger->error('Loaded key is not a private key', ['keyType' => get_class($caPrivateKey)]);
×
828
                        throw new \RuntimeException('Loaded key is not a private key');
×
829
                }
830

831
                $issuer->setPrivateKey($caPrivateKey);
18✔
832
                return $issuer;
18✔
833
        }
834

835
        private function createAndSignCrl(\phpseclib3\File\X509 $issuer, array $revokedCertificates, int $crlNumber): array {
836
                $utcZone = new \DateTimeZone('UTC');
18✔
837
                $crlToSign = new \phpseclib3\File\X509();
18✔
838
                $crlToSign->setSerialNumber((string)$crlNumber, 10);
18✔
839
                $crlToSign->setStartDate(new \DateTime('now', $utcZone));
18✔
840
                $crlToSign->setEndDate(new \DateTime('+7 days', $utcZone));
18✔
841

842
                $initialCrl = $crlToSign->signCRL($issuer, $crlToSign);
18✔
843
                if ($initialCrl === false) {
18✔
844
                        $this->logger->error('Failed to create initial CRL structure');
×
845
                        throw new \RuntimeException('Failed to create initial CRL structure');
×
846
                }
847

848
                if (!empty($revokedCertificates)) {
18✔
849
                        $savedCrl = $crlToSign->saveCRL($initialCrl);
17✔
850
                        if ($savedCrl === false) {
17✔
851
                                $this->logger->error('Failed to save initial CRL structure');
×
852
                                throw new \RuntimeException('Failed to save initial CRL structure');
×
853
                        }
854

855
                        $crlToSign->loadCRL($savedCrl);
17✔
856

857
                        $dateFormat = 'D, d M Y H:i:s O';
17✔
858
                        foreach ($revokedCertificates as $cert) {
17✔
859
                                $serialNumber = $cert->getSerialNumber();
17✔
860
                                $normalizedSerial = ltrim($serialNumber, '0') ?: '0';
17✔
861
                                $crlToSign->revoke(
17✔
862
                                        new \phpseclib3\Math\BigInteger($normalizedSerial, 16),
17✔
863
                                        $cert->getRevokedAt()->format($dateFormat)
17✔
864
                                );
17✔
865
                        }
866

867
                        $signedCrl = $crlToSign->signCRL($issuer, $crlToSign);
17✔
868
                } else {
869
                        $signedCrl = $initialCrl;
1✔
870
                }
871

872
                if ($signedCrl === false) {
18✔
873
                        $this->logger->error('Failed to sign CRL', ['crlNumber' => $crlNumber]);
×
874
                        throw new \RuntimeException('Failed to sign CRL');
×
875
                }
876

877
                if (!isset($signedCrl['signatureAlgorithm'])) {
18✔
878
                        $signedCrl['signatureAlgorithm'] = ['algorithm' => 'sha256WithRSAEncryption'];
×
879
                }
880

881
                return $signedCrl;
18✔
882
        }
883

884
        private function saveCrlToDer(array $signedCrl, string $configPath): string {
885
                $crlDerPath = $configPath . DIRECTORY_SEPARATOR . 'crl.der';
18✔
886
                $crlToSign = new \phpseclib3\File\X509();
18✔
887

888
                $crlDerData = $crlToSign->saveCRL($signedCrl, \phpseclib3\File\X509::FORMAT_DER);
18✔
889

890
                if ($crlDerData === false) {
18✔
891
                        $this->logger->error('Failed to save CRL in DER format');
×
892
                        throw new \RuntimeException('Failed to save CRL in DER format');
×
893
                }
894

895
                if (file_put_contents($crlDerPath, $crlDerData) === false) {
18✔
896
                        $this->logger->error('Failed to write CRL DER file', ['path' => $crlDerPath]);
×
897
                        throw new \RuntimeException('Failed to write CRL DER file');
×
898
                }
899

900
                return $crlDerData;
18✔
901
        }
902

903
        #[\Override]
904
        public function validateRootCertificate(): void {
905
                $configPath = $this->getCurrentConfigPath();
23✔
906
                if (empty($configPath)) {
23✔
907
                        return;
×
908
                }
909

910
                if (!is_dir($configPath)) {
23✔
911
                        return;
×
912
                }
913

914
                $rootCertPath = $configPath . DIRECTORY_SEPARATOR . 'ca.pem';
23✔
915

916
                if (!file_exists($rootCertPath)) {
23✔
917
                        return;
3✔
918
                }
919

920
                $rootCert = file_get_contents($rootCertPath);
20✔
921
                if (empty($rootCert)) {
20✔
922
                        return;
×
923
                }
924

925
                $certificate = openssl_x509_read($rootCert);
20✔
926
                if ($certificate === false) {
20✔
927
                        throw new LibresignException('Invalid root certificate content');
×
928
                }
929
                $certInfo = openssl_x509_parse($certificate);
20✔
930
                if ($certInfo === false) {
20✔
931
                        throw new LibresignException('Failed to parse root certificate');
×
932
                }
933

934
                if ($this->checkCertificateRevoked($certInfo['serialNumber'])) {
20✔
935
                        $this->logger->error('Root certificate has been revoked', [
×
936
                                'ca_id' => $this->getCaId(),
×
937
                                'impact' => 'all_leaf_certificates_invalid',
×
938
                        ]);
×
939
                        throw new LibresignException(
×
940
                                'Root certificate has been revoked. Please contact the administrator to regenerate the signing certificate.',
×
941
                                \OC\AppFramework\Http::STATUS_PRECONDITION_FAILED
×
942
                        );
×
943
                }
944

945
                if ($certInfo['validTo_time_t'] < time()) {
20✔
946
                        $this->logger->error('Root certificate has expired', [
×
947
                                'ca_id' => $this->getCaId(),
×
948
                        ]);
×
949
                        throw new LibresignException(
×
950
                                'Root certificate has expired. Please contact the administrator to regenerate the signing certificate.',
×
951
                                \OC\AppFramework\Http::STATUS_PRECONDITION_FAILED
×
952
                        );
×
953
                }
954

955
                $remainingDays = $this->calculateRemainingDays($certInfo['validTo_time_t']);
20✔
956
                $leafExpiryDays = $this->getLeafExpiryInDays();
20✔
957

958
                if ($remainingDays <= $leafExpiryDays) {
20✔
959
                        $this->logger->warning('Root certificate renewal needed', [
6✔
960
                                'remaining_days' => $remainingDays,
6✔
961
                                'leaf_expiry_days' => $leafExpiryDays,
6✔
962
                        ]);
6✔
963
                }
964
        }
965

966
        private function checkCertificateRevoked(string $serialNumber): bool {
967
                try {
968
                        /** @var \OCA\Libresign\Service\Crl\CrlService */
969
                        $crlService = \OC::$server->get(\OCA\Libresign\Service\Crl\CrlService::class);
20✔
970
                        $status = $crlService->getCertificateStatus($serialNumber);
20✔
971
                        return $status['status'] === 'revoked';
20✔
972
                } catch (\Exception $e) {
×
973
                        $this->logger->warning('Failed to check root certificate revocation status', [
×
974
                                'error' => $e->getMessage()
×
975
                        ]);
×
976
                        return false;
×
977
                }
978
        }
979
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc