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

LibreSign / libresign / 24934850626

25 Apr 2026 04:01PM UTC coverage: 56.513%. First build
24934850626

Pull #7605

github

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

34 of 40 new or added lines in 1 file covered. (85.0%)

10590 of 18739 relevant lines covered (56.51%)

6.85 hits per line

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

68.91
/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');
155✔
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
                $extensions = $certData['extensions'] ?? [];
10✔
186
                if (is_array($extensions)) {
10✔
187
                        ['hasExtension' => $hasCrlExtension, 'urls' => $extractedUrls] = $this->extractCrlUrlsFromExtensions($extensions);
10✔
188
                        if ($hasCrlExtension) {
10✔
189
                                $certData['crl_urls'] = $extractedUrls;
9✔
190
                                if (empty($extractedUrls)) {
9✔
NEW
191
                                        $certData['crl_validation'] = CrlValidationStatus::NO_URLS;
×
NEW
192
                                        return;
×
193
                                }
194

195
                                $crlDetails = $this->crlRevocationChecker->validate($extractedUrls, $certPem);
9✔
196
                                $certData['crl_validation'] = $crlDetails['status'];
9✔
197
                                if (!empty($crlDetails['revoked_at'])) {
9✔
NEW
198
                                        $certData['crl_revoked_at'] = $crlDetails['revoked_at'];
×
199
                                }
200
                                return;
9✔
201
                        }
202
                }
203

204
                        $externalValidationEnabled = $this->appConfig->getValueBool(Application::APP_ID, 'crl_external_validation_enabled', true);
2✔
205
                        $certData['crl_validation'] = $externalValidationEnabled
2✔
206
                                ? CrlValidationStatus::MISSING
2✔
207
                                : CrlValidationStatus::DISABLED;
×
208
                        $certData['crl_urls'] = [];
2✔
209
        }
210

211
        /**
212
         * @return array{hasExtension: bool, urls: array<int, string>}
213
         */
214
        private function extractCrlUrlsFromExtensions(array $extensions): array {
215
                $values = [];
12✔
216
                foreach ($extensions as $extensionName => $extensionValue) {
12✔
217
                        if (!is_string($extensionName)) {
12✔
NEW
218
                                continue;
×
219
                        }
220

221
                        $normalizedName = strtolower(trim($extensionName));
12✔
222
                        $isCrlDistributionPoints =
12✔
223
                                $normalizedName === 'crldistributionpoints'
12✔
224
                                || $normalizedName === 'x509v3 crl distribution points'
12✔
225
                                || $normalizedName === '2.5.29.31'
12✔
226
                                || str_contains($normalizedName, 'crl distribution points');
12✔
227

228
                        if (!$isCrlDistributionPoints) {
12✔
229
                                continue;
10✔
230
                        }
231

232
                        if (is_string($extensionValue)) {
11✔
233
                                $values[] = $extensionValue;
11✔
NEW
234
                        } elseif (is_array($extensionValue)) {
×
NEW
235
                                $values[] = implode("\n", array_filter($extensionValue, 'is_string'));
×
236
                        }
237
                }
238

239
                if (empty($values)) {
12✔
240
                        return ['hasExtension' => false, 'urls' => []];
2✔
241
                }
242

243
                $urls = [];
11✔
244
                foreach ($values as $value) {
11✔
245
                        preg_match_all('/URI\s*:\s*([^\s,\n]+)/i', $value, $matches);
11✔
246
                        if (!empty($matches[1])) {
11✔
247
                                $urls = [...$urls, ...$matches[1]];
11✔
248
                        }
249
                }
250

251
                return [
11✔
252
                        'hasExtension' => true,
11✔
253
                        'urls' => array_values(array_unique($urls)),
11✔
254
                ];
11✔
255
        }
256

257
        private static function convertArrayToUtf8($array) {
258
                foreach ($array as $key => $value) {
10✔
259
                        if (is_array($value)) {
10✔
260
                                $array[$key] = self::convertArrayToUtf8($value);
10✔
261
                        } elseif (is_string($value)) {
10✔
262
                                $array[$key] = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
10✔
263
                        }
264
                }
265
                return $array;
10✔
266
        }
267

