errorcode418/php
0
1<?php2 3/*4 * This file is part of composer/ca-bundle.5 *6 * (c) Composer <https://github.com/composer>7 *8 * For the full copyright and license information, please view9 * the LICENSE file that was distributed with this source code.10 */11 12namespace Composer\CaBundle;13 14use Psr\Log\LoggerInterface;15use Symfony\Component\Process\PhpProcess;16 17/**18 * @author Chris Smith <chris@cs278.org>19 * @author Jordi Boggiano <j.boggiano@seld.be>20 */21class CaBundle22{23 private static $caPath;24 private static $caFileValidity = array();25 private static $useOpensslParse;26 27 /**28 * Returns the system CA bundle path, or a path to the bundled one29 *30 * This method was adapted from Sslurp.31 * https://github.com/EvanDotPro/Sslurp32 *33 * (c) Evan Coury <me@evancoury.com>34 *35 * For the full copyright and license information, please see below:36 *37 * Copyright (c) 2013, Evan Coury38 * All rights reserved.39 *40 * Redistribution and use in source and binary forms, with or without modification,41 * are permitted provided that the following conditions are met:42 *43 * * Redistributions of source code must retain the above copyright notice,44 * this list of conditions and the following disclaimer.45 *46 * * Redistributions in binary form must reproduce the above copyright notice,47 * this list of conditions and the following disclaimer in the documentation48 * and/or other materials provided with the distribution.49 *50 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED52 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE53 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR54 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES55 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;56 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON57 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT58 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60 *61 * @param LoggerInterface $logger optional logger for information about which CA files were loaded62 * @return string path to a CA bundle file or directory63 */64 public static function getSystemCaRootBundlePath(LoggerInterface $logger = null)65 {66 if (self::$caPath !== null) {67 return self::$caPath;68 }69 $caBundlePaths = array();70 71 72 // If SSL_CERT_FILE env variable points to a valid certificate/bundle, use that.73 // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.74 $caBundlePaths[] = self::getEnvVariable('SSL_CERT_FILE');75 76 // If SSL_CERT_DIR env variable points to a valid certificate/bundle, use that.77 // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.78 $caBundlePaths[] = self::getEnvVariable('SSL_CERT_DIR');79 80 $caBundlePaths[] = ini_get('openssl.cafile');81 $caBundlePaths[] = ini_get('openssl.capath');82 83 $otherLocations = array(84 '/etc/pki/tls/certs/ca-bundle.crt', // Fedora, RHEL, CentOS (ca-certificates package)85 '/etc/ssl/certs/ca-certificates.crt', // Debian, Ubuntu, Gentoo, Arch Linux (ca-certificates package)86 '/etc/ssl/ca-bundle.pem', // SUSE, openSUSE (ca-certificates package)87 '/usr/local/share/certs/ca-root-nss.crt', // FreeBSD (ca_root_nss_package)88 '/usr/ssl/certs/ca-bundle.crt', // Cygwin89 '/opt/local/share/curl/curl-ca-bundle.crt', // OS X macports, curl-ca-bundle package90 '/usr/local/share/curl/curl-ca-bundle.crt', // Default cURL CA bunde path (without --with-ca-bundle option)91 '/usr/share/ssl/certs/ca-bundle.crt', // Really old RedHat?92 '/etc/ssl/cert.pem', // OpenBSD93 '/usr/local/etc/ssl/cert.pem', // FreeBSD 10.x94 '/usr/local/etc/openssl/cert.pem', // OS X homebrew, openssl package95 '/usr/local/etc/openssl@1.1/cert.pem', // OS X homebrew, openssl@1.1 package96 );97 98 foreach($otherLocations as $location) {99 $otherLocations[] = dirname($location);100 }101 102 $caBundlePaths = array_merge($caBundlePaths, $otherLocations);103 104 foreach ($caBundlePaths as $caBundle) {105 if (self::caFileUsable($caBundle, $logger)) {106 return self::$caPath = $caBundle;107 }108 109 if (self::caDirUsable($caBundle)) {110 return self::$caPath = $caBundle;111 }112 }113 114 return self::$caPath = static::getBundledCaBundlePath(); // Bundled CA file, last resort115 }116 117 /**118 * Returns the path to the bundled CA file119 *120 * In case you don't want to trust the user or the system, you can use this directly121 *122 * @return string path to a CA bundle file123 */124 public static function getBundledCaBundlePath()125 {126 $caBundleFile = __DIR__.'/../res/cacert.pem';127 128 // cURL does not understand 'phar://' paths129 // see https://github.com/composer/ca-bundle/issues/10130 if (0 === strpos($caBundleFile, 'phar://')) {131 file_put_contents(132 $tempCaBundleFile = tempnam(sys_get_temp_dir(), 'openssl-ca-bundle-'),133 file_get_contents($caBundleFile)134 );135 136 register_shutdown_function(function() use ($tempCaBundleFile) {137 @unlink($tempCaBundleFile);138 });139 140 $caBundleFile = $tempCaBundleFile;141 }142 143 return $caBundleFile;144 }145 146 /**147 * Validates a CA file using opensl_x509_parse only if it is safe to use148 *149 * @param string $filename150 * @param LoggerInterface $logger optional logger for information about which CA files were loaded151 *152 * @return bool153 */154 public static function validateCaFile($filename, LoggerInterface $logger = null)155 {156 static $warned = false;157 158 if (isset(self::$caFileValidity[$filename])) {159 return self::$caFileValidity[$filename];160 }161 162 $contents = file_get_contents($filename);163 164 // assume the CA is valid if php is vulnerable to165 // https://www.sektioneins.de/advisories/advisory-012013-php-openssl_x509_parse-memory-corruption-vulnerability.html166 if (!static::isOpensslParseSafe()) {167 if (!$warned && $logger) {168 $logger->warning(sprintf(169 'Your version of PHP, %s, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.',170 PHP_VERSION171 ));172 $warned = true;173 }174 175 $isValid = !empty($contents);176 } else {177 $isValid = (bool) openssl_x509_parse($contents);178 }179 180 if ($logger) {181 $logger->debug('Checked CA file '.realpath($filename).': '.($isValid ? 'valid' : 'invalid'));182 }183 184 return self::$caFileValidity[$filename] = $isValid;185 }186 187 /**188 * Test if it is safe to use the PHP function openssl_x509_parse().189 *190 * This checks if OpenSSL extensions is vulnerable to remote code execution191 * via the exploit documented as CVE-2013-6420.192 *193 * @return bool194 */195 public static function isOpensslParseSafe()196 {197 if (null !== self::$useOpensslParse) {198 return self::$useOpensslParse;199 }200 201 if (PHP_VERSION_ID >= 50600) {202 return self::$useOpensslParse = true;203 }204 205 // Vulnerable:206 // PHP 5.3.0 - PHP 5.3.27207 // PHP 5.4.0 - PHP 5.4.22208 // PHP 5.5.0 - PHP 5.5.6209 if (210 (PHP_VERSION_ID < 50400 && PHP_VERSION_ID >= 50328)211 || (PHP_VERSION_ID < 50500 && PHP_VERSION_ID >= 50423)212 || (PHP_VERSION_ID < 50600 && PHP_VERSION_ID >= 50507)213 ) {214 // This version of PHP has the fix for CVE-2013-6420 applied.215 return self::$useOpensslParse = true;216 }217 218 if (defined('PHP_WINDOWS_VERSION_BUILD')) {219 // Windows is probably insecure in this case.220 return self::$useOpensslParse = false;221 }222 223 $compareDistroVersionPrefix = function ($prefix, $fixedVersion) {224 $regex = '{^'.preg_quote($prefix).'([0-9]+)$}';225 226 if (preg_match($regex, PHP_VERSION, $m)) {227 return ((int) $m[1]) >= $fixedVersion;228 }229 230 return false;231 };232 233 // Hard coded list of PHP distributions with the fix backported.234 if (235 $compareDistroVersionPrefix('5.3.3-7+squeeze', 18) // Debian 6 (Squeeze)236 || $compareDistroVersionPrefix('5.4.4-14+deb7u', 7) // Debian 7 (Wheezy)237 || $compareDistroVersionPrefix('5.3.10-1ubuntu3.', 9) // Ubuntu 12.04 (Precise)238 ) {239 return self::$useOpensslParse = true;240 }241 242 // Symfony Process component is missing so we assume it is unsafe at this point243 if (!class_exists('Symfony\Component\Process\PhpProcess')) {244 return self::$useOpensslParse = false;245 }246 247 // This is where things get crazy, because distros backport security248 // fixes the chances are on NIX systems the fix has been applied but249 // it's not possible to verify that from the PHP version.250 //251 // To verify exec a new PHP process and run the issue testcase with252 // known safe input that replicates the bug.253 254 // Based on testcase in https://github.com/php/php-src/commit/c1224573c773b6845e83505f717fbf820fc18415255 // changes in https://github.com/php/php-src/commit/76a7fd893b7d6101300cc656058704a73254d593256 $cert = 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUVwRENDQTR5Z0F3SUJBZ0lKQUp6dThyNnU2ZUJjTUEwR0NTcUdTSWIzRFFFQkJRVUFNSUhETVFzd0NRWUQKVlFRR0V3SkVSVEVjTUJvR0ExVUVDQXdUVG05eVpISm9aV2x1TFZkbGMzUm1ZV3hsYmpFUU1BNEdBMVVFQnd3SApTOE9Ed3Jac2JqRVVNQklHQTFVRUNnd0xVMlZyZEdsdmJrVnBibk14SHpBZEJnTlZCQXNNRmsxaGJHbGphVzkxCmN5QkRaWEowSUZObFkzUnBiMjR4SVRBZkJnTlZCQU1NR0cxaGJHbGphVzkxY3k1elpXdDBhVzl1WldsdWN5NWsKWlRFcU1DZ0dDU3FHU0liM0RRRUpBUlliYzNSbFptRnVMbVZ6YzJWeVFITmxhM1JwYjI1bGFXNXpMbVJsTUhVWQpaREU1TnpBd01UQXhNREF3TURBd1dnQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUEKQUFBQUFBQVhEVEUwTVRFeU9ERXhNemt6TlZvd2djTXhDekFKQmdOVkJBWVRBa1JGTVJ3d0dnWURWUVFJREJOTwpiM0prY21obGFXNHRWMlZ6ZEdaaGJHVnVNUkF3RGdZRFZRUUhEQWRMdzRQQ3RteHVNUlF3RWdZRFZRUUtEQXRUClpXdDBhVzl1UldsdWN6RWZNQjBHQTFVRUN3d1dUV0ZzYVdOcGIzVnpJRU5sY25RZ1UyVmpkR2x2YmpFaE1COEcK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NyOVRuWFRmcmR4R1ZFYnY3S1ZRNmJkaGc1cDVTanBXSDErTXEwM3VSM1pYUEJZZHlWODMxOQpvMGxWajFLRkkyRENML2xpV2lzSlJvb2YrMWNSMzVDdGQwd1lCY3BCNlRac2xNY09QbDc2ZHdLd0pnZUpvMlFnClpzZm1jMnZDMS9xT2xOdU5xLzBUenprVkd2OEVUVDNDZ2FVK1VYZTRYT1Z2a2NjZWJKbjJkZz09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K';257 $script = <<<'EOT'258 259error_reporting(-1);260$info = openssl_x509_parse(base64_decode('%s'));261var_dump(PHP_VERSION, $info['issuer']['emailAddress'], $info['validFrom_time_t']);262 263EOT;264 $script = '<'."?php\n".sprintf($script, $cert);265 266 try {267 $process = new PhpProcess($script);268 $process->mustRun();269 } catch (\Exception $e) {270 // In the case of any exceptions just accept it is not possible to271 // determine the safety of openssl_x509_parse and bail out.272 return self::$useOpensslParse = false;273 }274 275 $output = preg_split('{\r?\n}', trim($process->getOutput()));276 $errorOutput = trim($process->getErrorOutput());277 278 if (279 count($output) === 3280 && $output[0] === sprintf('string(%d) "%s"', strlen(PHP_VERSION), PHP_VERSION)281 && $output[1] === 'string(27) "stefan.esser@sektioneins.de"'282 && $output[2] === 'int(-1)'283 && preg_match('{openssl_x509_parse\(\): illegal (?:ASN1 data type for|length in) timestamp in - on line \d+}', $errorOutput)284 ) {285 // This PHP has the fix backported probably by a distro security team.286 return self::$useOpensslParse = true;287 }288 289 return self::$useOpensslParse = false;290 }291 292 /**293 * Resets the static caches294 */295 public static function reset()296 {297 self::$caFileValidity = array();298 self::$caPath = null;299 self::$useOpensslParse = null;300 }301 302 private static function getEnvVariable($name)303 {304 if (isset($_SERVER[$name])) {305 return (string) $_SERVER[$name];306 }307 308 if (PHP_SAPI === 'cli' && ($value = getenv($name)) !== false && $value !== null) {309 return (string) $value;310 }311 312 return false;313 }314 315 private static function caFileUsable($certFile, LoggerInterface $logger = null)316 {317 return $certFile && @is_file($certFile) && @is_readable($certFile) && static::validateCaFile($certFile, $logger);318 }319 320 private static function caDirUsable($certDir)321 {322 return $certDir && @is_dir($certDir) && @is_readable($certDir) && glob($certDir . '/*');323 }324}325 