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

LibreSign / libresign / 19860846804

02 Dec 2025 01:48PM UTC coverage: 40.769%. First build
19860846804

Pull #5916

github

web-flow
Merge a76827235 into d5be546c9
Pull Request #5916: fix: handle corrupted signature data

6 of 8 new or added lines in 1 file covered. (75.0%)

4975 of 12203 relevant lines covered (40.77%)

3.98 hits per line

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

70.27
/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 OCP\Files\File;
20
use OCP\IAppConfig;
21
use OCP\IL10N;
22
use OCP\ITempManager;
23
use phpseclib3\File\ASN1;
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);
52✔
45
        }
46

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

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

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

70
                        rewind($resource);
3✔
71

72
                        $signature = stream_get_contents($resource, $signatureLength, $signatureStart);
3✔
73
                        if ($signature === false) {
3✔
NEW
74
                                yield null;
×
NEW
75
                                continue;
×
76
                        }
77

78
                        $decodedSignature = @hex2bin($signature);
3✔
79
                        if ($decodedSignature === false) {
3✔
80
                                yield null;
1✔
81
                                continue;
1✔
82
                        }
83
                        yield $decodedSignature;
2✔
84
                }
85

86
                $this->tempManager->clean();
3✔
87
        }
88

89
        public function setIsLibreSignFile(): void {
90
                $this->isLibreSignFile = true;
×
91
        }
92

93
        /**
94
         * @param resource $resource
95
         * @throws LibresignException When is not a signed file
96
         * @return array
97
         */
98
        #[\Override]
99
        public function getCertificateChain($resource): array {
100
                $certificates = [];
7✔
101

102
                foreach ($this->getSignatures($resource) as $signature) {
7✔
103
                        $certificates[] = $this->processSignature($resource, $signature);
3✔
104
                }
105
                return $certificates;
3✔
106
        }
107

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

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

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

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

128
        private function applyLibreSignRootCAFlag(array $signer): array {
129
                if (empty($signer['chain'])) {
2✔
130
                        return $signer;
×
131
                }
132

133
                foreach ($signer['chain'] as $key => $cert) {
2✔
134
                        if ($cert['isLibreSignRootCA']
2✔
135
                                && $cert['certificate_validation']['id'] !== 1
2✔
136
                        ) {
137
                                $signer['chain'][$key]['certificate_validation'] = [
×
138
                                        'id' => 1,
×
139
                                        'label' => $this->l10n->t('Certificate is trusted.'),
×
140
                                ];
×
141
                        }
142
                }
143

144
                return $signer;
2✔
145
        }
146

147
        private function extractTimestampData(array $decoded, array $result): array {
148
                $tsa = new TSA();
2✔
149

150
                try {
151
                        $timestampData = $tsa->extract($decoded);
2✔
152
                        if (!empty($timestampData['genTime']) || !empty($timestampData['policy']) || !empty($timestampData['serialNumber'])) {
2✔
153
                                $result['timestamp'] = $timestampData;
2✔
154
                        }
155
                } catch (\Throwable $e) {
×
156
                }
157

158
                if (!isset($result['signingTime']) || !$result['signingTime'] instanceof \DateTime) {
2✔
159
                        $result['signingTime'] = $tsa->getSigninTime($decoded);
2✔
160
                }
161
                return $result;
2✔
162
        }
163

164
        private function extractCertificateChain(string $signature): array {
165
                $pkcs7PemSignature = $this->der2pem($signature);
2✔
166
                $pemCertificates = [];
2✔
167

168
                if (!openssl_pkcs7_read($pkcs7PemSignature, $pemCertificates)) {
2✔
169
                        return [];
×
170
                }
171

172
                $chain = [];
2✔
173
                $isLibreSignRootCA = false;
2✔
174
                $certificateEngine = $this->getCertificateEngine();
2✔
175

176
                foreach ($pemCertificates as $index => $pemCertificate) {
2✔
177
                        $parsed = $certificateEngine->parseCertificate($pemCertificate);
2✔
178
                        if ($parsed) {
2✔
179
                                $parsed['signature_validation'] = [
2✔
180
                                        'id' => 1,
2✔
181
                                        'label' => $this->l10n->t('Signature is valid.'),
2✔
182
                                ];
2✔
183
                                if (!$isLibreSignRootCA) {
2✔
184
                                        $isLibreSignRootCA = $this->isLibreSignRootCA($pemCertificate, $parsed);
2✔
185
                                }
186
                                $parsed['isLibreSignRootCA'] = $isLibreSignRootCA;
2✔
187
                                $chain[$index] = $parsed;
2✔
188
                        }
189
                }
190
                if ($isLibreSignRootCA || $this->isLibreSignFile) {
2✔
191
                        foreach ($chain as &$cert) {
×
192
                                $cert['isLibreSignRootCA'] = true;
×
193
                        }
194
                }
195

196
                return $chain;
2✔
197
        }