268
        public function opensslPkcs12Read(string &$certificate, string $privateKey): array {
269
                openssl_pkcs12_read($certificate, $certContent, $privateKey);
9✔
270
                if (!empty($certContent)) {
9✔
271
                        return $certContent;
7✔
272
                }
273
                /**
274
                 * Reference:
275
                 *
276
                 * https://github.com/php/php-src/issues/12128
277
                 * https://www.php.net/manual/en/function.openssl-pkcs12-read.php#128992
278
                 */
279
                $msg = openssl_error_string();
2✔
280
                if ($msg === 'error:0308010C:digital envelope routines::unsupported') {
2✔
281
                        $tempPassword = $this->tempManager->getTemporaryFile();
×
282
                        $tempEncriptedOriginal = $this->tempManager->getTemporaryFile();
×
283
                        $tempEncriptedRepacked = $this->tempManager->getTemporaryFile();
×
284
                        $tempDecrypted = $this->tempManager->getTemporaryFile();
×
285
                        file_put_contents($tempPassword, $privateKey);
×
286
                        file_put_contents($tempEncriptedOriginal, $certificate);
×
287
                        shell_exec(<<<REPACK_COMMAND
×
288
                                cat $tempPassword | openssl pkcs12 -legacy -in $tempEncriptedOriginal -nodes -out $tempDecrypted -passin stdin &&
×
289
                                cat $tempPassword | openssl pkcs12 -in $tempDecrypted -export -out $tempEncriptedRepacked -passout stdin
×
290
                                REPACK_COMMAND
×
291
                        );
×
292
                        $certificateRepacked = file_get_contents($tempEncriptedRepacked);
×
293
                        openssl_pkcs12_read($certificateRepacked, $certContent, $privateKey);
×
294
                        if (!empty($certContent)) {
×
295
                                $certificate = $certificateRepacked;
×
296
                                return $certContent;
×
297
                        }
298
                }
299
                throw new InvalidPasswordException();
2✔
300
        }
301

302
        /**
303
         * @param (int|string) $name
304
         *
305
         * @psalm-param array-key $name
306
         */
307
        public function translateToLong($name): string {
308
                return match ($name) {
3✔
309
                        'CN' => 'CommonName',
×
310
                        'C' => 'Country',
3✔
311
                        'ST' => 'State',
×
312
                        'L' => 'Locality',
×
313
                        'O' => 'Organization',
3✔
314
                        'OU' => 'OrganizationalUnit',
2✔
315
                        'UID' => 'UserIdentifier',
×
316
                        default => '',
3✔
317
                };
3✔
318
        }
319

320
        #[\Override]
321
        public function setEngine(string $engine): void {
322
                $this->appConfig->setValueString(Application::APP_ID, 'certificate_engine', $engine);
16✔
323
                $this->engine = $engine;
16✔
324
                $this->configureIdentifyMethodsForEngine($engine);
16✔
325
        }
326

327
        /**
328
         * Configure identification methods based on the certificate engine.
329
         *
330
         * When the engine is set to 'none', only the 'account' identification method
331
         * is allowed. This is because:
332
         * - The 'none' engine doesn't generate digital certificates
333
         * - Without certificates, only basic password authentication is viable
334
         * - The 'account' method ensures users authenticate with their Nextcloud credentials
335
         *
336
         * For other engines (openssl, cfssl, java), the identification methods remain
337
         * unchanged to preserve existing configurations.
338
         *
339
         * @param string $engine The certificate engine name (i.e. 'none', 'openssl', 'cfssl')
340
         */
341
        private function configureIdentifyMethodsForEngine(string $engine): void {
342
                if ($engine !== 'none') {
16✔
343
                        return;
10✔
344
                }
345

346
                $config = [[
6✔
347
                        'name' => 'account',
6✔
348
                        'enabled' => true,
6✔
349
                        'mandatory' => true,
6✔
350
                ]];
6✔
351
                $this->appConfig->setValueArray(Application::APP_ID, 'identify_methods', $config);
6✔
352
        }
353

354
        #[\Override]
355
        public function getEngine(): string {
356
                if ($this->engine) {
3✔
357
                        return $this->engine;
3✔
358
                }
359
                $this->engine = $this->appConfig->getValueString(Application::APP_ID, 'certificate_engine', 'openssl');
×
360
                return $this->engine;
×
361
        }
362

363
        #[\Override]
364
        public function populateInstance(array $rootCert): IEngineHandler {
365
                if (empty($rootCert)) {
24✔
366
                        $rootCert = $this->appConfig->getValueArray(Application::APP_ID, 'rootCert');
24✔
367
                }
368
                if (!$rootCert) {
24✔
369
                        return $this;
24✔
370
                }
371
                if (!empty($rootCert['names'])) {
×
372
                        foreach ($rootCert['names'] as $id => $customName) {
×
373
                                $longCustomName = $this->translateToLong($id);
×
374
                                // Prevent to save a property that don't exists
375
                                if (!property_exists($this, lcfirst($longCustomName))) {
×
376
                                        continue;
×
377
                                }
378
                                $this->{'set' . ucfirst($longCustomName)}($customName['value']);
×
379
                        }
380
                }
381
                if (!$this->getCommonName()) {
×
382
                        $this->setCommonName($rootCert['commonName']);
×
383
                }
384
                return $this;
×
385
        }
386

387
        #[\Override]
