1: <?php
2: /**
3: * X509Cert.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\core;
41:
42: // Use.
43: use DateTime;
44: use DateTimeZone;
45: use Exception;
46:
47: /**
48: * Analyze an X.509 certificate.
49: *
50: * The `X509Cert` class provides a set of convenient methods for extracting
51: * essential information contained in an X.509 certificate and for performing
52: * some useful checks. Every signature of a certificate is verified by
53: * OpenSSL. isTrustedBy() leaves the whole chain of trust to OpenSSL, at the
54: * current date; getTrustedChain(), which the seals use at the time of a
55: * time-stamp, builds the chain and checks the dates and the constraints of
56: * the CAs itself, from the DER of the certificates, with the rules of
57: * OpenSSL. This class belongs to the core, shared by the tokens
58: * (`XMLDSigToken`) and the seals.
59: */
60: class X509Cert
61: {
62: /** @var string The X.509 certificate in PEM format. */
63: private $cert;
64:
65: /** @var array The X.509 information of the certificate. */
66: private $x509Info;
67:
68: /** @var array|null The fields read from the DER of the certificate (see der()). */
69: private $der = null;
70:
71: /** Extensions, by OID. */
72: const OID_KEY_USAGE = '2.5.29.15';
73: const OID_BASIC_CONSTRAINTS = '2.5.29.19';
74: const OID_NAME_CONSTRAINTS = '2.5.29.30';
75: const OID_SUBJECT_KEY_ID = '2.5.29.14';
76: const OID_AUTHORITY_KEY_ID = '2.5.29.35';
77:
78: /** The key usages, by their bit in the extension. */
79: const KEY_USAGE_DIGITAL_SIGNATURE = 0;
80: const KEY_USAGE_NON_REPUDIATION = 1;
81: const KEY_USAGE_KEY_CERT_SIGN = 5;
82: const KEY_USAGE_CRL_SIGN = 6;
83:
84: /**
85: * The extensions whose criticality the verification of a chain accepts.
86: * They are those OpenSSL handles (`X509_supported_extension()`), but name
87: * constraints, which it enforces and this library does not: a CA
88: * certificate that has them is refused (see getTrustedChain()), and the
89: * extensions of IP addresses and AS numbers (RFC 3779) and of proxy
90: * certificates, which it does not handle either.
91: */
92: const HANDLED_CRITICAL_EXTENSIONS = [
93: '2.16.840.1.113730.1.1', // Netscape certificate type
94: self::OID_KEY_USAGE,
95: '2.5.29.17', // subject alternative name
96: self::OID_BASIC_CONSTRAINTS,
97: '2.5.29.32', // certificate policies
98: '2.5.29.31', // CRL distribution points
99: '2.5.29.37', // extended key usage
100: '1.3.6.1.5.5.7.48.1.5', // OCSP no check
101: '2.5.29.36', // policy constraints
102: '2.5.29.33', // policy mappings
103: '2.5.29.54', // inhibit any policy
104: ];
105:
106: /**
107: * The key types that may sign with each signature algorithm. OpenSSL
108: * takes a certificate whose signature algorithm does not suit the key of
109: * a certificate as not issued by it.
110: */
111: const SIGNATURE_KEY_TYPES = [
112: '1.2.840.113549.1.1.4' => ['rsa'], // md5WithRSAEncryption
113: '1.2.840.113549.1.1.5' => ['rsa'], // sha1WithRSAEncryption
114: '1.2.840.113549.1.1.11' => ['rsa'], // sha256WithRSAEncryption
115: '1.2.840.113549.1.1.12' => ['rsa'], // sha384WithRSAEncryption
116: '1.2.840.113549.1.1.13' => ['rsa'], // sha512WithRSAEncryption
117: '1.2.840.113549.1.1.14' => ['rsa'], // sha224WithRSAEncryption
118: '1.2.840.113549.1.1.10' => ['rsa'], // RSASSA-PSS
119: '1.2.840.10045.4.1' => ['ec'], // ecdsa-with-SHA1
120: '1.2.840.10045.4.3.1' => ['ec'], // ecdsa-with-SHA224
121: '1.2.840.10045.4.3.2' => ['ec'], // ecdsa-with-SHA256
122: '1.2.840.10045.4.3.3' => ['ec'], // ecdsa-with-SHA384
123: '1.2.840.10045.4.3.4' => ['ec'], // ecdsa-with-SHA512
124: '1.2.840.10040.4.3' => ['dsa'], // dsa-with-SHA1
125: '2.16.840.1.101.3.4.3.1' => ['dsa'], // dsa-with-SHA224
126: '2.16.840.1.101.3.4.3.2' => ['dsa'], // dsa-with-SHA256
127: ];
128:
129: /** The string types OpenSSL compares names by in canonical form
130: (`ASN1_MASK_CANON`): UTF8String, BMPString, UniversalString,
131: PrintableString, T61String, IA5String, VisibleString. */
132: const CANONICAL_STRING_TAGS = [0x0c, 0x1e, 0x1c, 0x13, 0x14, 0x16, 0x1a];
133:
134: /** The deepest chain OpenSSL builds by default. */
135: const MAX_CHAIN_LENGTH = 100;
136:
137:
138: /**
139: * Create a new X509Cert object.
140: *
141: * @param string $cert An X.509 certificate (public key) in PEM format.
142: *
143: * @throws Exception
144: */
145: public function __construct($cert)
146: {
147: // Check that OpenSSL can read the certificate.
148: if (!is_string($cert) || false === @openssl_x509_read($cert))
149: {
150: throw new Exception("Invalid certificate!");
151: }
152:
153: // Get X.509 information.
154: $x509Info = openssl_x509_parse($cert);
155: if ($x509Info === false)
156: {
157: $msg = "Failed to extract X.509 information from certificate!";
158: throw new Exception($msg);
159: }
160:
161: // Store the PEM certificate.
162: $this->cert = $cert;
163:
164: // Store X.509 information.
165: $this->x509Info = $x509Info;
166: }
167:
168:
169: /**
170: * Get the certificate (public key) in PEM format.
171: *
172: * @return String The certificate (public key) in PEM format.
173: */
174: public function getPem()
175: {
176: return $this->cert;
177: }
178:
179:
180: /**
181: * Get the fingerprint of the certificate: the hash of its DER encoding.
182: *
183: * Two certificates are the same certificate if, and only if, their
184: * fingerprints are equal.
185: *
186: * @param string $algorithm The hash algorithm. Default: 'sha256'.
187: *
188: * @return string The fingerprint, as a lowercase hexadecimal string.
189: *
190: * @throws Exception
191: */
192: public function getFingerprint($algorithm = 'sha256')
193: {
194: $fingerprint = openssl_x509_fingerprint($this->cert, $algorithm);
195: if (false === $fingerprint)
196: {
197: throw new Exception("Failed to compute the fingerprint of the certificate!");
198: }
199:
200: return $fingerprint;
201: }
202:
203:
204: /**
205: * Get the issuer information of the certificate.
206: *
207: * @return array The issuer information of the certificate.
208: */
209: public function getIssuer()
210: {
211: return $this->x509Info['issuer'];
212: }
213:
214:
215: /**
216: * Get the subject information of the certificate.
217: *
218: * @return array The subject information of the certificate.
219: */
220: public function getSubject()
221: {
222: return $this->x509Info['subject'];
223: }
224:
225:
226: /**
227: * Get the Distinguished Name of the certificate.
228: *
229: * @return string The Distinguished Name of the certificate.
230: */
231: public function getDN()
232: {
233: return $this->x509Info['name'];
234: }
235:
236:
237: /**
238: * Get the UTC date from which the certificate is valid.
239: *
240: * @param string $dateFormat The format of the returned date.
241: * Default: 'ymdHise'
242: *
243: * @return string|false The date from which the certificate is valid,
244: * FALSE if $dateFormat is invalid.
245: */
246: public function getValidFrom($dateFormat = 'ymdHise')
247: {
248: return $this->_date('validFrom_time_t')->format($dateFormat);
249: }
250:
251:
252: /**
253: * Get the UTC date to which the certificate is valid.
254: *
255: * @param string $dateFormat The format of the returned date.
256: * Default: 'ymdHise'
257: *
258: * @return string|false The date to which the certificate is valid,
259: * FALSE if $dateFormat is invalid.
260: */
261: public function getValidTo($dateFormat = 'ymdHise')
262: {
263: return $this->_date('validTo_time_t')->format($dateFormat);
264: }
265:
266:
267: /**
268: * Get a date of the certificate, from the UNIX timestamp OpenSSL gives
269: * for it.
270: *
271: * openssl_x509_parse() also gives the dates as written in the
272: * certificate, "validFrom" and "validTo", but X.509 writes a date before
273: * 2050 as UTCTime (YYMMDDHHMMSSZ) and from 2050 on as GeneralizedTime
274: * (YYYYMMDDHHMMSSZ): read with one format, the other gives no date. The
275: * timestamps "validFrom_time_t" and "validTo_time_t" hold both.
276: *
277: * @param string $field "validFrom_time_t" or "validTo_time_t".
278: *
279: * @return DateTime The date, in UTC.
280: */
281: private function _date($field)
282: {
283: $date = new DateTime('@' . (int) $this->x509Info[$field]);
284: $date->setTimezone(new DateTimeZone('UTC'));
285:
286: return $date;
287: }
288:
289:
290: /**
291: * Indicates whether the certificate is out of date or not.
292: *
293: * @return boolean TRUE if embedded certificate is out of date,
294: * FALSE otherwise.
295: */
296: public function isOutOfDate()
297: {
298: // Compare UNIX timestamps (see _date()).
299: $now = time();
300:
301: return $now < $this->_date('validFrom_time_t')->getTimestamp()
302: || $now > $this->_date('validTo_time_t')->getTimestamp();
303: }
304:
305:
306: /**
307: * Indicates whether the key usage of the certificate allows it to sign
308: * data.
309: *
310: * The "keyUsage" extension, when the certificate has one, must allow
311: * "digitalSignature" or "nonRepudiation". A certificate without this
312: * extension is not restricted.
313: *
314: * @return boolean TRUE if the certificate may sign data, FALSE otherwise.
315: */
316: public function canSign()
317: {
318: if (!isset($this->x509Info['extensions']['keyUsage']))
319: {
320: return true;
321: }
322:
323: $keyUsage = array_map('trim', explode(',', $this->x509Info['extensions']['keyUsage']));
324:
325: return in_array('Digital Signature', $keyUsage, true)
326: || in_array('Non Repudiation', $keyUsage, true);
327: }
328:
329:
330: /**
331: * Check that the certificate is trusted: OpenSSL builds and verifies its
332: * chain up to a certificate of the given CA files.
333: *
334: * Every certificate of the given files is trusted, and the chain is built
335: * from these certificates only. OpenSSL verifies the signature of each
336: * link, the validity dates of every certificate of the chain at the
337: * current date, that each issuer is a CA (basic constraints, key usage,
338: * path length) and that the chain ends at a self-signed certificate of
339: * the given files. A chain that stops at an intermediate CA is rejected:
340: * to trust the certificates issued by an intermediate CA, give its
341: * certificate and the certificates up to its root (in one file or in
342: * several). A certificate issued by another intermediate CA of the same
343: * root is then rejected, since the chain cannot be built without that
344: * other intermediate certificate.
345: *
346: * @param string|array $caCertPaths The path, or the list of paths, of PEM
347: * files that hold the trusted CA certificates.
348: *
349: * @return boolean TRUE if the chain of the certificate has been verified,
350: * FALSE otherwise.
351: *
352: * @throws Exception
353: */
354: public function isTrustedBy($caCertPaths)
355: {
356: $caCertPaths = (array) $caCertPaths;
357: if (empty($caCertPaths))
358: {
359: throw new Exception("No CA certificate file to verify the certificate chain!");
360: }
361: foreach ($caCertPaths as $caCertPath)
362: {
363: if (!is_string($caCertPath) || !is_file($caCertPath) || !is_readable($caCertPath))
364: {
365: throw new Exception("Cannot read CA certificate file! File: " . (is_string($caCertPath) ? $caCertPath : gettype($caCertPath)));
366: }
367: }
368:
369: // Only the given CA certificates may be trusted, not those of the
370: // system. When the list given to openssl_x509_checkpurpose() holds no
371: // directory, PHP adds the default CA directory of OpenSSL (that of
372: // the system, or the one named by the environment variable
373: // SSL_CERT_DIR) to the trusted certificates, and the default CA file
374: // when the list holds no file: any public CA would then be a trust
375: // anchor. An empty directory, created for this call, is therefore
376: // always added to the list. This guard must not be removed.
377: $emptyDir = self::createEmptyDirectory();
378: try
379: {
380: // X509_PURPOSE_ANY: the chain is verified, but no purpose is
381: // required from the certificate (see canSign() for its key
382: // usage). openssl_x509_checkpurpose() returns -1 on error: only
383: // TRUE is a success.
384: $caInfo = array_merge(array_values($caCertPaths), [$emptyDir]);
385: return true === openssl_x509_checkpurpose($this->cert, X509_PURPOSE_ANY, $caInfo);
386: }
387: finally
388: {
389: @rmdir($emptyDir);
390: }
391: }
392:
393:
394: /**
395: * Create an empty directory, readable by its owner only, in the
396: * temporary directory of the system.
397: *
398: * @return string The path of the directory.
399: *
400: * @throws Exception If the directory cannot be created.
401: */
402: static private function createEmptyDirectory()
403: {
404: // mkdir() fails if the path exists (even as a link): the directory is
405: // the one created here, hence empty.
406: $path = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'ezxmldsig-ca-' . bin2hex(random_bytes(16));
407: if (!@mkdir($path, 0700))
408: {
409: throw new Exception("Cannot create an empty directory to verify the certificate chain in " . sys_get_temp_dir() . "!");
410: }
411:
412: return $path;
413: }
414:
415:
416: /**
417: * Check the origin of the certificate.
418: *
419: * Verify that the X.509 certificate has been issued by the given CA
420: * certificate: OpenSSL verifies the signature of the certificate with the
421: * public key of the CA certificate, the issuer name of the certificate
422: * must be the subject name of the CA certificate, and the CA certificate
423: * must be a CA ("CA:TRUE" basic constraint and, if it has a "keyUsage"
424: * extension, "keyCertSign").
425: *
426: * Only this link is checked: neither the validity dates nor the chain of
427: * the CA certificate. Use `isTrustedBy()` to verify the whole chain.
428: *
429: * NOTE: More than one CA certificate can give a positive result,
430: * some CAs re-issue signing certificates after having only
431: * changed the expiration dates.
432: * Note that it also works with self-signed CA certificates. In this
433: * case, pass the X.509 certificate itself to the function.
434: *
435: * @param string $caCert The certificate (in PEM format) corresponding to
436: * the private key that is supposed to be used by the CA to sign the X.509
437: * certificate.
438: *
439: * @return boolean TRUE if origin of the X.509 certificate has been
440: * validated, FALSE otherwise.
441: *
442: * @throws Exception
443: */
444: public function isValidCA($caCert)
445: {
446: if (!is_string($caCert) || false === @openssl_x509_read($caCert))
447: {
448: throw new Exception("Invalid CA certificate!");
449: }
450:
451: $caInfo = openssl_x509_parse($caCert);
452: if ($caInfo === false)
453: {
454: throw new Exception("Failed to extract X.509 information from CA certificate!");
455: }
456:
457: // The CA certificate must be allowed to issue certificates.
458: $basicConstraints = isset($caInfo['extensions']['basicConstraints']) ? $caInfo['extensions']['basicConstraints'] : '';
459: if (!in_array('CA:TRUE', array_map('trim', explode(',', $basicConstraints)), true))
460: {
461: return false;
462: }
463: if (isset($caInfo['extensions']['keyUsage']))
464: {
465: $keyUsage = array_map('trim', explode(',', $caInfo['extensions']['keyUsage']));
466: if (!in_array('Certificate Sign', $keyUsage, true))
467: {
468: return false;
469: }
470: }
471:
472: // The certificate must name the CA as its issuer.
473: if ($this->x509Info['issuer'] !== $caInfo['subject'])
474: {
475: return false;
476: }
477:
478: // The signature of the certificate must verify with the public key of
479: // the CA. openssl_x509_verify() returns 1 (valid), 0 (invalid) or -1
480: // (error): only 1 is a success.
481: return 1 === openssl_x509_verify($this->cert, $caCert);
482: }
483:
484:
485: /**
486: * Convert PEM encoded X.509 certificate to DER encoding.
487: *
488: * @param string $pemCertificate PEM encoded X.509 certificate.
489: *
490: * @return string|false DER encoded X.509 certificate on success,
491: * FALSE on failure.
492: */
493: static public function pemToDer($pemCertificate)
494: {
495: if (!is_string($pemCertificate))
496: {
497: // Invalid parameter.
498: return false;
499: }
500:
501: $pattern = '/(-----((BEGIN)|(END)) CERTIFICATE-----)/';
502: $base64Content = preg_split($pattern, $pemCertificate);
503: if (!isset($base64Content[1]))
504: {
505: // Invalid PEM certificate.
506: return false;
507: }
508:
509: // Returns the DER encoded certificate.
510: return base64_decode($base64Content[1]);
511: }
512:
513:
514: /**
515: * Convert DER encoded X.509 certificate to PEM encoding.
516: *
517: * The base64 is written in lines of 64 characters (RFC 7468): the PEM is
518: * the one OpenSSL writes for the same certificate.
519: *
520: * @param string $derCertificate DER encoded X.509 certificate.
521: *
522: * @return string|false PEM encoded X.509 certificate on success,
523: * FALSE on failure.
524: */
525: static public function derToPem($derCertificate)
526: {
527: if (!is_string($derCertificate))
528: {
529: // Invalid parameter.
530: return false;
531: }
532:
533: $b64DerCert = base64_encode($derCertificate);
534: $pem = "-----BEGIN CERTIFICATE-----\n";
535: // Lines of 64 characters, as RFC 7468 (section 2) requires and
536: // OpenSSL writes.
537: $pem .= implode("\n", str_split($b64DerCert, 64)) . "\n";
538: $pem .= "-----END CERTIFICATE-----\n";
539:
540: return $pem;
541: }
542:
543:
544: /**
545: * Indicates whether a name (the subject or the issuer of a certificate,
546: * as returned by `openssl_x509_parse()`) holds the expected fields.
547: *
548: * Each expected field must be present with the very same value: character
549: * case is significant, and a field repeated in the name (e.g. two "OU")
550: * is an array of its values.
551: *
552: * @param array $name The name to check.
553: *
554: * @param array $expected The expected fields.
555: *
556: * @return boolean TRUE if every expected field matches, FALSE otherwise.
557: *
558: * @internal
559: */
560: public static function matchesName($name, $expected)
561: {
562: foreach ($expected as $key => $value)
563: {
564: if (!isset($name[$key]) || $name[$key] !== $value)
565: {
566: return false;
567: }
568: }
569:
570: return true;
571: }
572:
573:
574: /**
575: * The DER encoding of the certificate.
576: *
577: * @return string The DER.
578: */
579: public function getDer()
580: {
581: return self::pemToDer($this->cert);
582: }
583:
584:
585: /**
586: * The serial number, as unsigned big-endian bytes.
587: *
588: * @return string The bytes.
589: */
590: public function getSerialNumber()
591: {
592: $serial = $this->der()['serial'];
593:
594: return strlen($serial) > 1 && "\0" === $serial[0] ? substr($serial, 1) : $serial;
595: }
596:
597:
598: /**
599: * The DER encoding of the issuer name, as a CRL names its issuer.
600: *
601: * @return string The DER.
602: */
603: public function getRawIssuer()
604: {
605: return $this->der()['rawIssuer'];
606: }
607:
608:
609: /**
610: * The DER encoding of the subject name.
611: *
612: * @return string The DER.
613: */
614: public function getRawSubject()
615: {
616: return $this->der()['rawSubject'];
617: }
618:
619:
620: /**
621: * An extension, by its OID.
622: *
623: * @param string $oid The OID, in its dotted form.
624: *
625: * @return array|null 'critical' (boolean) and 'value' (the DER of its
626: * value, the content of its OCTET STRING), or NULL.
627: */
628: public function getExtension($oid)
629: {
630: $extensions = $this->der()['extensions'];
631:
632: return isset($extensions[$oid]) ? $extensions[$oid] : null;
633: }
634:
635:
636: /**
637: * Indicates whether the key usage of the certificate, if it has one,
638: * allows it to sign CRLs.
639: *
640: * @return boolean TRUE if it may sign CRLs.
641: */
642: public function canSignCrls()
643: {
644: $keyUsage = $this->der()['keyUsage'];
645:
646: return null === $keyUsage || !empty($keyUsage[self::KEY_USAGE_CRL_SIGN]);
647: }
648:
649:
650: /**
651: * Indicates whether the certificate is a CA by its basic constraints.
652: *
653: * @return boolean TRUE if it is a CA.
654: */
655: public function isCA()
656: {
657: $basicConstraints = $this->der()['basicConstraints'];
658:
659: return null !== $basicConstraints && $basicConstraints['ca'];
660: }
661:
662:
663: /**
664: * The chain of the certificate, from it to its root, built and verified
665: * from the given CA certificates as OpenSSL does for `isTrustedBy()`, at
666: * the current date or at another one; NULL if the certificate is not
667: * trusted.
668: *
669: * Every given certificate is trusted, and the chain is built from these
670: * certificates only (and the `$untrusted` ones), never from those of the
671: * system. A certificate is taken as the issuer of another one when its
672: * subject is the issuer of the other one (names compared in the canonical
673: * form of OpenSSL), when the authority key identifier of the other one
674: * matches it, and when its key suits the signature algorithm of the other
675: * one. Then:
676: *
677: * - OpenSSL verifies the signature of each link (but the root's own);
678: * - every certificate of the chain, the root included, is valid at the
679: * date of the verification;
680: * - every issuer is a CA: basic constraints with "CA:TRUE" and, if it has
681: * a key usage, "keyCertSign"; the root may also be a CA by its key
682: * usage alone, or by being self-signed and of version 1;
683: * - the path length of each CA is respected;
684: * - no certificate has a critical extension the verification does not
685: * handle, nor a repeated or malformed extension.
686: *
687: * A chain that stops at an intermediate CA is rejected: the root must be
688: * one of the CA certificates. Name constraints are not enforced: a CA
689: * certificate that has them is rejected, where OpenSSL would enforce
690: * them.
691: *
692: * @param string|array $caCerts The CA certificates: paths of PEM files,
693: * or PEM contents, each of which may hold several certificates.
694: *
695: * @param array $untrusted Certificates (X509Cert) the chain may be built
696: * with, after the CA certificates, without being trusted: the
697: * intermediate CAs a signature embeds.
698: *
699: * @param int|null $at The UNIX time the certificates must be valid at;
700: * NULL for the current time.
701: *
702: * @return array|null The chain (X509Cert), or NULL.
703: *
704: * @throws Exception If a CA certificate file cannot be read.
705: */
706: public function getTrustedChain($caCerts, array $untrusted = [], $at = null)
707: {
708: $sources = (array) $caCerts;
709: if (empty($sources))
710: {
711: throw new Exception("No CA certificate file to verify the certificate chain!");
712: }
713: $trusted = [];
714: foreach ($sources as $source)
715: {
716: $pem = self::readPemSource($source);
717: if (null === $pem)
718: {
719: throw new Exception("Cannot read CA certificate file! File: " . (is_string($source) ? $source : gettype($source)));
720: }
721: // A file OpenSSL cannot load as a whole trusts nothing.
722: if (!preg_match_all('/-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----/s', $pem, $blocks))
723: {
724: return null;
725: }
726: foreach ($blocks[0] as $block)
727: {
728: try
729: {
730: $trusted[] = new X509Cert($block);
731: }
732: catch (Exception $e)
733: {
734: return null;
735: }
736: }
737: }
738:
739: $time = null === $at ? time() : (int) floor($at);
740: $chain = $this->buildChain($trusted, $untrusted, $time);
741:
742: return null !== $chain && self::verifyChain($chain, $time) ? $chain : null;
743: }
744:
745:
746: /**
747: * The content of a PEM source: a path of a file, or PEM content.
748: *
749: * @return string|null The content, or NULL if the file cannot be read.
750: */
751: private static function readPemSource($source)
752: {
753: if (!is_string($source))
754: {
755: return null;
756: }
757: if (false !== strpos($source, '-----BEGIN'))
758: {
759: return $source;
760: }
761: if (!is_file($source) || !is_readable($source))
762: {
763: return null;
764: }
765: $content = file_get_contents($source);
766:
767: return false === $content ? null : $content;
768: }
769:
770:
771: /**
772: * Build the chain of the certificate from the trusted certificates, as
773: * OpenSSL does: from the certificate, take as issuer the first trusted
774: * certificate, then the first untrusted one, that may have issued it and
775: * is valid at the given time (or else the last one that may have issued
776: * it), until a self-signed certificate, which must be a trusted one.
777: *
778: * @return array|null The chain, from this certificate to its root, or NULL.
779: */
780: private function buildChain(array $trusted, array $untrusted, $time)
781: {
782: $known = array_merge($trusted, $untrusted);
783: $chain = [$this];
784: for (;;)
785: {
786: $last = $chain[count($chain) - 1];
787: if ($last->isSelfSigned())
788: {
789: foreach ($trusted as $cert)
790: {
791: if ($cert->getDer() === $last->getDer())
792: {
793: return $chain;
794: }
795: }
796: return null;
797: }
798: if (count($chain) >= self::MAX_CHAIN_LENGTH)
799: {
800: return null;
801: }
802: $issuer = null;
803: $lastCandidate = null;
804: foreach ($known as $cert)
805: {
806: if ($last->mayBeIssuedBy($cert))
807: {
808: $lastCandidate = $cert;
809: if (null === $issuer && $cert->isValidAt($time))
810: {
811: $issuer = $cert;
812: }
813: }
814: }
815: $issuer = null !== $issuer ? $issuer : $lastCandidate;
816: if (null === $issuer)
817: {
818: return null;
819: }
820: $chain[] = $issuer;
821: }
822: }
823:
824:
825: /**
826: * Verify a chain built by buildChain(), as OpenSSL does (see
827: * getTrustedChain()).
828: */
829: private static function verifyChain(array $chain, $time)
830: {
831: $pathLength = 0;
832: foreach ($chain as $i => $cert)
833: {
834: if (!$cert->isValidAt($time))
835: {
836: return false;
837: }
838: // openssl_x509_verify() returns 1 (valid), 0 (invalid) or -1
839: // (error): only 1 is a success.
840: if (isset($chain[$i + 1]) && 1 !== openssl_x509_verify($cert->cert, $chain[$i + 1]->cert))
841: {
842: return false;
843: }
844:
845: $der = $cert->der();
846: if ($der['invalidExtension'])
847: {
848: return false;
849: }
850: foreach ($der['extensions'] as $oid => $extension)
851: {
852: if ($extension['critical'] && !in_array($oid, self::HANDLED_CRITICAL_EXTENSIONS, true))
853: {
854: return false;
855: }
856: }
857: if (0 === $i)
858: {
859: continue;
860: }
861:
862: if (isset($der['extensions'][self::OID_NAME_CONSTRAINTS]))
863: {
864: return false;
865: }
866: // An intermediate CA must be one by its basic constraints; the
867: // root may be one otherwise.
868: $kind = $cert->caKind();
869: if (0 === $kind || (isset($chain[$i + 1]) && 1 !== $kind))
870: {
871: return false;
872: }
873: // The path length of a CA counts the CAs below it, but the
874: // self-issued ones.
875: $limit = null === $der['basicConstraints'] ? null : $der['basicConstraints']['pathLength'];
876: if ($i > 1 && null !== $limit && $pathLength > $limit)
877: {
878: return false;
879: }
880: if (!$cert->isSelfIssued())
881: {
882: $pathLength++;
883: }
884: }
885:
886: return true;
887: }
888:
889:
890: /**
891: * Indicates whether the certificate may have been issued by another one,
892: * as OpenSSL tells it to build a chain (`ossl_x509_likely_issued()`): the
893: * issuer of the certificate is the subject of the other one, its
894: * authority key identifier, if any, matches the other one, and the key of
895: * the other one suits its signature algorithm. Neither the signature nor
896: * the key usage of the other one are checked here.
897: */
898: private function mayBeIssuedBy(X509Cert $issuer)
899: {
900: $der = $this->der();
901: $issuerDer = $issuer->der();
902: if ($der['invalidExtension'] || $issuerDer['invalidExtension'])
903: {
904: return false;
905: }
906: if (!self::sameName($der['issuer'], $issuerDer['subject']))
907: {
908: return false;
909: }
910: $akid = $der['authorityKeyId'];
911: if (null !== $akid)
912: {
913: if (null !== $akid['keyId'] && null !== $issuerDer['subjectKeyId'] && $akid['keyId'] !== $issuerDer['subjectKeyId'])
914: {
915: return false;
916: }
917: if (null !== $akid['serial'] && $akid['serial'] !== $issuerDer['serial'])
918: {
919: return false;
920: }
921: if (null !== $akid['issuer'] && !self::sameName($akid['issuer'], $issuerDer['issuer']))
922: {
923: return false;
924: }
925: }
926: $keyTypes = isset(self::SIGNATURE_KEY_TYPES[$der['signatureAlgorithm']]) ? self::SIGNATURE_KEY_TYPES[$der['signatureAlgorithm']] : [];
927:
928: return in_array($issuer->keyType(), $keyTypes, true);
929: }
930:
931:
932: /**
933: * Indicates whether the certificate is self-signed, as OpenSSL tells it
934: * (its signature is not verified).
935: */
936: private function isSelfSigned()
937: {
938: return $this->mayBeIssuedBy($this);
939: }
940:
941:
942: /**
943: * Indicates whether the certificate is self-issued: its subject is its
944: * issuer, whatever key signed it.
945: */
946: private function isSelfIssued()
947: {
948: $der = $this->der();
949:
950: return self::sameName($der['issuer'], $der['subject']);
951: }
952:
953:
954: /**
955: * Indicates whether the certificate is valid at a UNIX time, as OpenSSL
956: * tells it: it is no longer valid at its very date of expiry.
957: */
958: private function isValidAt($time)
959: {
960: return $time >= (int) $this->x509Info['validFrom_time_t'] && $time < (int) $this->x509Info['validTo_time_t'];
961: }
962:
963:
964: /**
965: * Indicates how the certificate is a CA, as OpenSSL does
966: * (`X509_check_ca()`): 0 if it is not, 1 by its basic constraints, 3 by
967: * being self-signed and of version 1, 4 by its key usage alone.
968: */
969: private function caKind()
970: {
971: $der = $this->der();
972: if (null !== $der['keyUsage'] && empty($der['keyUsage'][self::KEY_USAGE_KEY_CERT_SIGN]))
973: {
974: return 0;
975: }
976: if (null !== $der['basicConstraints'])
977: {
978: return $der['basicConstraints']['ca'] ? 1 : 0;
979: }
980: if (1 === $der['version'] && $this->isSelfSigned())
981: {
982: return 3;
983: }
984:
985: return null !== $der['keyUsage'] ? 4 : 0;
986: }
987:
988:
989: /**
990: * The type of the public key: "rsa", "ec", "dsa", or NULL for another
991: * one.
992: */
993: private function keyType()
994: {
995: $key = @openssl_pkey_get_public($this->cert);
996: $details = false === $key ? false : @openssl_pkey_get_details($key);
997: if (false === $details)
998: {
999: return null;
1000: }
1001: switch ($details['type'])
1002: {
1003: case OPENSSL_KEYTYPE_RSA:
1004: return 'rsa';
1005: case OPENSSL_KEYTYPE_EC:
1006: return 'ec';
1007: case OPENSSL_KEYTYPE_DSA:
1008: return 'dsa';
1009: default:
1010: return null;
1011: }
1012: }
1013:
1014:
1015: /**
1016: * The fields of the certificate read from its DER, once: those the
1017: * OpenSSL extension of PHP does not give.
1018: *
1019: * TBSCertificate: [0] version (absent: v1), serialNumber, signature,
1020: * issuer, validity, subject, subjectPublicKeyInfo, [1] issuerUniqueID,
1021: * [2] subjectUniqueID, [3] extensions. An extension the verification of
1022: * a chain reads that cannot be decoded makes the certificate invalid, as
1023: * for OpenSSL.
1024: *
1025: * @throws Exception If the DER cannot be read.
1026: */
1027: private function der()
1028: {
1029: if (null !== $this->der)
1030: {
1031: return $this->der;
1032: }
1033: try
1034: {
1035: $tbs = Der::childrenOf(Der::childrenOf(Der::readElement($this->getDer()), Der::SEQUENCE)[0], Der::SEQUENCE);
1036: $version = 1;
1037: if (isset($tbs[0]) && 0xa0 === $tbs[0]['tag'])
1038: {
1039: $version = Der::decodeSmallInteger(Der::readElement(array_shift($tbs)['content'])) + 1;
1040: }
1041: if (count($tbs) < 6 || Der::INTEGER !== $tbs[0]['tag'])
1042: {
1043: throw new Exception('DER: malformed certificate.');
1044: }
1045: $info = [
1046: 'version' => $version,
1047: 'serial' => $tbs[0]['content'],
1048: 'signatureAlgorithm' => Der::decodeOid(Der::childrenOf($tbs[1], Der::SEQUENCE)[0]),
1049: 'rawIssuer' => Der::reencode($tbs[2]),
1050: 'issuer' => self::readName($tbs[2]),
1051: 'rawSubject' => Der::reencode($tbs[4]),
1052: 'subject' => self::readName($tbs[4]),
1053: ];
1054: $extensionsElement = null;
1055: foreach (array_slice($tbs, 6) as $element)
1056: {
1057: if (0xa3 === $element['tag'])
1058: {
1059: $extensionsElement = $element;
1060: }
1061: }
1062: list($info['extensions'], $info['invalidExtension']) = self::readExtensions($extensionsElement);
1063: }
1064: catch (Exception $e)
1065: {
1066: throw new Exception("Failed to extract X.509 information from certificate!");
1067: }
1068:
1069: $info += ['keyUsage' => null, 'basicConstraints' => null, 'subjectKeyId' => null, 'authorityKeyId' => null];
1070: $extensions = $info['extensions'];
1071: try
1072: {
1073: if (isset($extensions[self::OID_KEY_USAGE]))
1074: {
1075: $info['keyUsage'] = Der::decodeBits(Der::readElement($extensions[self::OID_KEY_USAGE]['value']));
1076: }
1077: if (isset($extensions[self::OID_BASIC_CONSTRAINTS]))
1078: {
1079: $info['basicConstraints'] = self::readBasicConstraints($extensions[self::OID_BASIC_CONSTRAINTS]['value']);
1080: // A path length without CA is invalid for OpenSSL.
1081: if (null !== $info['basicConstraints']['pathLength'] && !$info['basicConstraints']['ca'])
1082: {
1083: $info['invalidExtension'] = true;
1084: }
1085: }
1086: if (isset($extensions[self::OID_SUBJECT_KEY_ID]))
1087: {
1088: $element = Der::readElement($extensions[self::OID_SUBJECT_KEY_ID]['value']);
1089: if (Der::OCTET_STRING !== $element['tag'])
1090: {
1091: throw new Exception('DER: malformed subject key identifier.');
1092: }
1093: $info['subjectKeyId'] = $element['content'];
1094: }
1095: if (isset($extensions[self::OID_AUTHORITY_KEY_ID]))
1096: {
1097: $info['authorityKeyId'] = self::readAuthorityKeyId($extensions[self::OID_AUTHORITY_KEY_ID]['value']);
1098: }
1099: }
1100: catch (Exception $e)
1101: {
1102: $info['invalidExtension'] = true;
1103: }
1104:
1105: return $this->der = $info;
1106: }
1107:
1108:
1109: /**
1110: * Read the extensions: by OID, 'critical' and 'value'; and whether one
1111: * is repeated.
1112: */
1113: private static function readExtensions($element)
1114: {
1115: $extensions = [];
1116: $invalid = false;
1117: if (null === $element)
1118: {
1119: return [$extensions, $invalid];
1120: }
1121: foreach (Der::childrenOf(Der::readElement($element['content']), Der::SEQUENCE) as $extension)
1122: {
1123: $fields = Der::childrenOf($extension, Der::SEQUENCE);
1124: if (count($fields) < 2 || count($fields) > 3 || Der::OCTET_STRING !== $fields[count($fields) - 1]['tag'])
1125: {
1126: throw new Exception('DER: malformed extension.');
1127: }
1128: $oid = Der::decodeOid($fields[0]);
1129: if (isset($extensions[$oid]))
1130: {
1131: $invalid = true;
1132: }
1133: $extensions[$oid] = [
1134: 'critical' => 3 === count($fields) ? Der::decodeBoolean($fields[1]) : false,
1135: 'value' => $fields[count($fields) - 1]['content'],
1136: ];
1137: }
1138:
1139: return [$extensions, $invalid];
1140: }
1141:
1142:
1143: /**
1144: * Read the basic constraints: 'ca' and 'pathLength' (NULL if none).
1145: */
1146: private static function readBasicConstraints($value)
1147: {
1148: $ca = false;
1149: $pathLength = null;
1150: foreach (Der::childrenOf(Der::readElement($value), Der::SEQUENCE) as $field)
1151: {
1152: if (Der::BOOLEAN === $field['tag'] && null === $pathLength)
1153: {
1154: $ca = Der::decodeBoolean($field);
1155: }
1156: else
1157: {
1158: $pathLength = Der::decodeSmallInteger($field);
1159: }
1160: }
1161:
1162: return ['ca' => $ca, 'pathLength' => $pathLength];
1163: }
1164:
1165:
1166: /**
1167: * Read the authority key identifier: [0] key identifier, [1] issuer (the
1168: * first directory name of the general names, as OpenSSL takes it), [2]
1169: * serial number of the issuer.
1170: */
1171: private static function readAuthorityKeyId($value)
1172: {
1173: $akid = ['keyId' => null, 'issuer' => null, 'serial' => null];
1174: foreach (Der::childrenOf(Der::readElement($value), Der::SEQUENCE) as $field)
1175: {
1176: if (0x80 === $field['tag'])
1177: {
1178: $akid['keyId'] = $field['content'];
1179: }
1180: elseif (0xa1 === $field['tag'])
1181: {
1182: foreach (Der::readElements($field['content']) as $name)
1183: {
1184: if (0xa4 === $name['tag'])
1185: {
1186: $akid['issuer'] = self::readName(Der::readElement($name['content']));
1187: break;
1188: }
1189: }
1190: }
1191: elseif (0x82 === $field['tag'])
1192: {
1193: $akid['serial'] = $field['content'];
1194: }
1195: else
1196: {
1197: throw new Exception('DER: malformed authority key identifier.');
1198: }
1199: }
1200:
1201: return $akid;
1202: }
1203:
1204:
1205: /**
1206: * Read a name (a sequence of sets of fields), in the canonical form
1207: * OpenSSL compares names by (`x509_name_canon()`): the values of the
1208: * string types converted to UTF-8, without leading and trailing white
1209: * space, each run of white space collapsed into one space, ASCII letters
1210: * in lowercase; the values of other types kept as they are, with their
1211: * type. The fields of an RDN are compared as a set. NULL if a value
1212: * cannot be converted: the name then matches none.
1213: */
1214: private static function readName($element)
1215: {
1216: $rdns = [];
1217: foreach (Der::childrenOf($element, Der::SEQUENCE) as $set => $rdn)
1218: {
1219: foreach (Der::childrenOf($rdn, Der::SET) as $attribute)
1220: {
1221: $parts = Der::childrenOf($attribute, Der::SEQUENCE);
1222: if (2 !== count($parts))
1223: {
1224: throw new Exception('DER: malformed name.');
1225: }
1226: $oid = Der::decodeOid($parts[0]);
1227: $value = $parts[1];
1228: if (in_array($value['tag'], self::CANONICAL_STRING_TAGS, true))
1229: {
1230: $utf8 = self::toUtf8($value);
1231: if (null === $utf8)
1232: {
1233: return null;
1234: }
1235: $text = 's:' . bin2hex(self::canonicalString($utf8));
1236: }
1237: else
1238: {
1239: $text = $value['tag'] . ':' . bin2hex($value['content']);
1240: }
1241: $rdns[$set][] = $oid . '=' . $text;
1242: }
1243: }
1244: $canonical = [];
1245: foreach ($rdns as $rdn)
1246: {
1247: sort($rdn, SORT_STRING);
1248: $canonical[] = implode('+', $rdn);
1249: }
1250:
1251: return implode('/', $canonical);
1252: }
1253:
1254:
1255: /**
1256: * Indicates whether two names are the same name, as OpenSSL compares
1257: * them (`X509_NAME_cmp()`).
1258: */
1259: private static function sameName($a, $b)
1260: {
1261: return null !== $a && $a === $b;
1262: }
1263:
1264:
1265: /**
1266: * Convert the value of a field to UTF-8, as OpenSSL does
1267: * (`ASN1_STRING_to_UTF8()`), or give NULL for a type it does not
1268: * convert.
1269: */
1270: private static function toUtf8($value)
1271: {
1272: $content = $value['content'];
1273: switch ($value['tag'])
1274: {
1275: case 0x0c: // UTF8String
1276: return preg_match('//u', $content) ? $content : null;
1277: case 0x12: // NumericString
1278: case 0x13: // PrintableString
1279: case 0x14: // T61String
1280: case 0x16: // IA5String
1281: case 0x1a: // VisibleString
1282: // Each byte is a character, as in ISO-8859-1.
1283: return self::codePointsToUtf8('' === $content ? [] : array_values(unpack('C*', $content)));
1284: case 0x1e: // BMPString
1285: if (0 !== strlen($content) % 2)
1286: {
1287: return null;
1288: }
1289: // UTF-16BE, surrogate pairs included.
1290: $units = '' === $content ? [] : array_values(unpack('n*', $content));
1291: $codePoints = [];
1292: for ($i = 0, $n = count($units); $i < $n; $i++)
1293: {
1294: $unit = $units[$i];
1295: if ($unit >= 0xd800 && $unit <= 0xdbff && $i + 1 < $n && $units[$i + 1] >= 0xdc00 && $units[$i + 1] <= 0xdfff)
1296: {
1297: $codePoints[] = 0x10000 + (($unit - 0xd800) << 10) + ($units[++$i] - 0xdc00);
1298: }
1299: else
1300: {
1301: $codePoints[] = $unit;
1302: }
1303: }
1304: return self::codePointsToUtf8($codePoints);
1305: case 0x1c: // UniversalString
1306: if (0 !== strlen($content) % 4)
1307: {
1308: return null;
1309: }
1310: return self::codePointsToUtf8('' === $content ? [] : array_values(unpack('N*', $content)));
1311: default:
1312: return null;
1313: }
1314: }
1315:
1316:
1317: /**
1318: * The UTF-8 encoding of code points, or NULL if one is not a Unicode
1319: * scalar value (a surrogate, or beyond U+10FFFF).
1320: */
1321: private static function codePointsToUtf8(array $codePoints)
1322: {
1323: $utf8 = '';
1324: foreach ($codePoints as $codePoint)
1325: {
1326: if ($codePoint < 0 || $codePoint > 0x10ffff || ($codePoint >= 0xd800 && $codePoint <= 0xdfff))
1327: {
1328: return null;
1329: }
1330: if ($codePoint < 0x80)
1331: {
1332: $utf8 .= chr($codePoint);
1333: }
1334: elseif ($codePoint < 0x800)
1335: {
1336: $utf8 .= chr(0xc0 | ($codePoint >> 6)) . chr(0x80 | ($codePoint & 0x3f));
1337: }
1338: elseif ($codePoint < 0x10000)
1339: {
1340: $utf8 .= chr(0xe0 | ($codePoint >> 12)) . chr(0x80 | (($codePoint >> 6) & 0x3f)) . chr(0x80 | ($codePoint & 0x3f));
1341: }
1342: else
1343: {
1344: $utf8 .= chr(0xf0 | ($codePoint >> 18)) . chr(0x80 | (($codePoint >> 12) & 0x3f)) . chr(0x80 | (($codePoint >> 6) & 0x3f)) . chr(0x80 | ($codePoint & 0x3f));
1345: }
1346: }
1347:
1348: return $utf8;
1349: }
1350:
1351:
1352: /**
1353: * Trim, collapse the white space of, and lowercase a string, as
1354: * `asn1_string_canon()` does with the ASCII characters.
1355: */
1356: private static function canonicalString($value)
1357: {
1358: $value = preg_replace('/\A[ \t\n\v\f\r]+|[ \t\n\v\f\r]+\z/', '', $value);
1359: $value = preg_replace('/[ \t\n\v\f\r]+/', ' ', $value);
1360:
1361: return strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
1362: }
1363: }
1364: