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

LibreSign / libresign / 20243880086

15 Dec 2025 06:53PM UTC coverage: 45.15%. First build
20243880086

Pull #6197

github

web-flow
Merge 9274075bf into 54b16f7f5
Pull Request #6197: refactor: consolidate pdf fixtures

13 of 15 new or added lines in 1 file covered. (86.67%)

6084 of 13475 relevant lines covered (45.15%)

5.22 hits per line

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

74.41
/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);
54✔
47
        }
48

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

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

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

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

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

71
                        $decodedSignature = @hex2bin($signatureHex);
8✔
72
                        if ($decodedSignature === false) {
8✔
73
                                yield null;
×
74
                                continue;
×
75
                        }
76
                        yield $decodedSignature;
8✔
77
                }
78

79
                $this->tempManager->clean();
5✔
80
        }
81

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

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

95
                foreach ($this->getSignatures($resource) as $signature) {
17✔
96
                        if (!$signature) {
8✔
NEW
97
                                continue;
×
98
                        }
99

100
                        $result = $this->processSignature($resource, $signature);
8✔
101

102
                        if (empty($result['chain'])) {
5✔
NEW
103
                                continue;
×
104
                        }
105

106
                        $certificates[] = $result;
5✔
107
                }
108
                return $certificates;
5✔
109
        }
110

111
        private function processSignature($resource, ?string $signature): array {
112
                $result = [];
8✔
113

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

119
                $decoded = ASN1::decodeBER($signature);
8✔
120
                $result = $this->extractTimestampData($decoded, $result);
8✔
121

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

128
                $result = $this->extractDocMdpData($resource, $result);
5✔
129

130
                $result = $this->applyLibreSignRootCAFlag($result);
5✔
131
                return $result;
5✔
132
        }
133

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

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

150
                return $signer;
5✔
151
        }
152

153

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

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

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

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

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

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

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

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

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

212
                return $chain;
5✔
213
        }
214

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

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

227
                return $this->hasLibreSignCaId($parsed);
1✔
228
        }
229

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

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

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

248
                return false;
1✔
249
        }
250

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

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

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

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

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

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

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

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

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

423

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

457

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

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

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

481
                return $result;
3✔
482
        }
483

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

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

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

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

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