388
        public function getCurrentConfigPath(): string {
389
                if ($this->configPath) {
78✔
390
                        return $this->configPath;
72✔
391
                }
392

393
                $customConfigPath = $this->appConfig->getValueString(Application::APP_ID, 'config_path');
68✔
394
                if ($customConfigPath && is_dir($customConfigPath)) {
68✔
395
                        $this->configPath = $customConfigPath;
10✔
396
                        return $this->configPath;
10✔
397
                }
398

399
                $this->configPath = $this->initializePkiConfigPath();
68✔
400
                if (!empty($this->configPath)) {
68✔
401
                        $this->appConfig->setValueString(Application::APP_ID, 'config_path', $this->configPath);
68✔
402
                }
403
                return $this->configPath;
68✔
404
        }
405

406
        #[\Override]
407
        public function getConfigPathByParams(string $instanceId, int $generation): string {
408
                $engineName = $this->getName();
20✔
409

410
                $pkiDirName = $this->caIdentifierService->generatePkiDirectoryNameFromParams($instanceId, $generation, $engineName);
20✔
411
                $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
20✔
412
                $systemInstanceId = $this->config->getSystemValue('instanceid');
20✔
413
                $pkiPath = $dataDir . '/appdata_' . $systemInstanceId . '/libresign/' . $pkiDirName;
20✔
414

415
                if (!is_dir($pkiPath)) {
20✔
416
                        throw new \RuntimeException("Config path does not exist for instanceId: {$instanceId}, generation: {$generation}");
2✔
417
                }
418

419
                return $pkiPath;
18✔
420
        }
421

422
        private function initializePkiConfigPath(): string {
423
                $caId = $this->getCaId();
68✔
424
                if (empty($caId)) {
68✔
425
                        return '';
×
426
                }
427
                $pkiDirName = $this->caIdentifierService->generatePkiDirectoryName($caId);
68✔
428
                $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
68✔
429
                $systemInstanceId = $this->config->getSystemValue('instanceid');
68✔
430
                $pkiPath = $dataDir . '/appdata_' . $systemInstanceId . '/libresign/' . $pkiDirName;
68✔
431

432
                if (!is_dir($pkiPath)) {
68✔
433
                        $this->createDirectoryWithCorrectOwnership($pkiPath);
68✔
434
                }
435

436
                return $pkiPath;
68✔
437
        }
438

439
        private function createDirectoryWithCorrectOwnership(string $path): void {
440
                $ownerInfo = $this->getFilesOwnerInfo();
68✔
441
                $fullCommand = 'mkdir -p ' . escapeshellarg($path);
68✔
442

443
                if (posix_getuid() !== $ownerInfo['uid']) {
68✔
444
                        $fullCommand = 'runuser -u ' . $ownerInfo['name'] . ' -- ' . $fullCommand;
×
445
                }
446

447
                exec($fullCommand);
68✔
448
        }
449

450
        private function getFilesOwnerInfo(): array {
451
                $currentFile = realpath(__DIR__);
68✔
452
                $owner = fileowner($currentFile);
68✔
453
                if ($owner === false) {
68✔
454
                        throw new \RuntimeException('Unable to get file information');
×
455
                }
456
                $ownerInfo = posix_getpwuid($owner);
68✔
457
                if ($ownerInfo === false) {
68✔
458
                        throw new \RuntimeException('Unable to get file owner information');
×
459
                }
460

461
                return $ownerInfo;
68✔
462
        }
463

464
        /**
465
         * @todo check a best solution to don't use reflection
466
         */
467
        private function getInternalPathOfFolder(ISimpleFolder $node): string {
468
                $reflection = new \ReflectionClass($node);
×
469
                $reflectionProperty = $reflection->getProperty('folder');
×
470
                $folder = $reflectionProperty->getValue($node);
×
471
                $path = $folder->getInternalPath();
×
472
                return $path;
×
473
        }
474

475
        #[\Override]
476
        public function setConfigPath(string $configPath): IEngineHandler {
477
                if (!$configPath) {
8✔
478
                        $this->appConfig->deleteKey(Application::APP_ID, 'config_path');
×
479
                } else {
480
                        if (!is_dir($configPath)) {
8✔
481
                                mkdir(
×
482
                                        directory: $configPath,
×
483
                                        recursive: true,
×
484
                                );
×
485
                        }
486
                        $this->appConfig->setValueString(Application::APP_ID, 'config_path', $configPath);
8✔
487
                }
488
                $this->configPath = $configPath;
8✔
489
                return $this;
8✔
490
        }
491

492
        public function getName(): string {
493
                $reflect = new ReflectionClass($this);
24✔
494
                $className = $reflect->getShortName();
24✔
495
                $name = strtolower(substr($className, 0, -7));
24✔
496
                return $name;
24✔
497
        }
498

499
        protected function getNames(): array {
500
                $names = [
74✔
501
                        'C' => $this->getCountry(),
74✔
502
                        'ST' => $this->getState(),
74✔
503
                        'L' => $this->getLocality(),
74✔
504
                        'O' => $this->getOrganization(),
74✔
505
                        'OU' => $this->getOrganizationalUnit(),
74✔
506
                ];
74✔
507
                if ($uid = $this->getUID()) {
74✔
508
                        $names['UID'] = $uid;
×
509
                }
510
                $names = array_filter($names, fn ($v) => !empty($v));
74✔
511
                return $names;
74✔
512
        }
