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

LibreSign / libresign / 18984179626

31 Oct 2025 08:18PM UTC coverage: 39.551%. First build
18984179626

Pull #5719

github

web-flow
Merge c1201283f into 7b46c098c
Pull Request #5719: fix: trust LibreSign cert when is a LibreSign file

3 of 13 new or added lines in 2 files covered. (23.08%)

4529 of 11451 relevant lines covered (39.55%)

2.91 hits per line

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

72.63
/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\FolderService;
18
use OCA\Libresign\Vendor\phpseclib3\File\ASN1;
19
use OCP\Files\File;
20
use OCP\IAppConfig;
21
use OCP\IL10N;
22
use OCP\ITempManager;
23
use Psr\Log\LoggerInterface;
24

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

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

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

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

65
                        $signatureStart = $offset1 + $length1 + 1;
2✔
66
                        $signatureLength = $offset2 - $signatureStart - 1;
2✔
67

68
                        rewind($resource);
2✔
69

70
                        $signature = stream_get_contents($resource, $signatureLength, $signatureStart);
2✔
71

72
                        yield hex2bin($signature);
2✔
73
                }
74

75
                $this->tempManager->clean();
2✔
76
        }
77

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

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

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

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

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

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

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

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

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

133
                return $signer;
2✔
134
        }
135

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

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

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

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

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

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

183
                return $chain;
2✔
184
        }
185

186
        private function isLibreSignRootCA(string $certificate): bool {
187
                $rootCertificatePem = $this->getRootCertificatePem();
2✔
188
                if (empty($rootCertificatePem)) {
2✔
189
                        return false;
2✔
190
                }
191
                $rootFingerprint = openssl_x509_fingerprint($rootCertificatePem, 'sha256');
×
192
                $fingerprint = openssl_x509_fingerprint($certificate, 'sha256');
×
193
                return $rootFingerprint === $fingerprint;
×
194
        }
195

196
        private function getRootCertificatePem(): string {
197
                if (!empty($this->rootCertificatePem)) {
2✔
198
                        return $this->rootCertificatePem;
×
199
                }
200
                $configPath = $this->appConfig->getValueString(Application::APP_ID, 'config_path');
2✔
201
                if (empty($configPath)
2✔
202
                        || !is_dir($configPath)
2✔
203
                        || !is_readable($configPath . DIRECTORY_SEPARATOR . 'ca.pem')
2✔
204
                ) {
205
                        return '';
2✔
206
                }
207
                $rootCertificatePem = file_get_contents($configPath . DIRECTORY_SEPARATOR . 'ca.pem');
×
208
                if ($rootCertificatePem === false) {
×
209
                        return '';
×
210
                }
211
                $this->rootCertificatePem = $rootCertificatePem;
×
212
                return $this->rootCertificatePem;
×
213
        }
214

215
        private function enrichLeafWithPopplerData($resource, array $result): array {
216
                if (empty($result['chain'])) {
2✔
217
                        return $result;
×
218
                }
219

220
                $popplerOnlyFields = ['field', 'range', 'certificate_validation'];
2✔
221
                if (!isset($result['chain'][0]['subject'])) {
2✔
222
                        return $result;
×
223
                }
224
                $needPoppler = false;
2✔
225
                foreach ($popplerOnlyFields as $field) {
2✔
226
                        if (empty($result['chain'][0][$field])) {
2✔
227
                                $needPoppler = true;
2✔
228
                                break;
2✔
229
                        }
230
                }
231
                if (!isset($result['chain'][0]['signature_validation']) || $result['chain'][0]['signature_validation']['id'] !== 1) {
2✔
232
                        $needPoppler = true;
×
233
                }
234
                if (!$needPoppler) {
2✔
235
                        return $result;
×
236
                }
237
                $popplerChain = $this->chainFromPoppler($result['chain'][0]['subject'], $resource);
2✔
238
                if (empty($popplerChain)) {
2✔
239
                        return $result;
×
240
                }
241
                foreach ($popplerOnlyFields as $field) {
2✔
242
                        if (isset($popplerChain[$field])) {
2✔
243
                                $result['chain'][0][$field] = $popplerChain[$field];
2✔
244
                        }
245
                }
246
                if (!isset($result['chain'][0]['signature_validation']) || $result['chain'][0]['signature_validation']['id'] !== 1) {
2✔
247
                        if (isset($popplerChain['signature_validation'])) {
×
248
                                $result['chain'][0]['signature_validation'] = $popplerChain['signature_validation'];
×
249
                        }
250
                }
251
                return $result;
2✔
252
        }
253

254
        private function chainFromPoppler(array $subject, $resource): array {
255
                $fromFallback = $this->popplerUtilsPdfSignFallback($resource);
2✔
256
                foreach ($fromFallback as $popplerSig) {
2✔
257
                        if (!isset($popplerSig['chain'][0]['subject'])) {
2✔
258
                                continue;
×
259
                        }
260
                        if ($popplerSig['chain'][0]['subject'] == $subject) {
2✔
261
                                return $popplerSig['chain'][0];
2✔
262
                        }
263
                }
264
                return [];
×
265
        }
