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

LibreSign / libresign / 19118950120

05 Nov 2025 10:58PM UTC coverage: 39.847%. First build
19118950120

Pull #5754

github

web-flow
Merge adfafab73 into 681cce019
Pull Request #5754: feat: preserve previous root cert

86 of 120 new or added lines in 10 files covered. (71.67%)

4633 of 11627 relevant lines covered (39.85%)

3.06 hits per line

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

69.34
/lib/Handler/SignEngine/Pkcs12Handler.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\SignEngine;
10

11
use DateTime;
12
use OCA\Libresign\AppInfo\Application;
13
use OCA\Libresign\Exception\LibresignException;
14
use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory;
15
use OCA\Libresign\Handler\CertificateEngine\OrderCertificatesTrait;
16
use OCA\Libresign\Handler\FooterHandler;
17
use OCA\Libresign\Service\CaIdentifierService;
18
use OCA\Libresign\Service\FolderService;
19
use OCA\Libresign\Vendor\phpseclib3\File\ASN1;
20
use OCP\Files\File;
21
use OCP\IAppConfig;
22
use OCP\IL10N;
23
use OCP\ITempManager;
24
use Psr\Log\LoggerInterface;
25

26
class Pkcs12Handler extends SignEngineHandler {
27
        use OrderCertificatesTrait;
28
        protected string $certificate = '';
29
        private array $signaturesFromPoppler = [];
30
        private ?JSignPdfHandler $jSignPdfHandler = null;
31
        private string $rootCertificatePem = '';
32
        private bool $isLibreSignFile = false;
33

34
        public function __construct(
35
                private FolderService $folderService,
36
                private IAppConfig $appConfig,
37
                protected CertificateEngineFactory $certificateEngineFactory,
38
                private IL10N $l10n,
39
                private FooterHandler $footerHandler,
40
                private ITempManager $tempManager,
41
                private LoggerInterface $logger,
42
                private CaIdentifierService $caIdentifierService,
43
        ) {
44
                parent::__construct($l10n, $folderService, $logger);
51✔
45
        }
46

47
        /**
48
         * @throws LibresignException When is not a signed file
49
         */
50
        private function getSignatures($resource): iterable {
51
                rewind($resource);
6✔
52
                $content = stream_get_contents($resource);
6✔
53
                preg_match_all(
6✔
54
                        '/ByteRange\s*\[\s*(?<offset1>\d+)\s+(?<length1>\d+)\s+(?<offset2>\d+)\s+(?<length2>\d+)\s*\]/',
6✔
55
                        $content,
6✔
56
                        $bytes
6✔
57
                );
6✔
58
                if (empty($bytes['offset1']) || empty($bytes['length1']) || empty($bytes['offset2']) || empty($bytes['length2'])) {
6✔
59
                        throw new LibresignException($this->l10n->t('Unsigned file.'));
4✔
60
                }
61

62
                for ($i = 0; $i < count($bytes['offset1']); $i++) {
2✔
63
                        $offset1 = (int)$bytes['offset1'][$i];
2✔
64
                        $length1 = (int)$bytes['length1'][$i];
2✔
65
                        $offset2 = (int)$bytes['offset2'][$i];
2✔
66

67
                        $signatureStart = $offset1 + $length1 + 1;
2✔
68
                        $signatureLength = $offset2 - $signatureStart - 1;
2✔
69

70
                        rewind($resource);
2✔
71

72
                        $signature = stream_get_contents($resource, $signatureLength, $signatureStart);
2✔
73

74
                        yield hex2bin($signature);
2✔
75
                }
76

77
                $this->tempManager->clean();
2✔
78
        }
79

80
        public function setIsLibreSignFile(): void {
81
                $this->isLibreSignFile = true;
×
82
        }
83

84
        /**
85
         * @param resource $resource
86
         * @throws LibresignException When is not a signed file
87
         * @return array
88
         */
89
        #[\Override]
90
        public function getCertificateChain($resource): array {
91
                $certificates = [];
6✔
92

93
                foreach ($this->getSignatures($resource) as $signature) {
6✔
94
                        $certificates[] = $this->processSignature($resource, $signature);
2✔
95
                }
96
                return $certificates;
2✔
97
        }
98

99
        private function processSignature($resource, ?string $signature): array {
100
                $result = [];
2✔
101

102
                if (!$signature) {
2✔
103
                        $result['chain'][0]['signature_validation'] = $this->getReadableSigState('Digest Mismatch.');
×
104
                        return $result;
×
105
                }
106

107
                $decoded = ASN1::decodeBER($signature);
2✔
108
                $result = $this->extractTimestampData($decoded, $result);
2✔
109

110
                $chain = $this->extractCertificateChain($signature);
2✔
111
                if (!empty($chain)) {
2✔
112
                        $result['chain'] = $this->orderCertificates($chain);
2✔
113
                        $result = $this->enrichLeafWithPopplerData($resource, $result);
2✔
114
                }
115
                $result = $this->applyLibreSignRootCAFlag($result);
2✔
116
                return $result;
2✔
117
        }
118

119
        private function applyLibreSignRootCAFlag(array $signer): array {
120
                if (empty($signer['chain'])) {
2✔
121
                        return $signer;
×
122
                }
123

124
                foreach ($signer['chain'] as $key => $cert) {
2✔
125
                        if ($cert['isLibreSignRootCA']
2✔
126
                                && $cert['certificate_validation']['id'] !== 1
2✔
127
                        ) {
128
                                $signer['chain'][$key]['certificate_validation'] = [
×
129
                                        'id' => 1,
×
130
                                        'label' => $this->l10n->t('Certificate is trusted.'),
×
131
                                ];
×
132
                        }
133
                }
134

135
                return $signer;
2✔
136
        }
137

138
        private function extractTimestampData(array $decoded, array $result): array {
139
                $tsa = new TSA();
2✔
140

141
                try {
142
                        $timestampData = $tsa->extract($decoded);
2✔
143
                        if (!empty($timestampData['genTime']) || !empty($timestampData['policy']) || !empty($timestampData['serialNumber'])) {
2✔
144
                                $result['timestamp'] = $timestampData;
2✔
145
                        }
146
                } catch (\Throwable $e) {
×
147
                }
148

149
                if (!isset($result['signingTime']) || !$result['signingTime'] instanceof \DateTime) {
2✔
150
                        $result['signingTime'] = $tsa->getSigninTime($decoded);
2✔
151
                }
152
                return $result;
2✔
153
        }
154

155
        private function extractCertificateChain(string $signature): array {
156
                $pkcs7PemSignature = $this->der2pem($signature);
2✔
157
                $pemCertificates = [];
2✔
158

159
                if (!openssl_pkcs7_read($pkcs7PemSignature, $pemCertificates)) {
2✔
160
                        return [];
×
161
                }
162

163
                $chain = [];
2✔
164
                $isLibreSignRootCA = false;
2✔
165
                foreach ($pemCertificates as $index => $pemCertificate) {
2✔
166
                        $parsed = openssl_x509_parse($pemCertificate);
2✔
167
                        if ($parsed) {
2✔
168
                                $parsed['signature_validation'] = [
2✔
169
                                        'id' => 1,
2✔
170
                                        'label' => $this->l10n->t('Signature is valid.'),
2✔
171
                                ];
2✔
172
                                if (!$isLibreSignRootCA) {
2✔
173
                                        $isLibreSignRootCA = $this->isLibreSignRootCA($pemCertificate, $parsed);
2✔
174
                                }
175
                                $parsed['isLibreSignRootCA'] = $isLibreSignRootCA;
2✔
176
                                $chain[$index] = $parsed;
2✔
177
                        }
178
                }
179
                if ($isLibreSignRootCA || $this->isLibreSignFile) {
2✔
180
                        foreach ($chain as &$cert) {
×
181
                                $cert['isLibreSignRootCA'] = true;
×
182
                        }
183
                }
184

185
                return $chain;
2✔
186
        }
187

188
        private function isLibreSignRootCA(string $certificate, array $parsed): bool {
189
                $rootCertificatePem = $this->getRootCertificatePem();
2✔
190
                if (empty($rootCertificatePem)) {
2✔
191
                        return false;
2✔
192
                }
193

194
                $rootFingerprint = openssl_x509_fingerprint($rootCertificatePem, 'sha256');
×
195
                $fingerprint = openssl_x509_fingerprint($certificate, 'sha256');
×
196
                if ($rootFingerprint === $fingerprint) {
×
197
                        return true;
×
198
                }
199

200
                return $this->hasLibreSignCaId($parsed);
×
201
        }
202

203
        private function hasLibreSignCaId(array $parsed): bool {
204
                $instanceId = $this->appConfig->getValueString(Application::APP_ID, 'instance_id', '');
×
205
                if (strlen($instanceId) !== 10 || !isset($parsed['subject']['OU'])) {
×
206
                        return false;
×
207
                }
208

209
                $organizationalUnits = $parsed['subject']['OU'];
×
210
                if (is_string($organizationalUnits)) {
×
NEW
211
                        $organizationalUnits = [$organizationalUnits];
×
212
                }
213

NEW
214
                foreach ($organizationalUnits as $ou) {
×
NEW
215
                        $ou = trim($ou);
×
NEW
216
                        if ($this->caIdentifierService->isValidCaId($ou, $instanceId)) {
×
NEW
217
                                return true;
×
218
                        }
219
                }
220

NEW
221
                return false;
×
222
        }
223

224
        private function getRootCertificatePem(): string {
225
                if (!empty($this->rootCertificatePem)) {
2✔
226
                        return $this->rootCertificatePem;
×
227
                }
228
                $configPath = $this->appConfig->getValueString(Application::APP_ID, 'config_path');
2✔
229
                if (empty($configPath)
2✔
230
                        || !is_dir($configPath)
2✔
231
                        || !is_readable($configPath . DIRECTORY_SEPARATOR . 'ca.pem')
2✔
232
                ) {
233
                        return '';
2✔
234
                }
235
                $rootCertificatePem = file_get_contents($configPath . DIRECTORY_SEPARATOR . 'ca.pem');
×
236
                if ($rootCertificatePem === false) {
×
237
                        return '';
×
238
                }
239
                $this->rootCertificatePem = $rootCertificatePem;
×
240
                return $this->rootCertificatePem;
×
241
        }
242

243
        private function enrichLeafWithPopplerData($resource, array $result): array {
244
                if (empty($result['chain'])) {
2✔
245
                        return $result;
×
246
                }
247

248
                $popplerOnlyFields = ['field', 'range', 'certificate_validation'];
2✔
249
                if (!isset($result['chain'][0]['subject'])) {
2✔
250
                        return $result;
×
251
                }
252
                $needPoppler = false;
2✔
253
                foreach ($popplerOnlyFields as $field) {
2✔
254
                        if (empty($result['chain'][0][$field])) {
2✔
255
                                $needPoppler = true;
2✔
256
                                break;
2✔
257
                        }
258
                }
259
                if (!isset($result['chain'][0]['signature_validation']) || $result['chain'][0]['signature_validation']['id'] !== 1) {
2✔
260
                        $needPoppler = true;
×
261
                }
262
                if (!$needPoppler) {
2✔
263
                        return $result;
×
264
                }
265
                $popplerChain = $this->chainFromPoppler($result['chain'][0]['subject'], $resource);
2✔
266
                if (empty($popplerChain)) {
2✔
267
                        return $result;
×
268
                }
269
                foreach ($popplerOnlyFields as $field) {
2✔
270
                        if (isset($popplerChain[$field])) {
2✔
271
                                $result['chain'][0][$field] = $popplerChain[$field];
2✔
272
                        }
273
                }
274
                if (!isset($result['chain'][0]['signature_validation']) || $result['chain'][0]['signature_validation']['id'] !== 1) {
2✔
275
                        if (isset($popplerChain['signature_validation'])) {
×
276
                                $result['chain'][0]['signature_validation'] = $popplerChain['signature_validation'];
×
277
                        }
278
                }
279
                return $result;
2✔
280
        }
281

282
        private function chainFromPoppler(array $subject, $resource): array {
283
                $fromFallback = $this->popplerUtilsPdfSignFallback($resource);
2✔
284
                foreach ($fromFallback as $popplerSig) {
2✔
285
                        if (!isset($popplerSig['chain'][0]['subject'])) {
2✔
286
                                continue;
×
287
                        }
288
                        if ($popplerSig['chain'][0]['subject'] == $subject) {
2✔
289
                                return $popplerSig['chain'][0];
2✔
290
                        }
291
                }
292
                return [];
×
293
        }
294

295
        private function popplerUtilsPdfSignFallback($resource): array {
296
                if (!empty($this->signaturesFromPoppler)) {
2✔
297
                        return $this->signaturesFromPoppler;
1✔
298
                }
299
                if (shell_exec('which pdfsig') === null) {
1✔
300
                        return $this->signaturesFromPoppler;
×
301
                }
302
                rewind($resource);
1✔
303
                $content = stream_get_contents($resource);
1✔
304
                $tempFile = $this->tempManager->getTemporaryFile('file.pdf');
1✔
305
                file_put_contents($tempFile, $content);
1✔
306

307
                $content = shell_exec('env TZ=UTC pdfsig ' . $tempFile);
1✔
308
                if (empty($content)) {
1✔
309
                        return $this->signaturesFromPoppler;
×
310
                }
311
                $lines = explode("\n", $content);
1✔
312

313
                $lastSignature = 0;
1✔
314
                foreach ($lines as $item) {
1✔
315
                        $isFirstLevel = preg_match('/^Signature\s#(\d)/', $item, $match);
1✔
316
                        if ($isFirstLevel) {
1✔
317
                                $lastSignature = (int)$match[1] - 1;
1✔
318
                                $this->signaturesFromPoppler[$lastSignature] = [];
1✔
319
                                continue;
1✔
320
                        }
321

322
                        $match = [];
1✔
323
                        $isSecondLevel = preg_match('/^\s+-\s(?<key>.+):\s(?<value>.*)/', $item, $match);
1✔
324
                        if ($isSecondLevel) {
1✔
325
                                switch ((string)$match['key']) {
1✔
326
                                        case 'Signing Time':
1✔
327
                                                $this->signaturesFromPoppler[$lastSignature]['signingTime'] = DateTime::createFromFormat('M d Y H:i:s', $match['value'], new \DateTimeZone('UTC'));
1✔
328
                                                break;
1✔
329
                                        case 'Signer full Distinguished Name':
1✔
330
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['subject'] = $this->parseDistinguishedNameWithMultipleValues($match['value']);
1✔
331
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['name'] = $match['value'];
1✔
332
                                                break;
1✔
333
                                        case 'Signing Hash Algorithm':
1✔
334
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['signatureTypeSN'] = $match['value'];
1✔
335
                                                break;
1✔
336
                                        case 'Signature Validation':
1✔
337
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['signature_validation'] = $this->getReadableSigState($match['value']);
1✔
338
                                                break;
1✔
339
                                        case 'Certificate Validation':
1✔
340
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['certificate_validation'] = $this->getReadableCertState($match['value']);
1✔
341
                                                break;
1✔
342
                                        case 'Signed Ranges':
1✔
343
                                                if (preg_match('/\[(\d+) - (\d+)\], \[(\d+) - (\d+)\]/', $match['value'], $ranges)) {
1✔
344
                                                        $this->signaturesFromPoppler[$lastSignature]['chain'][0]['range'] = [
1✔
345
                                                                'offset1' => (int)$ranges[1],
1✔
346
                                                                'length1' => (int)$ranges[2],
1✔
347
                                                                'offset2' => (int)$ranges[3],
1✔
348
                                                                'length2' => (int)$ranges[4],
1✔
349
                                                        ];
1✔
350
                                                }
351
                                                break;
1✔
352
                                        case 'Signature Field Name':
1✔
353
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['field'] = $match['value'];
1✔
354
                                                break;
1✔
355
                                        case 'Signature Validation':
1✔
356
                                        case 'Signature Type':
1✔
357
                                        case 'Total document signed':
1✔
358
                                        case 'Not total document signed':
1✔
359
                                        default:
360
                                                break;
1✔
361
                                }
362
                        }
363
                }
364
                return $this->signaturesFromPoppler;
1✔
365
        }
366

367
        private function getReadableSigState(string $status) {
368
                return match ($status) {
1✔
369
                        'Signature is Valid.' => [
1✔
370
                                'id' => 1,
1✔
371
                                'label' => $this->l10n->t('Signature is valid.'),
1✔
372
                        ],
1✔
373
                        'Signature is Invalid.' => [
×
374
                                'id' => 2,
×
375
                                'label' => $this->l10n->t('Signature is invalid.'),
×
376
                        ],
×
377
                        'Digest Mismatch.' => [
×
378
                                'id' => 3,
×
379
                                'label' => $this->l10n->t('Digest mismatch.'),
×
380
                        ],
×
381
                        "Document isn't signed or corrupted data." => [
×
382
                                'id' => 4,
×
383
                                'label' => $this->l10n->t("Document isn't signed or corrupted data."),
×
384
                        ],
×
385
                        'Signature has not yet been verified.' => [
×
386
                                'id' => 5,
×
387
                                'label' => $this->l10n->t('Signature has not yet been verified.'),
×
388
                        ],
×
389
                        default => [
1✔
390
                                'id' => 6,
1✔
391
                                'label' => $this->l10n->t('Unknown validation failure.'),
1✔
392
                        ],
1✔
393
                };
1✔
394
        }
395

396

397
        private function getReadableCertState(string $status) {
398
                return match ($status) {
1✔
399
                        'Certificate is Trusted.' => [
×
400
                                'id' => 1,
×
401
                                'label' => $this->l10n->t('Certificate is trusted.'),
×
402
                        ],
×
403
                        "Certificate issuer isn't Trusted." => [
×
404
                                'id' => 2,
×
405
                                'label' => $this->l10n->t("Certificate issuer isn't trusted."),
×
406
                        ],
×
407
                        'Certificate issuer is unknown.' => [
1✔
408
                                'id' => 3,
1✔
409
                                'label' => $this->l10n->t('Certificate issuer is unknown.'),
1✔
410
                        ],
1✔
411
                        'Certificate has been Revoked.' => [
×
412
                                'id' => 4,
×
413
                                'label' => $this->l10n->t('Certificate has been revoked.'),
×
414
                        ],
×
415
                        'Certificate has Expired' => [
×
416
                                'id' => 5,
×
417
                                'label' => $this->l10n->t('Certificate has expired'),
×
418
                        ],
×
419
                        'Certificate has not yet been verified.' => [
×
420
                                'id' => 6,
×
421
                                'label' => $this->l10n->t('Certificate has not yet been verified.'),
×
422
                        ],
×
423
                        default => [
1✔
424
                                'id' => 7,
1✔
425
                                'label' => $this->l10n->t('Unknown issue with Certificate or corrupted data.')
1✔
426
                        ],
1✔
427
                };
1✔
428
        }
429

430

431
        private function parseDistinguishedNameWithMultipleValues(string $dn): array {
432
                $result = [];
1✔
433
                $pairs = preg_split('/,(?=(?:[^"]*"[^"]*")*[^"]*$)/', $dn);
1✔
434

435
                foreach ($pairs as $pair) {
1✔
436
                        [$key, $value] = explode('=', $pair, 2);
1✔
437
                        if (empty($key) || empty($value)) {
1✔
438
                                return $result;
×
439
                        }
440
                        $key = trim($key);
1✔
441
                        $value = trim($value);
1✔
442
                        $value = trim($value, '"');
1✔
443

444
                        if (!isset($result[$key])) {
1✔
445
                                $result[$key] = $value;
1✔
446
                        } else {
447
                                if (!is_array($result[$key])) {
×
448
                                        $result[$key] = [$result[$key]];
×
449
                                }
450
                                $result[$key][] = $value;
×
451
                        }
452
                }
453

454
                return $result;
1✔
455
        }
456

457
        private function der2pem($derData) {
458
                $pem = chunk_split(base64_encode((string)$derData), 64, "\n");
2✔
459
                $pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
2✔
460
                return $pem;
2✔
461
        }
462

463
        private function getHandler(): SignEngineHandler {
464
                $sign_engine = $this->appConfig->getValueString(Application::APP_ID, 'sign_engine', 'JSignPdf');
1✔
465
                $property = lcfirst($sign_engine) . 'Handler';
1✔
466
                if (!property_exists($this, $property)) {
1✔
467
                        throw new LibresignException($this->l10n->t('Invalid Sign engine.'), 400);
×
468
                }
469
                $classHandler = 'OCA\\Libresign\\Handler\\SignEngine\\' . ucfirst($property);
1✔
470
                if (!$this->$property instanceof $classHandler) {
1✔
471
                        $this->$property = \OCP\Server::get($classHandler);
1✔
472
                }
473
                return $this->$property;
1✔
474
        }
475

476
        #[\Override]
477
        public function sign(): File {
478
                $signedContent = $this->getHandler()
1✔
479
                        ->setCertificate($this->getCertificate())
1✔
480
                        ->setInputFile($this->getInputFile())
1✔
481
                        ->setPassword($this->getPassword())
1✔
482
                        ->setSignatureParams($this->getSignatureParams())
1✔
483
                        ->setVisibleElements($this->getVisibleElements())
1✔
484
                        ->getSignedContent();
1✔
485
                $this->getInputFile()->putContent($signedContent);
×
486
                return $this->getInputFile();
×
487
        }
488

489
        public function isHandlerOk(): bool {
490
                return $this->certificateEngineFactory->getEngine()->isSetupOk();
1✔
491
        }
492
}
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