-
-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathPkcs12Handler.php
More file actions
451 lines (413 loc) · 14.4 KB
/
Pkcs12Handler.php
File metadata and controls
451 lines (413 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Libresign\Handler\SignEngine;
use DateTime;
use OCA\Libresign\AppInfo\Application;
use OCA\Libresign\Exception\InvalidPasswordException;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory;
use OCA\Libresign\Handler\CertificateEngine\OrderCertificatesTrait;
use OCA\Libresign\Handler\FooterHandler;
use OCA\Libresign\Service\FolderService;
use OCP\Files\File;
use OCP\Files\GenericFileException;
use OCP\IAppConfig;
use OCP\IL10N;
use OCP\ITempManager;
use phpseclib3\File\ASN1;
use TypeError;
class Pkcs12Handler extends SignEngineHandler {
use OrderCertificatesTrait;
private string $pfxFilename = 'signature.pfx';
protected string $certificate = '';
private array $signaturesFromPoppler = [];
/**
* Used by method self::getHandler()
*/
private ?JSignPdfHandler $jSignPdfHandler = null;
public function __construct(
private FolderService $folderService,
private IAppConfig $appConfig,
protected CertificateEngineFactory $certificateEngineFactory,
private IL10N $l10n,
private FooterHandler $footerHandler,
private ITempManager $tempManager,
) {
}
public function savePfx(string $uid, string $content): string {
$this->folderService->setUserId($uid);
$folder = $this->folderService->getFolder();
if ($folder->nodeExists($this->pfxFilename)) {
$file = $folder->get($this->pfxFilename);
if (!$file instanceof File) {
throw new LibresignException("path {$this->pfxFilename} already exists and is not a file!", 400);
}
try {
$file->putContent($content);
} catch (GenericFileException $e) {
throw new LibresignException("path {$file->getPath()} does not exists!", 400);
}
return $content;
}
$file = $folder->newFile($this->pfxFilename);
$file->putContent($content);
return $content;
}
public function deletePfx(string $uid): void {
$this->folderService->setUserId($uid);
$folder = $this->folderService->getFolder();
try {
$file = $folder->get($this->pfxFilename);
$file->delete();
} catch (\Throwable $th) {
}
}
public function updatePassword(string $uid, string $currentPrivateKey, string $newPrivateKey): string {
$pfx = $this->getPfxOfCurrentSigner($uid);
$content = $this->certificateEngineFactory->getEngine()->updatePassword(
$pfx,
$currentPrivateKey,
$newPrivateKey
);
return $this->savePfx($uid, $content);
}
/**
* @throws LibresignException When is not a signed file
*/
private function getSignatures($resource): iterable {
$content = stream_get_contents($resource);
preg_match_all(
'/ByteRange\s*\[\s*(?<offset1>\d+)\s+(?<length1>\d+)\s+(?<offset2>\d+)\s+(?<length2>\d+)\s*\]/',
$content,
$bytes
);
if (empty($bytes['offset1']) || empty($bytes['length1']) || empty($bytes['offset2']) || empty($bytes['length2'])) {
throw new LibresignException($this->l10n->t('Unsigned file.'));
}
for ($i = 0; $i < count($bytes['offset1']); $i++) {
// Starting position (in bytes) of the first part of the PDF that will be included in the validation.
$offset1 = (int)$bytes['offset1'][$i];
// Length (in bytes) of the first part.
$length1 = (int)$bytes['length1'][$i];
// Starting position (in bytes) of the second part, immediately after the signature.
$offset2 = (int)$bytes['offset2'][$i];
$signatureStart = $offset1 + $length1 + 1;
$signatureLength = $offset2 - $signatureStart - 1;
rewind($resource);
$signature = stream_get_contents($resource, $signatureLength, $signatureStart);
yield hex2bin($signature);
}
$this->tempManager->clean();
}
/**
* @param resource $resource
* @throws LibresignException When is not a signed file
* @return array
*/
public function getCertificateChain($resource): array {
$signerCounter = 0;
$certificates = [];
foreach ($this->getSignatures($resource) as $signature) {
// The signature could be invalid
$fromFallback = $this->popplerUtilsPdfSignFallback($resource, $signerCounter);
if ($fromFallback) {
$certificates[$signerCounter] = $fromFallback;
}
if (!$signature) {
$certificates[$signerCounter]['chain'][0]['signature_validation'] = $this->getReadableSigState('Digest Mismatch.');
$signerCounter++;
continue;
}
if (!isset($fromFallback['signingTime'])) {
// Probably the best way to do this would be:
// ASN1::asn1map($decoded[0], Maps\TheMapName::MAP);
// But, what's the MAP to use?
//
// With maps also could be possible read all certificate data and
// maybe discart openssl at this pint
try {
$decoded = ASN1::decodeBER($signature);
$certificates[$signerCounter]['signingTime'] = $decoded[0]['content'][1]['content'][0]['content'][4]['content'][0]['content'][3]['content'][1]['content'][1]['content'][0]['content'];
} catch (\Throwable $th) {
}
}
$pkcs7PemSignature = $this->der2pem($signature);
if (openssl_pkcs7_read($pkcs7PemSignature, $pemCertificates)) {
foreach ($pemCertificates as $certificateIndex => $pemCertificate) {
$parsed = openssl_x509_parse($pemCertificate);
foreach ($parsed as $key => $value) {
if (!isset($certificates[$signerCounter]['chain'][$certificateIndex][$key])) {
$certificates[$signerCounter]['chain'][$certificateIndex][$key] = $value;
} elseif ($key === 'name') {
$certificates[$signerCounter]['chain'][$certificateIndex][$key] = $value;
} elseif ($key === 'signatureTypeSN' && $certificates[$signerCounter]['chain'][$certificateIndex][$key] !== $value) {
$certificates[$signerCounter]['chain'][$certificateIndex][$key] = $value;
}
}
if (empty($certificates[$signerCounter]['chain'][$certificateIndex]['signature_validation'])) {
$certificates[$signerCounter]['chain'][$certificateIndex]['signature_validation'] = [
'id' => 1,
'label' => $this->l10n->t('Signature is valid.'),
];
}
}
};
$certificates[$signerCounter]['chain'] = $this->orderCertificates($certificates[$signerCounter]['chain']);
$signerCounter++;
}
return $certificates;
}
private function popplerUtilsPdfSignFallback($resource, int $signerCounter): array {
if (shell_exec('which pdfsig') === null) {
return [];
}
if (!empty($this->signaturesFromPoppler)) {
if (isset($this->signaturesFromPoppler[$signerCounter])) {
return $this->signaturesFromPoppler[$signerCounter];
}
return [];
}
rewind($resource);
$content = stream_get_contents($resource);
$tempFile = $this->tempManager->getTemporaryFile('file.pdf');
file_put_contents($tempFile, $content);
$content = shell_exec('pdfsig ' . $tempFile);
if (empty($content)) {
return [];
}
$lines = explode("\n", $content);
$lastSignature = 0;
foreach ($lines as $item) {
$isFirstLevel = preg_match('/^Signature\s#(\d)/', $item, $match);
if ($isFirstLevel) {
$lastSignature = (int)$match[1] - 1;
$this->signaturesFromPoppler[$lastSignature] = [];
continue;
}
$match = [];
$isSecondLevel = preg_match('/^\s+-\s(?<key>.+):\s(?<value>.*)/', $item, $match);
if ($isSecondLevel) {
switch ((string)$match['key']) {
case 'Signing Time':
$this->signaturesFromPoppler[$lastSignature]['signingTime'] = DateTime::createFromFormat('M d Y H:i:s', $match['value']);
break;
case 'Signer full Distinguished Name':
$this->signaturesFromPoppler[$lastSignature]['chain'][0]['subject'] = $this->parseDistinguishedNameWithMultipleValues($match['value']);
$this->signaturesFromPoppler[$lastSignature]['chain'][0]['name'] = $match['value'];
break;
case 'Signing Hash Algorithm':
$this->signaturesFromPoppler[$lastSignature]['chain'][0]['signatureTypeSN'] = $match['value'];
break;
case 'Signature Validation':
$this->signaturesFromPoppler[$lastSignature]['chain'][0]['signature_validation'] = $this->getReadableSigState($match['value']);
break;
case 'Certificate Validation':
$this->signaturesFromPoppler[$lastSignature]['chain'][0]['certificate_validation'] = $this->getReadableCertState($match['value']);
break;
case 'Signed Ranges':
preg_match('/\[(\d+) - (\d+)\], \[(\d+) - (\d+)\]/', $match['value'], $ranges);
$this->signaturesFromPoppler[$lastSignature]['chain'][0]['range'] = [
'offset1' => (int)$ranges[1],
'length1' => (int)$ranges[2],
'offset2' => (int)$ranges[3],
'length2' => (int)$ranges[4],
];
break;
case 'Signature Field Name':
$this->signaturesFromPoppler[$lastSignature]['chain'][0]['field'] = $match['value'];
break;
case 'Signature Validation':
case 'Signature Type':
case 'Total document signed':
case 'Not total document signed':
default:
break;
}
}
}
if (isset($this->signaturesFromPoppler[$signerCounter])) {
return $this->signaturesFromPoppler[$signerCounter];
}
return [];
}
private function getReadableSigState(string $status) {
switch ($status) {
case 'Signature is Valid.':
return [
'id' => 1,
'label' => $this->l10n->t('Signature is valid.'),
];
case 'Signature is Invalid.':
return [
'id' => 2,
'label' => $this->l10n->t('Signature is invalid.'),
];
case 'Digest Mismatch.':
return [
'id' => 3,
'label' => $this->l10n->t('Digest mismatch.'),
];
case "Document isn't signed or corrupted data.":
return [
'id' => 4,
'label' => $this->l10n->t("Document isn't signed or corrupted data."),
];
case 'Signature has not yet been verified.':
return [
'id' => 5,
'label' => $this->l10n->t('Signature has not yet been verified.'),
];
default:
return [
'id' => 6,
'label' => $this->l10n->t('Unknown validation failure.'),
];
}
}
private function getReadableCertState(string $status) {
switch ($status) {
case 'Certificate is Trusted.':
return [
'id' => 1,
'label' => $this->l10n->t('Certificate is trusted.'),
];
case "Certificate issuer isn't Trusted.":
return [
'id' => 2,
'label' => $this->l10n->t("Certificate issuer isn't trusted."),
];
case 'Certificate issuer is unknown.':
return [
'id' => 3,
'label' => $this->l10n->t('Certificate issuer is unknown.'),
];
case 'Certificate has been Revoked.':
return [
'id' => 4,
'label' => $this->l10n->t('Certificate has been revoked.'),
];
case 'Certificate has Expired':
return [
'id' => 5,
'label' => $this->l10n->t('Certificate has expired'),
];
case 'Certificate has not yet been verified.':
return [
'id' => 6,
'label' => $this->l10n->t('Certificate has not yet been verified.'),
];
default:
return [
'id' => 7,
'label' => $this->l10n->t('Unknown issue with Certificate or corrupted data.')
];
}
}
private function parseDistinguishedNameWithMultipleValues(string $dn): array {
$result = [];
$pairs = preg_split('/,(?=(?:[^"]*"[^"]*")*[^"]*$)/', $dn);
foreach ($pairs as $pair) {
[$key, $value] = explode('=', $pair, 2);
$key = trim($key);
$value = trim($value);
$value = trim($value, '"');
if (!isset($result[$key])) {
$result[$key] = $value;
} else {
if (!is_array($result[$key])) {
$result[$key] = [$result[$key]];
}
$result[$key][] = $value;
}
}
return $result;
}
private function der2pem($derData) {
$pem = chunk_split(base64_encode($derData), 64, "\n");
$pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
return $pem;
}
/**
* Get content of pfx file
*/
public function getPfxOfCurrentSigner(?string $uid = null): string {
if (!empty($this->certificate) || empty($uid)) {
return $this->certificate;
}
$this->folderService->setUserId($uid);
$folder = $this->folderService->getFolder();
if (!$folder->nodeExists($this->pfxFilename)) {
throw new LibresignException($this->l10n->t('Password to sign not defined. Create a password to sign.'), 400);
}
try {
/** @var \OCP\Files\File */
$node = $folder->get($this->pfxFilename);
$this->certificate = $node->getContent();
} catch (GenericFileException $e) {
throw new LibresignException($this->l10n->t('Password to sign not defined. Create a password to sign.'), 400);
} catch (\Throwable $th) {
}
if (empty($this->certificate)) {
throw new LibresignException($this->l10n->t('Password to sign not defined. Create a password to sign.'), 400);
}
if ($this->getPassword()) {
try {
$this->certificateEngineFactory->getEngine()->readCertificate($this->certificate, $this->getPassword());
} catch (InvalidPasswordException $e) {
throw new LibresignException($this->l10n->t('Invalid password'));
}
}
return $this->certificate;
}
private function getHandler(): SignEngineHandler {
$sign_engine = $this->appConfig->getValueString(Application::APP_ID, 'sign_engine', 'JSignPdf');
$property = lcfirst($sign_engine) . 'Handler';
if (!property_exists($this, $property)) {
throw new LibresignException($this->l10n->t('Invalid Sign engine.'), 400);
}
$classHandler = 'OCA\\Libresign\\Handler\\SignEngine\\' . ucfirst($property);
if (!$this->$property instanceof $classHandler) {
$this->$property = \OCP\Server::get($classHandler);
}
return $this->$property;
}
public function sign(): File {
$signedContent = $this->getHandler()
->setCertificate($this->getCertificate())
->setInputFile($this->getInputFile())
->setPassword($this->getPassword())
->setSignatureParams($this->getSignatureParams())
->setVisibleElements($this->getVisibleElements())
->setReason($this->getReason())
->getSignedContent();
$this->getInputFile()->putContent($signedContent);
return $this->getInputFile();
}
public function isHandlerOk(): bool {
return $this->certificateEngineFactory->getEngine()->isSetupOk();
}
/**
* Generate certificate
*
* @param array $user Example: ['host' => '', 'name' => '']
* @param string $signPassword Password of signature
* @param string $friendlyName Friendly name
*/
public function generateCertificate(array $user, string $signPassword, string $friendlyName): string {
$content = $this->certificateEngineFactory->getEngine()
->setHosts([$user['host']])
->setCommonName($user['name'])
->setFriendlyName($friendlyName)
->setUID($user['uid'])
->setPassword($signPassword)
->generateCertificate();
if (!$content) {
throw new TypeError();
}
return $content;
}
}