266

267
        private function popplerUtilsPdfSignFallback($resource): array {
268
                if (!empty($this->signaturesFromPoppler)) {
2✔
269
                        return $this->signaturesFromPoppler;
1✔
270
                }
271
                if (shell_exec('which pdfsig') === null) {
1✔
272
                        return $this->signaturesFromPoppler;
×
273
                }
274
                rewind($resource);
1✔
275
                $content = stream_get_contents($resource);
1✔
276
                $tempFile = $this->tempManager->getTemporaryFile('file.pdf');
1✔
277
                file_put_contents($tempFile, $content);
1✔
278

279
                $content = shell_exec('env TZ=UTC pdfsig ' . $tempFile);
1✔
280
                if (empty($content)) {
1✔
281
                        return $this->signaturesFromPoppler;
×
282
                }
283
                $lines = explode("\n", $content);
1✔
284

285
                $lastSignature = 0;
1✔
286
                foreach ($lines as $item) {
1✔
287
                        $isFirstLevel = preg_match('/^Signature\s#(\d)/', $item, $match);
1✔
288
                        if ($isFirstLevel) {
1✔
289
                                $lastSignature = (int)$match[1] - 1;
1✔
290
                                $this->signaturesFromPoppler[$lastSignature] = [];
1✔
291
                                continue;
1✔
292
                        }
293

294
                        $match = [];
1✔
295
                        $isSecondLevel = preg_match('/^\s+-\s(?<key>.+):\s(?<value>.*)/', $item, $match);
1✔
296
                        if ($isSecondLevel) {
1✔
297
                                switch ((string)$match['key']) {
1✔
298
                                        case 'Signing Time':
1✔
299
                                                $this->signaturesFromPoppler[$lastSignature]['signingTime'] = DateTime::createFromFormat('M d Y H:i:s', $match['value'], new \DateTimeZone('UTC'));
1✔
300
                                                break;
1✔
301
                                        case 'Signer full Distinguished Name':
1✔
302
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['subject'] = $this->parseDistinguishedNameWithMultipleValues($match['value']);
1✔
303
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['name'] = $match['value'];
1✔
304
                                                break;
1✔
305
                                        case 'Signing Hash Algorithm':
1✔
306
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['signatureTypeSN'] = $match['value'];
1✔
307
                                                break;
1✔
308
                                        case 'Signature Validation':
1✔
309
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['signature_validation'] = $this->getReadableSigState($match['value']);
1✔
310
                                                break;
1✔
311
                                        case 'Certificate Validation':
1✔
312
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['certificate_validation'] = $this->getReadableCertState($match['value']);
1✔
313
                                                break;
1✔
314
                                        case 'Signed Ranges':
1✔
315
                                                if (preg_match('/\[(\d+) - (\d+)\], \[(\d+) - (\d+)\]/', $match['value'], $ranges)) {
1✔
316
                                                        $this->signaturesFromPoppler[$lastSignature]['chain'][0]['range'] = [
1✔
317
                                                                'offset1' => (int)$ranges[1],
1✔
318
                                                                'length1' => (int)$ranges[2],
1✔
319
                                                                'offset2' => (int)$ranges[3],
1✔
320
                                                                'length2' => (int)$ranges[4],
1✔
321
                                                        ];
1✔
322
                                                }
323
                                                break;
1✔
324
                                        case 'Signature Field Name':
1✔
325
                                                $this->signaturesFromPoppler[$lastSignature]['chain'][0]['field'] = $match['value'];
1✔
326
                                                break;
1✔
327
                                        case 'Signature Validation':
1✔
328
                                        case 'Signature Type':
1✔
329
                                        case 'Total document signed':
1✔
330
                                        case 'Not total document signed':
1✔
331
                                        default:
332
                                                break;
1✔
333
                                }
334
                        }
335
                }
336
                return $this->signaturesFromPoppler;
1✔
337
        }
338

339
        private function getReadableSigState(string $status) {
340
                return match ($status) {
1✔
341
                        'Signature is Valid.' => [
1✔
342
                                'id' => 1,
1✔
343
                                'label' => $this->l10n->t('Signature is valid.'),
1✔
344
                        ],
1✔
345
                        'Signature is Invalid.' => [
×
346
                                'id' => 2,
×
347
                                'label' => $this->l10n->t('Signature is invalid.'),
×
348
                        ],
×
349
                        'Digest Mismatch.' => [
×
350
                                'id' => 3,
×
351
                                'label' => $this->l10n->t('Digest mismatch.'),
×
352
                        ],
×
353
                        "Document isn't signed or corrupted data." => [
×
354
                                'id' => 4,
×
355
                                'label' => $this->l10n->t("Document isn't signed or corrupted data."),
×
356
                        ],
×
357
                        'Signature has not yet been verified.' => [
×
358
                                'id' => 5,
×
359
                                'label' => $this->l10n->t('Signature has not yet been verified.'),
×
360
                        ],
×
361
                        default => [
1✔
362
                                'id' => 6,
1✔
363
                                'label' => $this->l10n->t('Unknown validation failure.'),
1✔
364
                        ],
1✔
365
                };
1✔
366
        }
367

368

369
        private function getReadableCertState(string $status) {
370
                return match ($status) {
1✔
371
                        'Certificate is Trusted.' => [
×
372
                                'id' => 1,
×
373
                                'label' => $this->l10n->t('Certificate is trusted.'),
×
374
                        ],
×
375
                        "Certificate issuer isn't Trusted." => [
×
376
                                'id' => 2,
×
377
                                'label' => $this->l10n->t("Certificate issuer isn't trusted."),
×
378
                        ],
×
379
                        'Certificate issuer is unknown.' => [
1✔
380
                                'id' => 3,
1✔
381
                                'label' => $this->l10n->t('Certificate issuer is unknown.'),
1✔
382
                        ],
1✔
383
                        'Certificate has been Revoked.' => [
×
384
                                'id' => 4,
×
385
                                'label' => $this->l10n->t('Certificate has been revoked.'),
×
386
                        ],
×
387
                        'Certificate has Expired' => [
×
388
                                'id' => 5,
×
389
                                'label' => $this->l10n->t('Certificate has expired'),
×
390
                        ],
×
391
                        'Certificate has not yet been verified.' => [
×
392
                                'id' => 6,
×
393
                                'label' => $this->l10n->t('Certificate has not yet been verified.'),
×
394
                        ],
×
395
                        default => [
1✔
396
                                'id' => 7,
1✔
397
                                'label' => $this->l10n->t('Unknown issue with Certificate or corrupted data.')
1✔
398
                        ],
1✔
399
                };
1✔
400
        }
401

402

403
        private function parseDistinguishedNameWithMultipleValues(string $dn): array {
404
                $result = [];
1✔
405
                $pairs = preg_split('/,(?=(?:[^"]*"[^"]*")*[^"]*$)/', $dn);
1✔
406

407
                foreach ($pairs as $pair) {
1✔
408
                        [$key, $value] = explode('=', $pair, 2);
1✔
409
                        if (empty($key) || empty($value)) {
1✔
410
                                return $result;
×
411
                        }
412
                        $key = trim($key);
1✔
413
                        $value = trim($value);
1✔
414
                        $value = trim($value, '"');
1✔
415

416
                        if (!isset($result[$key])) {
1✔
417
                                $result[$key] = $value;
1✔
418
                        } else {
419
                                if (!is_array($result[$key])) {
×
420
                                        $result[$key] = [$result[$key]];
×
421
                                }
422
                                $result[$key][] = $value;
×
423
                        }
424
                }
425

426
                return $result;
1✔
427
        }
428

429
        private function der2pem($derData) {
430
                $pem = chunk_split(base64_encode((string)$derData), 64, "\n");
2✔
431
                $pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
2✔
432
                return $pem;
2✔
433
        }
434

435
        private function getHandler(): SignEngineHandler {
436
                $sign_engine = $this->appConfig->getValueString(Application::APP_ID, 'sign_engine', 'JSignPdf');
1✔
437
                $property = lcfirst($sign_engine) . 'Handler';
1✔
438
                if (!property_exists($this, $property)) {
1✔
439
                        throw new LibresignException($this->l10n->t('Invalid Sign engine.'), 400);
×
440
                }
441
                $classHandler = 'OCA\\Libresign\\Handler\\SignEngine\\' . ucfirst($property);
1✔
442
                if (!$this->$property instanceof $classHandler) {
1✔
443
                        $this->$property = \OCP\Server::get($classHandler);
1✔
444
                }
445
                return $this->$property;
1✔
446
        }
447

448
        #[\Override]
449
        public function sign(): File {
450
                $signedContent = $this->getHandler()
1✔
451
                        ->setCertificate($this->getCertificate())
1✔
452
                        ->setInputFile($this->getInputFile())
1✔
453
                        ->setPassword($this->getPassword())
1✔
454
                        ->setSignatureParams($this->getSignatureParams())
1✔
455
                        ->setVisibleElements($this->getVisibleElements())
1✔
456
                        ->getSignedContent();
1✔
457
                $this->getInputFile()->putContent($signedContent);
×
458
                return $this->getInputFile();
×
459
        }
460

461
        public function isHandlerOk(): bool {
462
                return $this->certificateEngineFactory->getEngine()->isSetupOk();
1✔
463
        }
464
}
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