198

199
        private function isLibreSignRootCA(string $certificate, array $parsed): bool {
200
                $rootCertificatePem = $this->getRootCertificatePem();
2✔
201
                if (empty($rootCertificatePem)) {
2✔
202
                        return false;
2✔
203
                }
204

205
                $rootFingerprint = openssl_x509_fingerprint($rootCertificatePem, 'sha256');
×
206
                $fingerprint = openssl_x509_fingerprint($certificate, 'sha256');
×
207
                if ($rootFingerprint === $fingerprint) {
×
208
                        return true;
×
209
                }
210

211
                return $this->hasLibreSignCaId($parsed);
×
212
        }
213

214
        private function hasLibreSignCaId(array $parsed): bool {
215
                $instanceId = $this->appConfig->getValueString(Application::APP_ID, 'instance_id', '');
×
216
                if (strlen($instanceId) !== 10 || !isset($parsed['subject']['OU'])) {
×
217
                        return false;
×
218
                }
219

220
                $organizationalUnits = $parsed['subject']['OU'];
×
221
                if (is_string($organizationalUnits)) {
×
222
                        $organizationalUnits = [$organizationalUnits];
×
223
                }
224

225
                foreach ($organizationalUnits as $ou) {
×
226
                        $ou = trim($ou);
×
227
                        if ($this->caIdentifierService->isValidCaId($ou, $instanceId)) {
×
228
                                return true;
×
229
                        }
230
                }
231

232
                return false;
×
233
        }
234

235
        private function getRootCertificatePem(): string {
236
                if (!empty($this->rootCertificatePem)) {
2✔
237
                        return $this->rootCertificatePem;
×
238
                }
239
                $configPath = $this->appConfig->getValueString(Application::APP_ID, 'config_path');
2✔
240
                if (empty($configPath)
2✔
241
                        || !is_dir($configPath)
2✔
242
                        || !is_readable($configPath . DIRECTORY_SEPARATOR . 'ca.pem')
2✔
243
                ) {
244
                        return '';
2✔
245
                }
246
                $rootCertificatePem = file_get_contents($configPath . DIRECTORY_SEPARATOR . 'ca.pem');
×
247
                if ($rootCertificatePem === false) {
×
248
                        return '';
×
249
                }
250
                $this->rootCertificatePem = $rootCertificatePem;
×
251
                return $this->rootCertificatePem;
×
252
        }
253

254
        private function enrichLeafWithPopplerData($resource, array $result): array {
255
                if (empty($result['chain'])) {
2✔
256
                        return $result;
×
257
                }
258

259
                $popplerOnlyFields = ['field', 'range', 'certificate_validation'];
2✔
260
                if (!isset($result['chain'][0]['subject'])) {
2✔
261
                        return $result;
×
262
                }
263
                $needPoppler = false;
2✔
264
                foreach ($popplerOnlyFields as $field) {
2✔
265
                        if (empty($result['chain'][0][$field])) {
2✔
266
                                $needPoppler = true;
2✔
267
                                break;
2✔
268
                        }
269
                }
270
                if (!isset($result['chain'][0]['signature_validation']) || $result['chain'][0]['signature_validation']['id'] !== 1) {
2✔
271
                        $needPoppler = true;
×
272
                }
273
                if (!$needPoppler) {
2✔
274
                        return $result;
×
275
                }
276
                $popplerChain = $this->chainFromPoppler($result['chain'][0]['subject'], $resource);
2✔
277
                if (empty($popplerChain)) {
2✔
278
                        return $result;
2✔
279
                }
280
                foreach ($popplerOnlyFields as $field) {
×
281
                        if (isset($popplerChain[$field])) {
×
282
                                $result['chain'][0][$field] = $popplerChain[$field];
×
283
                        }
284
                }
285
                if (!isset($result['chain'][0]['signature_validation']) || $result['chain'][0]['signature_validation']['id'] !== 1) {
×
286
                        if (isset($popplerChain['signature_validation'])) {
×
287
                                $result['chain'][0]['signature_validation'] = $popplerChain['signature_validation'];
×
288
                        }
289
                }
290
                return $result;
×
291
        }
