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

LibreSign / libresign / 21885466958

10 Feb 2026 10:50PM UTC coverage: 48.819%. First build
21885466958

Pull #6824

github

web-flow
Merge 4c660d2db into 0f8cd5ad8
Pull Request #6824: fix: signature methods names

21 of 90 new or added lines in 15 files covered. (23.33%)

8498 of 17407 relevant lines covered (48.82%)

5.53 hits per line

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

68.01
/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\DocMdpHandler;
17
use OCA\Libresign\Handler\FooterHandler;
18
use OCA\Libresign\Service\CaIdentifierService;
19
use OCA\Libresign\Service\FolderService;
20
use OCP\Files\File;
21
use OCP\IAppConfig;
22
use OCP\IL10N;
23
use OCP\ITempManager;
24
use phpseclib3\File\ASN1;
25
use Psr\Log\LoggerInterface;
26

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

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

49
        /**
50
         * @throws LibresignException When is not a signed file
51
         */
52
        private function getSignatures($resource): iterable {
53
                rewind($resource);
14✔
54
                $content = stream_get_contents($resource);
14✔
55

56
                preg_match_all('/\/Contents\s*<([0-9a-fA-F]+)>/', $content, $contents, PREG_OFFSET_CAPTURE);
14✔
57

58
                if (empty($contents[1])) {
14✔
59
                        throw new LibresignException($this->l10n->t('Unsigned file.'));
8✔
60
                }
61

62
                $seenHexSignatures = [];
6✔
63
                foreach ($contents[1] as $match) {
6✔
64
                        $signatureHex = $match[0];
6✔
65

66
                        if (isset($seenHexSignatures[$signatureHex])) {
6✔
67
                                continue;
×
68
                        }
69
                        $seenHexSignatures[$signatureHex] = true;
6✔
70

71
                        $decodedSignature = @hex2bin($signatureHex);
6✔
72
                        if ($decodedSignature === false) {
6✔
73
                                yield null;
×
74
                                continue;
×
75
                        }
76
                        yield $decodedSignature;
6✔
77
                }
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 = [];
14✔
92

93
                foreach ($this->getSignatures($resource) as $signature) {
14✔
94
                        if (!$signature) {
6✔
95
                                continue;
×
96
                        }
97

98
                        $result = $this->processSignature($resource, $signature);
6✔
99

100
                        if (empty($result['chain'])) {
3✔
101
                                continue;
×
102
                        }
103

104
                        $certificates[] = $result;
3✔
105
                }
106
                return $certificates;
3✔
107
        }
108

109
        private function processSignature($resource, ?string $signature): array {
110
                $result = [];
6✔
111

112
                if (!$signature) {
6✔
113
                        $result['chain'][0]['signature_validation'] = $this->getReadableSigState('Digest Mismatch.');
×
114
                        return $result;
×
115
                }
116

117
                $decoded = ASN1::decodeBER($signature);
6✔
118
                $result = $this->extractTimestampData($decoded, $result);
6✔
119

120
                $chain = $this->extractCertificateChain($signature);
3✔
121
                if (!empty($chain)) {
3✔
122
                        $result['chain'] = $this->orderCertificates($chain);
3✔
123
                        $result = $this->enrichLeafWithPopplerData($resource, $result);
3✔
124
                }
125

126
                $result = $this->extractDocMdpData($resource, $result);
3✔
127

128
                $result = $this->applyLibreSignRootCAFlag($result);
3✔
129
                return $result;
3✔
130
        }
131

132
        private function applyLibreSignRootCAFlag(array $signer): array {
133
                if (empty($signer['chain'])) {
3✔
134
                        return $signer;
×
135
                }
136

137
                foreach ($signer['chain'] as $key => $cert) {
3✔
138
                        if ($cert['isLibreSignRootCA']
3✔
139
                                && isset($cert['certificate_validation'])
3✔
140
                                && $cert['certificate_validation']['id'] !== 1
3✔
141
                        ) {
142
                                $signer['chain'][$key]['certificate_validation'] = [
×
143
                                        'id' => 1,
×
144
                                        'label' => $this->l10n->t('Certificate is trusted.'),
×
145
                                ];
×
146
                        }
147
                }
148

149
                return $signer;
3✔
150
        }
151

152

153
        private function extractDocMdpData($resource, array $result): array {
154
                if (empty($result['chain'])) {
3✔
155
                        return $result;
×
156
                }
157

158
                $docMdpData = $this->docMdpHandler->extractDocMdpData($resource);
3✔
159
                return array_merge($result, $docMdpData);
3✔
160
        }
161

162
        private function extractTimestampData(array $decoded, array $result): array {
163
                $tsa = new TSA();
3✔
164

165
                try {
166
                        $timestampData = $tsa->extract($decoded);
3✔
167
                        if (!empty($timestampData['genTime']) || !empty($timestampData['policy']) || !empty($timestampData['serialNumber'])) {
3✔
168
                                $result['timestamp'] = $timestampData;
3✔
169
                        }
170
                } catch (\Throwable $e) {
×
171
                }
172

173
                if (!isset($result['signingTime']) || !$result['signingTime'] instanceof \DateTime) {
3✔
174
                        $result['signingTime'] = $tsa->getSigninTime($decoded);
3✔
175
                }
176
                return $result;
3✔
177
        }
178

179
        private function extractCertificateChain(string $signature): array {
180
                $pkcs7PemSignature = $this->der2pem($signature);
3✔
181
                $pemCertificates = [];
3✔
182

183
                if (!openssl_pkcs7_read($pkcs7PemSignature, $pemCertificates)) {
3✔
184
                        return [];
×
185
                }
186

187
                $chain = [];
3✔
188
                $isLibreSignRootCA = false;
3✔
189
                $certificateEngine = $this->getCertificateEngine();
3✔
190

191
                foreach ($pemCertificates as $index => $pemCertificate) {
3✔
192
                        $parsed = $certificateEngine->parseCertificate($pemCertificate);
3✔
193
                        if ($parsed) {
3✔
194
                                $parsed['signature_validation'] = [
3✔
195
                                        'id' => 1,
3✔
196
                                        'label' => $this->l10n->t('Signature is valid.'),
3✔
197
                                ];
3✔
198
                                if (!$isLibreSignRootCA) {
3✔
199
                                        $isLibreSignRootCA = $this->isLibreSignRootCA($pemCertificate, $parsed);
3✔
200
                                }
201
                                $parsed['isLibreSignRootCA'] = $isLibreSignRootCA;
3✔
202
                                $chain[$index] = $parsed;
3✔
203
                        }
204
                }
205
                if ($isLibreSignRootCA || $this->isLibreSignFile) {
3✔
206
                        foreach ($chain as &$cert) {
×
207
                                $cert['isLibreSignRootCA'] = true;
×
208
                        }
209
                }
210

211
                return $chain;
3✔
212
        }
213

214
        private function isLibreSignRootCA(string $certificate, array $parsed): bool {
215
                $rootCertificatePem = $this->getRootCertificatePem();
3✔
216
                if (empty($rootCertificatePem)) {
3✔
217
                        return false;
3✔
218
                }
219

NEW
220
                $rootFingerprint = openssl_x509_fingerprint($rootCertificatePem, 'sha256');
×
NEW
221
                $fingerprint = openssl_x509_fingerprint($certificate, 'sha256');
×
NEW
222
                if ($rootFingerprint === $fingerprint) {
×
NEW
223
                        return true;
×
224
                }
225

226
                return $this->hasLibreSignCaId($parsed);
×
227
        }
228

229
        private function hasLibreSignCaId(array $parsed): bool {
230
                $instanceId = $this->appConfig->getValueString(Application::APP_ID, 'instance_id', '');
×
231
                if (strlen($instanceId) !== 10 || !isset($parsed['subject']['OU'])) {
×
232
                        return false;
×
233
                }
234

235
                $organizationalUnits = $parsed['subject']['OU'];
×
236
                if (is_string($organizationalUnits)) {
×
237
                        $organizationalUnits = [$organizationalUnits];
×
238
                }
239

240
                foreach ($organizationalUnits as $ou) {
×
241
                        $ou = trim($ou);
×
242
                        if ($this->caIdentifierService->isValidCaId($ou, $instanceId)) {
×
243
                                return true;
×
244
                        }
245
                }
246

247
                return false;
×
248
        }
249

250
        private function getRootCertificatePem(): string {
251
                if (!empty($this->rootCertificatePem)) {
3✔
252
                        return $this->rootCertificatePem;
×
253
                }
254
                $configPath = $this->appConfig->getValueString(Application::APP_ID, 'config_path');
3✔
255
                if (empty($configPath)
3✔
256
                        || !is_dir($configPath)
×
257
                        || !is_readable($configPath . DIRECTORY_SEPARATOR . 'ca.pem')
3✔
258
                ) {
259
                        return '';
3✔
260
                }
261
                $rootCertificatePem = file_get_contents($configPath . DIRECTORY_SEPARATOR . 'ca.pem');
×
262
                if ($rootCertificatePem === false) {
×
263
                        return '';
×
264
                }
265
                $this->rootCertificatePem = $rootCertificatePem;
×
266
                return $this->rootCertificatePem;
×
267
        }
268

269
        private function enrichLeafWithPopplerData($resource, array $result): array {
270
                if (empty($result['chain'])) {
3✔
271
                        return $result;
×
272
                }
273

274
                $popplerOnlyFields = ['field', 'range', 'certificate_validation'];
3✔
275
                if (!isset($result['chain'][0]['subject'])) {
3✔
276
                        return $result;
×
277
                }
278
                $needPoppler = false;
3✔
279
                foreach ($popplerOnlyFields as $field) {
3✔
280
                        if (empty($result['chain'][0][$field])) {
3✔
281
                                $needPoppler = true;
3✔
282
                                break;
3✔
283
                        }
284
                }
285
                if (!isset($result['chain'][0]['signature_validation']) || $result['chain'][0]['signature_validation']['id'] !== 1) {
3✔
286
                        $needPoppler = true;
×
287
                }
288
                if (!$needPoppler) {
3✔
289
                        return $result;
×
290
                }
291
                $popplerChain = $this->chainFromPoppler($result['chain'][0]['subject'], $resource);
3✔
292
                if (empty($popplerChain)) {
3✔
293
                        return $result;
3✔
294
                }
295
                foreach ($popplerOnlyFields as $field) {
×
296
                        if (isset($popplerChain[$field])) {
×
297
                                $result['chain'][0][$field] = $popplerChain[$field];
×
298
                        }
299
                }
300
                if (!isset($result['chain'][0]['signature_validation']) || $result['chain'][0]['signature_validation']['id'] !== 1) {
×
301
                        if (isset($popplerChain['signature_validation'])) {
×
302
                                $result['chain'][0]['signature_validation'] = $popplerChain['signature_validation'];
×
303
                        }
304
                }
305
                return $result;
×
306
        }
307

308
        private function chainFromPoppler(array $subject, $resource): array {
309
                $fromFallback = $this->popplerUtilsPdfSignFallback($resource);
3✔
310
                foreach ($fromFallback as $popplerSig) {
3✔
311
                        if (!isset($popplerSig['chain'][0]['subject'])) {
3✔
312
                                continue;
×
313
                        }
314
                        if ($popplerSig['chain'][0]['subject'] == $subject) {
3✔
315
                                return $popplerSig['chain'][0];
×
316
                        }
317
                }
318
                return [];
3✔
319
        }
320

