1: <?php
2: /**
3: * Seal.php
4: *
5: * Copyright © 2017-2026 - Thierry Thiers <webcoder31@gmail.com>
6: *
7: * This software is governed by the CeCILL-C license under French law and
8: * abiding by the rules of distribution of free software. You can use, modify
9: * and/or redistribute the software under the terms of the CeCILL-C license as
10: * circulated by CEA, CNRS and INRIA at the following URL:
11: *
12: * http://www.cecill.info
13: *
14: * As a counterpart to the access to the source code and rights to copy, modify
15: * and redistribute granted by the license, users are provided only with a
16: * limited warranty and the software's author, the holder of the economic
17: * rights, and the successive licensors have only limited liability.
18: *
19: * In this respect, the user's attention is drawn to the risks associated with
20: * loading, using, modifying and/or developing or reproducing the software by
21: * the user in light of its specific status of free software, that may mean that
22: * it is complicated to manipulate, and that also therefore means that it is
23: * reserved for developers and experienced professionals having in-depth
24: * computer knowledge. Users are therefore encouraged to load and test the
25: * software's suitability as regards their requirements in conditions enabling
26: * the security of their systems and/or data to be ensured and, more generally,
27: * to use and operate it in the same conditions as regards security.
28: *
29: * The fact that you are presently reading this means that you have had
30: * knowledge of the CeCILL-C license and that you accept its terms.
31: *
32: * @author Thierry Thiers <webcoder31@gmail.com>
33: * @copyright 2017-2026 - Thierry Thiers <webcoder31@gmail.com>
34: * @license http://www.cecill.info CeCILL-C License
35: * @version 2.1.0
36: */
37:
38:
39: // Namespace.
40: namespace webcoder31\ezxmldsig\seal;
41:
42: // Use.
43: use DOMDocument;
44: use DOMElement;
45: use Exception;
46: use webcoder31\ezxmldsig\core\Algorithms;
47: use webcoder31\ezxmldsig\core\Der;
48: use webcoder31\ezxmldsig\core\X509Cert;
49: use webcoder31\ezxmldsig\core\Xml;
50:
51: /**
52: * Seals of files: an ASiC-E container (ETSI EN 319 162-1) holding the files
53: * and one detached XAdES baseline signature over them (ETSI EN 319 132-1),
54: * at level B, T (a signature time-stamp, RFC 3161) or LT (the certificates,
55: * CRLs and OCSP responses that validate it, embedded). The Node.js library
56: * ezxmldsig-js creates and verifies the same seals; its design document,
57: * design/seal.md, gives the structure and the rules followed.
58: *
59: * The seals are an experimental feature of the 2.x versions: their API may
60: * change in a minor version.
61: */
62: class Seal
63: {
64: const XMLDSIG_NS = 'http://www.w3.org/2000/09/xmldsig#';
65: const ASIC_NS = 'http://uri.etsi.org/02918/v1.2.1#';
66: const XADES_NS = 'http://uri.etsi.org/01903/v1.3.2#';
67: /** The namespace of the properties XAdES 1.4.1 added, such as TimeStampValidationData. */
68: const XADES141_NS = 'http://uri.etsi.org/01903/v1.4.1#';
69: const MANIFEST_NS = 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0';
70: const SIGNED_PROPERTIES_TYPE = 'http://uri.etsi.org/01903#SignedProperties';
71: const ASICE_MIMETYPE = 'application/vnd.etsi.asic-e+zip';
72:
73: /** The path of the signature in the container. */
74: const SIGNATURE_PATH = 'META-INF/signatures001.xml';
75: const MANIFEST_PATH = 'META-INF/manifest.xml';
76:
77: /** The canonicalizations accepted for SignedInfo and the signed properties. */
78: const CANONICALIZATIONS = [Algorithms::EXC_C14N, Algorithms::C14N];
79:
80:
81: /**
82: * Verify a seal.
83: *
84: * The structure is read strictly: every element of the signature is
85: * where the baseline puts it, once, and anything this library does not
86: * process (a signature policy, a manifest of references, a transform)
87: * makes the seal invalid rather than ignored. A seal is valid only if
88: * every file of the container outside META-INF is covered, so that a
89: * file added to a sealed container cannot pass for a sealed one.
90: *
91: * The signing certificate is trusted at the time of the signature
92: * time-stamp, if any, and at the current date otherwise: SigningTime is
93: * claimed by the signer, and cannot date the check of its certificate.
94: * The certificate of the time-stamping authority is checked at the
95: * current date. The revocation of the certificates is checked, by CRLs
96: * or OCSP responses, unless 'revocation' is FALSE: the library sends no
97: * request, the data come from the seal (level LT) and from the options.
98: *
99: * @param string $container The ASiC-E container.
100: *
101: * @param array $options
102: * - 'caCertPath' (required): the trusted CA certificates, paths of
103: * PEM files or PEM contents: the root of the signer, and the
104: * intermediate CAs if the seal does not embed them;
105: * - 'tsaCertPath': the trusted certificates of the time-stamping
106: * authorities, required to verify a time-stamped seal;
107: * - 'expectedSubject': the subject the signing certificate must
108: * have, its DN as X509Cert::getDN() gives it, or fields that
109: * must all match (see XMLDSigToken's option of the same name);
110: * - 'revocation': whether the revocation is checked (default
111: * TRUE);
112: * - 'crls': CRLs, in DER or PEM, for the certificates of the
113: * signer and of the time-stamping authority, used besides those
114: * of a seal of level LT;
115: * - 'ocspResponses': OCSP responses (DER), likewise;
116: * - 'maxEntries', 'maxTotalSize': the limits of the reading of
117: * the container (default 1000 entries, 512 MiB uncompressed).
118: *
119: * @return SealVerification The result. An invalid seal does not throw:
120: * see its getError().
121: *
122: * @throws Exception On a misuse: the options are not valid, or a CA
123: * certificate cannot be read.
124: */
125: public static function verifySeal($container, array $options)
126: {
127: return self::inspectSeal($container, $options)['result'];
128: }
129:
130:
131: /**
132: * verifySeal(), with what the extension of a seal needs: the chains, the
133: * certificates the signature and its time-stamp hold, and the sources
134: * that told the status of each chain.
135: *
136: * @internal
137: */
138: public static function inspectSeal($container, array $options, $forLevelLT = false)
139: {
140: if (!is_string($container))
141: {
142: throw new Exception('Seal verification: the container must be bytes (a string).');
143: }
144: $caCerts = self::readCertificates(isset($options['caCertPath']) ? $options['caCertPath'] : null, 'caCertPath');
145: $tsaCerts = isset($options['tsaCertPath']) ? self::readCertificates($options['tsaCertPath'], 'tsaCertPath') : null;
146: $expectedSubject = isset($options['expectedSubject']) ? $options['expectedSubject'] : null;
147: if (array_key_exists('expectedSubject', $options) && ((!is_string($expectedSubject) && !is_array($expectedSubject)) || '' === $expectedSubject || [] === $expectedSubject))
148: {
149: throw new Exception("Seal verification: invalid option 'expectedSubject'.");
150: }
151: $revocation = array_key_exists('revocation', $options) ? $options['revocation'] : true;
152: if (!is_bool($revocation))
153: {
154: throw new Exception("Seal verification: invalid option 'revocation'.");
155: }
156: foreach (['crls' => 'CRLs', 'ocspResponses' => 'OCSP responses'] as $name => $what)
157: {
158: if (isset($options[$name]) && (!is_array($options[$name]) || count(array_filter($options[$name], 'is_string')) !== count($options[$name])))
159: {
160: throw new Exception("Seal verification: invalid option '" . $name . "': an array of " . $what . ' (strings).');
161: }
162: }
163: $given = [];
164: foreach (isset($options['crls']) ? $options['crls'] : [] as $crl)
165: {
166: try
167: {
168: $given[] = Crl::source(Crl::read($crl));
169: }
170: catch (Exception $e)
171: {
172: throw new Exception('Seal verification: a CRL cannot be used. ' . $e->getMessage());
173: }
174: }
175: foreach (isset($options['ocspResponses']) ? $options['ocspResponses'] : [] as $response)
176: {
177: try
178: {
179: $given = array_merge($given, Ocsp::sources(Ocsp::read($response)));
180: }
181: catch (Exception $e)
182: {
183: throw new Exception('Seal verification: an OCSP response cannot be used. ' . $e->getMessage());
184: }
185: }
186: $maxEntries = isset($options['maxEntries']) ? $options['maxEntries'] : Zip::MAX_ENTRIES;
187: $maxTotalSize = isset($options['maxTotalSize']) ? $options['maxTotalSize'] : Zip::MAX_TOTAL_SIZE;
188:
189: $signer = null;
190: $signingTime = null;
191: $found = ['chain' => null, 'tsaChain' => null, 'keyInfo' => [], 'tokenCertificates' => [], 'signerSources' => [], 'tsaSources' => [], 'hasValidationData' => false];
192: try
193: {
194: list($files, $signatureFile) = self::readContainer($container, $maxEntries, $maxTotalSize);
195: $signature = self::readSignature($signatureFile, $files);
196: $signer = $signature['signer'];
197: $signingTime = $signature['signingTime'];
198: $validationData = null === $signature['validationData'] ? null : self::readValidationData($signature['validationData']);
199:
200: // The signature time-stamp proves that the signature existed at
201: // its time: the certificates of the signer are checked at that
202: // time. The certificate of the authority is checked at the
203: // current date: only a time-stamp over the time-stamp (level LTA)
204: // would check it at an earlier one.
205: $timestampTime = null;
206: $tsaChain = null;
207: $tokenCertificates = [];
208: if (null !== $signature['timestamp'])
209: {
210: if (null === $tsaCerts)
211: {
212: self::invalid("The seal is time-stamped: the option 'tsaCertPath' is needed to trust its time-stamping authority.");
213: }
214: list($timestampTime, $tsaChain, $tokenCertificates) = self::checkTimestamp($signature['timestamp'], $tsaCerts, null === $validationData ? [] : $validationData['certificates']);
215: }
216: elseif (null !== $validationData)
217: {
218: self::invalid('The seal has validation data but no signature time-stamp: level LT is time-stamped.');
219: }
220:
221: // Without time-stamp, the trust in the signer is checked at the
222: // current date: SigningTime is claimed by the signer, and cannot
223: // date the check of its certificate.
224: $certificate = $signature['signer'];
225: if (!$certificate->canSign())
226: {
227: self::invalid('The key usage of the signing certificate does not allow signing.');
228: }
229: $untrusted = array_merge($signature['chain'], null === $validationData ? [] : $validationData['certificates']);
230: $chain = $certificate->getTrustedChain($caCerts, $untrusted, $timestampTime);
231: if (null === $chain)
232: {
233: self::invalid('The signing certificate is not trusted: no valid chain up to a trusted CA certificate' . (null === $timestampTime ? '' : ' at the time of the time-stamp') . '.');
234: }
235: if (null !== $expectedSubject)
236: {
237: $matches = is_string($expectedSubject) ? $certificate->getDN() === $expectedSubject : X509Cert::matchesName($certificate->getSubject(), $expectedSubject);
238: if (!$matches)
239: {
240: self::invalid('The subject of the signing certificate is not the expected one.');
241: }
242: }
243: $found = ['chain' => $chain, 'tsaChain' => $tsaChain, 'keyInfo' => $signature['keyInfo'], 'tokenCertificates' => $tokenCertificates, 'hasValidationData' => null !== $validationData] + $found;
244:
245: if ($revocation)
246: {
247: // The signer: from the time of the time-stamp, if any. The
248: // time-stamping authority: at the current date, unless the
249: // seal embeds its validation data, which are no longer
250: // current when it is verified.
251: $now = time();
252: $signerCheck = ['now' => $now, 'issuedAfter' => $timestampTime, 'time' => $timestampTime];
253: $tsaCheck = ['now' => $now, 'issuedAfter' => null === $validationData && !$forLevelLT ? null : $timestampTime, 'time' => $timestampTime, 'authority' => true];
254: $run = function (array $pool) use ($chain, $tsaChain, $signerCheck, $tsaCheck)
255: {
256: $ofSigner = Revocation::check($chain, $pool, $signerCheck);
257: $ofAuthority = null === $tsaChain ? null : Revocation::check($tsaChain, $pool, $tsaCheck);
258: $error = null !== $ofSigner['error'] ? $ofSigner['error'] : (null === $ofAuthority ? null : $ofAuthority['error']);
259: return ['error' => $error, 'signerSources' => $ofSigner['used'], 'tsaSources' => null === $ofAuthority ? [] : $ofAuthority['used']];
260: };
261: if (null !== $validationData)
262: {
263: // Level LT: the embedded data must suffice by themselves.
264: $own = $run($validationData['sources']);
265: if (null !== $own['error'])
266: {
267: self::invalid('The validation data of the seal do not suffice. ' . $own['error']);
268: }
269: $found['signerSources'] = $own['signerSources'];
270: $found['tsaSources'] = $own['tsaSources'];
271: }
272: if (null === $validationData || !empty($given))
273: {
274: $all = $run(array_merge(null === $validationData ? [] : $validationData['sources'], $given));
275: if (null !== $all['error'])
276: {
277: self::invalid($all['error'] . (null === $validationData ? " (the option 'revocation' => false verifies the seal without revocation.)" : ''));
278: }
279: if (null === $validationData)
280: {
281: $found['signerSources'] = $all['signerSources'];
282: $found['tsaSources'] = $all['tsaSources'];
283: }
284: }
285: }
286: $level = null === $timestampTime ? 'B' : (null === $validationData ? 'T' : 'LT');
287:
288: return ['result' => new SealVerification([
289: 'error' => null,
290: 'files' => $signature['files'],
291: 'signingTime' => $signingTime,
292: 'signer' => $signer,
293: 'revocationChecked' => $revocation,
294: 'timestampTime' => $timestampTime,
295: 'level' => $level,
296: ])] + $found;
297: }
298: catch (InvalidSeal $e)
299: {
300: return ['result' => new SealVerification(['error' => $e->getMessage(), 'signingTime' => $signingTime, 'signer' => $signer])] + $found;
301: }
302: }
303:
304:
305: /**
306: * @throws InvalidSeal Always.
307: */
308: private static function invalid($message)
309: {
310: throw new InvalidSeal($message);
311: }
312:
313:
314: /**
315: * A value between double quotes, for the messages, as JSON writes it
316: * but without escaping slashes and non-ASCII characters.
317: */
318: private static function quote($value)
319: {
320: return json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
321: }
322:
323:
324: /**
325: * Bytes read as ISO-8859-1 (each byte a character), in UTF-8, for a
326: * message.
327: */
328: private static function latin1($bytes)
329: {
330: return preg_replace_callback('/[\x80-\xff]/', function ($m) { $c = ord($m[0]); return chr(0xc0 | ($c >> 6)) . chr(0x80 | ($c & 0x3f)); }, $bytes);
331: }
332:
333:
334: /**
335: * The PEM contents of trusted certificates given as an option: paths of
336: * PEM files or PEM contents.
337: *
338: * @throws Exception If the option is missing or a file cannot be read.
339: */
340: private static function readCertificates($source, $name)
341: {
342: $sources = is_array($source) ? $source : [$source];
343: if (null === $source || empty($sources))
344: {
345: throw new Exception("Seal verification: the option '" . $name . "' is required.");
346: }
347: $pems = [];
348: foreach ($sources as $item)
349: {
350: if (is_string($item) && false !== strpos($item, '-----BEGIN'))
351: {
352: $pems[] = $item;
353: continue;
354: }
355: $pem = is_string($item) && is_file($item) && is_readable($item) ? file_get_contents($item) : false;
356: if (false === $pem)
357: {
358: throw new Exception('Seal verification: cannot read the certificate file ' . (is_string($item) ? $item : gettype($item)) . " ('" . $name . "').");
359: }
360: $pems[] = $pem;
361: }
362:
363: return $pems;
364: }
365:
366:
367: /**
368: * The validation data the seal embeds, read.
369: */
370: private static function readValidationData(array $data)
371: {
372: $certificates = [];
373: foreach ($data['certificates'] as $der)
374: {
375: try
376: {
377: $certificates[] = new X509Cert(X509Cert::derToPem($der));
378: }
379: catch (Exception $e)
380: {
381: self::invalid('A certificate of the validation data of the seal cannot be read.');
382: }
383: }
384: $sources = [];
385: foreach ($data['crls'] as $der)
386: {
387: try
388: {
389: $sources[] = Crl::source(Crl::read($der));
390: }
391: catch (Exception $e)
392: {
393: self::invalid('A CRL of the validation data of the seal cannot be used. ' . $e->getMessage());
394: }
395: }
396: foreach ($data['ocspResponses'] as $der)
397: {
398: try
399: {
400: $sources = array_merge($sources, Ocsp::sources(Ocsp::read($der)));
401: }
402: catch (Exception $e)
403: {
404: self::invalid('An OCSP response of the validation data of the seal cannot be used. ' . $e->getMessage());
405: }
406: }
407:
408: return ['certificates' => $certificates, 'sources' => $sources];
409: }
410:
411:
412: /**
413: * The signature time-stamp: a valid token, over this signature, of a
414: * trusted authority. Returns its time, the chain of the authority, and
415: * the DER of the certificates of the token.
416: */
417: private static function checkTimestamp(array $timestamp, array $tsaCerts, array $embedded)
418: {
419: try
420: {
421: $token = Timestamp::verifyToken($timestamp['token']);
422: }
423: catch (Exception $e)
424: {
425: self::invalid('The signature time-stamp is not valid. ' . $e->getMessage());
426: }
427: try
428: {
429: $imprint = self::imprintOf($timestamp['signatureValue'], $token['imprintAlgorithm'], $timestamp['canonicalization']);
430: }
431: catch (Exception $e)
432: {
433: self::invalid('The signature time-stamp cannot be checked. ' . $e->getMessage());
434: }
435: if (!hash_equals($token['imprint'], $imprint))
436: {
437: self::invalid('The signature time-stamp is not over the signature value of this seal.');
438: }
439: $chain = $token['certificate']->getTrustedChain($tsaCerts, array_merge($token['chain'], $embedded));
440: if (null === $chain)
441: {
442: self::invalid('The time-stamping authority is not trusted.');
443: }
444: $certificates = array_map(function (X509Cert $cert) { return $cert->getDer(); }, array_merge([$token['certificate']], $token['chain']));
445:
446: return [$token['time'], $chain, $certificates];
447: }
448:
449:
450: /**
451: * The imprint of the signature time-stamp: the digest of the canonical
452: * ds:SignatureValue (EN 319 132-1, 5.3).
453: *
454: * @internal
455: */
456: public static function imprintOf(DOMElement $signatureValue, $digest, $canonicalization)
457: {
458: return hash($digest, self::canonicalize($signatureValue, $canonicalization, 'ds:SignatureValue'), true);
459: }
460:
461:
462: /**
463: * Canonicalize an element in the context of its document. A
464: * canonicalization that fails or yields an empty string throws, so that
465: * a forged reference cannot be validated by the digest of an empty
466: * string. This check must not be removed.
467: *
468: * @throws Exception If the canonicalization fails or is empty.
469: */
470: private static function canonicalize(DOMElement $element, $algorithm, $what)
471: {
472: $exclusive = Algorithms::EXC_C14N === $algorithm || Algorithms::EXC_C14N_COMMENTS === $algorithm;
473: $withComments = Algorithms::C14N_COMMENTS === $algorithm || Algorithms::EXC_C14N_COMMENTS === $algorithm;
474: $data = $element->C14N($exclusive, $withComments);
475: if (!is_string($data) || '' === $data)
476: {
477: throw new Exception('Canonicalization of ' . $what . ' failed or is empty!');
478: }
479:
480: return $data;
481: }
482:
483:
484: /**
485: * The layout of the container (EN 319 162-1, 4.4.3.2, Table 5, A.1).
486: *
487: * @return array The files outside META-INF (name => content), and the
488: * signature file.
489: */
490: private static function readContainer($archive, $maxEntries, $maxTotalSize)
491: {
492: try
493: {
494: $entries = Zip::read($archive, $maxEntries, $maxTotalSize);
495: }
496: catch (Exception $e)
497: {
498: self::invalid('The container is not a valid ZIP archive. ' . $e->getMessage());
499: }
500: $files = [];
501: $signatureFiles = [];
502: $manifest = null;
503: foreach ($entries as $index => $entry)
504: {
505: if ('mimetype' === $entry['name'])
506: {
507: if (0 !== $index || 0 !== $entry['method'] || '' !== $entry['extra'])
508: {
509: self::invalid('The mimetype file must be the first entry, stored, without extra field.');
510: }
511: if (self::ASICE_MIMETYPE !== $entry['content'])
512: {
513: self::invalid('The container is not an ASiC-E container (mimetype ' . self::quote(self::latin1(substr($entry['content'], 0, 100))) . ').');
514: }
515: }
516: elseif (0 === strpos($entry['name'], 'META-INF/'))
517: {
518: $base = strtolower(substr($entry['name'], strlen('META-INF/')));
519: if (self::MANIFEST_PATH === $entry['name'])
520: {
521: $manifest = $entry;
522: }
523: elseif (false !== strpos($base, 'signatures') && '.xml' === substr($base, -4) && false === strpos($base, '/'))
524: {
525: $signatureFiles[] = $entry;
526: }
527: elseif (preg_match('/signature|timestamp|manifest|evidencerecord/', $base))
528: {
529: self::invalid('Unsupported file in META-INF: ' . self::quote($entry['name']) . ' (only XAdES signatures are supported).');
530: }
531: }
532: else
533: {
534: $files[$entry['name']] = $entry['content'];
535: }
536: }
537: if (null === $manifest)
538: {
539: self::invalid('The container has no META-INF/manifest.xml.');
540: }
541: self::checkManifest($manifest['content']);
542: if (1 !== count($signatureFiles))
543: {
544: self::invalid(empty($signatureFiles) ? 'The container has no signature file.' : 'The container has several signature files: one seal per container is supported.');
545: }
546: if (empty($files))
547: {
548: self::invalid('The container has no file outside META-INF.');
549: }
550:
551: return [$files, $signatureFiles[0]['content']];
552: }
553:
554:
555: /**
556: * The manifest must be an ODF manifest. It is not signed: the media
557: * types of the seal are those of its signature.
558: */
559: private static function checkManifest($content)
560: {
561: try
562: {
563: $doc = Xml::load($content, 'manifest');
564: }
565: catch (Exception $e)
566: {
567: self::invalid('The manifest is not valid: ' . $e->getMessage());
568: }
569: $root = $doc->documentElement;
570: if (null === $root || self::MANIFEST_NS !== $root->namespaceURI || 'manifest' !== $root->localName)
571: {
572: self::invalid('The manifest is not an ODF manifest.');
573: }
574: }
575:
576:
577: /**
578: * The XAdES signature (EN 319 132-1, level B-B): its structure, its
579: * references, its signed properties, its value.
580: */
581: private static function readSignature($content, array $files)
582: {
583: try
584: {
585: $doc = Xml::load($content, 'XAdES signature');
586: }
587: catch (Exception $e)
588: {
589: self::invalid('The signature file is not valid: ' . $e->getMessage());
590: }
591: $root = $doc->documentElement;
592: if (!self::is($root, self::ASIC_NS, 'XAdESSignatures'))
593: {
594: self::invalid('The root of the signature file must be asic:XAdESSignatures.');
595: }
596: $signature = self::sequence($root, [[self::XMLDSIG_NS, 'Signature', 1, PHP_INT_MAX]])['Signature'][0];
597: if (1 !== $root->getElementsByTagNameNS(self::XMLDSIG_NS, 'Signature')->length)
598: {
599: self::invalid('The signature file must hold one ds:Signature: one seal per container is supported.');
600: }
601: // With unique Ids, the reference to the signed properties has one
602: // target: the element whose digest is checked below.
603: self::uniqueIds($doc);
604: $signatureId = self::attribute($signature, 'Id', 'ds:Signature');
605:
606: $parts = self::sequence($signature, [
607: [self::XMLDSIG_NS, 'SignedInfo', 1, 1],
608: [self::XMLDSIG_NS, 'SignatureValue', 1, 1],
609: [self::XMLDSIG_NS, 'KeyInfo', 1, 1],
610: [self::XMLDSIG_NS, 'Object', 1, 1],
611: ]);
612: $signedInfo = $parts['SignedInfo'][0];
613: $info = self::sequence($signedInfo, [
614: [self::XMLDSIG_NS, 'CanonicalizationMethod', 1, 1],
615: [self::XMLDSIG_NS, 'SignatureMethod', 1, 1],
616: [self::XMLDSIG_NS, 'Reference', 2, PHP_INT_MAX],
617: ]);
618: $canonicalization = self::algorithmOf($info['CanonicalizationMethod'][0]);
619: if (!in_array($canonicalization, self::CANONICALIZATIONS, true))
620: {
621: self::invalid('Unsupported canonicalization of SignedInfo: ' . $canonicalization . '.');
622: }
623: $signatureAlgorithm = self::algorithmOf($info['SignatureMethod'][0]);
624: if (!isset(Policy::SIGNATURE_SCHEMES[$signatureAlgorithm]))
625: {
626: self::invalid('Unsupported signature algorithm: ' . $signatureAlgorithm . '.');
627: }
628: $scheme = Policy::SIGNATURE_SCHEMES[$signatureAlgorithm];
629:
630: // The qualifying properties, in the one ds:Object.
631: $qualifying = self::sequence($parts['Object'][0], [[self::XADES_NS, 'QualifyingProperties', 1, 1]])['QualifyingProperties'][0];
632: if ($qualifying->getAttribute('Target') !== '#' . $signatureId)
633: {
634: self::invalid('The Target of QualifyingProperties must be the Id of the signature.');
635: }
636: $qualifyingParts = self::sequence($qualifying, [
637: [self::XADES_NS, 'SignedProperties', 1, 1],
638: [self::XADES_NS, 'UnsignedProperties', 0, 1],
639: ]);
640: $timestamp = null;
641: $validationData = null;
642: if (!empty($qualifyingParts['UnsignedProperties']))
643: {
644: $unsignedSignature = self::sequence($qualifyingParts['UnsignedProperties'][0], [[self::XADES_NS, 'UnsignedSignatureProperties', 1, 1]])['UnsignedSignatureProperties'][0];
645: // Level LT: the validation data of the time-stamp right after it
646: // (5.5.1.2), then those of the signer (5.4.2, 5.4.3).
647: $timestamps = self::sequence($unsignedSignature, [
648: [self::XADES_NS, 'SignatureTimeStamp', 1, 1],
649: [self::XADES141_NS, 'TimeStampValidationData', 0, 1],
650: [self::XADES_NS, 'CertificateValues', 0, 1],
651: [self::XADES_NS, 'RevocationValues', 0, 1],
652: ]);
653: $holders = [];
654: foreach ($timestamps['TimeStampValidationData'] as $element)
655: {
656: $holderParts = self::sequence($element, [[self::XADES_NS, 'CertificateValues', 0, 1], [self::XADES_NS, 'RevocationValues', 0, 1]]);
657: $holders = array_merge($holders, $holderParts['CertificateValues'], $holderParts['RevocationValues']);
658: }
659: $holders = array_merge($holders, $timestamps['CertificateValues'], $timestamps['RevocationValues']);
660: if (!empty($timestamps['TimeStampValidationData']) && empty($holders))
661: {
662: self::invalid('The xades141:TimeStampValidationData of the seal is empty.');
663: }
664: if (!empty($holders))
665: {
666: $validationData = ['certificates' => [], 'crls' => [], 'ocspResponses' => []];
667: foreach ($holders as $holder)
668: {
669: if ('CertificateValues' === $holder->localName)
670: {
671: foreach (self::sequence($holder, [[self::XADES_NS, 'EncapsulatedX509Certificate', 1, PHP_INT_MAX]])['EncapsulatedX509Certificate'] as $value)
672: {
673: $validationData['certificates'][] = self::encapsulated($value, 'an EncapsulatedX509Certificate');
674: }
675: }
676: else
677: {
678: $kinds = self::sequence($holder, [[self::XADES_NS, 'CRLValues', 0, 1], [self::XADES_NS, 'OCSPValues', 0, 1]]);
679: if (empty($kinds['CRLValues']) && empty($kinds['OCSPValues']))
680: {
681: self::invalid('Missing xades:CRLValues or xades:OCSPValues in xades:RevocationValues.');
682: }
683: foreach ($kinds['OCSPValues'] as $values)
684: {
685: foreach (self::sequence($values, [[self::XADES_NS, 'EncapsulatedOCSPValue', 1, PHP_INT_MAX]])['EncapsulatedOCSPValue'] as $value)
686: {
687: $validationData['ocspResponses'][] = self::encapsulated($value, 'an EncapsulatedOCSPValue');
688: }
689: }
690: foreach ($kinds['CRLValues'] as $values)
691: {
692: foreach (self::sequence($values, [[self::XADES_NS, 'EncapsulatedCRLValue', 1, PHP_INT_MAX]])['EncapsulatedCRLValue'] as $value)
693: {
694: $validationData['crls'][] = self::encapsulated($value, 'an EncapsulatedCRLValue');
695: }
696: }
697: }
698: }
699: }
700: $timestampParts = self::sequence($timestamps['SignatureTimeStamp'][0], [
701: // Required: EN 319 132-1, 4.5, sets no default for the new signatures.
702: [self::XMLDSIG_NS, 'CanonicalizationMethod', 1, 1],
703: [self::XADES_NS, 'EncapsulatedTimeStamp', 1, 1],
704: ]);
705: $timestampCanonicalization = self::algorithmOf($timestampParts['CanonicalizationMethod'][0]);
706: if (!in_array($timestampCanonicalization, self::CANONICALIZATIONS, true))
707: {
708: self::invalid('Unsupported canonicalization of the signature time-stamp: ' . $timestampCanonicalization . '.');
709: }
710: $timestamp = ['token' => self::encapsulated($timestampParts['EncapsulatedTimeStamp'][0], 'the EncapsulatedTimeStamp'), 'canonicalization' => $timestampCanonicalization];
711: }
712: $signedProperties = $qualifyingParts['SignedProperties'][0];
713: $signedPropertiesId = self::attribute($signedProperties, 'Id', 'xades:SignedProperties');
714: $properties = self::sequence($signedProperties, [
715: [self::XADES_NS, 'SignedSignatureProperties', 1, 1],
716: [self::XADES_NS, 'SignedDataObjectProperties', 1, 1],
717: ]);
718: $signatureProperties = self::sequence($properties['SignedSignatureProperties'][0], [
719: [self::XADES_NS, 'SigningTime', 1, 1],
720: [self::XADES_NS, 'SigningCertificateV2', 1, 1],
721: [self::XADES_NS, 'SignatureProductionPlaceV2', 0, 1],
722: [self::XADES_NS, 'SignerRoleV2', 0, 1],
723: ]);
724: $signingTime = self::parseDateTime(self::text($signatureProperties['SigningTime'][0]));
725: $cert = self::sequence($signatureProperties['SigningCertificateV2'][0], [[self::XADES_NS, 'Cert', 1, 1]])['Cert'][0];
726: $certDigest = self::sequence($cert, [[self::XADES_NS, 'CertDigest', 1, 1], [self::XADES_NS, 'IssuerSerialV2', 0, 1]])['CertDigest'][0];
727: $certDigestParts = self::sequence($certDigest, [[self::XMLDSIG_NS, 'DigestMethod', 1, 1], [self::XMLDSIG_NS, 'DigestValue', 1, 1]]);
728: $certDigestAlgorithm = self::digestOf($certDigestParts['DigestMethod'][0]);
729: $certDigestValue = self::base64(self::text($certDigestParts['DigestValue'][0]), 'the digest of the signing certificate');
730: $formats = self::sequence($properties['SignedDataObjectProperties'][0], [
731: [self::XADES_NS, 'DataObjectFormat', 1, PHP_INT_MAX],
732: [self::XADES_NS, 'CommitmentTypeIndication', 0, PHP_INT_MAX],
733: ])['DataObjectFormat'];
734: $mimeTypes = [];
735: foreach ($formats as $format)
736: {
737: $target = $format->getAttribute('ObjectReference');
738: $formatParts = self::sequence($format, [
739: [self::XADES_NS, 'Description', 0, 1],
740: [self::XADES_NS, 'ObjectIdentifier', 0, 1],
741: [self::XADES_NS, 'MimeType', 1, 1],
742: [self::XADES_NS, 'Encoding', 0, 1],
743: ]);
744: if ('#' !== substr($target, 0, 1) || array_key_exists(substr($target, 1), $mimeTypes))
745: {
746: self::invalid('Each DataObjectFormat must point at a reference of its own.');
747: }
748: $mimeTypes[(string) substr($target, 1)] = self::text($formatParts['MimeType'][0]);
749: }
750:
751: // The signing certificate, and the chain the seal embeds.
752: $x509Data = self::sequence(self::sequence($parts['KeyInfo'][0], [[self::XMLDSIG_NS, 'X509Data', 1, 1]])['X509Data'][0], [
753: [self::XMLDSIG_NS, 'X509Certificate', 1, PHP_INT_MAX],
754: ])['X509Certificate'];
755: $certificates = [];
756: foreach ($x509Data as $element)
757: {
758: $certificates[] = self::base64(self::text($element), 'a certificate of KeyInfo');
759: }
760: $signerDer = null;
761: foreach ($certificates as $der)
762: {
763: if (hash_equals($certDigestValue, hash($certDigestAlgorithm, $der, true)))
764: {
765: $signerDer = $der;
766: break;
767: }
768: }
769: if (null === $signerDer)
770: {
771: self::invalid('The signing certificate (SigningCertificateV2) is not in KeyInfo.');
772: }
773: try
774: {
775: $signer = new X509Cert(X509Cert::derToPem($signerDer));
776: $publicKey = openssl_pkey_get_public($signer->getPem());
777: $chain = [];
778: foreach ($certificates as $der)
779: {
780: if ($der !== $signerDer)
781: {
782: $chain[] = new X509Cert(X509Cert::derToPem($der));
783: }
784: }
785: }
786: catch (Exception $e)
787: {
788: self::invalid('A certificate of KeyInfo cannot be read.');
789: }
790: if (false === $publicKey)
791: {
792: self::invalid('A certificate of KeyInfo cannot be read.');
793: }
794: self::checkSigningKey($publicKey, $signatureAlgorithm, $scheme);
795:
796: // The references: the signed properties once, then each file of the
797: // container once.
798: $sealed = [];
799: $covered = [];
800: $propertiesReferences = 0;
801: foreach ($info['Reference'] as $reference)
802: {
803: $referenceParts = self::sequence($reference, [
804: [self::XMLDSIG_NS, 'Transforms', 0, 1],
805: [self::XMLDSIG_NS, 'DigestMethod', 1, 1],
806: [self::XMLDSIG_NS, 'DigestValue', 1, 1],
807: ]);
808: $digest = self::digestOf($referenceParts['DigestMethod'][0]);
809: $expected = self::base64(self::text($referenceParts['DigestValue'][0]), 'a DigestValue');
810: $transforms = $referenceParts['Transforms'];
811: $uri = $reference->hasAttribute('URI') ? $reference->getAttribute('URI') : null;
812: $type = $reference->hasAttribute('Type') ? $reference->getAttribute('Type') : null;
813: if (self::SIGNED_PROPERTIES_TYPE === $type)
814: {
815: $propertiesReferences++;
816: if ($uri !== '#' . $signedPropertiesId)
817: {
818: self::invalid('The reference of type SignedProperties must point at the signed properties of the signature.');
819: }
820: if (1 !== count($transforms))
821: {
822: self::invalid('The reference to the signed properties must canonicalize them (one Transform).');
823: }
824: $transform = self::sequence($transforms[0], [[self::XMLDSIG_NS, 'Transform', 1, 1]])['Transform'][0];
825: $transformAlgorithm = self::algorithmOf($transform);
826: if (!in_array($transformAlgorithm, self::CANONICALIZATIONS, true) || null !== $transform->firstChild)
827: {
828: self::invalid('Unsupported transform of the signed properties: ' . $transformAlgorithm . '.');
829: }
830: try
831: {
832: $computed = hash($digest, self::canonicalize($signedProperties, $transformAlgorithm, 'xades:SignedProperties'), true);
833: }
834: catch (Exception $e)
835: {
836: self::invalid($e->getMessage());
837: }
838: if (!hash_equals($expected, $computed))
839: {
840: self::invalid('The signed properties have been altered (digest mismatch).');
841: }
842: continue;
843: }
844: if (null !== $type && '' !== $type)
845: {
846: self::invalid('Unsupported reference type: ' . $type . '.');
847: }
848: if (!empty($transforms))
849: {
850: self::invalid('A reference to a file must have no transform.');
851: }
852: $name = self::fileName($uri);
853: if (!array_key_exists($name, $files))
854: {
855: self::invalid('A reference points at no file of the container: ' . self::quote($uri) . '.');
856: }
857: if (isset($covered[$name]))
858: {
859: self::invalid('Two references point at the same file: ' . self::quote($name) . '.');
860: }
861: $covered[$name] = true;
862: if (!hash_equals($expected, hash($digest, $files[$name], true)))
863: {
864: self::invalid('The file ' . self::quote($name) . ' has been altered (digest mismatch).');
865: }
866: $referenceId = $reference->getAttribute('Id');
867: if ('' === $referenceId || !array_key_exists($referenceId, $mimeTypes))
868: {
869: self::invalid('The reference to ' . self::quote($name) . ' has no DataObjectFormat.');
870: }
871: $sealed[] = ['name' => (string) $name, 'mimeType' => $mimeTypes[$referenceId]];
872: unset($mimeTypes[$referenceId]);
873: }
874: if (1 !== $propertiesReferences)
875: {
876: self::invalid('The signature must have one reference to its signed properties.');
877: }
878: if (!empty($mimeTypes))
879: {
880: self::invalid('A DataObjectFormat points at no reference to a file.');
881: }
882: foreach (array_keys($files) as $name)
883: {
884: if (!isset($covered[$name]))
885: {
886: self::invalid('The file ' . self::quote((string) $name) . ' is in the container but not sealed.');
887: }
888: }
889:
890: // The signature value, over SignedInfo as the document holds it.
891: $signatureValueElement = $parts['SignatureValue'][0];
892: $signatureValue = self::base64(self::text($signatureValueElement), 'the SignatureValue');
893: try
894: {
895: $data = self::canonicalize($signedInfo, $canonicalization, 'ds:SignedInfo');
896: }
897: catch (Exception $e)
898: {
899: self::invalid($e->getMessage());
900: }
901: if (!Policy::verifyValue($scheme, $data, $signatureValue, $publicKey))
902: {
903: self::invalid('The signature value is not valid.');
904: }
905:
906: return [
907: 'files' => $sealed,
908: 'signingTime' => $signingTime,
909: 'signer' => $signer,
910: 'chain' => $chain,
911: 'keyInfo' => $certificates,
912: 'validationData' => $validationData,
913: 'timestamp' => null === $timestamp ? null : $timestamp + ['signatureValue' => $signatureValueElement],
914: ];
915: }
916:
917:
918: /**
919: * The key of the signing certificate must suit the signature algorithm,
920: * with the sizes the seals accept.
921: */
922: private static function checkSigningKey($key, $signatureAlgorithm, array $scheme)
923: {
924: $description = Policy::describeKey($key);
925: if ($description['type'] !== $scheme['keyType'])
926: {
927: self::invalid('The signature algorithm ' . $signatureAlgorithm . ' does not suit the key of the signing certificate.');
928: }
929: if ('rsa' === $scheme['keyType'] && $description['bits'] < Policy::MIN_RSA_BITS)
930: {
931: self::invalid('The RSA key of the signing certificate has less than ' . Policy::MIN_RSA_BITS . ' bits.');
932: }
933: if ('ec' === $scheme['keyType'] && !isset(Policy::CURVES[$description['curve']]))
934: {
935: self::invalid('The EC key of the signing certificate is not on P-256, P-384 or P-521.');
936: }
937: }
938:
939:
940: /**
941: * The name of the file a reference points at: a relative URI, resolved
942: * against the root of the container (EN 319 162-1, A.6), each segment
943: * percent-decoded. An absolute URI, a query or a fragment points
944: * outside.
945: */
946: private static function fileName($uri)
947: {
948: if (null === $uri || '' === $uri || '/' === $uri[0] || preg_match('/\A[A-Za-z][A-Za-z0-9+.-]*:/', $uri) || preg_match('/[?#]/', $uri))
949: {
950: self::invalid('A reference to a file must be a relative URI inside the container: ' . self::quote($uri) . '.');
951: }
952: $segments = [];
953: foreach (explode('/', $uri) as $segment)
954: {
955: // decodeURIComponent() refuses a malformed escape and what does
956: // not decode to UTF-8.
957: if (preg_match('/%(?![0-9A-Fa-f]{2})/', $segment))
958: {
959: self::invalid('A reference to a file is not a valid URI: ' . self::quote($uri) . '.');
960: }
961: $decoded = rawurldecode($segment);
962: if (!preg_match('//u', $decoded))
963: {
964: self::invalid('A reference to a file is not a valid URI: ' . self::quote($uri) . '.');
965: }
966: $segments[] = $decoded;
967: }
968:
969: return implode('/', $segments);
970: }
971:
972:
973: /**
974: * The element children of an element, checked against a sequence of
975: * [namespace, name, min, max]; nothing else is allowed.
976: *
977: * @return array The elements found, by name.
978: */
979: private static function sequence(DOMElement $parent, array $spec)
980: {
981: $found = [];
982: foreach ($spec as $entry)
983: {
984: $found[$entry[1]] = [];
985: }
986: $position = 0;
987: for ($node = $parent->firstChild; null !== $node; $node = $node->nextSibling)
988: {
989: if (XML_TEXT_NODE === $node->nodeType)
990: {
991: if ('' !== trim($node->nodeValue))
992: {
993: self::invalid('Unexpected text in ' . $parent->nodeName . '.');
994: }
995: continue;
996: }
997: if (XML_ELEMENT_NODE !== $node->nodeType)
998: {
999: self::invalid('Unexpected ' . $node->nodeName . ' in ' . $parent->nodeName . '.');
1000: }
1001: while ($position < count($spec) && !self::is($node, $spec[$position][0], $spec[$position][1]))
1002: {
1003: $position++;
1004: }
1005: if ($position >= count($spec))
1006: {
1007: self::invalid('Unexpected or misplaced element ' . $node->nodeName . ' in ' . $parent->nodeName . '.');
1008: }
1009: $entry = $spec[$position];
1010: $found[$entry[1]][] = $node;
1011: if (count($found[$entry[1]]) > $entry[3])
1012: {
1013: self::invalid('Too many ' . $node->nodeName . ' in ' . $parent->nodeName . '.');
1014: }
1015: }
1016: foreach ($spec as $entry)
1017: {
1018: if (count($found[$entry[1]]) < $entry[2])
1019: {
1020: self::invalid('Missing ' . (self::XMLDSIG_NS === $entry[0] ? 'ds' : 'xades') . ':' . $entry[1] . ' in ' . $parent->nodeName . '.');
1021: }
1022: }
1023:
1024: return $found;
1025: }
1026:
1027:
1028: private static function is($element, $namespace, $name)
1029: {
1030: return $element instanceof DOMElement && $element->namespaceURI === $namespace && $element->localName === $name;
1031: }
1032:
1033:
1034: private static function attribute(DOMElement $element, $name, $what)
1035: {
1036: $value = $element->getAttribute($name);
1037: if ('' === $value)
1038: {
1039: self::invalid($what . ' must have an ' . $name . '.');
1040: }
1041:
1042: return $value;
1043: }
1044:
1045:
1046: private static function algorithmOf(DOMElement $element)
1047: {
1048: if (null !== $element->firstChild && 'DigestMethod' !== $element->localName)
1049: {
1050: self::invalid('Unsupported parameters of ' . $element->nodeName . '.');
1051: }
1052:
1053: return self::attribute($element, 'Algorithm', $element->nodeName);
1054: }
1055:
1056:
1057: private static function digestOf(DOMElement $element)
1058: {
1059: $algorithm = self::attribute($element, 'Algorithm', $element->nodeName);
1060: if (!isset(Policy::DIGESTS[$algorithm]) || null !== $element->firstChild)
1061: {
1062: self::invalid('Unsupported digest algorithm: ' . $algorithm . '.');
1063: }
1064:
1065: return Policy::DIGESTS[$algorithm];
1066: }
1067:
1068:
1069: /**
1070: * The text of an element that holds text only.
1071: */
1072: private static function text(DOMElement $element)
1073: {
1074: for ($node = $element->firstChild; null !== $node; $node = $node->nextSibling)
1075: {
1076: if (XML_TEXT_NODE !== $node->nodeType)
1077: {
1078: self::invalid($element->nodeName . ' must hold text only.');
1079: }
1080: }
1081:
1082: return $element->textContent;
1083: }
1084:
1085:
1086: /**
1087: * Base64 content, white space allowed (XML Schema base64Binary).
1088: */
1089: private static function base64($value, $what)
1090: {
1091: $compact = preg_replace('/\s/', '', $value);
1092: if ('' === $compact || 0 !== strlen($compact) % 4 || !preg_match('#\A[A-Za-z0-9+/]*={0,2}\z#', $compact))
1093: {
1094: self::invalid($what . ' is not valid base64.');
1095: }
1096:
1097: return base64_decode($compact);
1098: }
1099:
1100:
1101: /**
1102: * The DER an EncapsulatedPKIData element holds (EN 319 132-1, 5.1.3):
1103: * base64, of the encoding DER, the default.
1104: */
1105: private static function encapsulated(DOMElement $element, $what)
1106: {
1107: $encoding = $element->getAttribute('Encoding');
1108: if ('' !== $encoding && 'http://uri.etsi.org/01903/v1.2.2#DER' !== $encoding)
1109: {
1110: self::invalid('Unsupported encoding of ' . $what . ': ' . $encoding . '.');
1111: }
1112:
1113: return self::base64(self::text($element), $what);
1114: }
1115:
1116:
1117: /**
1118: * An xsd:dateTime with a time zone, as SigningTime is written.
1119: *
1120: * @return float The UNIX time.
1121: */
1122: private static function parseDateTime($value)
1123: {
1124: if (!preg_match('/\A\s*(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|([+-])(\d{2}):(\d{2}))\s*\z/', $value, $m)
1125: || !checkdate((int) $m[2], (int) $m[3], (int) $m[1]) || (int) $m[4] > 23 || (int) $m[5] > 59 || (int) $m[6] > 59
1126: || (isset($m[10]) && ((int) $m[10] > 23 || (int) $m[11] > 59)))
1127: {
1128: self::invalid('SigningTime is not a date and time with a time zone: ' . self::quote($value) . '.');
1129: }
1130: $time = gmmktime((int) $m[4], (int) $m[5], (int) $m[6], (int) $m[2], (int) $m[3], (int) $m[1]);
1131: if (isset($m[9]))
1132: {
1133: $offset = ((int) $m[10] * 60 + (int) $m[11]) * 60;
1134: $time += '+' === $m[9] ? -$offset : $offset;
1135: }
1136: $fraction = '' !== $m[7] ? floor((float) ('0' . $m[7]) * 1000) / 1000 : 0;
1137:
1138: return $time + $fraction;
1139: }
1140:
1141:
1142: /**
1143: * The Id attributes of the document, which must be unique: a reference
1144: * by Id must not have two targets.
1145: */
1146: private static function uniqueIds(DOMDocument $doc)
1147: {
1148: $ids = [];
1149: $visit = function (DOMElement $element) use (&$visit, &$ids)
1150: {
1151: if ($element->hasAttribute('Id'))
1152: {
1153: $id = $element->getAttribute('Id');
1154: if (isset($ids[$id]))
1155: {
1156: self::invalid('Two elements have the Id ' . self::quote($id) . '.');
1157: }
1158: $ids[$id] = true;
1159: }
1160: for ($node = $element->firstChild; null !== $node; $node = $node->nextSibling)
1161: {
1162: if ($node instanceof DOMElement)
1163: {
1164: $visit($node);
1165: }
1166: }
1167: };
1168: $visit($doc->documentElement);
1169: }
1170:
1171:
1172: /** The media types written for the most common extensions; any other file is application/octet-stream. */
1173: const MEDIA_TYPES = [
1174: 'pdf' => 'application/pdf',
1175: 'txt' => 'text/plain',
1176: 'md' => 'text/markdown',
1177: 'html' => 'text/html',
1178: 'htm' => 'text/html',
1179: 'xml' => 'application/xml',
1180: 'json' => 'application/json',
1181: 'csv' => 'text/csv',
1182: 'png' => 'image/png',
1183: 'jpg' => 'image/jpeg',
1184: 'jpeg' => 'image/jpeg',
1185: 'svg' => 'image/svg+xml',
1186: 'odt' => 'application/vnd.oasis.opendocument.text',
1187: 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
1188: 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
1189: ];
1190:
1191: /** A media type: type/subtype, then parameters (RFC 6838, 4.2). */
1192: const MEDIA_TYPE = '/\A[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;\s*[A-Za-z0-9!#$&^_.+-]+=("[^"\\\\\r\n]*"|[A-Za-z0-9!#$&^_.+-]+))*\z/';
1193:
1194:
1195: /**
1196: * Seal files: an ASiC-E container that holds them, its manifest, and a
1197: * XAdES-B-B signature over them.
1198: *
1199: * @param array $files The files to seal, in the order of the container:
1200: * each an array with 'name' (its path in the container, `/`
1201: * separated, outside `META-INF/`), 'content' (its bytes) and,
1202: * optionally, 'mimeType' (by default, from the extension of its
1203: * name, see MEDIA_TYPES).
1204: *
1205: * @param string $signKey The private key: the path of a PEM file, or its
1206: * content.
1207: *
1208: * @param string $signCert The certificate of the key: the path of a PEM
1209: * file, or its content; the certificates that follow the first
1210: * one are embedded as its chain.
1211: *
1212: * @param string|null $signKeyPassword The password of the key, or NULL.
1213: *
1214: * @param array $options
1215: * - 'chain': certificates of the path of the signing certificate,
1216: * to embed for the verifier (the intermediate CAs): paths of
1217: * PEM files or PEM contents;
1218: * - 'signatureAlgorithm': by default, RSA-PSS for an RSA key,
1219: * ECDSA for an EC key (its digest after the curve);
1220: * - 'digestAlgorithm': the digest of the sealed files, the signed
1221: * properties and the signing certificate (default SHA-256);
1222: * - 'signingTime': the time the signer claims, a UNIX time
1223: * (default: now), written to the second.
1224: *
1225: * @return string The container (`.asice`).
1226: *
1227: * @throws Exception On a misuse: no file, a name or a media type that
1228: * cannot be sealed, a key that does not match the certificate,
1229: * an algorithm that does not suit the key, a certificate that
1230: * cannot sign at the signing time.
1231: */
1232: public static function createSeal(array $files, $signKey, $signCert, $signKeyPassword, array $options = [])
1233: {
1234: if (empty($files))
1235: {
1236: throw new Exception('Seal: no file to seal.');
1237: }
1238: $sealed = [];
1239: foreach (array_values($files) as $index => $file)
1240: {
1241: $sealed[] = self::checkFile($file, $index);
1242: }
1243:
1244: $certPem = self::readPem($signCert);
1245: if (null === $certPem)
1246: {
1247: throw new Exception('Seal: unable to read the signing certificate (' . self::describe($signCert) . ').');
1248: }
1249: $certificates = self::extractCertificates($certPem);
1250: foreach (isset($options['chain']) ? (array) $options['chain'] : [] as $source)
1251: {
1252: $pem = self::readPem($source);
1253: if (null === $pem)
1254: {
1255: throw new Exception('Seal: unable to read a chain certificate (' . self::describe($source) . ').');
1256: }
1257: $certificates = array_merge($certificates, self::extractCertificates($pem));
1258: }
1259: if (empty($certificates))
1260: {
1261: throw new Exception('Seal: the signing certificate holds no certificate.');
1262: }
1263: $certificateDer = base64_decode($certificates[0]);
1264: $certificate = new X509Cert(X509Cert::derToPem($certificateDer));
1265:
1266: $keyPem = self::readPem($signKey);
1267: if (null === $keyPem)
1268: {
1269: throw new Exception('Seal: unable to read the signing key (' . self::describe($signKey) . ').');
1270: }
1271: $privateKey = null === $signKeyPassword ? @openssl_pkey_get_private($keyPem) : @openssl_pkey_get_private($keyPem, $signKeyPassword);
1272: if (false === $privateKey)
1273: {
1274: throw new Exception('Seal: unable to load the signing key (wrong password?).');
1275: }
1276: if (!openssl_x509_check_private_key($certificate->getPem(), $privateKey))
1277: {
1278: throw new Exception('Seal: the signing key does not match the signing certificate.');
1279: }
1280: $signatureAlgorithm = isset($options['signatureAlgorithm']) ? $options['signatureAlgorithm'] : self::defaultSignatureAlgorithm($privateKey);
1281: self::checkKey($privateKey, $signatureAlgorithm);
1282: $scheme = Policy::SIGNATURE_SCHEMES[$signatureAlgorithm];
1283:
1284: $digestAlgorithm = isset($options['digestAlgorithm']) ? $options['digestAlgorithm'] : Algorithms::SHA256;
1285: if (!isset(Policy::DIGESTS[$digestAlgorithm]))
1286: {
1287: throw new Exception('Seal: unsupported digest algorithm ' . $digestAlgorithm . '.');
1288: }
1289: $digest = Policy::DIGESTS[$digestAlgorithm];
1290:
1291: $signingTime = isset($options['signingTime']) ? $options['signingTime'] : time();
1292: if (!is_int($signingTime) && !is_float($signingTime))
1293: {
1294: throw new Exception('Seal: invalid signing time.');
1295: }
1296: $signingTime = (int) floor($signingTime);
1297: if ($signingTime < (int) $certificate->getValidFrom('U') || $signingTime > (int) $certificate->getValidTo('U'))
1298: {
1299: throw new Exception('Seal: the signing certificate is not valid at the signing time.');
1300: }
1301: if (!$certificate->canSign())
1302: {
1303: throw new Exception('Seal: the key usage of the signing certificate does not allow signing.');
1304: }
1305:
1306: // Identifiers of the signature, of its references, of its signed properties.
1307: $id = 'S-' . bin2hex(random_bytes(16));
1308: $hash = function ($data) use ($digest) { return base64_encode(hash($digest, $data, true)); };
1309: $method = function ($name, $algorithm) { return '<ds:' . $name . ' Algorithm="' . self::escapeAttribute($algorithm) . '"/>'; };
1310:
1311: $fileReferences = '';
1312: $formats = '';
1313: foreach ($sealed as $index => $file)
1314: {
1315: $reference = $id . '-R' . ($index + 1);
1316: $fileReferences .= '<ds:Reference Id="' . $reference . '" URI="' . self::escapeAttribute(self::referenceUri($file['name'])) . '">'
1317: . $method('DigestMethod', $digestAlgorithm)
1318: . '<ds:DigestValue>' . $hash($file['content']) . '</ds:DigestValue></ds:Reference>';
1319: $formats .= '<xades:DataObjectFormat ObjectReference="#' . $reference . '">'
1320: . '<xades:MimeType>' . self::escapeText($file['mimeType']) . '</xades:MimeType></xades:DataObjectFormat>';
1321: }
1322: $signedProperties = '<xades:SignedProperties Id="' . $id . '-SP">'
1323: . '<xades:SignedSignatureProperties>'
1324: . '<xades:SigningTime>' . gmdate('Y-m-d\TH:i:s\Z', $signingTime) . '</xades:SigningTime>'
1325: . '<xades:SigningCertificateV2><xades:Cert><xades:CertDigest>'
1326: . $method('DigestMethod', $digestAlgorithm)
1327: . '<ds:DigestValue>' . $hash($certificateDer) . '</ds:DigestValue>'
1328: . '</xades:CertDigest></xades:Cert></xades:SigningCertificateV2>'
1329: . '</xades:SignedSignatureProperties>'
1330: . '<xades:SignedDataObjectProperties>' . $formats . '</xades:SignedDataObjectProperties>'
1331: . '</xades:SignedProperties>';
1332: $keyInfo = '';
1333: foreach ($certificates as $cert)
1334: {
1335: $keyInfo .= '<ds:X509Certificate>' . $cert . '</ds:X509Certificate>';
1336: }
1337:
1338: $document = function ($propertiesDigest, $signatureValue) use ($id, $method, $signatureAlgorithm, $fileReferences, $digestAlgorithm, $keyInfo, $signedProperties)
1339: {
1340: return '<?xml version="1.0" encoding="UTF-8"?>'
1341: . '<asic:XAdESSignatures xmlns:asic="' . self::ASIC_NS . '">'
1342: . '<ds:Signature xmlns:ds="' . self::XMLDSIG_NS . '" Id="' . $id . '">'
1343: . '<ds:SignedInfo>'
1344: . $method('CanonicalizationMethod', Algorithms::EXC_C14N)
1345: . $method('SignatureMethod', $signatureAlgorithm)
1346: . $fileReferences
1347: . '<ds:Reference Type="' . self::SIGNED_PROPERTIES_TYPE . '" URI="#' . $id . '-SP">'
1348: . '<ds:Transforms>' . $method('Transform', Algorithms::EXC_C14N) . '</ds:Transforms>'
1349: . $method('DigestMethod', $digestAlgorithm)
1350: . '<ds:DigestValue>' . $propertiesDigest . '</ds:DigestValue></ds:Reference>'
1351: . '</ds:SignedInfo>'
1352: . '<ds:SignatureValue Id="' . $id . '-SV">' . $signatureValue . '</ds:SignatureValue>'
1353: . '<ds:KeyInfo><ds:X509Data>' . $keyInfo . '</ds:X509Data></ds:KeyInfo>'
1354: . '<ds:Object><xades:QualifyingProperties xmlns:xades="' . self::XADES_NS . '" Target="#' . $id . '">' . $signedProperties . '</xades:QualifyingProperties></ds:Object>'
1355: . '</ds:Signature></asic:XAdESSignatures>';
1356: };
1357:
1358: // The digest of the signed properties, then the signature of
1359: // SignedInfo, each computed over the document as it will be read.
1360: $doc = Xml::load($document('', ''), 'XAdES signature');
1361: $propertiesDigest = $hash(self::canonicalize($doc->getElementsByTagNameNS(self::XADES_NS, 'SignedProperties')->item(0), Algorithms::EXC_C14N, 'xades:SignedProperties'));
1362: $doc = Xml::load($document($propertiesDigest, ''), 'XAdES signature');
1363: $data = self::canonicalize($doc->getElementsByTagNameNS(self::XMLDSIG_NS, 'SignedInfo')->item(0), Algorithms::EXC_C14N, 'ds:SignedInfo');
1364: $signatureValue = base64_encode(self::signValue($scheme, $data, $privateKey));
1365:
1366: $entries = [['name' => 'mimetype', 'content' => self::ASICE_MIMETYPE, 'stored' => true]];
1367: foreach ($sealed as $file)
1368: {
1369: $entries[] = ['name' => $file['name'], 'content' => $file['content']];
1370: }
1371: $entries[] = ['name' => self::MANIFEST_PATH, 'content' => self::manifest($sealed)];
1372: $entries[] = ['name' => self::SIGNATURE_PATH, 'content' => $document($propertiesDigest, $signatureValue)];
1373:
1374: return Zip::write($entries, $signingTime);
1375: }
1376:
1377:
1378: /**
1379: * Sign with a scheme of the seals: RSASSA-PSS (see RsaPss), RSA PKCS#1
1380: * v1.5, or ECDSA, its value written as r || s (RFC 4050).
1381: */
1382: private static function signValue(array $scheme, $data, $privateKey)
1383: {
1384: if ('pss' === $scheme['padding'])
1385: {
1386: return RsaPss::sign($data, $privateKey, $scheme['hash']);
1387: }
1388: $signature = '';
1389: if (!openssl_sign($data, $signature, $privateKey, $scheme['hash']))
1390: {
1391: throw new Exception('Seal: the signature failed.');
1392: }
1393: if ('ecdsa' === $scheme['padding'])
1394: {
1395: $signature = Policy::derToRaw($signature, Policy::describeKey($privateKey)['curve']);
1396: }
1397:
1398: return $signature;
1399: }
1400:
1401:
1402: /**
1403: * The reference to a file of the container: a relative URI, each
1404: * segment of its path percent-encoded as encodeURIComponent() does.
1405: *
1406: * @internal
1407: */
1408: public static function referenceUri($name)
1409: {
1410: $segments = [];
1411: foreach (explode('/', $name) as $segment)
1412: {
1413: $segments[] = strtr(rawurlencode($segment), ['%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')']);
1414: }
1415:
1416: return implode('/', $segments);
1417: }
1418:
1419:
1420: /**
1421: * The ODF manifest of the container (EN 319 162-1, A.4): the container
1422: * itself, then each sealed file.
1423: */
1424: private static function manifest(array $files)
1425: {
1426: $entries = '';
1427: foreach ($files as $file)
1428: {
1429: $entries .= '<manifest:file-entry manifest:full-path="' . self::escapeAttribute($file['name']) . '" manifest:media-type="' . self::escapeAttribute($file['mimeType']) . '"/>';
1430: }
1431:
1432: return '<?xml version="1.0" encoding="UTF-8"?>'
1433: . '<manifest:manifest xmlns:manifest="' . self::MANIFEST_NS . '" manifest:version="1.2">'
1434: . '<manifest:file-entry manifest:full-path="/" manifest:media-type="' . self::ASICE_MIMETYPE . '"/>'
1435: . $entries
1436: . '</manifest:manifest>';
1437: }
1438:
1439:
1440: private static function checkFile($file, $index)
1441: {
1442: if (!is_array($file) || !isset($file['name'], $file['content']) || !is_string($file['name']) || !is_string($file['content']))
1443: {
1444: throw new Exception('Seal: file ' . ($index + 1) . ' must have a name and a content (strings).');
1445: }
1446: $name = $file['name'];
1447: if ('mimetype' === $name || 0 === strpos($name, 'META-INF/') || 'META-INF' === $name)
1448: {
1449: throw new Exception('Seal: ' . self::quote($name) . ' is reserved by the container.');
1450: }
1451: if (class_exists('Normalizer') && \Normalizer::normalize($name, \Normalizer::FORM_C) !== $name)
1452: {
1453: throw new Exception('Seal: the name ' . self::quote($name) . ' is not in Unicode normalization form C.');
1454: }
1455: if (!preg_match('//u', $name))
1456: {
1457: throw new Exception('Seal: the name of file ' . ($index + 1) . ' is not UTF-8.');
1458: }
1459: $mimeType = isset($file['mimeType']) ? $file['mimeType'] : null;
1460: if (null === $mimeType)
1461: {
1462: $extension = preg_match('/\.([^.\/]+)\z/', $name, $match) ? strtolower($match[1]) : null;
1463: $mimeType = null !== $extension && isset(self::MEDIA_TYPES[$extension]) ? self::MEDIA_TYPES[$extension] : 'application/octet-stream';
1464: }
1465: if (!is_string($mimeType) || !preg_match(self::MEDIA_TYPE, $mimeType))
1466: {
1467: throw new Exception('Seal: invalid media type for ' . self::quote($name) . '.');
1468: }
1469:
1470: return ['name' => $name, 'content' => $file['content'], 'mimeType' => $mimeType];
1471: }
1472:
1473:
1474: private static function defaultSignatureAlgorithm($key)
1475: {
1476: $description = Policy::describeKey($key);
1477: if ('rsa' === $description['type'])
1478: {
1479: return Algorithms::RSA_PSS_SHA256;
1480: }
1481: if ('ec' === $description['type'] && isset(Policy::CURVES[$description['curve']]))
1482: {
1483: return Policy::CURVES[$description['curve']];
1484: }
1485: throw new Exception('Seal: the signing key must be an RSA key or an EC key on P-256, P-384 or P-521.');
1486: }
1487:
1488:
1489: private static function checkKey($key, $signatureAlgorithm)
1490: {
1491: if (!isset(Policy::SIGNATURE_SCHEMES[$signatureAlgorithm]))
1492: {
1493: throw new Exception('Seal: unsupported signature algorithm ' . $signatureAlgorithm . '.');
1494: }
1495: $scheme = Policy::SIGNATURE_SCHEMES[$signatureAlgorithm];
1496: $description = Policy::describeKey($key);
1497: if ($description['type'] !== $scheme['keyType'])
1498: {
1499: throw new Exception('Seal: the signature algorithm ' . $signatureAlgorithm . ' needs an ' . strtoupper($scheme['keyType']) . ' key.');
1500: }
1501: if ('rsa' === $scheme['keyType'] && $description['bits'] < Policy::MIN_RSA_BITS)
1502: {
1503: throw new Exception('Seal: RSA keys of less than ' . Policy::MIN_RSA_BITS . ' bits are refused.');
1504: }
1505: if ('ec' === $scheme['keyType'] && !isset(Policy::CURVES[$description['curve']]))
1506: {
1507: throw new Exception('Seal: the EC key must be on P-256, P-384 or P-521.');
1508: }
1509: }
1510:
1511:
1512: /**
1513: * The content of a PEM source: the path of a file, or PEM content; NULL
1514: * if it cannot be read.
1515: */
1516: private static function readPem($source)
1517: {
1518: if (!is_string($source))
1519: {
1520: return null;
1521: }
1522: if (false !== strpos($source, '-----BEGIN'))
1523: {
1524: return $source;
1525: }
1526: $content = is_file($source) && is_readable($source) ? file_get_contents($source) : false;
1527:
1528: return false === $content ? null : $content;
1529: }
1530:
1531:
1532: private static function describe($source)
1533: {
1534: return is_string($source) ? (false !== strpos($source, '-----BEGIN') ? 'PEM content' : $source) : gettype($source);
1535: }
1536:
1537:
1538: /**
1539: * The base64 of each certificate of a PEM content, its line breaks
1540: * removed.
1541: */
1542: private static function extractCertificates($pem)
1543: {
1544: $certificates = [];
1545: $data = null;
1546: foreach (explode("\n", $pem) as $line)
1547: {
1548: if (null === $data)
1549: {
1550: if (0 === strpos($line, '-----BEGIN CERTIFICATE'))
1551: {
1552: $data = '';
1553: }
1554: }
1555: elseif (0 === strpos($line, '-----END CERTIFICATE'))
1556: {
1557: $certificates[] = $data;
1558: $data = null;
1559: }
1560: else
1561: {
1562: $data .= trim($line);
1563: }
1564: }
1565:
1566: return $certificates;
1567: }
1568:
1569:
1570: /**
1571: * Escape text content as libxml writes it.
1572: */
1573: private static function escapeText($text)
1574: {
1575: return strtr($text, ['&' => '&amp;', '<' => '&lt;', '>' => '&gt;', "\r" => '&#xD;']);
1576: }
1577:
1578:
1579: /**
1580: * Escape an attribute value (in double quotes) as libxml writes it.
1581: */
1582: private static function escapeAttribute($text)
1583: {
1584: return strtr($text, ['&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', "\r" => '&#13;', "\n" => '&#10;', "\t" => '&#9;']);
1585: }
1586:
1587:
1588: /** The canonicalization of ds:SignatureValue for its time-stamp. */
1589: const TIMESTAMP_CANONICALIZATION = Algorithms::EXC_C14N;
1590:
1591: const CRL_DISTRIBUTION_POINTS = '2.5.29.31';
1592: const AUTHORITY_INFO_ACCESS = '1.3.6.1.5.5.7.1.1';
1593: const ID_AD_OCSP = '1.3.6.1.5.5.7.48.1';
1594:
1595:
1596: /**
1597: * The time-stamp request of a seal (RFC 3161 TimeStampReq, DER), to send
1598: * to a time-stamping authority, with the media type
1599: * `application/timestamp-query`. The library sends no request: the
1600: * caller sends it to the authority of its choice, and gives the response
1601: * to addSignatureTimestamp().
1602: *
1603: * @param string $container The container.
1604: *
1605: * @param string $digestAlgorithm The digest of the imprint: SHA256
1606: * (default), SHA384 or SHA512 of Algorithms.
1607: *
1608: * @return string The request.
1609: *
1610: * @throws Exception If the container does not hold one XAdES signature.
1611: */
1612: public static function timestampRequest($container, $digestAlgorithm = Algorithms::SHA256)
1613: {
1614: if (!isset(Policy::DIGESTS[$digestAlgorithm]))
1615: {
1616: throw new Exception('Time-stamp: unsupported digest algorithm ' . $digestAlgorithm . '.');
1617: }
1618: $digest = Policy::DIGESTS[$digestAlgorithm];
1619: $located = self::locate(Zip::read($container));
1620:
1621: return Timestamp::buildRequest(self::imprintOf($located['signatureValue'], $digest, self::TIMESTAMP_CANONICALIZATION), $digest);
1622: }
1623:
1624:
1625: /**
1626: * Add the signature time-stamp of a response to a seal: level B becomes
1627: * level T (EN 319 132-1, 5.3). The signed parts of the signature file
1628: * are left byte for byte as they are: the unsigned properties are
1629: * inserted after the signed ones.
1630: *
1631: * @param string $container The container.
1632: *
1633: * @param string $response The response of the authority (RFC 3161
1634: * TimeStampResp, DER).
1635: *
1636: * @param array $options 'tsaCertPath' (required): the trusted
1637: * certificates of the time-stamping authority, its root and its
1638: * intermediate CAs if the token does not embed them.
1639: *
1640: * @return string The container, with the time-stamp in its signature.
1641: *
1642: * @throws Exception If the authority did not grant the time-stamp, if
1643: * the token is not valid, is not over this seal, or its
1644: * authority is not trusted, or if the seal is already
1645: * time-stamped.
1646: */
1647: public static function addSignatureTimestamp($container, $response, array $options)
1648: {
1649: $tsaCerts = self::readTrusted(isset($options['tsaCertPath']) ? $options['tsaCertPath'] : null, 'tsaCertPath', 'Time-stamp');
1650: $entries = Zip::read($container);
1651: $located = self::locate($entries);
1652: if ($located['signedProperties']->parentNode->getElementsByTagNameNS(self::XADES_NS, 'UnsignedProperties')->length > 0)
1653: {
1654: throw new Exception('Time-stamp: the seal already has unsigned properties.');
1655: }
1656:
1657: $token = Timestamp::readResponse($response);
1658: $verified = Timestamp::verifyToken($token);
1659: if (!hash_equals($verified['imprint'], self::imprintOf($located['signatureValue'], $verified['imprintAlgorithm'], self::TIMESTAMP_CANONICALIZATION)))
1660: {
1661: throw new Exception('Time-stamp: the token is not over the signature of this seal.');
1662: }
1663: if (null === $verified['certificate']->getTrustedChain($tsaCerts, $verified['chain']))
1664: {
1665: throw new Exception('Time-stamp: the time-stamping authority is not trusted.');
1666: }
1667:
1668: // Inserted after the closing tag of SignedProperties, the namespaces
1669: // declared on the inserted elements themselves.
1670: $xml = $entries[$located['index']]['content'];
1671: $closing = '</' . $located['signedProperties']->nodeName . '>';
1672: $at = strpos($xml, $closing);
1673: if (false === $at || false !== strpos($xml, $closing, $at + 1))
1674: {
1675: throw new Exception('Time-stamp: the end of the signed properties cannot be told in the signature file.');
1676: }
1677: // An Id of its own, as DSS writes one, unless the signature has no Id to derive it from.
1678: $id = $located['signature']->getAttribute('Id') . '-TS';
1679: $idAttribute = '-TS' === $id || false !== strpos($xml, '"' . $id . '"') ? '' : ' Id="' . self::escapeAttribute($id) . '"';
1680: $unsigned = '<xades:UnsignedProperties xmlns:xades="' . self::XADES_NS . '"><xades:UnsignedSignatureProperties>'
1681: . '<xades:SignatureTimeStamp' . $idAttribute . '>'
1682: . '<ds:CanonicalizationMethod xmlns:ds="' . self::XMLDSIG_NS . '" Algorithm="' . self::TIMESTAMP_CANONICALIZATION . '"/>'
1683: . '<xades:EncapsulatedTimeStamp>' . base64_encode($token) . '</xades:EncapsulatedTimeStamp>'
1684: . '</xades:SignatureTimeStamp></xades:UnsignedSignatureProperties></xades:UnsignedProperties>';
1685: $extended = substr($xml, 0, $at + strlen($closing)) . $unsigned . substr($xml, $at + strlen($closing));
1686: Xml::load($extended, 'XAdES signature');
1687:
1688: return self::rewriteEntries($entries, $located['index'], $extended, (int) floor($verified['time']));
1689: }
1690:
1691:
1692: /**
1693: * The revocation data a seal needs: for each certificate of the chains
1694: * of the signer and of the time-stamping authority, their trust anchors
1695: * excepted, the CRL to fetch, and the OCSP request to send if the
1696: * certificate names a responder. One of the two suffices for a
1697: * certificate. Also useful at level B or T, to get the data
1698: * verifySeal() needs.
1699: *
1700: * @param string $container The container.
1701: *
1702: * @param array $options 'caCertPath' and 'tsaCertPath', as for
1703: * verifySeal() (both required).
1704: *
1705: * @return array 'crls': the CRLs to fetch, one per certificate, each
1706: * with 'certificate', 'issuer' (X509Cert) and 'urls' (the http
1707: * and https URLs of its CRL distribution points, empty if it
1708: * names none); 'ocsp': the OCSP requests to send, each with
1709: * 'certificate', 'issuer', 'urls' (of its responders) and
1710: * 'request' (the OCSPRequest, DER, to POST with the media type
1711: * `application/ocsp-request`).
1712: *
1713: * @throws Exception If the seal is not valid, revocation aside.
1714: */
1715: public static function validationDataRequests($container, array $options)
1716: {
1717: $inspected = self::inspectForExtension($container, ['revocation' => false] + $options);
1718: $crls = [];
1719: $ocsp = [];
1720: foreach ([$inspected['chain'], $inspected['tsaChain']] as $chain)
1721: {
1722: for ($index = 0; null !== $chain && $index + 1 < count($chain); $index++)
1723: {
1724: $certificate = $chain[$index];
1725: $issuer = $chain[$index + 1];
1726: foreach ($crls as $request)
1727: {
1728: if ($request['certificate']->getDer() === $certificate->getDer())
1729: {
1730: continue 2;
1731: }
1732: }
1733: $crls[] = ['certificate' => $certificate, 'issuer' => $issuer, 'urls' => self::distributionPoints($certificate)];
1734: $responders = self::ocspResponders($certificate);
1735: if (!empty($responders))
1736: {
1737: $ocsp[] = ['certificate' => $certificate, 'issuer' => $issuer, 'urls' => $responders, 'request' => Ocsp::buildRequest($certificate, $issuer)];
1738: }
1739: }
1740: }
1741:
1742: return ['crls' => $crls, 'ocsp' => $ocsp];
1743: }
1744:
1745:
1746: /**
1747: * Add to a seal of level T the certificates, CRLs and OCSP responses
1748: * that validate it: it becomes a seal of level LT (EN 319 132-1, 5.4,
1749: * 5.5.1, 6.3), which a third party can validate without reaching the
1750: * CAs. The answers are checked before they are embedded, only those that
1751: * told the status of a certificate; they must be issued after the
1752: * time-stamp. The signed parts of the signature file are left byte for
1753: * byte as they are.
1754: *
1755: * What goes where: xades141:TimeStampValidationData, right after the
1756: * time-stamp, the certificates of the chain of the time-stamping
1757: * authority the token does not hold, and their CRLs or OCSP responses;
1758: * xades:CertificateValues, the certificates of the chain of the signer
1759: * ds:KeyInfo does not hold, its trust anchor included;
1760: * xades:RevocationValues, a CRL or an OCSP response for each certificate
1761: * of that chain, its trust anchor excepted. Each one is embedded once.
1762: *
1763: * @param string $container The container.
1764: *
1765: * @param array $options 'caCertPath' and 'tsaCertPath', as for
1766: * verifySeal(), and at least one of 'crls' (in DER or PEM) and
1767: * 'ocspResponses' (DER), fetched as validationDataRequests()
1768: * lists.
1769: *
1770: * @return string The container, with the validation data in its
1771: * signature.
1772: *
1773: * @throws Exception If the seal is not valid, is not of level T, or if
1774: * the data do not tell the status of every certificate after the
1775: * time-stamp.
1776: */
1777: public static function addValidationData($container, array $options)
1778: {
1779: if (!isset($options['crls']) && !isset($options['ocspResponses']))
1780: {
1781: throw new Exception("Validation data: the option 'crls' or 'ocspResponses' is required.");
1782: }
1783: $inspected = self::inspectForExtension($container, array_intersect_key($options, ['caCertPath' => 1, 'tsaCertPath' => 1, 'crls' => 1, 'ocspResponses' => 1]));
1784: $level = $inspected['result']->getLevel();
1785: if ('T' !== $level)
1786: {
1787: throw new Exception('B' === $level ? 'Validation data: the seal must be time-stamped first (level T).' : 'Validation data: the seal already has validation data.');
1788: }
1789:
1790: // Each certificate, CRL and OCSP response once: the signer's first,
1791: // then what the time-stamping authority needs besides.
1792: $ders = function (array $certificates) { return array_map(function (X509Cert $cert) { return $cert->getDer(); }, $certificates); };
1793: $held = array_merge($inspected['keyInfo'], $inspected['tokenCertificates']);
1794: $signerCertificates = self::unique($ders($inspected['chain']), $inspected['keyInfo']);
1795: $tsaCertificates = self::unique($ders($inspected['tsaChain']), array_merge($held, $signerCertificates));
1796: $sourcesOf = function (array $sources, $kind)
1797: {
1798: return array_map(function (RevocationSource $source) { return $source->der; },
1799: array_values(array_filter($sources, function (RevocationSource $source) use ($kind) { return $kind === $source->kind; })));
1800: };
1801: $signerCrls = self::unique($sourcesOf($inspected['signerSources'], 'crl'), []);
1802: $signerOcsp = self::unique($sourcesOf($inspected['signerSources'], 'ocsp'), []);
1803: $tsaCrls = self::unique($sourcesOf($inspected['tsaSources'], 'crl'), $signerCrls);
1804: $tsaOcsp = self::unique($sourcesOf($inspected['tsaSources'], 'ocsp'), $signerOcsp);
1805:
1806: $entries = Zip::read($container);
1807: $located = self::locate($entries, 'Validation data');
1808: $properties = $located['signature']->getElementsByTagNameNS(self::XADES_NS, 'UnsignedSignatureProperties');
1809: $xml = $entries[$located['index']]['content'];
1810: $closing = '</' . (1 === $properties->length ? $properties->item(0)->nodeName : '') . '>';
1811: $at = strpos($xml, $closing);
1812: if (1 !== $properties->length || false === $at || false !== strpos($xml, $closing, $at + 1))
1813: {
1814: throw new Exception('Validation data: the end of the unsigned signature properties cannot be told in the signature file.');
1815: }
1816: $timestampData = 0 === count($tsaCertificates) + count($tsaCrls) + count($tsaOcsp) ? ''
1817: : '<xades141:TimeStampValidationData xmlns:xades141="' . self::XADES141_NS . '">' . self::certificateValues($tsaCertificates) . self::revocationValues($tsaCrls, $tsaOcsp) . '</xades141:TimeStampValidationData>';
1818: $added = $timestampData . self::certificateValues($signerCertificates) . self::revocationValues($signerCrls, $signerOcsp);
1819: $extended = substr($xml, 0, $at) . $added . substr($xml, $at);
1820: Xml::load($extended, 'XAdES signature');
1821: $result = self::rewriteEntries($entries, $located['index'], $extended, time());
1822:
1823: // The seal must now validate with what it embeds alone.
1824: $check = self::inspectSeal($result, array_intersect_key($options, ['caCertPath' => 1, 'tsaCertPath' => 1]));
1825: if ('LT' !== $check['result']->getLevel())
1826: {
1827: throw new Exception('Validation data: the extended seal does not validate by itself. '
1828: . (null !== $check['result']->getError() ? $check['result']->getError() : 'Level ' . $check['result']->getLevel() . '.'));
1829: }
1830:
1831: return $result;
1832: }
1833:
1834:
1835: /**
1836: * inspectSeal(), an invalid seal turned into an exception.
1837: */
1838: private static function inspectForExtension($container, array $options)
1839: {
1840: if (!isset($options['tsaCertPath']))
1841: {
1842: throw new Exception("Validation data: the option 'tsaCertPath' is required.");
1843: }
1844: try
1845: {
1846: $inspected = self::inspectSeal($container, $options, true);
1847: }
1848: catch (Exception $e)
1849: {
1850: throw new Exception('Validation data: ' . $e->getMessage());
1851: }
1852: $error = $inspected['result']->getError();
1853: if (null !== $error)
1854: {
1855: // verifySeal() suggests 'revocation' => false, which the extension has not.
1856: throw new Exception('Validation data: the seal is not valid. ' . preg_replace("/ \\(the option 'revocation' => false [^)]*\\)\\z/", '', $error));
1857: }
1858:
1859: return $inspected;
1860: }
1861:
1862:
1863: /**
1864: * The signature file of a seal, and its elements the extensions need.
1865: *
1866: * @return array 'index' (of the entry), 'doc', 'signature',
1867: * 'signatureValue', 'signedProperties'.
1868: */
1869: private static function locate(array $entries, $what = 'Time-stamp')
1870: {
1871: $found = [];
1872: foreach ($entries as $index => $entry)
1873: {
1874: if (preg_match('/\AMETA-INF\/[^\/]*signatures[^\/]*\.xml\z/i', $entry['name']))
1875: {
1876: $found[] = $index;
1877: }
1878: }
1879: if (1 !== count($found))
1880: {
1881: throw new Exception($what . ': the container must hold one signature file.');
1882: }
1883: $doc = Xml::load($entries[$found[0]]['content'], 'XAdES signature');
1884: $signatures = $doc->getElementsByTagNameNS(self::XMLDSIG_NS, 'Signature');
1885: if (1 !== $signatures->length)
1886: {
1887: throw new Exception($what . ': the signature file must hold one ds:Signature.');
1888: }
1889: $signature = $signatures->item(0);
1890: $values = [];
1891: foreach ($signature->childNodes as $node)
1892: {
1893: if ($node instanceof DOMElement && 'SignatureValue' === $node->localName && self::XMLDSIG_NS === $node->namespaceURI)
1894: {
1895: $values[] = $node;
1896: }
1897: }
1898: $properties = $signature->getElementsByTagNameNS(self::XADES_NS, 'SignedProperties');
1899: if (1 !== count($values) || 1 !== $properties->length)
1900: {
1901: throw new Exception($what . ': the signature has no SignatureValue or no SignedProperties.');
1902: }
1903:
1904: return ['index' => $found[0], 'doc' => $doc, 'signature' => $signature, 'signatureValue' => $values[0], 'signedProperties' => $properties->item(0)];
1905: }
1906:
1907:
1908: /**
1909: * The entries of a container written again, one replaced.
1910: */
1911: private static function rewriteEntries(array $entries, $index, $content, $modified)
1912: {
1913: $inputs = [];
1914: foreach ($entries as $i => $entry)
1915: {
1916: $inputs[] = ['name' => $entry['name'], 'content' => $i === $index ? $content : $entry['content'], 'stored' => 0 === $entry['method']];
1917: }
1918:
1919: return Zip::write($inputs, $modified);
1920: }
1921:
1922:
1923: /**
1924: * The PEM contents of trusted certificates given to an extension.
1925: */
1926: private static function readTrusted($source, $name, $what)
1927: {
1928: $sources = is_array($source) ? $source : [$source];
1929: if (null === $source || empty($sources))
1930: {
1931: throw new Exception($what . ": the option '" . $name . "' is required.");
1932: }
1933: $pems = [];
1934: foreach ($sources as $item)
1935: {
1936: $pem = self::readPem($item);
1937: if (null === $pem)
1938: {
1939: throw new Exception($what . ': cannot read the certificate file ' . self::describe($item) . '.');
1940: }
1941: $pems[] = $pem;
1942: }
1943:
1944: return $pems;
1945: }
1946:
1947:
1948: /**
1949: * The DER encodings of a list, without duplicates nor those of $held.
1950: */
1951: private static function unique(array $list, array $held)
1952: {
1953: $kept = [];
1954: foreach ($list as $der)
1955: {
1956: if (!in_array($der, $held, true) && !in_array($der, $kept, true))
1957: {
1958: $kept[] = $der;
1959: }
1960: }
1961:
1962: return $kept;
1963: }
1964:
1965:
1966: private static function certificateValues(array $certificates)
1967: {
1968: if (empty($certificates))
1969: {
1970: return '';
1971: }
1972: $values = '';
1973: foreach ($certificates as $der)
1974: {
1975: $values .= '<xades:EncapsulatedX509Certificate>' . base64_encode($der) . '</xades:EncapsulatedX509Certificate>';
1976: }
1977:
1978: return '<xades:CertificateValues xmlns:xades="' . self::XADES_NS . '">' . $values . '</xades:CertificateValues>';
1979: }
1980:
1981:
1982: private static function revocationValues(array $crls, array $responses)
1983: {
1984: if (0 === count($crls) + count($responses))
1985: {
1986: return '';
1987: }
1988: $values = function ($name, array $list)
1989: {
1990: if (empty($list))
1991: {
1992: return '';
1993: }
1994: $encapsulated = '';
1995: foreach ($list as $der)
1996: {
1997: $encapsulated .= '<xades:Encapsulated' . $name . 'Value>' . base64_encode($der) . '</xades:Encapsulated' . $name . 'Value>';
1998: }
1999: return '<xades:' . $name . 'Values>' . $encapsulated . '</xades:' . $name . 'Values>';
2000: };
2001:
2002: return '<xades:RevocationValues xmlns:xades="' . self::XADES_NS . '">' . $values('CRL', $crls) . $values('OCSP', $responses) . '</xades:RevocationValues>';
2003: }
2004:
2005:
2006: /**
2007: * The http and https URLs of the OCSP responders of a certificate (RFC
2008: * 5280, 4.2.2.1).
2009: */
2010: private static function ocspResponders(X509Cert $certificate)
2011: {
2012: $extension = $certificate->getExtension(self::AUTHORITY_INFO_ACCESS);
2013: if (null === $extension)
2014: {
2015: return [];
2016: }
2017: $urls = [];
2018: try
2019: {
2020: foreach (Der::childrenOf(Der::readElement($extension['value']), Der::SEQUENCE) as $description)
2021: {
2022: $parts = Der::childrenOf($description, Der::SEQUENCE);
2023: if (isset($parts[0], $parts[1]) && self::ID_AD_OCSP === Der::decodeOid($parts[0]) && 0x86 === $parts[1]['tag'] && preg_match('#\Ahttps?://#i', $parts[1]['content']))
2024: {
2025: $urls[] = $parts[1]['content'];
2026: }
2027: }
2028: }
2029: catch (Exception $e)
2030: {
2031: return [];
2032: }
2033:
2034: return $urls;
2035: }
2036:
2037:
2038: /**
2039: * The http and https URLs of the CRL distribution points of a
2040: * certificate (RFC 5280, 4.2.1.13). A distribution point restricted to
2041: * some reasons or with a CRL issuer of its own is left out: its CRLs are
2042: * partial or indirect, which this library does not use.
2043: */
2044: private static function distributionPoints(X509Cert $certificate)
2045: {
2046: $extension = $certificate->getExtension(self::CRL_DISTRIBUTION_POINTS);
2047: if (null === $extension)
2048: {
2049: return [];
2050: }
2051: $urls = [];
2052: try
2053: {
2054: foreach (Der::childrenOf(Der::readElement($extension['value']), Der::SEQUENCE) as $point)
2055: {
2056: $fields = Der::childrenOf($point, Der::SEQUENCE);
2057: // distributionPoint [0], reasons [1], cRLIssuer [2].
2058: foreach ($fields as $field)
2059: {
2060: if (0xa0 !== $field['tag'])
2061: {
2062: continue 2;
2063: }
2064: }
2065: foreach ($fields as $field)
2066: {
2067: foreach (Der::readElements($field['content']) as $name)
2068: {
2069: // fullName [0] GeneralNames, of which uniformResourceIdentifier [6].
2070: if (0xa0 !== $name['tag'])
2071: {
2072: continue;
2073: }
2074: foreach (Der::readElements($name['content']) as $general)
2075: {
2076: if (0x86 === $general['tag'] && preg_match('#\Ahttps?://#i', $general['content']))
2077: {
2078: $urls[] = $general['content'];
2079: }
2080: }
2081: }
2082: }
2083: }
2084: }
2085: catch (Exception $e)
2086: {
2087: return [];
2088: }
2089:
2090: return $urls;
2091: }
2092: }
2093: