1<?php 2 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 view 9 * 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 CaBundle 22{ 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 one 29 * 30 * This method was adapted from Sslurp. 31 * https://github.com/EvanDotPro/Sslurp 32 * 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 Coury 38 * 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 documentation 48 * and/or other materials provided with the distribution. 49 * 50 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 52 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 53 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 54 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 55 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 56 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 57 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 58 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 59 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 60 * 61 * @param LoggerInterface $logger optional logger for information about which CA files were loaded 62 * @return string path to a CA bundle file or directory 63 */ 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[] = getenv('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[] = getenv('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', // Cygwin 89 '/opt/local/share/curl/curl-ca-bundle.crt', // OS X macports, curl-ca-bundle package 90 '/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', // OpenBSD 93 '/usr/local/etc/ssl/cert.pem', // FreeBSD 10.x 94 '/usr/local/etc/openssl/cert.pem', // OS X homebrew, openssl package 95 ); 96 97 foreach($otherLocations as $location) { 98 $otherLocations[] = dirname($location); 99 } 100 101 $caBundlePaths = array_merge($caBundlePaths, $otherLocations); 102 103 foreach ($caBundlePaths as $caBundle) { 104 if (self::caFileUsable($caBundle, $logger)) { 105 return self::$caPath = $caBundle; 106 } 107 108 if (self::caDirUsable($caBundle)) { 109 return self::$caPath = $caBundle; 110 } 111 } 112 113 return self::$caPath = static::getBundledCaBundlePath(); // Bundled CA file, last resort 114 } 115 116 /** 117 * Returns the path to the bundled CA file 118 * 119 * In case you don't want to trust the user or the system, you can use this directly 120 * 121 * @return string path to a CA bundle file 122 */ 123 public static function getBundledCaBundlePath() 124 { 125 $caBundleFile = __DIR__.'/../res/cacert.pem'; 126 127 // cURL does not understand 'phar://' paths 128 // see https://github.com/composer/ca-bundle/issues/10 129 if (0 === strpos($caBundleFile, 'phar://')) { 130 file_put_contents( 131 $tempCaBundleFile = tempnam(sys_get_temp_dir(), 'openssl-ca-bundle-'), 132 file_get_contents($caBundleFile) 133 ); 134 135 register_shutdown_function(function() use ($tempCaBundleFile) { 136 @unlink($tempCaBundleFile); 137 }); 138 139 $caBundleFile = $tempCaBundleFile; 140 } 141 142 return $caBundleFile; 143 } 144 145 /** 146 * Validates a CA file using opensl_x509_parse only if it is safe to use 147 * 148 * @param string $filename 149 * @param LoggerInterface $logger optional logger for information about which CA files were loaded 150 * 151 * @return bool 152 */ 153 public static function validateCaFile($filename, LoggerInterface $logger = null) 154 { 155 static $warned = false; 156 157 if (isset(self::$caFileValidity[$filename])) { 158 return self::$caFileValidity[$filename]; 159 } 160 161 $contents = file_get_contents($filename); 162 163 // assume the CA is valid if php is vulnerable to 164 // https://www.sektioneins.de/advisories/advisory-012013-php-openssl_x509_parse-memory-corruption-vulnerability.html 165 if (!static::isOpensslParseSafe()) { 166 if (!$warned && $logger) { 167 $logger->warning(sprintf( 168 'Your version of PHP, %s, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.', 169 PHP_VERSION 170 )); 171 $warned = true; 172 } 173 174 $isValid = !empty($contents); 175 } else { 176 $isValid = (bool) openssl_x509_parse($contents); 177 } 178 179 if ($logger) { 180 $logger->debug('Checked CA file '.realpath($filename).': '.($isValid ? 'valid' : 'invalid')); 181 } 182 183 return self::$caFileValidity[$filename] = $isValid; 184 } 185 186 /** 187 * Test if it is safe to use the PHP function openssl_x509_parse(). 188 * 189 * This checks if OpenSSL extensions is vulnerable to remote code execution 190 * via the exploit documented as CVE-2013-6420. 191 * 192 * @return bool 193 */ 194 public static function isOpensslParseSafe() 195 { 196 if (null !== self::$useOpensslParse) { 197 return self::$useOpensslParse; 198 } 199 200 if (PHP_VERSION_ID >= 50600) { 201 return self::$useOpensslParse = true; 202 } 203 204 // Vulnerable: 205 // PHP 5.3.0 - PHP 5.3.27 206 // PHP 5.4.0 - PHP 5.4.22 207 // PHP 5.5.0 - PHP 5.5.6 208 if ( 209 (PHP_VERSION_ID < 50400 && PHP_VERSION_ID >= 50328) 210 || (PHP_VERSION_ID < 50500 && PHP_VERSION_ID >= 50423) 211 || (PHP_VERSION_ID < 50600 && PHP_VERSION_ID >= 50507) 212 ) { 213 // This version of PHP has the fix for CVE-2013-6420 applied. 214 return self::$useOpensslParse = true; 215 } 216 217 if (defined('PHP_WINDOWS_VERSION_BUILD')) { 218 // Windows is probably insecure in this case. 219 return self::$useOpensslParse = false; 220 } 221 222 $compareDistroVersionPrefix = function ($prefix, $fixedVersion) { 223 $regex = '{^'.preg_quote($prefix).'([0-9]+)$}'; 224 225 if (preg_match($regex, PHP_VERSION, $m)) { 226 return ((int) $m[1]) >= $fixedVersion; 227 } 228 229 return false; 230 }; 231 232 // Hard coded list of PHP distributions with the fix backported. 233 if ( 234 $compareDistroVersionPrefix('5.3.3-7+squeeze', 18) // Debian 6 (Squeeze) 235 || $compareDistroVersionPrefix('5.4.4-14+deb7u', 7) // Debian 7 (Wheezy) 236 || $compareDistroVersionPrefix('5.3.10-1ubuntu3.', 9) // Ubuntu 12.04 (Precise) 237 ) { 238 return self::$useOpensslParse = true; 239 } 240 241 // Symfony Process component is missing so we assume it is unsafe at this point 242 if (!class_exists('Symfony\Component\Process\PhpProcess')) { 243 return self::$useOpensslParse = false; 244 } 245 246 // This is where things get crazy, because distros backport security 247 // fixes the chances are on NIX systems the fix has been applied but 248 // it's not possible to verify that from the PHP version. 249 // 250 // To verify exec a new PHP process and run the issue testcase with 251 // known safe input that replicates the bug. 252 253 // Based on testcase in https://github.com/php/php-src/commit/c1224573c773b6845e83505f717fbf820fc18415 254 // changes in https://github.com/php/php-src/commit/76a7fd893b7d6101300cc656058704a73254d593 255 $cert = 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUVwRENDQTR5Z0F3SUJBZ0lKQUp6dThyNnU2ZUJjTUEwR0NTcUdTSWIzRFFFQkJRVUFNSUhETVFzd0NRWUQKVlFRR0V3SkVSVEVjTUJvR0ExVUVDQXdUVG05eVpISm9aV2x1TFZkbGMzUm1ZV3hsYmpFUU1BNEdBMVVFQnd3SApTOE9Ed3Jac2JqRVVNQklHQTFVRUNnd0xVMlZyZEdsdmJrVnBibk14SHpBZEJnTlZCQXNNRmsxaGJHbGphVzkxCmN5QkRaWEowSUZObFkzUnBiMjR4SVRBZkJnTlZCQU1NR0cxaGJHbGphVzkxY3k1elpXdDBhVzl1WldsdWN5NWsKWlRFcU1DZ0dDU3FHU0liM0RRRUpBUlliYzNSbFptRnVMbVZ6YzJWeVFITmxhM1JwYjI1bGFXNXpMbVJsTUhVWQpaREU1TnpBd01UQXhNREF3TURBd1dnQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUEKQUFBQUFBQVhEVEUwTVRFeU9ERXhNemt6TlZvd2djTXhDekFKQmdOVkJBWVRBa1JGTVJ3d0dnWURWUVFJREJO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WWhkbnlVNGdnYTBCQWNEclk5ZTk0ZUVBdTZacXljRjZGakxxWFhkQWJvcHBXb2NyNlQ2R0QxeDMzQ2tsClZBcnpHL0t4UW9oR0QySmVxa2hJTWxEb214SE83a2EzOStPYThpMnZXTFZ5alU4QVp2V01BcnVIYTRFRU55RzcKbFcyQWFnYUZLRkNyOVRuWFRmcmR4R1ZFYnY3S1ZRNmJkaGc1cDVTanBXSDErTXEwM3VSM1pYUEJZZHlWODMxOQpvMGxWajFLRkkyRENML2xpV2lzSlJvb2YrMWNSMzVDdGQwd1lCY3BCNlRac2xNY09QbDc2ZHdLd0pnZUpvMlFnClpzZm1jMnZDMS9xT2xOdU5xLzBUenprVkd2OEVUVDNDZ2FVK1VYZTRYT1Z2a2NjZWJKbjJkZz09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K'; 256 $script = <<<'EOT' 257 258error_reporting(-1); 259$info = openssl_x509_parse(base64_decode('%s')); 260var_dump(PHP_VERSION, $info['issuer']['emailAddress'], $info['validFrom_time_t']); 261 262EOT; 263 $script = '<'."?php\n".sprintf($script, $cert); 264 265 try { 266 $process = new PhpProcess($script); 267 $process->mustRun(); 268 } catch (\Exception $e) { 269 // In the case of any exceptions just accept it is not possible to 270 // determine the safety of openssl_x509_parse and bail out. 271 return self::$useOpensslParse = false; 272 } 273 274 $output = preg_split('{\r?\n}', trim($process->getOutput())); 275 $errorOutput = trim($process->getErrorOutput()); 276 277 if ( 278 count($output) === 3 279 && $output[0] === sprintf('string(%d) "%s"', strlen(PHP_VERSION), PHP_VERSION) 280 && $output[1] === 'string(27) "stefan.esser@sektioneins.de"' 281 && $output[2] === 'int(-1)' 282 && preg_match('{openssl_x509_parse\(\): illegal (?:ASN1 data type for|length in) timestamp in - on line \d+}', $errorOutput) 283 ) { 284 // This PHP has the fix backported probably by a distro security team. 285 return self::$useOpensslParse = true; 286 } 287 288 return self::$useOpensslParse = false; 289 } 290 291 /** 292 * Resets the static caches 293 */ 294 public static function reset() 295 { 296 self::$caFileValidity = array(); 297 self::$caPath = null; 298 self::$useOpensslParse = null; 299 } 300 301 private static function caFileUsable($certFile, LoggerInterface $logger = null) 302 { 303 return $certFile && @is_file($certFile) && @is_readable($certFile) && static::validateCaFile($certFile, $logger); 304 } 305 306 private static function caDirUsable($certDir) 307 { 308 return $certDir && @is_dir($certDir) && @is_readable($certDir) && glob($certDir . '/*'); 309 } 310} 311