513

514
        public function getUID(): string {
515
                return str_replace(' ', '+', $this->UID);
74✔
516
        }
517

518
        #[\Override]
519
        public function getLeafExpiryInDays(): int {
520
                if ($this->leafExpiryOverrideInDays !== null) {
27✔
521
                        return $this->leafExpiryOverrideInDays;
×
522
                }
523
                $exp = $this->appConfig->getValueInt(Application::APP_ID, 'expiry_in_days', 365);
27✔
524
                return $exp > 0 ? $exp : 365;
27✔
525
        }
526

527
        #[\Override]
528
        public function setLeafExpiryOverrideInDays(?int $days): self {
529
                $this->leafExpiryOverrideInDays = ($days !== null && $days > 0) ? $days : null;
×
530
                return $this;
×
531
        }
532

533
        #[\Override]
534
        public function getCaExpiryInDays(): int {
535
                $exp = $this->appConfig->getValueInt(Application::APP_ID, 'ca_expiry_in_days', 3650); // 10 years
62✔
536
                return $exp > 0 ? $exp : 3650;
62✔
537
        }
538

539
        private function getCertificatePolicy(): array {
540
                $return = ['policySection' => []];
11✔
541
                $oid = $this->certificatePolicyService->getOid();
11✔
542
                $cps = $this->certificatePolicyService->getCps();
11✔
543
                if ($oid && $cps) {
11✔
544
                        $return['policySection'][] = [
×
545
                                'OID' => $oid,
×
546
                                'CPS' => $cps,
×
547
                        ];
×
548
                }
549
                return $return;
11✔
550
        }
551

552
        abstract protected function getConfigureCheckResourceName(): string;
553

554
        abstract protected function getCertificateRegenerationTip(): string;
555

556
        abstract protected function getEngineSpecificChecks(): array;
557

558
        abstract protected function getSetupSuccessMessage(): string;
559

560
        abstract protected function getSetupErrorMessage(): string;
561

562
        abstract protected function getSetupErrorTip(): string;
563

564
        #[\Override]
565
        public function configureCheck(): array {
566
                $checks = $this->getEngineSpecificChecks();
8✔
567

568
                if (!$this->isSetupOk()) {
8✔
569
                        return array_merge($checks, [
1✔
570
                                (new ConfigureCheckHelper())
1✔
571
                                        ->setErrorMessage($this->getSetupErrorMessage())
1✔
572
                                        ->setResource($this->getConfigureCheckResourceName())
1✔
573
                                        ->setTip($this->getSetupErrorTip())
1✔
574
                        ]);
1✔
575
                }
576

577
                $checks[] = (new ConfigureCheckHelper())
7✔
578
                        ->setSuccessMessage($this->getSetupSuccessMessage())
7✔
579
                        ->setResource($this->getConfigureCheckResourceName());
7✔
580

581
                $modernFeaturesCheck = $this->checkRootCertificateModernFeatures();
7✔
582
                if ($modernFeaturesCheck) {
7✔
583
                        $checks[] = $modernFeaturesCheck;
7✔
584
                }
585

586
                $expiryCheck = $this->checkRootCertificateExpiry();
7✔
587
                if ($expiryCheck) {
7✔
588
                        $checks[] = $expiryCheck;
5✔
589
                }
590

591
                return $checks;
7✔
592
        }
593