321
        private function popplerUtilsPdfSignFallback($resource): array {
322
                if (!empty($this->signaturesFromPoppler)) {
3✔
323
                        return $this->signaturesFromPoppler;
1✔
324
                }
325
                if (shell_exec('which pdfsig') === null) {
3✔
326
                        return $this->signaturesFromPoppler;
×
327
                }
328
                rewind($resource);
3✔
329
                $content = stream_get_contents($resource);
3✔
330
                $tempFile = $this->tempManager->getTemporaryFile('file.pdf');
3✔
331
                file_put_contents($tempFile, $content);
3✔
332

333
                $content = shell_exec('env TZ=UTC pdfsig ' . $tempFile);
3✔
334
                if (empty($content)) {
3✔
335
                        return $this->signaturesFromPoppler;
×
336
                }
337
                $lines = explode("\n", $content);
3✔
338

339
                $lastSignature = 0;
3✔
340
                foreach ($lines as $item) {
3✔
341
                        $isFirstLevel = preg_match('/^Signature\s#(\d)/', $item, $match);
3✔
342
                        if ($isFirstLevel) {
3✔
343
                                $lastSignature = (int)$match[1] - 1;
3✔
344
                                $this->signaturesFromPoppler[$lastSignature] = [];
3✔
345
                                continue;
3✔
346
                        }
347

348
                        $match = [];
3✔
349
                        $isSecondLevel = preg_match('/^\s+-\s(?<key>.+):\s(?<value>.*)/', $item, $match);
3✔
350
                        if ($isSecondLevel) {
3✔
351
                                switch ((string)$match['key']) {
3✔
352
                                        case 'Signing Time':
3✔
353
                                                $this->signaturesFromPoppler[$lastSignature]['signingTime'] = DateTime::createFromFormat('M d Y H:i:s', $match['value'], new \DateTimeZone('UTC'));
3✔
354
                                                break;
3✔
355
                                        case 'Signer full Distinguished Name':
3✔
356
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['subject'] = $this->parseDistinguishedNameWithMultipleValues($match['value']);
3✔
357
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['name'] = $match['value'];
3✔
358
                                                break;
3✔
359
                                        case 'Signing Hash Algorithm':
3✔
360
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['signatureTypeSN'] = $match['value'];
3✔
361
                                                break;
3✔
362
                                        case 'Signature Validation':
3✔
363
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['signature_validation'] = $this->getReadableSigState($match['value']);
3✔
364
                                                break;
3✔
365
                                        case 'Certificate Validation':
3✔
366
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['certificate_validation'] = $this->getReadableCertState($match['value']);
3✔
367
                                                break;
3✔
368
                                        case 'Signed Ranges':
3✔
369
                                                if (preg_match('/\[(\d+) - (\d+)\], \[(\d+) - (\d+)\]/', $match['value'], $ranges)) {
3✔
370
                                                        $this->signaturesFromPoppler[$lastSignature]['chain'][0]['range'] = [
3✔
371
                                                                'offset1' => (int)$ranges[1],
3✔
372
                                                                'length1' => (int)$ranges[2],
3✔
373
                                                                'offset2' => (int)$ranges[3],
3✔
374
                                                                'length2' => (int)$ranges[4],
3✔
375
                                                        ];
3✔
376
                                                }
377
                                                break;
3✔
378
                                        case 'Signature Field Name':
3✔
379
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['field'] = $match['value'];
3✔
380
                                                break;
3✔
381
                                        case 'Signature Validation':
3✔
382
                                        case 'Signature Type':
3✔
383
                                        case 'Total document signed':
3✔
384
                                        case 'Not total document signed':
3✔
385
                                        default:
386
                                                break;
3✔
387
                                }
388
                        }
389
                }
390
                return $this->signaturesFromPoppler;
3✔
391
        }
392

393
        private function getReadableSigState(string $status) {
394
                return match ($status) {
3✔
395
                        'Signature is Valid.' => [
3✔
396
                                'id' => 1,
3✔
397
                                'label' => $this->l10n->t('Signature is valid.'),
3✔
398
                        ],
3✔
399
                        'Signature is Invalid.' => [
×
400
                                'id' => 2,
×
401
                                'label' => $this->l10n->t('Signature is invalid.'),
×
402
                        ],
×
403
                        'Digest Mismatch.' => [
×
404
                                'id' => 3,
×
405
                                'label' => $this->l10n->t('Digest mismatch.'),
×
406
                        ],
×
407
                        "Document isn't signed or corrupted data." => [
×
408
                                'id' => 4,
×
409
                                'label' => $this->l10n->t("Document isn't signed or corrupted data."),
×
410
                        ],
×
411
                        'Signature has not yet been verified.' => [
×
412
                                'id' => 5,
×
413
                                'label' => $this->l10n->t('Signature has not yet been verified.'),
×
414
                        ],
×
415
                        default => [
3✔
416
                                'id' => 6,
3✔
417
                                'label' => $this->l10n->t('Unknown validation failure.'),
3✔
418
                        ],
3✔
419
                };
3✔
420
        }
421

422

