StreamContextFactory.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Util;
  12. use Composer\Composer;
  13. use Composer\CaBundle\CaBundle;
  14. use Composer\Downloader\TransportException;
  15. use Psr\Log\LoggerInterface;
  16. /**
  17. * Allows the creation of a basic context supporting http proxy
  18. *
  19. * @author Jordan Alliot <jordan.alliot@gmail.com>
  20. * @author Markus Tacker <m@coderbyheart.de>
  21. */
  22. final class StreamContextFactory
  23. {
  24. /**
  25. * Creates a context supporting HTTP proxies
  26. *
  27. * @param string $url URL the context is to be used for
  28. * @param array $defaultOptions Options to merge with the default
  29. * @param array $defaultParams Parameters to specify on the context
  30. * @throws \RuntimeException if https proxy required and OpenSSL uninstalled
  31. * @return resource Default context
  32. */
  33. public static function getContext($url, array $defaultOptions = array(), array $defaultParams = array())
  34. {
  35. $options = array('http' => array(
  36. // specify defaults again to try and work better with curlwrappers enabled
  37. 'follow_location' => 1,
  38. 'max_redirects' => 20,
  39. ));
  40. $options = array_replace_recursive($options, self::initOptions($url, $defaultOptions));
  41. unset($defaultOptions['http']['header']);
  42. $options = array_replace_recursive($options, $defaultOptions);
  43. if (isset($options['http']['header'])) {
  44. $options['http']['header'] = self::fixHttpHeaderField($options['http']['header']);
  45. }
  46. return stream_context_create($options, $defaultParams);
  47. }
  48. /**
  49. * @param string $url
  50. * @param array $options
  51. * @return array ['http' => ['header' => [...], 'proxy' => '..', 'request_fulluri' => bool]] formatted as a stream context array
  52. */
  53. public static function initOptions($url, array $options)
  54. {
  55. // Make sure the headers are in an array form
  56. if (!isset($options['http']['header'])) {
  57. $options['http']['header'] = array();
  58. }
  59. if (is_string($options['http']['header'])) {
  60. $options['http']['header'] = explode("\r\n", $options['http']['header']);
  61. }
  62. // Handle HTTP_PROXY/http_proxy on CLI only for security reasons
  63. if ((PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') && (!empty($_SERVER['HTTP_PROXY']) || !empty($_SERVER['http_proxy']))) {
  64. $proxy = parse_url(!empty($_SERVER['http_proxy']) ? $_SERVER['http_proxy'] : $_SERVER['HTTP_PROXY']);
  65. }
  66. // Prefer CGI_HTTP_PROXY if available
  67. if (!empty($_SERVER['CGI_HTTP_PROXY'])) {
  68. $proxy = parse_url($_SERVER['CGI_HTTP_PROXY']);
  69. }
  70. // Override with HTTPS proxy if present and URL is https
  71. if (preg_match('{^https://}i', $url) && (!empty($_SERVER['HTTPS_PROXY']) || !empty($_SERVER['https_proxy']))) {
  72. $proxy = parse_url(!empty($_SERVER['https_proxy']) ? $_SERVER['https_proxy'] : $_SERVER['HTTPS_PROXY']);
  73. }
  74. // Remove proxy if URL matches no_proxy directive
  75. if (!empty($_SERVER['NO_PROXY']) || !empty($_SERVER['no_proxy']) && parse_url($url, PHP_URL_HOST)) {
  76. $pattern = new NoProxyPattern(!empty($_SERVER['no_proxy']) ? $_SERVER['no_proxy'] : $_SERVER['NO_PROXY']);
  77. if ($pattern->test($url)) {
  78. unset($proxy);
  79. }
  80. }
  81. if (!empty($proxy)) {
  82. $proxyURL = isset($proxy['scheme']) ? $proxy['scheme'] . '://' : '';
  83. $proxyURL .= isset($proxy['host']) ? $proxy['host'] : '';
  84. if (isset($proxy['port'])) {
  85. $proxyURL .= ":" . $proxy['port'];
  86. } elseif ('http://' == substr($proxyURL, 0, 7)) {
  87. $proxyURL .= ":80";
  88. } elseif ('https://' == substr($proxyURL, 0, 8)) {
  89. $proxyURL .= ":443";
  90. }
  91. // http(s):// is not supported in proxy
  92. $proxyURL = str_replace(array('http://', 'https://'), array('tcp://', 'ssl://'), $proxyURL);
  93. if (0 === strpos($proxyURL, 'ssl:') && !extension_loaded('openssl')) {
  94. throw new \RuntimeException('You must enable the openssl extension to use a proxy over https');
  95. }
  96. $options['http']['proxy'] = $proxyURL;
  97. // enabled request_fulluri unless it is explicitly disabled
  98. switch (parse_url($url, PHP_URL_SCHEME)) {
  99. case 'http': // default request_fulluri to true for HTTP
  100. $reqFullUriEnv = getenv('HTTP_PROXY_REQUEST_FULLURI');
  101. if ($reqFullUriEnv === false || $reqFullUriEnv === '' || (strtolower($reqFullUriEnv) !== 'false' && (bool) $reqFullUriEnv)) {
  102. $options['http']['request_fulluri'] = true;
  103. }
  104. break;
  105. case 'https': // default request_fulluri to false for HTTPS
  106. $reqFullUriEnv = getenv('HTTPS_PROXY_REQUEST_FULLURI');
  107. if (strtolower($reqFullUriEnv) !== 'false' && (bool) $reqFullUriEnv) {
  108. $options['http']['request_fulluri'] = true;
  109. }
  110. break;
  111. }
  112. // add SNI opts for https URLs
  113. if ('https' === parse_url($url, PHP_URL_SCHEME)) {
  114. $options['ssl']['SNI_enabled'] = true;
  115. if (PHP_VERSION_ID < 50600) {
  116. $options['ssl']['SNI_server_name'] = parse_url($url, PHP_URL_HOST);
  117. }
  118. }
  119. // handle proxy auth if present
  120. if (isset($proxy['user'])) {
  121. $auth = rawurldecode($proxy['user']);
  122. if (isset($proxy['pass'])) {
  123. $auth .= ':' . rawurldecode($proxy['pass']);
  124. }
  125. $auth = base64_encode($auth);
  126. $options['http']['header'][] = "Proxy-Authorization: Basic {$auth}";
  127. }
  128. }
  129. if (defined('HHVM_VERSION')) {
  130. $phpVersion = 'HHVM ' . HHVM_VERSION;
  131. } else {
  132. $phpVersion = 'PHP ' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION;
  133. }
  134. if (extension_loaded('curl')) {
  135. $curl = curl_version();
  136. $httpVersion = 'curl '.$curl['version'];
  137. } else {
  138. $httpVersion = 'streams';
  139. }
  140. if (!isset($options['http']['header']) || false === stripos(implode('', $options['http']['header']), 'user-agent')) {
  141. $options['http']['header'][] = sprintf(
  142. 'User-Agent: Composer/%s (%s; %s; %s; %s%s)',
  143. Composer::getVersion(),
  144. function_exists('php_uname') ? php_uname('s') : 'Unknown',
  145. function_exists('php_uname') ? php_uname('r') : 'Unknown',
  146. $phpVersion,
  147. $httpVersion,
  148. getenv('CI') ? '; CI' : ''
  149. );
  150. }
  151. return $options;
  152. }
  153. /**
  154. * @param array $options
  155. *
  156. * @return array
  157. */
  158. public static function getTlsDefaults(array $options, LoggerInterface $logger = null)
  159. {
  160. $ciphers = implode(':', array(
  161. 'ECDHE-RSA-AES128-GCM-SHA256',
  162. 'ECDHE-ECDSA-AES128-GCM-SHA256',
  163. 'ECDHE-RSA-AES256-GCM-SHA384',
  164. 'ECDHE-ECDSA-AES256-GCM-SHA384',
  165. 'DHE-RSA-AES128-GCM-SHA256',
  166. 'DHE-DSS-AES128-GCM-SHA256',
  167. 'kEDH+AESGCM',
  168. 'ECDHE-RSA-AES128-SHA256',
  169. 'ECDHE-ECDSA-AES128-SHA256',
  170. 'ECDHE-RSA-AES128-SHA',
  171. 'ECDHE-ECDSA-AES128-SHA',
  172. 'ECDHE-RSA-AES256-SHA384',
  173. 'ECDHE-ECDSA-AES256-SHA384',
  174. 'ECDHE-RSA-AES256-SHA',
  175. 'ECDHE-ECDSA-AES256-SHA',
  176. 'DHE-RSA-AES128-SHA256',
  177. 'DHE-RSA-AES128-SHA',
  178. 'DHE-DSS-AES128-SHA256',
  179. 'DHE-RSA-AES256-SHA256',
  180. 'DHE-DSS-AES256-SHA',
  181. 'DHE-RSA-AES256-SHA',
  182. 'AES128-GCM-SHA256',
  183. 'AES256-GCM-SHA384',
  184. 'AES128-SHA256',
  185. 'AES256-SHA256',
  186. 'AES128-SHA',
  187. 'AES256-SHA',
  188. 'AES',
  189. 'CAMELLIA',
  190. 'DES-CBC3-SHA',
  191. '!aNULL',
  192. '!eNULL',
  193. '!EXPORT',
  194. '!DES',
  195. '!RC4',
  196. '!MD5',
  197. '!PSK',
  198. '!aECDH',
  199. '!EDH-DSS-DES-CBC3-SHA',
  200. '!EDH-RSA-DES-CBC3-SHA',
  201. '!KRB5-DES-CBC3-SHA',
  202. ));
  203. /**
  204. * CN_match and SNI_server_name are only known once a URL is passed.
  205. * They will be set in the getOptionsForUrl() method which receives a URL.
  206. *
  207. * cafile or capath can be overridden by passing in those options to constructor.
  208. */
  209. $defaults = array(
  210. 'ssl' => array(
  211. 'ciphers' => $ciphers,
  212. 'verify_peer' => true,
  213. 'verify_depth' => 7,
  214. 'SNI_enabled' => true,
  215. 'capture_peer_cert' => true,
  216. ),
  217. );
  218. if (isset($options['ssl'])) {
  219. $defaults['ssl'] = array_replace_recursive($defaults['ssl'], $options['ssl']);
  220. }
  221. /**
  222. * Attempt to find a local cafile or throw an exception if none pre-set
  223. * The user may go download one if this occurs.
  224. */
  225. if (!isset($defaults['ssl']['cafile']) && !isset($defaults['ssl']['capath'])) {
  226. $result = CaBundle::getSystemCaRootBundlePath($logger);
  227. if (is_dir($result)) {
  228. $defaults['ssl']['capath'] = $result;
  229. } else {
  230. $defaults['ssl']['cafile'] = $result;
  231. }
  232. }
  233. if (isset($defaults['ssl']['cafile']) && (!is_readable($defaults['ssl']['cafile']) || !CaBundle::validateCaFile($defaults['ssl']['cafile'], $logger))) {
  234. throw new TransportException('The configured cafile was not valid or could not be read.');
  235. }
  236. if (isset($defaults['ssl']['capath']) && (!is_dir($defaults['ssl']['capath']) || !is_readable($defaults['ssl']['capath']))) {
  237. throw new TransportException('The configured capath was not valid or could not be read.');
  238. }
  239. /**
  240. * Disable TLS compression to prevent CRIME attacks where supported.
  241. */
  242. if (PHP_VERSION_ID >= 50413) {
  243. $defaults['ssl']['disable_compression'] = true;
  244. }
  245. return $defaults;
  246. }
  247. /**
  248. * A bug in PHP prevents the headers from correctly being sent when a content-type header is present and
  249. * NOT at the end of the array
  250. *
  251. * This method fixes the array by moving the content-type header to the end
  252. *
  253. * @link https://bugs.php.net/bug.php?id=61548
  254. * @param string|array $header
  255. * @return array
  256. */
  257. private static function fixHttpHeaderField($header)
  258. {
  259. if (!is_array($header)) {
  260. $header = explode("\r\n", $header);
  261. }
  262. uasort($header, function ($el) {
  263. return stripos($el, 'content-type') === 0 ? 1 : -1;
  264. });
  265. return $header;
  266. }
  267. }