CaBundle.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. <?php
  2. /*
  3. * This file is part of composer/ca-bundle.
  4. *
  5. * (c) Composer <https://github.com/composer>
  6. *
  7. * For the full copyright and license information, please view
  8. * the LICENSE file that was distributed with this source code.
  9. */
  10. namespace Composer\CaBundle;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\Process\PhpProcess;
  13. /**
  14. * @author Chris Smith <chris@cs278.org>
  15. * @author Jordi Boggiano <j.boggiano@seld.be>
  16. */
  17. class CaBundle
  18. {
  19. /** @var string|null */
  20. private static $caPath;
  21. /** @var array<string, bool> */
  22. private static $caFileValidity = array();
  23. /**
  24. * Returns the system CA bundle path, or a path to the bundled one
  25. *
  26. * This method was adapted from Sslurp.
  27. * https://github.com/EvanDotPro/Sslurp
  28. *
  29. * (c) Evan Coury <me@evancoury.com>
  30. *
  31. * For the full copyright and license information, please see below:
  32. *
  33. * Copyright (c) 2013, Evan Coury
  34. * All rights reserved.
  35. *
  36. * Redistribution and use in source and binary forms, with or without modification,
  37. * are permitted provided that the following conditions are met:
  38. *
  39. * * Redistributions of source code must retain the above copyright notice,
  40. * this list of conditions and the following disclaimer.
  41. *
  42. * * Redistributions in binary form must reproduce the above copyright notice,
  43. * this list of conditions and the following disclaimer in the documentation
  44. * and/or other materials provided with the distribution.
  45. *
  46. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  47. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  48. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  49. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  50. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  51. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  52. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  53. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  54. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  55. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  56. *
  57. * @param LoggerInterface $logger optional logger for information about which CA files were loaded
  58. * @return string path to a CA bundle file or directory
  59. */
  60. public static function getSystemCaRootBundlePath(?LoggerInterface $logger = null)
  61. {
  62. if (self::$caPath !== null) {
  63. return self::$caPath;
  64. }
  65. $caBundlePaths = array();
  66. // If SSL_CERT_FILE env variable points to a valid certificate/bundle, use that.
  67. // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.
  68. $caBundlePaths[] = self::getEnvVariable('SSL_CERT_FILE');
  69. // If SSL_CERT_DIR env variable points to a valid certificate/bundle, use that.
  70. // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.
  71. $caBundlePaths[] = self::getEnvVariable('SSL_CERT_DIR');
  72. $caBundlePaths[] = ini_get('openssl.cafile');
  73. $caBundlePaths[] = ini_get('openssl.capath');
  74. $otherLocations = array(
  75. '/etc/pki/tls/certs/ca-bundle.crt', // Fedora, RHEL, CentOS (ca-certificates package)
  76. '/etc/ssl/certs/ca-certificates.crt', // Debian, Ubuntu, Gentoo, Arch Linux (ca-certificates package)
  77. '/etc/ssl/ca-bundle.pem', // SUSE, openSUSE (ca-certificates package)
  78. '/usr/ssl/certs/ca-bundle.crt', // Cygwin
  79. '/opt/local/share/curl/curl-ca-bundle.crt', // OS X macports, curl-ca-bundle package
  80. '/usr/local/share/curl/curl-ca-bundle.crt', // Default cURL CA bunde path (without --with-ca-bundle option)
  81. '/usr/share/ssl/certs/ca-bundle.crt', // Really old RedHat?
  82. '/etc/ssl/cert.pem', // OpenBSD
  83. '/usr/local/etc/openssl/cert.pem', // OS X homebrew, openssl package
  84. '/usr/local/etc/openssl@1.1/cert.pem', // OS X homebrew, openssl@1.1 package
  85. '/opt/homebrew/etc/openssl@3/cert.pem', // macOS silicon homebrew, openssl@3 package
  86. '/opt/homebrew/etc/openssl@1.1/cert.pem', // macOS silicon homebrew, openssl@1.1 package
  87. '/etc/pki/tls/certs',
  88. '/etc/ssl/certs', // FreeBSD
  89. );
  90. $caBundlePaths = array_merge($caBundlePaths, $otherLocations);
  91. foreach ($caBundlePaths as $caBundle) {
  92. if ($caBundle && self::caFileUsable($caBundle, $logger)) {
  93. return self::$caPath = $caBundle;
  94. }
  95. if ($caBundle && self::caDirUsable($caBundle, $logger)) {
  96. return self::$caPath = $caBundle;
  97. }
  98. }
  99. return self::$caPath = static::getBundledCaBundlePath(); // Bundled CA file, last resort
  100. }
  101. /**
  102. * Returns the path to the bundled CA file
  103. *
  104. * In case you don't want to trust the user or the system, you can use this directly
  105. *
  106. * @return string path to a CA bundle file
  107. */
  108. public static function getBundledCaBundlePath()
  109. {
  110. $caBundleFile = __DIR__.'/../res/cacert.pem';
  111. // cURL does not understand 'phar://' paths
  112. // see https://github.com/composer/ca-bundle/issues/10
  113. if (0 === strpos($caBundleFile, 'phar://')) {
  114. $tempCaBundleFile = tempnam(sys_get_temp_dir(), 'openssl-ca-bundle-');
  115. if (false === $tempCaBundleFile) {
  116. throw new \RuntimeException('Could not create a temporary file to store the bundled CA file');
  117. }
  118. file_put_contents(
  119. $tempCaBundleFile,
  120. file_get_contents($caBundleFile)
  121. );
  122. register_shutdown_function(function() use ($tempCaBundleFile) {
  123. @unlink($tempCaBundleFile);
  124. });
  125. $caBundleFile = $tempCaBundleFile;
  126. }
  127. return $caBundleFile;
  128. }
  129. /**
  130. * Validates a CA file using opensl_x509_parse only if it is safe to use
  131. *
  132. * @param string $filename
  133. * @param LoggerInterface $logger optional logger for information about which CA files were loaded
  134. *
  135. * @return bool
  136. */
  137. public static function validateCaFile($filename, ?LoggerInterface $logger = null)
  138. {
  139. static $warned = false;
  140. if (isset(self::$caFileValidity[$filename])) {
  141. return self::$caFileValidity[$filename];
  142. }
  143. $contents = file_get_contents($filename);
  144. if (is_string($contents) && strlen($contents) > 0) {
  145. $contents = preg_replace("/^(\\-+(?:BEGIN|END))\\s+TRUSTED\\s+(CERTIFICATE\\-+)\$/m", '$1 $2', $contents);
  146. if (null === $contents) {
  147. // regex extraction failed
  148. $isValid = false;
  149. } else {
  150. $isValid = (bool) openssl_x509_parse($contents);
  151. }
  152. } else {
  153. $isValid = false;
  154. }
  155. if ($logger) {
  156. $logger->debug('Checked CA file '.realpath($filename).': '.($isValid ? 'valid' : 'invalid'));
  157. }
  158. return self::$caFileValidity[$filename] = $isValid;
  159. }
  160. /**
  161. * Test if it is safe to use the PHP function openssl_x509_parse().
  162. *
  163. * This checks if OpenSSL extensions is vulnerable to remote code execution
  164. * via the exploit documented as CVE-2013-6420.
  165. *
  166. * @return bool
  167. */
  168. public static function isOpensslParseSafe()
  169. {
  170. return true;
  171. }
  172. /**
  173. * Resets the static caches
  174. * @return void
  175. */
  176. public static function reset()
  177. {
  178. self::$caFileValidity = array();
  179. self::$caPath = null;
  180. }
  181. /**
  182. * @param string $name
  183. * @return string|false
  184. */
  185. private static function getEnvVariable($name)
  186. {
  187. if (isset($_SERVER[$name])) {
  188. return (string) $_SERVER[$name];
  189. }
  190. if (PHP_SAPI === 'cli' && ($value = getenv($name)) !== false && $value !== null) {
  191. return (string) $value;
  192. }
  193. return false;
  194. }
  195. /**
  196. * @param string|false $certFile
  197. * @param LoggerInterface|null $logger
  198. * @return bool
  199. */
  200. private static function caFileUsable($certFile, ?LoggerInterface $logger = null)
  201. {
  202. return $certFile
  203. && self::isFile($certFile, $logger)
  204. && self::isReadable($certFile, $logger)
  205. && self::validateCaFile($certFile, $logger);
  206. }
  207. /**
  208. * @param string|false $certDir
  209. * @param LoggerInterface|null $logger
  210. * @return bool
  211. */
  212. private static function caDirUsable($certDir, ?LoggerInterface $logger = null)
  213. {
  214. return $certDir
  215. && self::isDir($certDir, $logger)
  216. && self::isReadable($certDir, $logger)
  217. && self::glob($certDir . '/*', $logger);
  218. }
  219. /**
  220. * @param string $certFile
  221. * @param LoggerInterface|null $logger
  222. * @return bool
  223. */
  224. private static function isFile($certFile, ?LoggerInterface $logger = null)
  225. {
  226. $isFile = @is_file($certFile);
  227. if (!$isFile && $logger) {
  228. $logger->debug(sprintf('Checked CA file %s does not exist or it is not a file.', $certFile));
  229. }
  230. return $isFile;
  231. }
  232. /**
  233. * @param string $certDir
  234. * @param LoggerInterface|null $logger
  235. * @return bool
  236. */
  237. private static function isDir($certDir, ?LoggerInterface $logger = null)
  238. {
  239. $isDir = @is_dir($certDir);
  240. if (!$isDir && $logger) {
  241. $logger->debug(sprintf('Checked directory %s does not exist or it is not a directory.', $certDir));
  242. }
  243. return $isDir;
  244. }
  245. /**
  246. * @param string $certFileOrDir
  247. * @param LoggerInterface|null $logger
  248. * @return bool
  249. */
  250. private static function isReadable($certFileOrDir, ?LoggerInterface $logger = null)
  251. {
  252. $isReadable = @is_readable($certFileOrDir);
  253. if (!$isReadable && $logger) {
  254. $logger->debug(sprintf('Checked file or directory %s is not readable.', $certFileOrDir));
  255. }
  256. return $isReadable;
  257. }
  258. /**
  259. * @param string $pattern
  260. * @param LoggerInterface|null $logger
  261. * @return bool
  262. */
  263. private static function glob($pattern, ?LoggerInterface $logger = null)
  264. {
  265. $certs = glob($pattern);
  266. if ($certs === false) {
  267. if ($logger) {
  268. $logger->debug(sprintf("An error occurred while trying to find certificates for pattern: %s", $pattern));
  269. }
  270. return false;
  271. }
  272. if (count($certs) === 0) {
  273. if ($logger) {
  274. $logger->debug(sprintf("No CA files found for pattern: %s", $pattern));
  275. }
  276. return false;
  277. }
  278. return true;
  279. }
  280. }