423
        private function getReadableCertState(string $status) {
424
                return match ($status) {
3✔
425
                        'Certificate is Trusted.' => [
×
426
                                'id' => 1,
×
427
                                'label' => $this->l10n->t('Certificate is trusted.'),
×
428
                        ],
×
429
                        "Certificate issuer isn't Trusted." => [
1✔
430
                                'id' => 2,
1✔
431
                                'label' => $this->l10n->t("Certificate issuer isn't trusted."),
1✔
432
                        ],
1✔
433
                        'Certificate issuer is unknown.' => [
2✔
434
                                'id' => 3,
2✔
435
                                'label' => $this->l10n->t('Certificate issuer is unknown.'),
2✔
436
                        ],
2✔
437
                        'Certificate has been Revoked.' => [
×
438
                                'id' => 4,
×
439
                                'label' => $this->l10n->t('Certificate has been revoked.'),
×
440
                        ],
×
441
                        'Certificate has Expired' => [
×
442
                                'id' => 5,
×
443
                                'label' => $this->l10n->t('Certificate has expired'),
×
444
                        ],
×
445
                        'Certificate has not yet been verified.' => [
×
446
                                'id' => 6,
×
447
                                'label' => $this->l10n->t('Certificate has not yet been verified.'),
×
448
                        ],
×
449
                        default => [
3✔
450
                                'id' => 7,
3✔
451
                                'label' => $this->l10n->t('Unknown issue with Certificate or corrupted data.')
3✔
452
                        ],
3✔
453
                };
3✔
454
        }
455

456

457
        private function parseDistinguishedNameWithMultipleValues(string $dn): array {
458
                $result = [];
3✔
459
                $pairs = preg_split('/,(?=(?:[^"]*"[^"]*")*[^"]*$)/', $dn);
3✔
460

461
                foreach ($pairs as $pair) {
3✔
462
                        [$key, $value] = explode('=', $pair, 2);
3✔
463
                        if (empty($key) || empty($value)) {
3✔
464
                                return $result;
×
465
                        }
466
                        $key = trim($key);
3✔
467
                        $value = trim($value);
3✔
468
                        $value = trim($value, '"');
3✔
469

470
                        if (!isset($result[$key])) {
3✔
471
                                $result[$key] = $value;
3✔
472
                        } else {
473
                                if (!is_array($result[$key])) {
×
474
                                        $result[$key] = [$result[$key]];
×
475
                                }
476
                                $result[$key][] = $value;
×
477
                        }
478
                }
479

480
                return $result;
3✔
481
        }
482

483
        private function der2pem($derData) {
484
                $pem = chunk_split(base64_encode((string)$derData), 64, "\n");
3✔
485
                $pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
3✔
486
                return $pem;
3✔
487
        }
488

489
        private function getHandler(): SignEngineHandler {
490
                $sign_engine = $this->appConfig->getValueString(Application::APP_ID, 'sign_engine', 'JSignPdf');
1✔
491
                $property = lcfirst($sign_engine) . 'Handler';
1✔
492
                if (!property_exists($this, $property)) {
1✔
493
                        throw new LibresignException($this->l10n->t('Invalid Sign engine.'), 400);
×
494
                }
495
                $classHandler = 'OCA\\Libresign\\Handler\\SignEngine\\' . ucfirst($property);
1✔
496
                if (!$this->$property instanceof $classHandler) {
1✔
497
                        $this->$property = \OCP\Server::get($classHandler);
1✔
498
                }
499
                return $this->$property;
1✔
500
        }
501

502
        #[\Override]
503
        public function sign(): File {
504
                $this->beforeSign();
1✔
505

506
                $signedContent = $this->getHandler()
1✔
507
                        ->setCertificate($this->getCertificate())
1✔
508
                        ->setInputFile($this->getInputFile())
1✔
509
                        ->setPassword($this->getPassword())
1✔
510
                        ->setSignatureParams($this->getSignatureParams())
1✔
511
                        ->setVisibleElements($this->getVisibleElements())
1✔
512
                        ->getSignedContent();
1✔
513
                $this->getInputFile()->putContent($signedContent);
×
514
                return $this->getInputFile();
×
515
        }
516

517
        public function isHandlerOk(): bool {
518
                return $this->certificateEngineFactory->getEngine()->isSetupOk();
1✔
519
        }
520
}
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