594
        protected function checkRootCertificateModernFeatures(): ?ConfigureCheckHelper {
595
                $configPath = $this->getCurrentConfigPath();
7✔
596
                $caCertPath = $configPath . DIRECTORY_SEPARATOR . 'ca.pem';
7✔
597

598
                try {
599
                        $certContent = file_get_contents($caCertPath);
7✔
600
                        if (!$certContent) {
7✔
601
                                return (new ConfigureCheckHelper())
×
602
                                        ->setErrorMessage('Failed to read root certificate file')
×
603
                                        ->setResource($this->getConfigureCheckResourceName())
×
604
                                        ->setTip('Check file permissions and disk space');
×
605
                        }
606

607
                        $x509Resource = openssl_x509_read($certContent);
7✔
608
                        if (!$x509Resource) {
7✔
609
                                return (new ConfigureCheckHelper())
×
610
                                        ->setErrorMessage('Failed to parse root certificate')
×
611
                                        ->setResource($this->getConfigureCheckResourceName())
×
612
                                        ->setTip('Root certificate file may be corrupted or invalid');
×
613
                        }
614

615
                        $parsed = openssl_x509_parse($x509Resource);
7✔
616
                        if (!$parsed) {
7✔
617
                                return (new ConfigureCheckHelper())
×
618
                                        ->setErrorMessage('Failed to extract root certificate information')
×
619
                                        ->setResource($this->getConfigureCheckResourceName())
×
620
                                        ->setTip('Root certificate may be in an unsupported format');
×
621
                        }
622

623
                        $criticalIssues = [];
7✔
624
                        $minorIssues = [];
7✔
625

626
                        if (isset($parsed['serialNumber'])) {
7✔
627
                                $serialNumber = $parsed['serialNumber'];
7✔
628
                                $serialDecimal = hexdec($serialNumber);
7✔
629
                                if ($serialDecimal <= 1) {
7✔
630
                                        $minorIssues[] = 'Serial number is simple (zero or one)';
×
631
                                }
632
                        } else {
633
                                $criticalIssues[] = 'Serial number is missing';
×
634
                        }
635

636
                        $missingExtensions = [];
7✔
637
                        if (!isset($parsed['extensions']['subjectKeyIdentifier'])) {
7✔
638
                                $missingExtensions[] = 'Subject Key Identifier (SKI)';
×
639
                        }
640

641
                        $isSelfSigned = (isset($parsed['issuer']) && isset($parsed['subject'])
7✔
642
                                                        && $parsed['issuer'] === $parsed['subject']);
7✔
643

644
                        /**
645
                         * @todo workarround for missing AKI at certificates generated by CFSSL.
646
                         *
647
                         * CFSSL does not add Authority Key Identifier (AKI) to self-signed root certificates.
648
                         */
649
                        if (!$isSelfSigned && !isset($parsed['extensions']['authorityKeyIdentifier'])) {
7✔
650
                                $missingExtensions[] = 'Authority Key Identifier (AKI)';
×
651
                        }
652

653
                        if (!isset($parsed['extensions']['crlDistributionPoints'])) {
7✔
654
                                $missingExtensions[] = 'CRL Distribution Points';
×
655
                        }
656

657
                        if (!empty($missingExtensions)) {
7✔
658
                                $extensionsList = implode(', ', $missingExtensions);
×
659
                                $minorIssues[] = "Missing modern extensions: {$extensionsList}";
×
660
                        }
661

662
                        $hasLibresignCaUuid = $this->validateLibresignCaUuidInCertificate($parsed);
7✔
663
                        if (!$hasLibresignCaUuid) {
7✔
664
                                $minorIssues[] = 'LibreSign CA UUID not found in Organizational Unit';
7✔
665
                        }
666

667
                        if (!empty($criticalIssues)) {
7✔
668
                                $issuesList = implode(', ', $criticalIssues);
×
669
                                return (new ConfigureCheckHelper())
×
670
                                        ->setErrorMessage("Root certificate has critical issues: {$issuesList}")
×
671
                                        ->setResource($this->getConfigureCheckResourceName())
×
672
                                        ->setTip($this->getCertificateRegenerationTip());
×
673
                        }
674

675
                        if (!empty($minorIssues)) {
7✔
676
                                $issuesList = implode(', ', $minorIssues);
7✔
677
                                return (new ConfigureCheckHelper())
7✔
678
                                        ->setInfoMessage("Root certificate could benefit from modern features: {$issuesList}")
7✔
679
                                        ->setResource($this->getConfigureCheckResourceName())
7✔
680
                                        ->setTip($this->getCertificateRegenerationTip() . ' (recommended but not required)');
7✔
681
                        }
682

683
                        return null;
×
684

685
                } catch (\Exception $e) {
×
686
                        return (new ConfigureCheckHelper())
×
687
                                ->setErrorMessage('Failed to analyze root certificate: ' . $e->getMessage())
×
688
                                ->setResource($this->getConfigureCheckResourceName())
×
689
                                ->setTip('Check if the root certificate file is valid');
×
690
                }
691
        }
692

693
        private function validateLibresignCaUuidInCertificate(array $parsed): bool {
694
                if (!isset($parsed['subject']['OU'])) {
7✔
695
                        return false;
7✔
696
                }
697

698
                $instanceId = $this->getLibreSignInstanceId();
×
699
                if (empty($instanceId)) {
×
700
                        return false;
×
701
                }
702

703
                $organizationalUnits = $parsed['subject']['OU'];
×
704

705
                if (is_string($organizationalUnits)) {
×
706
                        if (str_contains($organizationalUnits, ', ')) {
×
707
                                $organizationalUnits = explode(', ', $organizationalUnits);
×
708
                        } else {
709
                                $organizationalUnits = [$organizationalUnits];
×
710
                        }
711
                }
712

713
                foreach ($organizationalUnits as $ou) {
×
714
                        $ou = trim($ou);
×
715
                        if ($this->caIdentifierService->isValidCaId($ou, $instanceId)) {
×
716
                                return true;
×
717
                        }
718
                }
719

720
                return false;
×
721
        }
722

723
        private function getLibreSignInstanceId(): string {
724
                $instanceId = $this->appConfig->getValueString(Application::APP_ID, 'instance_id', '');
×
725
                if (strlen($instanceId) === 10) {
×
726
                        return $instanceId;
×
727
                }
728
                return '';
×
729
        }
730

731
        private function calculateRemainingDays(int $validToTimestamp): int {
732
                $secondsPerDay = 60 * 60 * 24;
27✔
733
                $remainingSeconds = $validToTimestamp - time();
27✔
734
                return (int)ceil($remainingSeconds / $secondsPerDay);
27✔
735
        }
736

737
        protected function checkRootCertificateExpiry(): ?ConfigureCheckHelper {
738
                $configPath = $this->getCurrentConfigPath();
7✔
739
                $caCertPath = $configPath . DIRECTORY_SEPARATOR . 'ca.pem';
7✔
740

741
                if (!file_exists($caCertPath)) {
7✔
742
                        return null;
×
743
                }
744

745
                $certContent = file_get_contents($caCertPath);
7✔
746
                if (!$certContent) {
7✔
747
                        return null;
×
748
                }
749

750
                $x509Resource = openssl_x509_read($certContent);
7✔
751
                if (!$x509Resource) {
7✔
752
                        return null;
×
753
                }
754

755
                $parsed = openssl_x509_parse($x509Resource);
7✔
756
                if (!$parsed) {
7✔
757
                        return null;
×
758
                }
759

760
                $remainingDays = $this->calculateRemainingDays($parsed['validTo_time_t']);
7✔
761
                $leafExpiryDays = $this->getLeafExpiryInDays();
7✔
762

763
                if ($remainingDays < 0) {
7✔
764
                        return (new ConfigureCheckHelper())
×
765
                                ->setErrorMessage('Root certificate has expired')
×
766
                                ->setResource($this->getConfigureCheckResourceName())
×
767
                                ->setTip($this->getCertificateRegenerationTip() . ' URGENT: Certificate is expired!');
×
768
                }
769

770
                if ($remainingDays <= 7) {
7✔
771
                        return (new ConfigureCheckHelper())
2✔
772
                                ->setErrorMessage("Root certificate expires in {$remainingDays} days")
2✔
773
                                ->setResource($this->getConfigureCheckResourceName())
2✔
774
                                ->setTip($this->getCertificateRegenerationTip() . ' URGENT: Renew immediately!');
2✔
775
                }
776

777
                if ($remainingDays <= 30) {
5✔
778
                        return (new ConfigureCheckHelper())
1✔
779
                                ->setErrorMessage("Root certificate expires in {$remainingDays} days")
1✔
780
                                ->setResource($this->getConfigureCheckResourceName())
1✔
781
                                ->setTip($this->getCertificateRegenerationTip() . ' Renewal recommended soon.');
1✔
782
                }
783

784
                if ($remainingDays <= $leafExpiryDays) {
4✔
785
                        return (new ConfigureCheckHelper())
2✔
786
                                ->setInfoMessage("Root certificate expires in {$remainingDays} days (leaf validity: {$leafExpiryDays} days)")
2✔
787
                                ->setResource($this->getConfigureCheckResourceName())
2✔
788
                                ->setTip('Root certificate should be renewed to ensure it can sign CRLs for all issued leaf certificates.');
2✔
789
                }
790

791
                return null;
2✔
792
        }
793

794
        #[\Override]
795
        public function toArray(): array {
796
                $generated = $this->isSetupOk();
11✔
797
                $return = [
11✔
798
                        'configPath' => $this->getConfigPathForApi($generated),
11✔
799
                        'generated' => $generated,
11✔
800
                        'rootCert' => [
11✔
801
                                'commonName' => $this->getCommonName(),
11✔
802
                                'names' => [],
11✔
803
                        ],
11✔
804
                ];
11✔
805
                $return = array_merge(
11✔
806
                        $return,
11✔
807
                        $this->getCertificatePolicy(),
11✔
808
                );
11✔
809
                $names = $this->getNames();
11✔
810
                foreach ($names as $name => $value) {
11✔
811
                        $return['rootCert']['names'][] = [
6✔
812
                                'id' => $name,
6✔
813
                                'value' => $this->filterNameValue($name, $value, $generated),
6✔
814
                        ];
6✔
815
                }
816
                return $return;
11✔
817
        }
818

819
        private function getConfigPathForApi(bool $generated): string {
820
                return $generated ? $this->getCurrentConfigPath() : '';
11✔
821
        }
822

823
        private function filterNameValue(string $name, mixed $value, bool $generated): mixed {
824
                if ($name === 'OU' && is_array($value) && !$generated) {
6✔
825
                        $filtered = $this->removeCaIdFromOrganizationalUnit($value);
3✔
826
                        return empty($filtered) ? null : $filtered;
3✔
827
                }
828
                return $value;
6✔
829
        }
830