292

293
        private function chainFromPoppler(array $subject, $resource): array {
294
                $fromFallback = $this->popplerUtilsPdfSignFallback($resource);
2✔
295
                foreach ($fromFallback as $popplerSig) {
2✔
296
                        if (!isset($popplerSig['chain'][0]['subject'])) {
2✔
297
                                continue;
×
298
                        }
299
                        if ($popplerSig['chain'][0]['subject'] == $subject) {
2✔
300
                                return $popplerSig['chain'][0];
×
301
                        }
302
                }
303
                return [];
2✔
304
        }
305

306
        private function popplerUtilsPdfSignFallback($resource): array {
307
                if (!empty($this->signaturesFromPoppler)) {
2✔
308
                        return $this->signaturesFromPoppler;
1✔
309
                }
310
                if (shell_exec('which pdfsig') === null) {
1✔
311
                        return $this->signaturesFromPoppler;
×
312
                }
313
                rewind($resource);
1✔
314
                $content = stream_get_contents($resource);
1✔
315
                $tempFile = $this->tempManager->getTemporaryFile('file.pdf');
1✔
316
                file_put_contents($tempFile, $content);
1✔
317

318
                $content = shell_exec('env TZ=UTC pdfsig ' . $tempFile);
1✔
319
                if (empty($content)) {
1✔
320
                        return $this->signaturesFromPoppler;
×
321
                }
322
                $lines = explode("\n", $content);
1✔
323

324
                $lastSignature = 0;
1✔
325
                foreach ($lines as $item) {
1✔
326
                        $isFirstLevel = preg_match('/^Signature\s#(\d)/', $item, $match);
1✔
327
                        if ($isFirstLevel) {
1✔
328
                                $lastSignature = (int)$match[1] - 1;
1✔
329
                                $this->signaturesFromPoppler[$lastSignature] = [];
1✔
330
                                continue;
1✔
331
                        }
332

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

378
        private function getReadableSigState(string $status) {
379
                return match ($status) {
2✔
380
                        'Signature is Valid.' => [
1✔
381
                                'id' => 1,
1✔
382
                                'label' => $this->l10n->t('Signature is valid.'),
1✔
383
                        ],
1✔
384
                        'Signature is Invalid.' => [
×
385
                                'id' => 2,
×
386
                                'label' => $this->l10n->t('Signature is invalid.'),
×
387
                        ],
×
388
                        'Digest Mismatch.' => [
1✔
389
                                'id' => 3,
1✔
390
                                'label' => $this->l10n->t('Digest mismatch.'),
1✔
391
                        ],
1✔
392
                        "Document isn't signed or corrupted data." => [
×
393
                                'id' => 4,
×
394
                                'label' => $this->l10n->t("Document isn't signed or corrupted data."),
×
395
                        ],
×
396
                        'Signature has not yet been verified.' => [
×
397
                                'id' => 5,
×
398
                                'label' => $this->l10n->t('Signature has not yet been verified.'),
×
399
                        ],
×
400
                        default => [
2✔
401
                                'id' => 6,
2✔
402
                                'label' => $this->l10n->t('Unknown validation failure.'),
2✔
403
                        ],
2✔
404
                };
2✔
405
        }
406

407

408
        private function getReadableCertState(string $status) {
409
                return match ($status) {
1✔
410
                        'Certificate is Trusted.' => [
×
411
                                'id' => 1,
×
412
                                'label' => $this->l10n->t('Certificate is trusted.'),
×
413
                        ],
×
414
                        "Certificate issuer isn't Trusted." => [
×
415
                                'id' => 2,
×
416
                                'label' => $this->l10n->t("Certificate issuer isn't trusted."),
×
417
                        ],
×
418
                        'Certificate issuer is unknown.' => [
1✔
419
                                'id' => 3,
1✔
420
                                'label' => $this->l10n->t('Certificate issuer is unknown.'),
1✔
421
                        ],
1✔
422
                        'Certificate has been Revoked.' => [
×
423
                                'id' => 4,
×
424
                                'label' => $this->l10n->t('Certificate has been revoked.'),
×
425
                        ],
×
426
                        'Certificate has Expired' => [
×
427
                                'id' => 5,
×
428
                                'label' => $this->l10n->t('Certificate has expired'),
×
429
                        ],
×
430
                        'Certificate has not yet been verified.' => [
×
431
                                'id' => 6,
×
432
                                'label' => $this->l10n->t('Certificate has not yet been verified.'),
×
433
                        ],
×
434
                        default => [
1✔
435
                                'id' => 7,
1✔
436
                                'label' => $this->l10n->t('Unknown issue with Certificate or corrupted data.')
1✔
437
                        ],
1✔
438
                };
1✔
439
        }
440

441

442
        private function parseDistinguishedNameWithMultipleValues(string $dn): array {
443
                $result = [];
1✔
444
                $pairs = preg_split('/,(?=(?:[^"]*"[^"]*")*[^"]*$)/', $dn);
1✔
445

446
                foreach ($pairs as $pair) {
1✔
447
                        [$key, $value] = explode('=', $pair, 2);
1✔
448
                        if (empty($key) || empty($value)) {
1✔
449
                                return $result;
×
450
                        }
451
                        $key = trim($key);
1✔
452
                        $value = trim($value);
1✔
453
                        $value = trim($value, '"');
1✔
454

455
                        if (!isset($result[$key])) {
1✔
456
                                $result[$key] = $value;
1✔
457
                        } else {
458
                                if (!is_array($result[$key])) {
×
459
                                        $result[$key] = [$result[$key]];
×
460
                                }
461
                                $result[$key][] = $value;
×
462
                        }
463
                }
464

465
                return $result;
1✔
466
        }
467

468
        private function der2pem($derData) {
469
                $pem = chunk_split(base64_encode((string)$derData), 64, "\n");
2✔
470
                $pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
2✔
471
                return $pem;
2✔
472
        }
473

474
        private function getHandler(): SignEngineHandler {
475
                $sign_engine = $this->appConfig->getValueString(Application::APP_ID, 'sign_engine', 'JSignPdf');
1✔
476
                $property = lcfirst($sign_engine) . 'Handler';
1✔
477
                if (!property_exists($this, $property)) {
1✔
478
                        throw new LibresignException($this->l10n->t('Invalid Sign engine.'), 400);
×
479
                }
480
                $classHandler = 'OCA\\Libresign\\Handler\\SignEngine\\' . ucfirst($property);
1✔
481
                if (!$this->$property instanceof $classHandler) {
1✔
482
                        $this->$property = \OCP\Server::get($classHandler);
1✔
483
                }
484
                return $this->$property;
1✔
485
        }
486

487
        #[\Override]
488
        public function sign(): File {
489
                $this->beforeSign();
1✔
490

491
                $signedContent = $this->getHandler()
1✔
492
                        ->setCertificate($this->getCertificate())
1✔
493
                        ->setInputFile($this->getInputFile())
1✔
494
                        ->setPassword($this->getPassword())
1✔
495
                        ->setSignatureParams($this->getSignatureParams())
1✔
496
                        ->setVisibleElements($this->getVisibleElements())
1✔
497
                        ->getSignedContent();
1✔
498
                $this->getInputFile()->putContent($signedContent);
×
499
                return $this->getInputFile();
×
500
        }
501

502
        public function isHandlerOk(): bool {
503
                return $this->certificateEngineFactory->getEngine()->isSetupOk();
1✔
504
        }
505
}
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