-
-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathAEngineHandler.php
More file actions
1215 lines (1029 loc) · 37.4 KB
/
AEngineHandler.php
File metadata and controls
1215 lines (1029 loc) · 37.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Libresign\Handler\CertificateEngine;
use OCA\Libresign\AppInfo\Application;
use OCA\Libresign\Exception\EmptyCertificateException;
use OCA\Libresign\Exception\InvalidPasswordException;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Helper\ConfigureCheckHelper;
use OCA\Libresign\Helper\MagicGetterSetterTrait;
use OCA\Libresign\Service\CaIdentifierService;
use OCA\Libresign\Service\CertificatePolicyService;
use OCP\Files\AppData\IAppDataFactory;
use OCP\Files\IAppData;
use OCP\Files\SimpleFS\ISimpleFolder;
use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IDateTimeFormatter;
use OCP\ITempManager;
use OCP\IURLGenerator;
use OpenSSLAsymmetricKey;
use OpenSSLCertificate;
use Psr\Log\LoggerInterface;
use ReflectionClass;
/**
* @method IEngineHandler setPassword(string $password)
* @method string getPassword()
* @method IEngineHandler setCommonName(string $commonName)
* @method string getCommonName()
* @method IEngineHandler setHosts(array $hosts)
* @method array getHosts()
* @method IEngineHandler setFriendlyName(string $friendlyName)
* @method string getFriendlyName()
* @method IEngineHandler setCountry(string $country)
* @method string getCountry()
* @method IEngineHandler setState(string $state)
* @method string getState()
* @method IEngineHandler setLocality(string $locality)
* @method string getLocality()
* @method IEngineHandler setOrganization(string $organization)
* @method string getOrganization()
* @method IEngineHandler setOrganizationalUnit(array $organizationalUnit)
* @method array getOrganizationalUnit()
* @method IEngineHandler setUID(string $UID)
* @method string getName()
*/
abstract class AEngineHandler implements IEngineHandler {
use MagicGetterSetterTrait;
use OrderCertificatesTrait;
protected string $commonName = '';
protected array $hosts = [];
protected string $friendlyName = '';
protected string $country = '';
protected string $state = '';
protected string $locality = '';
protected string $organization = '';
protected array $organizationalUnit = [];
protected string $UID = '';
private ?int $leafExpiryOverrideInDays = null;
protected string $password = '';
protected string $configPath = '';
protected string $engine = '';
protected string $certificate = '';
protected string $currentCaId = '';
protected IAppData $appData;
public function __construct(
protected IConfig $config,
protected IAppConfig $appConfig,
protected IAppDataFactory $appDataFactory,
protected IDateTimeFormatter $dateTimeFormatter,
protected ITempManager $tempManager,
protected CertificatePolicyService $certificatePolicyService,
protected IURLGenerator $urlGenerator,
protected CaIdentifierService $caIdentifierService,
protected LoggerInterface $logger,
) {
$this->appData = $appDataFactory->get('libresign');
}
protected function exportToPkcs12(
OpenSSLCertificate|string $certificate,
OpenSSLAsymmetricKey|OpenSSLCertificate|string $privateKey,
array $options = [],
): string {
if (empty($certificate) || empty($privateKey)) {
throw new EmptyCertificateException();
}
$certContent = null;
try {
openssl_pkcs12_export(
$certificate,
$certContent,
$privateKey,
$this->getPassword(),
$options,
);
if (!$certContent) {
throw new \Exception();
}
} catch (\Throwable) {
throw new LibresignException('Error while creating certificate file', 500);
}
return $certContent;
}
#[\Override]
public function updatePassword(string $certificate, string $currentPrivateKey, string $newPrivateKey): string {
if (empty($certificate) || empty($currentPrivateKey) || empty($newPrivateKey)) {
throw new EmptyCertificateException();
}
$certContent = $this->opensslPkcs12Read($certificate, $currentPrivateKey);
$this->setPassword($newPrivateKey);
$certContent = self::exportToPkcs12($certContent['cert'], $certContent['pkey']);
return $certContent;
}
#[\Override]
public function readCertificate(string $certificate, string $privateKey): array {
if (empty($certificate) || empty($privateKey)) {
throw new EmptyCertificateException();
}
$certContent = $this->opensslPkcs12Read($certificate, $privateKey);
$return = $this->parseX509($certContent['cert']);
if (isset($certContent['extracerts'])) {
foreach ($certContent['extracerts'] as $extraCert) {
$return['extracerts'][] = $this->parseX509($extraCert);
}
$return['extracerts'] = $this->orderCertificates($return['extracerts']);
}
return $return;
}
public function getCaId(): string {
$caId = $this->caIdentifierService->getCaId();
if (empty($caId)) {
$this->appConfig->clearCache(true);
$caId = $this->caIdentifierService->getCaId() ?: $this->caIdentifierService->generateCaId($this->getName());
}
return $caId;
}
#[\Override]
public function parseCertificate(string $certificate): array {
return $this->parseX509($certificate);
}
private function parseX509(string $x509): array {
$parsed = openssl_x509_parse(openssl_x509_read($x509));
$return = self::convertArrayToUtf8($parsed);
foreach (['subject', 'issuer'] as $actor) {
foreach ($return[$actor] as $part => $value) {
if (is_string($value) && str_contains($value, ', ')) {
$return[$actor][$part] = explode(', ', $value);
} else {
$return[$actor][$part] = $value;
}
}
}
$return['valid_from'] = $this->dateTimeFormatter->formatDateTime($parsed['validFrom_time_t']);
$return['valid_to'] = $this->dateTimeFormatter->formatDateTime($parsed['validTo_time_t']);
$this->addCrlValidationInfo($return, $x509);
return $return;
}
private function addCrlValidationInfo(array &$certData, string $certPem): void {
if (isset($certData['extensions']['crlDistributionPoints'])) {
$crlDistributionPoints = $certData['extensions']['crlDistributionPoints'];
preg_match_all('/URI:([^\s,\n]+)/', $crlDistributionPoints, $matches);
$extractedUrls = $matches[1] ?? [];
$certData['crl_urls'] = $extractedUrls;
$crlDetails = $this->validateCrlFromUrlsWithDetails($extractedUrls, $certPem);
$certData['crl_validation'] = $crlDetails['status'];
if (!empty($crlDetails['revoked_at'])) {
$certData['crl_revoked_at'] = $crlDetails['revoked_at'];
}
} else {
$certData['crl_validation'] = 'missing';
$certData['crl_urls'] = [];
}
}
private static function convertArrayToUtf8($array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = self::convertArrayToUtf8($value);
} elseif (is_string($value)) {
$array[$key] = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
}
}
return $array;
}
public function opensslPkcs12Read(string &$certificate, string $privateKey): array {
openssl_pkcs12_read($certificate, $certContent, $privateKey);
if (!empty($certContent)) {
return $certContent;
}
/**
* Reference:
*
* https://github.com/php/php-src/issues/12128
* https://www.php.net/manual/en/function.openssl-pkcs12-read.php#128992
*/
$msg = openssl_error_string();
if ($msg === 'error:0308010C:digital envelope routines::unsupported') {
$tempPassword = $this->tempManager->getTemporaryFile();
$tempEncriptedOriginal = $this->tempManager->getTemporaryFile();
$tempEncriptedRepacked = $this->tempManager->getTemporaryFile();
$tempDecrypted = $this->tempManager->getTemporaryFile();
file_put_contents($tempPassword, $privateKey);
file_put_contents($tempEncriptedOriginal, $certificate);
shell_exec(<<<REPACK_COMMAND
cat $tempPassword | openssl pkcs12 -legacy -in $tempEncriptedOriginal -nodes -out $tempDecrypted -passin stdin &&
cat $tempPassword | openssl pkcs12 -in $tempDecrypted -export -out $tempEncriptedRepacked -passout stdin
REPACK_COMMAND
);
$certificateRepacked = file_get_contents($tempEncriptedRepacked);
openssl_pkcs12_read($certificateRepacked, $certContent, $privateKey);
if (!empty($certContent)) {
$certificate = $certificateRepacked;
return $certContent;
}
}
throw new InvalidPasswordException();
}
/**
* @param (int|string) $name
*
* @psalm-param array-key $name
*/
public function translateToLong($name): string {
return match ($name) {
'CN' => 'CommonName',
'C' => 'Country',
'ST' => 'State',
'L' => 'Locality',
'O' => 'Organization',
'OU' => 'OrganizationalUnit',
'UID' => 'UserIdentifier',
default => '',
};
}
#[\Override]
public function setEngine(string $engine): void {
$this->appConfig->setValueString(Application::APP_ID, 'certificate_engine', $engine);
$this->engine = $engine;
$this->configureIdentifyMethodsForEngine($engine);
}
/**
* Configure identification methods based on the certificate engine.
*
* When the engine is set to 'none', only the 'account' identification method
* is allowed. This is because:
* - The 'none' engine doesn't generate digital certificates
* - Without certificates, only basic password authentication is viable
* - The 'account' method ensures users authenticate with their Nextcloud credentials
*
* For other engines (openssl, cfssl, java), the identification methods remain
* unchanged to preserve existing configurations.
*
* @param string $engine The certificate engine name (i.e. 'none', 'openssl', 'cfssl')
*/
private function configureIdentifyMethodsForEngine(string $engine): void {
if ($engine !== 'none') {
return;
}
$config = [[
'name' => 'account',
'enabled' => true,
'mandatory' => true,
]];
$this->appConfig->setValueArray(Application::APP_ID, 'identify_methods', $config);
}
#[\Override]
public function getEngine(): string {
if ($this->engine) {
return $this->engine;
}
$this->engine = $this->appConfig->getValueString(Application::APP_ID, 'certificate_engine', 'openssl');
return $this->engine;
}
#[\Override]
public function populateInstance(array $rootCert): IEngineHandler {
if (empty($rootCert)) {
$rootCert = $this->appConfig->getValueArray(Application::APP_ID, 'rootCert');
}
if (!$rootCert) {
return $this;
}
if (!empty($rootCert['names'])) {
foreach ($rootCert['names'] as $id => $customName) {
$longCustomName = $this->translateToLong($id);
// Prevent to save a property that don't exists
if (!property_exists($this, lcfirst($longCustomName))) {
continue;
}
$this->{'set' . ucfirst($longCustomName)}($customName['value']);
}
}
if (!$this->getCommonName()) {
$this->setCommonName($rootCert['commonName']);
}
return $this;
}
#[\Override]
public function getCurrentConfigPath(): string {
if ($this->configPath) {
return $this->configPath;
}
$customConfigPath = $this->appConfig->getValueString(Application::APP_ID, 'config_path');
if ($customConfigPath && is_dir($customConfigPath)) {
$this->configPath = $customConfigPath;
return $this->configPath;
}
$this->configPath = $this->initializePkiConfigPath();
if (!empty($this->configPath)) {
$this->appConfig->setValueString(Application::APP_ID, 'config_path', $this->configPath);
}
return $this->configPath;
}
#[\Override]
public function getConfigPathByParams(string $instanceId, int $generation): string {
$engineName = $this->getName();
$pkiDirName = $this->caIdentifierService->generatePkiDirectoryNameFromParams($instanceId, $generation, $engineName);
$dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
$systemInstanceId = $this->config->getSystemValue('instanceid');
$pkiPath = $dataDir . '/appdata_' . $systemInstanceId . '/libresign/' . $pkiDirName;
if (!is_dir($pkiPath)) {
throw new \RuntimeException("Config path does not exist for instanceId: {$instanceId}, generation: {$generation}");
}
return $pkiPath;
}
private function initializePkiConfigPath(): string {
$caId = $this->getCaId();
if (empty($caId)) {
return '';
}
$pkiDirName = $this->caIdentifierService->generatePkiDirectoryName($caId);
$dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
$systemInstanceId = $this->config->getSystemValue('instanceid');
$pkiPath = $dataDir . '/appdata_' . $systemInstanceId . '/libresign/' . $pkiDirName;
if (!is_dir($pkiPath)) {
$this->createDirectoryWithCorrectOwnership($pkiPath);
}
return $pkiPath;
}
private function createDirectoryWithCorrectOwnership(string $path): void {
$ownerInfo = $this->getFilesOwnerInfo();
$fullCommand = 'mkdir -p ' . escapeshellarg($path);
if (posix_getuid() !== $ownerInfo['uid']) {
$fullCommand = 'runuser -u ' . $ownerInfo['name'] . ' -- ' . $fullCommand;
}
exec($fullCommand);
}
private function getFilesOwnerInfo(): array {
$currentFile = realpath(__DIR__);
$owner = fileowner($currentFile);
if ($owner === false) {
throw new \RuntimeException('Unable to get file information');
}
$ownerInfo = posix_getpwuid($owner);
if ($ownerInfo === false) {
throw new \RuntimeException('Unable to get file owner information');
}
return $ownerInfo;
}
/**
* @todo check a best solution to don't use reflection
*/
private function getInternalPathOfFolder(ISimpleFolder $node): string {
$reflection = new \ReflectionClass($node);
$reflectionProperty = $reflection->getProperty('folder');
$folder = $reflectionProperty->getValue($node);
$path = $folder->getInternalPath();
return $path;
}
#[\Override]
public function setConfigPath(string $configPath): IEngineHandler {
if (!$configPath) {
$this->appConfig->deleteKey(Application::APP_ID, 'config_path');
} else {
if (!is_dir($configPath)) {
mkdir(
directory: $configPath,
recursive: true,
);
}
$this->appConfig->setValueString(Application::APP_ID, 'config_path', $configPath);
}
$this->configPath = $configPath;
return $this;
}
public function getName(): string {
$reflect = new ReflectionClass($this);
$className = $reflect->getShortName();
$name = strtolower(substr($className, 0, -7));
return $name;
}
protected function getNames(): array {
$names = [
'C' => $this->getCountry(),
'ST' => $this->getState(),
'L' => $this->getLocality(),
'O' => $this->getOrganization(),
'OU' => $this->getOrganizationalUnit(),
];
if ($uid = $this->getUID()) {
$names['UID'] = $uid;
}
$names = array_filter($names, fn ($v) => !empty($v));
return $names;
}
public function getUID(): string {
return str_replace(' ', '+', $this->UID);
}
#[\Override]
public function getLeafExpiryInDays(): int {
if ($this->leafExpiryOverrideInDays !== null) {
return $this->leafExpiryOverrideInDays;
}
$exp = $this->appConfig->getValueInt(Application::APP_ID, 'expiry_in_days', 365);
return $exp > 0 ? $exp : 365;
}
#[\Override]
public function setLeafExpiryOverrideInDays(?int $days): self {
$this->leafExpiryOverrideInDays = ($days !== null && $days > 0) ? $days : null;
return $this;
}
#[\Override]
public function getCaExpiryInDays(): int {
$exp = $this->appConfig->getValueInt(Application::APP_ID, 'ca_expiry_in_days', 3650); // 10 years
return $exp > 0 ? $exp : 3650;
}
private function getCertificatePolicy(): array {
$return = ['policySection' => []];
$oid = $this->certificatePolicyService->getOid();
$cps = $this->certificatePolicyService->getCps();
if ($oid && $cps) {
$return['policySection'][] = [
'OID' => $oid,
'CPS' => $cps,
];
}
return $return;
}
abstract protected function getConfigureCheckResourceName(): string;
abstract protected function getCertificateRegenerationTip(): string;
abstract protected function getEngineSpecificChecks(): array;
abstract protected function getSetupSuccessMessage(): string;
abstract protected function getSetupErrorMessage(): string;
abstract protected function getSetupErrorTip(): string;
#[\Override]
public function configureCheck(): array {
$checks = $this->getEngineSpecificChecks();
if (!$this->isSetupOk()) {
return array_merge($checks, [
(new ConfigureCheckHelper())
->setErrorMessage($this->getSetupErrorMessage())
->setResource($this->getConfigureCheckResourceName())
->setTip($this->getSetupErrorTip())
]);
}
$checks[] = (new ConfigureCheckHelper())
->setSuccessMessage($this->getSetupSuccessMessage())
->setResource($this->getConfigureCheckResourceName());
$modernFeaturesCheck = $this->checkRootCertificateModernFeatures();
if ($modernFeaturesCheck) {
$checks[] = $modernFeaturesCheck;
}
$expiryCheck = $this->checkRootCertificateExpiry();
if ($expiryCheck) {
$checks[] = $expiryCheck;
}
return $checks;
}
protected function checkRootCertificateModernFeatures(): ?ConfigureCheckHelper {
$configPath = $this->getCurrentConfigPath();
$caCertPath = $configPath . DIRECTORY_SEPARATOR . 'ca.pem';
try {
$certContent = file_get_contents($caCertPath);
if (!$certContent) {
return (new ConfigureCheckHelper())
->setErrorMessage('Failed to read root certificate file')
->setResource($this->getConfigureCheckResourceName())
->setTip('Check file permissions and disk space');
}
$x509Resource = openssl_x509_read($certContent);
if (!$x509Resource) {
return (new ConfigureCheckHelper())
->setErrorMessage('Failed to parse root certificate')
->setResource($this->getConfigureCheckResourceName())
->setTip('Root certificate file may be corrupted or invalid');
}
$parsed = openssl_x509_parse($x509Resource);
if (!$parsed) {
return (new ConfigureCheckHelper())
->setErrorMessage('Failed to extract root certificate information')
->setResource($this->getConfigureCheckResourceName())
->setTip('Root certificate may be in an unsupported format');
}
$criticalIssues = [];
$minorIssues = [];
if (isset($parsed['serialNumber'])) {
$serialNumber = $parsed['serialNumber'];
$serialDecimal = hexdec($serialNumber);
if ($serialDecimal <= 1) {
$minorIssues[] = 'Serial number is simple (zero or one)';
}
} else {
$criticalIssues[] = 'Serial number is missing';
}
$missingExtensions = [];
if (!isset($parsed['extensions']['subjectKeyIdentifier'])) {
$missingExtensions[] = 'Subject Key Identifier (SKI)';
}
$isSelfSigned = (isset($parsed['issuer']) && isset($parsed['subject'])
&& $parsed['issuer'] === $parsed['subject']);
/**
* @todo workarround for missing AKI at certificates generated by CFSSL.
*
* CFSSL does not add Authority Key Identifier (AKI) to self-signed root certificates.
*/
if (!$isSelfSigned && !isset($parsed['extensions']['authorityKeyIdentifier'])) {
$missingExtensions[] = 'Authority Key Identifier (AKI)';
}
if (!isset($parsed['extensions']['crlDistributionPoints'])) {
$missingExtensions[] = 'CRL Distribution Points';
}
if (!empty($missingExtensions)) {
$extensionsList = implode(', ', $missingExtensions);
$minorIssues[] = "Missing modern extensions: {$extensionsList}";
}
$hasLibresignCaUuid = $this->validateLibresignCaUuidInCertificate($parsed);
if (!$hasLibresignCaUuid) {
$minorIssues[] = 'LibreSign CA UUID not found in Organizational Unit';
}
if (!empty($criticalIssues)) {
$issuesList = implode(', ', $criticalIssues);
return (new ConfigureCheckHelper())
->setErrorMessage("Root certificate has critical issues: {$issuesList}")
->setResource($this->getConfigureCheckResourceName())
->setTip($this->getCertificateRegenerationTip());
}
if (!empty($minorIssues)) {
$issuesList = implode(', ', $minorIssues);
return (new ConfigureCheckHelper())
->setInfoMessage("Root certificate could benefit from modern features: {$issuesList}")
->setResource($this->getConfigureCheckResourceName())
->setTip($this->getCertificateRegenerationTip() . ' (recommended but not required)');
}
return null;
} catch (\Exception $e) {
return (new ConfigureCheckHelper())
->setErrorMessage('Failed to analyze root certificate: ' . $e->getMessage())
->setResource($this->getConfigureCheckResourceName())
->setTip('Check if the root certificate file is valid');
}
}
private function validateLibresignCaUuidInCertificate(array $parsed): bool {
if (!isset($parsed['subject']['OU'])) {
return false;
}
$instanceId = $this->getLibreSignInstanceId();
if (empty($instanceId)) {
return false;
}
$organizationalUnits = $parsed['subject']['OU'];
if (is_string($organizationalUnits)) {
if (str_contains($organizationalUnits, ', ')) {
$organizationalUnits = explode(', ', $organizationalUnits);
} else {
$organizationalUnits = [$organizationalUnits];
}
}
foreach ($organizationalUnits as $ou) {
$ou = trim($ou);
if ($this->caIdentifierService->isValidCaId($ou, $instanceId)) {
return true;
}
}
return false;
}
private function getLibreSignInstanceId(): string {
$instanceId = $this->appConfig->getValueString(Application::APP_ID, 'instance_id', '');
if (strlen($instanceId) === 10) {
return $instanceId;
}
return '';
}
private function calculateRemainingDays(int $validToTimestamp): int {
$secondsPerDay = 60 * 60 * 24;
$remainingSeconds = $validToTimestamp - time();
return (int)ceil($remainingSeconds / $secondsPerDay);
}
protected function checkRootCertificateExpiry(): ?ConfigureCheckHelper {
$configPath = $this->getCurrentConfigPath();
$caCertPath = $configPath . DIRECTORY_SEPARATOR . 'ca.pem';
if (!file_exists($caCertPath)) {
return null;
}
$certContent = file_get_contents($caCertPath);
if (!$certContent) {
return null;
}
$x509Resource = openssl_x509_read($certContent);
if (!$x509Resource) {
return null;
}
$parsed = openssl_x509_parse($x509Resource);
if (!$parsed) {
return null;
}
$remainingDays = $this->calculateRemainingDays($parsed['validTo_time_t']);
$leafExpiryDays = $this->getLeafExpiryInDays();
if ($remainingDays < 0) {
return (new ConfigureCheckHelper())
->setErrorMessage('Root certificate has expired')
->setResource($this->getConfigureCheckResourceName())
->setTip($this->getCertificateRegenerationTip() . ' URGENT: Certificate is expired!');
}
if ($remainingDays <= 7) {
return (new ConfigureCheckHelper())
->setErrorMessage("Root certificate expires in {$remainingDays} days")
->setResource($this->getConfigureCheckResourceName())
->setTip($this->getCertificateRegenerationTip() . ' URGENT: Renew immediately!');
}
if ($remainingDays <= 30) {
return (new ConfigureCheckHelper())
->setErrorMessage("Root certificate expires in {$remainingDays} days")
->setResource($this->getConfigureCheckResourceName())
->setTip($this->getCertificateRegenerationTip() . ' Renewal recommended soon.');
}
if ($remainingDays <= $leafExpiryDays) {
return (new ConfigureCheckHelper())
->setInfoMessage("Root certificate expires in {$remainingDays} days (leaf validity: {$leafExpiryDays} days)")
->setResource($this->getConfigureCheckResourceName())
->setTip('Root certificate should be renewed to ensure it can sign CRLs for all issued leaf certificates.');
}
return null;
}
#[\Override]
public function toArray(): array {
$generated = $this->isSetupOk();
$return = [
'configPath' => $this->getConfigPathForApi($generated),
'generated' => $generated,
'rootCert' => [
'commonName' => $this->getCommonName(),
'names' => [],
],
];
$return = array_merge(
$return,
$this->getCertificatePolicy(),
);
$names = $this->getNames();
foreach ($names as $name => $value) {
$return['rootCert']['names'][] = [
'id' => $name,
'value' => $this->filterNameValue($name, $value, $generated),
];
}
return $return;
}
private function getConfigPathForApi(bool $generated): string {
return $generated ? $this->getCurrentConfigPath() : '';
}
private function filterNameValue(string $name, mixed $value, bool $generated): mixed {
if ($name === 'OU' && is_array($value)) {
if (!$generated) {
$value = $this->removeCaIdFromOrganizationalUnit($value);
}
return empty($value) ? null : implode(', ', $value);
}
return $value;
}
private function removeCaIdFromOrganizationalUnit(array $organizationalUnits): array {
$filtered = array_filter(
$organizationalUnits,
fn ($item) => !str_starts_with($item, 'libresign-ca-id:')
);
return array_values($filtered);
}
protected function getCrlDistributionUrl(): string {
$caIdParsed = $this->caIdentifierService->getCaIdParsed();
return $this->urlGenerator->linkToRouteAbsolute('libresign.crl.getRevocationList', [
'instanceId' => $caIdParsed['instanceId'],
'generation' => $caIdParsed['generation'],
'engineType' => $caIdParsed['engineType'],
]);
}
private function validateCrlFromUrls(array $crlUrls, string $certPem): string {
$details = $this->validateCrlFromUrlsWithDetails($crlUrls, $certPem);
return $details['status'];
}
private function validateCrlFromUrlsWithDetails(array $crlUrls, string $certPem): array {
if (empty($crlUrls)) {
return ['status' => 'no_urls'];
}
$accessibleUrls = 0;
foreach ($crlUrls as $crlUrl) {
try {
$validationResult = $this->downloadAndValidateCrlWithDetails($crlUrl, $certPem);
if ($validationResult['status'] === 'valid') {
return $validationResult;
}
if ($validationResult['status'] === 'revoked') {
return $validationResult;
}
$accessibleUrls++;
} catch (\Exception $e) {
continue;
}
}
if ($accessibleUrls === 0) {
return ['status' => 'urls_inaccessible'];
}
return ['status' => 'validation_failed'];
}
private function downloadAndValidateCrl(string $crlUrl, string $certPem): string {
try {
if ($this->isLocalCrlUrl($crlUrl)) {
$crlContent = $this->generateLocalCrl($crlUrl);
} else {
$crlContent = $this->downloadCrlContent($crlUrl);
}
if (!$crlContent) {
throw new \Exception('Failed to get CRL content');
}
return $this->checkCertificateInCrl($certPem, $crlContent);
} catch (\Exception $e) {
return 'validation_error';
}
}
private function downloadAndValidateCrlWithDetails(string $crlUrl, string $certPem): array {
try {
if ($this->isLocalCrlUrl($crlUrl)) {
$crlContent = $this->generateLocalCrl($crlUrl);
} else {
$crlContent = $this->downloadCrlContent($crlUrl);
}
if (!$crlContent) {
throw new \Exception('Failed to get CRL content');
}
return $this->checkCertificateInCrlWithDetails($certPem, $crlContent);
} catch (\Exception $e) {
return ['status' => 'validation_error'];
}
}
private function isLocalCrlUrl(string $url): bool {
$host = parse_url($url, PHP_URL_HOST);
if (!$host) {
return false;
}
$trustedDomains = $this->config->getSystemValue('trusted_domains', []);
return in_array($host, $trustedDomains, true);
}
private function generateLocalCrl(string $crlUrl): ?string {
try {
$templateUrl = $this->urlGenerator->linkToRouteAbsolute('libresign.crl.getRevocationList', [
'instanceId' => 'INSTANCEID',
'generation' => 999999,
'engineType' => 'ENGINETYPE',
]);
$patternUrl = str_replace('INSTANCEID', '([^/_]+)', $templateUrl);
$patternUrl = str_replace('999999', '(\d+)', $patternUrl);
$patternUrl = str_replace('ENGINETYPE', '([^/_]+)', $patternUrl);
$escapedPattern = str_replace([':', '/', '.'], ['\:', '\/', '\.'], $patternUrl);
$escapedPattern = str_replace('\/apps\/', '(?:\/index\.php)?\/apps\/', $escapedPattern);
$pattern = '/^' . $escapedPattern . '$/';
if (preg_match($pattern, $crlUrl, $matches)) {
$instanceId = $matches[1];
$generation = (int)$matches[2];
$engineType = $matches[3];
/** @var \OCA\Libresign\Service\Crl\CrlService */
$crlService = \OC::$server->get(\OCA\Libresign\Service\Crl\CrlService::class);
$crlData = $crlService->generateCrlDer($instanceId, $generation, $engineType);
return $crlData;
}
$this->logger->debug('CRL URL does not match expected pattern', ['url' => $crlUrl, 'pattern' => $pattern]);
return null;
} catch (\Exception $e) {
$this->logger->warning('Failed to generate local CRL: ' . $e->getMessage());
return null;
}
}
private function downloadCrlContent(string $url): ?string {
if (!filter_var($url, FILTER_VALIDATE_URL) || !in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'])) {
return null;
}
$context = stream_context_create([
'http' => [
'timeout' => 30,
'user_agent' => 'LibreSign/1.0 CRL Validator',
'follow_location' => 1,
'max_redirects' => 3,
]
]);
$content = @file_get_contents($url, false, $context);
return $content !== false ? $content : null;
}
private function isSerialNumberInCrl(string $crlText, string $serialNumber): bool {
$normalizedSerial = strtoupper($serialNumber);
$normalizedSerial = ltrim($normalizedSerial, '0') ?: '0';
return preg_match('/Serial Number: 0*' . preg_quote($normalizedSerial, '/') . '/', $crlText) === 1;
}
private function checkCertificateInCrl(string $certPem, string $crlContent): string {
try {
$certResource = openssl_x509_read($certPem);
if (!$certResource) {
return 'validation_error';
}
$certData = openssl_x509_parse($certResource);
if (!isset($certData['serialNumber'])) {
return 'validation_error';
}
return $this->checkCertificateInCrlWithDetails($certPem, $crlContent)['status'];
} catch (\Exception $e) {
return 'validation_error';
}
}
private function checkCertificateInCrlWithDetails(string $certPem, string $crlContent): array {
try {
$certResource = openssl_x509_read($certPem);
if (!$certResource) {
return ['status' => 'validation_error'];
}
$certData = openssl_x509_parse($certResource);
if (!isset($certData['serialNumber'])) {
return ['status' => 'validation_error'];
}
$tempCrlFile = $this->tempManager->getTemporaryFile('.crl');
file_put_contents($tempCrlFile, $crlContent);
try {
$crlTextCmd = sprintf(
'openssl crl -in %s -inform DER -text -noout',
escapeshellarg($tempCrlFile)
);
exec($crlTextCmd, $output, $exitCode);
if ($exitCode !== 0) {
return ['status' => 'validation_error'];
}
$crlText = implode("\n", $output);
$serialCandidates = [$certData['serialNumber']];
if (!empty($certData['serialNumberHex'])) {
$serialCandidates[] = $certData['serialNumberHex'];
}
foreach ($serialCandidates as $serial) {
if ($this->isSerialNumberInCrl($crlText, $serial)) {
$revokedAt = $this->extractRevocationDateFromCrlText($crlText, $serialCandidates);
return array_filter([
'status' => 'revoked',
'revoked_at' => $revokedAt,
]);
}
}
return ['status' => 'valid'];