831
        private function removeCaIdFromOrganizationalUnit(array $organizationalUnits): array {
832
                $filtered = array_filter(
3✔
833
                        $organizationalUnits,
3✔
834
                        fn ($item) => !str_starts_with($item, 'libresign-ca-id:')
3✔
835
                );
3✔
836
                return array_values($filtered);
3✔
837
        }
838

839
        protected function getCrlDistributionUrl(): string {
840
                $caIdParsed = $this->caIdentifierService->getCaIdParsed();
63✔
841
                return $this->urlGenerator->linkToRouteAbsolute('libresign.crl.getRevocationList', [
63✔
842
                        'instanceId' => $caIdParsed['instanceId'],
63✔
843
                        'generation' => $caIdParsed['generation'],
63✔
844
                        'engineType' => $caIdParsed['engineType'],
63✔
845
                ]);
63✔
846
        }
847

848
        #[\Override]
849
        public function generateCrlDer(array $revokedCertificates, string $instanceId, int $generation, int $crlNumber): string {
850
                $configPath = $this->getConfigPathByParams($instanceId, $generation);
20✔
851
                $issuer = $this->loadCaIssuer($configPath);
18✔
852
                $signedCrl = $this->createAndSignCrl($issuer, $revokedCertificates, $crlNumber);
18✔
853
                $crlDerData = $this->saveCrlToDer($signedCrl, $configPath);
18✔
854

855
                return $crlDerData;
18✔
856
        }
857

858
        private function loadCaIssuer(string $configPath): \phpseclib3\File\X509 {
859
                $caCertPath = $configPath . DIRECTORY_SEPARATOR . 'ca.pem';
18✔
860
                $caKeyPath = $configPath . DIRECTORY_SEPARATOR . 'ca-key.pem';
18✔
861

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

867
                $caCert = file_get_contents($caCertPath);
18✔
868
                $caKey = file_get_contents($caKeyPath);
18✔
869

870
                if (!$caCert || !$caKey) {
18✔
871
                        $this->logger->error('Failed to read CA certificate or private key', ['caCertPath' => $caCertPath, 'caKeyPath' => $caKeyPath]);
×
872
                        throw new \RuntimeException('Failed to read CA certificate or private key');
×
873
                }
874

875
                $issuer = new \phpseclib3\File\X509();
18✔
876
                $issuer->loadX509($caCert);
18✔
877
                $caPrivateKey = \phpseclib3\Crypt\PublicKeyLoader::load($caKey);
18✔
878

879
                if (!$caPrivateKey instanceof \phpseclib3\Crypt\Common\PrivateKey) {
18✔
880
                        $this->logger->error('Loaded key is not a private key', ['keyType' => get_class($caPrivateKey)]);
×
881
                        throw new \RuntimeException('Loaded key is not a private key');
×
882
                }
883

884
                $issuer->setPrivateKey($caPrivateKey);
18✔
885
                return $issuer;
18✔
886
        }
887

888
        private function createAndSignCrl(\phpseclib3\File\X509 $issuer, array $revokedCertificates, int $crlNumber): array {
889
                $utcZone = new \DateTimeZone('UTC');
18✔
890
                $crlToSign = new \phpseclib3\File\X509();
18✔
891
                $crlToSign->setSerialNumber((string)$crlNumber, 10);
18✔
892
                $crlToSign->setStartDate(new \DateTime('now', $utcZone));
18✔
893
                $crlToSign->setEndDate(new \DateTime('+7 days', $utcZone));
18✔
894

895
                $initialCrl = $crlToSign->signCRL($issuer, $crlToSign);
18✔
896
                if ($initialCrl === false) {
18✔
897
                        $this->logger->error('Failed to create initial CRL structure');
×
898
                        throw new \RuntimeException('Failed to create initial CRL structure');
×
899
                }
900

901
                if (!empty($revokedCertificates)) {
18✔
902
                        $savedCrl = $crlToSign->saveCRL($initialCrl);
17✔
903
                        if ($savedCrl === false) {
17✔
904
                                $this->logger->error('Failed to save initial CRL structure');
×
905
                                throw new \RuntimeException('Failed to save initial CRL structure');
×
906
                        }
907

908
                        $crlToSign->loadCRL($savedCrl);
17✔
909

910
                        $dateFormat = 'D, d M Y H:i:s O';
17✔
911
                        foreach ($revokedCertificates as $cert) {
17✔
912
                                $serialNumber = $cert->getSerialNumber();
17✔
913
                                $normalizedSerial = ltrim($serialNumber, '0') ?: '0';
17✔
914
                                $crlToSign->revoke(
17✔
915
                                        new \phpseclib3\Math\BigInteger($normalizedSerial, 16),
17✔
916
                                        $cert->getRevokedAt()->format($dateFormat)
17✔
917
                                );
17✔
918
                        }
919

920
                        $signedCrl = $crlToSign->signCRL($issuer, $crlToSign);
17✔
921
                } else {
922
                        $signedCrl = $initialCrl;
1✔
923
                }
924

925
                if ($signedCrl === false) {
18✔
926
                        $this->logger->error('Failed to sign CRL', ['crlNumber' => $crlNumber]);
×
927
                        throw new \RuntimeException('Failed to sign CRL');
×
928
                }
929

930
                if (!isset($signedCrl['signatureAlgorithm'])) {
18✔
931
                        $signedCrl['signatureAlgorithm'] = ['algorithm' => 'sha256WithRSAEncryption'];
×
932
                }
933

934
                return $signedCrl;
18✔
935
        }
936

937
        private function saveCrlToDer(array $signedCrl, string $configPath): string {
938
                $crlDerPath = $configPath . DIRECTORY_SEPARATOR . 'crl.der';
18✔
939
                $crlToSign = new \phpseclib3\File\X509();
18✔
940

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

943
                if ($crlDerData === false) {
18✔
944
                        $this->logger->error('Failed to save CRL in DER format');
×
945
                        throw new \RuntimeException('Failed to save CRL in DER format');
×
946
                }
947

948
                if (file_put_contents($crlDerPath, $crlDerData) === false) {
18✔
949
                        $this->logger->error('Failed to write CRL DER file', ['path' => $crlDerPath]);
×
950
                        throw new \RuntimeException('Failed to write CRL DER file');
×
951
                }
952

953
                return $crlDerData;
18✔
954
        }
955

956
        #[\Override]
957
        public function validateRootCertificate(): void {
958
                $configPath = $this->getCurrentConfigPath();
23✔
959
                if (empty($configPath)) {
23✔
960
                        return;
×
961
                }
962

963
                if (!is_dir($configPath)) {
23✔
964
                        return;
×
965
                }
966

967
                $rootCertPath = $configPath . DIRECTORY_SEPARATOR . 'ca.pem';
23✔
968

969
                if (!file_exists($rootCertPath)) {
23✔
970
                        return;
3✔
971
                }
972

973
                $rootCert = file_get_contents($rootCertPath);
20✔
974
                if (empty($rootCert)) {
20✔
975
                        return;
×
976
                }
977

978
                $certificate = openssl_x509_read($rootCert);
20✔
979
                if ($certificate === false) {
20✔
980
                        throw new LibresignException('Invalid root certificate content');
×
981
                }
982
                $certInfo = openssl_x509_parse($certificate);
20✔
983
                if ($certInfo === false) {
20✔
984
                        throw new LibresignException('Failed to parse root certificate');
×
985
                }
986

987
                if ($this->checkCertificateRevoked($certInfo['serialNumber'])) {
20✔
988
                        $this->logger->error('Root certificate has been revoked', [
×
989
                                'ca_id' => $this->getCaId(),
×
990
                                'impact' => 'all_leaf_certificates_invalid',
×
991
                        ]);
×
992
                        throw new LibresignException(
×
993
                                'Root certificate has been revoked. Please contact the administrator to regenerate the signing certificate.',
×
994
                                \OC\AppFramework\Http::STATUS_PRECONDITION_FAILED
×
995
                        );
×
996
                }
997

998
                if ($certInfo['validTo_time_t'] < time()) {
20✔
999
                        $this->logger->error('Root certificate has expired', [
×
1000
                                'ca_id' => $this->getCaId(),
×
1001
                        ]);
×
1002
                        throw new LibresignException(
×
1003
                                'Root certificate has expired. Please contact the administrator to regenerate the signing certificate.',
×
1004
                                \OC\AppFramework\Http::STATUS_PRECONDITION_FAILED
×
1005
                        );
×
1006
                }
1007

1008
                $remainingDays = $this->calculateRemainingDays($certInfo['validTo_time_t']);
20✔
1009
                $leafExpiryDays = $this->getLeafExpiryInDays();
20✔
1010

1011
                if ($remainingDays <= $leafExpiryDays) {
20✔
1012
                        $this->logger->warning('Root certificate renewal needed', [
6✔
1013
                                'remaining_days' => $remainingDays,
6✔
1014
                                'leaf_expiry_days' => $leafExpiryDays,
6✔
1015
                        ]);
6✔
1016
                }
1017
        }
1018

1019
        private function checkCertificateRevoked(string $serialNumber): bool {
1020
                try {
1021
                        /** @var \OCA\Libresign\Service\Crl\CrlService */
1022
                        $crlService = \OC::$server->get(\OCA\Libresign\Service\Crl\CrlService::class);
20✔
1023
                        $status = $crlService->getCertificateStatus($serialNumber);
20✔
1024
                        return $status['status'] === 'revoked';
20✔
1025
                } catch (\Exception $e) {
×
1026
                        $this->logger->warning('Failed to check root certificate revocation status', [
×
1027
                                'error' => $e->getMessage()
×
1028
                        ]);
×
1029
                        return false;
×
1030
                }
1031
        }
1032
}
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