| 1: | <?php |
| 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: | namespace webcoder31\ezxmldsig\seal; |
| 41: | |
| 42: | |
| 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: | |
| 53: | |
| 54: | |
| 55: | |
| 56: | |
| 57: | |
| 58: | |
| 59: | |
| 60: | |
| 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: | |
| 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: | |
| 74: | const SIGNATURE_PATH = 'META-INF/signatures001.xml'; |
| 75: | const MANIFEST_PATH = 'META-INF/manifest.xml'; |
| 76: | |
| 77: | |
| 78: | const CANONICALIZATIONS = [Algorithms::EXC_C14N, Algorithms::C14N]; |
| 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: | public static function verifySeal($container, array $options) |
| 126: | { |
| 127: | return self::inspectSeal($container, $options)['result']; |
| 128: | } |
| 129: | |
| 130: | |
| 131: | |
| 132: | |
| 133: | |
| 134: | |
| 135: | |
| 136: | |
| 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: | |
| 201: | |
| 202: | |
| 203: | |
| 204: | |
| 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: | |
| 222: | |
| 223: | |
| 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: | |
| 248: | |
| 249: | |
| 250: | |
| 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: | |
| 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: | |
| 307: | |
| 308: | private static function invalid($message) |
| 309: | { |
| 310: | throw new InvalidSeal($message); |
| 311: | } |
| 312: | |
| 313: | |
| 314: | |
| 315: | |
| 316: | |
| 317: | |
| 318: | private static function quote($value) |
| 319: | { |
| 320: | return json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
| 321: | } |
| 322: | |
| 323: | |
| 324: | |
| 325: | |
| 326: | |
| 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: | |
| 336: | |
| 337: | |
| 338: | |
| 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: | |
| 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: | |
| 414: | |
| 415: | |
| 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: | |
| 452: | |
| 453: | |
| 454: | |
| 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: | |
| 464: | |
| 465: | |
| 466: | |
| 467: | |
| 468: | |
| 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: | |
| 486: | |
| 487: | |
| 488: | |
| 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: | |
| 557: | |
| 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: | |
| 579: | |
| 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: | |
| 602: | |
| 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: | |
| 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: | |
| 646: | |
| 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: | |
| 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: | |
| 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: | |
| 797: | |
| 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: | |
| 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: | |
| 920: | |
| 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: | |
| 942: | |
| 943: | |
| 944: | |
| 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: | |
| 956: | |
| 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: | |
| 975: | |
| 976: | |
| 977: | |
| 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: | |
| 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: | |
| 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: | |
| 1103: | |
| 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: | |
| 1119: | |
| 1120: | |
| 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: | |
| 1144: | |
| 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: | |
| 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: | |
| 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: | |
| 1197: | |
| 1198: | |
| 1199: | |
| 1200: | |
| 1201: | |
| 1202: | |
| 1203: | |
| 1204: | |
| 1205: | |
| 1206: | |
| 1207: | |
| 1208: | |
| 1209: | |
| 1210: | |
| 1211: | |
| 1212: | |
| 1213: | |
| 1214: | |
| 1215: | |
| 1216: | |
| 1217: | |
| 1218: | |
| 1219: | |
| 1220: | |
| 1221: | |
| 1222: | |
| 1223: | |
| 1224: | |
| 1225: | |
| 1226: | |
| 1227: | |
| 1228: | |
| 1229: | |
| 1230: | |
| 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: | |
| 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: | |
| 1359: | |
| 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: | |
| 1380: | |
| 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: | |
| 1404: | |
| 1405: | |
| 1406: | |
| 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: | |
| 1422: | |
| 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: | |
| 1514: | |
| 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: | |
| 1540: | |
| 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: | |
| 1572: | |
| 1573: | private static function escapeText($text) |
| 1574: | { |
| 1575: | return strtr($text, ['&' => '&', '<' => '<', '>' => '>', "\r" => '
']); |
| 1576: | } |
| 1577: | |
| 1578: | |
| 1579: | |
| 1580: | |
| 1581: | |
| 1582: | private static function escapeAttribute($text) |
| 1583: | { |
| 1584: | return strtr($text, ['&' => '&', '<' => '<', '>' => '>', '"' => '"', "\r" => ' ', "\n" => ' ', "\t" => '	']); |
| 1585: | } |
| 1586: | |
| 1587: | |
| 1588: | |
| 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: | |
| 1598: | |
| 1599: | |
| 1600: | |
| 1601: | |
| 1602: | |
| 1603: | |
| 1604: | |
| 1605: | |
| 1606: | |
| 1607: | |
| 1608: | |
| 1609: | |
| 1610: | |
| 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: | |
| 1627: | |
| 1628: | |
| 1629: | |
| 1630: | |
| 1631: | |
| 1632: | |
| 1633: | |
| 1634: | |
| 1635: | |
| 1636: | |
| 1637: | |
| 1638: | |
| 1639: | |
| 1640: | |
| 1641: | |
| 1642: | |
| 1643: | |
| 1644: | |
| 1645: | |
| 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: | |
| 1669: | |
| 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: | |
| 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: | |
| 1694: | |
| 1695: | |
| 1696: | |
| 1697: | |
| 1698: | |
| 1699: | |
| 1700: | |
| 1701: | |
| 1702: | |
| 1703: | |
| 1704: | |
| 1705: | |
| 1706: | |
| 1707: | |
| 1708: | |
| 1709: | |
| 1710: | |
| 1711: | |
| 1712: | |
| 1713: | |
| 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: | |
| 1748: | |
| 1749: | |
| 1750: | |
| 1751: | |
| 1752: | |
| 1753: | |
| 1754: | |
| 1755: | |
| 1756: | |
| 1757: | |
| 1758: | |
| 1759: | |
| 1760: | |
| 1761: | |
| 1762: | |
| 1763: | |
| 1764: | |
| 1765: | |
| 1766: | |
| 1767: | |
| 1768: | |
| 1769: | |
| 1770: | |
| 1771: | |
| 1772: | |
| 1773: | |
| 1774: | |
| 1775: | |
| 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: | |
| 1791: | |
| 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: | |
| 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: | |
| 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: | |
| 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: | |
| 1865: | |
| 1866: | |
| 1867: | |
| 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: | |
| 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: | |
| 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: | |
| 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: | |
| 2008: | |
| 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: | |
| 2040: | |
| 2041: | |
| 2042: | |
| 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: | |
| 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: | |
| 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: | |