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

LibreSign / libresign / 19074450473

04 Nov 2025 03:47PM UTC coverage: 39.581%. First build
19074450473

Pull #5731

github

web-flow
Merge 4eab882d2 into b17fffe83
Pull Request #5731: feat: add multiple ou

35 of 112 new or added lines in 10 files covered. (31.25%)

4570 of 11546 relevant lines covered (39.58%)

2.95 hits per line

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

70.07
/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 {
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, $parsed);
2✔
172
                                }
173
                                $parsed['isLibreSignRootCA'] = $isLibreSignRootCA;
2✔
174
                                $chain[$index] = $parsed;
2✔
175
                        }
176
                }
177
                if ($isLibreSignRootCA || $this->isLibreSignFile) {
2✔
178
                        foreach ($chain as &$cert) {
×
179
                                $cert['isLibreSignRootCA'] = true;
×
180
                        }
181
                }
182

183
                return $chain;
2✔
184
        }
185

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

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

NEW
198
                return $this->hasLibreSignCaId($parsed);
×
199
        }
200

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

NEW
207
                $expectedCaUuid = 'libresign-ca-id:' . $instanceId;
×
NEW
208
                $organizationalUnits = $parsed['subject']['OU'];
×
209

NEW
210
                if (is_string($organizationalUnits)) {
×
NEW
211
                        return str_contains($organizationalUnits, $expectedCaUuid);
×
212
                }
213

NEW
214
                return in_array($expectedCaUuid, array_map('trim', $organizationalUnits));
×
215
        }
216

217
        private function getRootCertificatePem(): string {
218
                if (!empty($this->rootCertificatePem)) {
2✔
219
                        return $this->rootCertificatePem;
×
220
                }
221
                $configPath = $this->appConfig->getValueString(Application::APP_ID, 'config_path');
2✔
222
                if (empty($configPath)
2✔
223
                        || !is_dir($configPath)
2✔
224
                        || !is_readable($configPath . DIRECTORY_SEPARATOR . 'ca.pem')
2✔
225
                ) {
226
                        return '';
2✔
227
                }
228
                $rootCertificatePem = file_get_contents($configPath . DIRECTORY_SEPARATOR . 'ca.pem');
×
229
                if ($rootCertificatePem === false) {
×
230
                        return '';
×
231
                }
232
                $this->rootCertificatePem = $rootCertificatePem;
×
233
                return $this->rootCertificatePem;
×
234
        }
235

236
        private function enrichLeafWithPopplerData($resource, array $result): array {
237
                if (empty($result['chain'])) {
2✔
238
                        return $result;
×
239
                }
240

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

275
        private function chainFromPoppler(array $subject, $resource): array {
276
                $fromFallback = $this->popplerUtilsPdfSignFallback($resource);
2✔
277
                foreach ($fromFallback as $popplerSig) {
2✔
278
                        if (!isset($popplerSig['chain'][0]['subject'])) {
2✔
279
                                continue;
×
280
                        }
281
                        if ($popplerSig['chain'][0]['subject'] == $subject) {
2✔
282
                                return $popplerSig['chain'][0];
2✔
283
                        }
284
                }
285
                return [];
×
286
        }
287

288
        private function popplerUtilsPdfSignFallback($resource): array {
289
                if (!empty($this->signaturesFromPoppler)) {
2✔
290
                        return $this->signaturesFromPoppler;
1✔
291
                }
292
                if (shell_exec('which pdfsig') === null) {
1✔
293
                        return $this->signaturesFromPoppler;
×
294
                }
295
                rewind($resource);
1✔
296
                $content = stream_get_contents($resource);
1✔
297
                $tempFile = $this->tempManager->getTemporaryFile('file.pdf');
1✔
298
                file_put_contents($tempFile, $content);
1✔
299

300
                $content = shell_exec('env TZ=UTC pdfsig ' . $tempFile);
1✔
301
                if (empty($content)) {
1✔
302
                        return $this->signaturesFromPoppler;
×
303
                }
304
                $lines = explode("\n", $content);
1✔
305

306
                $lastSignature = 0;
1✔
307
                foreach ($lines as $item) {
1✔
308
                        $isFirstLevel = preg_match('/^Signature\s#(\d)/', $item, $match);
1✔
309
                        if ($isFirstLevel) {
1✔
310
                                $lastSignature = (int)$match[1] - 1;
1✔
311
                                $this->signaturesFromPoppler[$lastSignature] = [];
1✔
312
                                continue;
1✔
313
                        }
314

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

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

389

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

423

424
        private function parseDistinguishedNameWithMultipleValues(string $dn): array {
425
                $result = [];
1✔
426
                $pairs = preg_split('/,(?=(?:[^"]*"[^"]*")*[^"]*$)/', $dn);
1✔
427

428
                foreach ($pairs as $pair) {
1✔
429
                        [$key, $value] = explode('=', $pair, 2);
1✔
430
                        if (empty($key) || empty($value)) {
1✔
431
                                return $result;
×
432
                        }
433
                        $key = trim($key);
1✔
434
                        $value = trim($value);
1✔
435
                        $value = trim($value, '"');
1✔
436

437
                        if (!isset($result[$key])) {
1✔
438
                                $result[$key] = $value;
1✔
439
                        } else {
440
                                if (!is_array($result[$key])) {
×
441
                                        $result[$key] = [$result[$key]];
×
442
                                }
443
                                $result[$key][] = $value;
×
444
                        }
445
                }
446

447
                return $result;
1✔
448
        }
449

450
        private function der2pem($derData) {
451
                $pem = chunk_split(base64_encode((string)$derData), 64, "\n");
2✔
452
                $pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
2✔
453
                return $pem;
2✔
454
        }
455

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

469
        #[\Override]
470
        public function sign(): File {
471
                $signedContent = $this->getHandler()
1✔
472
                        ->setCertificate($this->getCertificate())
1✔
473
                        ->setInputFile($this->getInputFile())
1✔
474
                        ->setPassword($this->getPassword())
1✔
475
                        ->setSignatureParams($this->getSignatureParams())
1✔
476
                        ->setVisibleElements($this->getVisibleElements())
1✔
477
                        ->getSignedContent();
1✔
478
                $this->getInputFile()->putContent($signedContent);
×
479
                return $this->getInputFile();
×
480
        }
481

482
        public function isHandlerOk(): bool {
483
                return $this->certificateEngineFactory->getEngine()->isSetupOk();
1✔
484
        }
485
}
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