From 09417cae504dfecb87a92a59113c1d98fb37f6de Mon Sep 17 00:00:00 2001 From: Radek Benkel Date: Sun, 20 Jul 2014 21:01:17 +0200 Subject: [PATCH 01/28] Composer gives .ini hints about missing extensions --- .../SolverProblemsException.php | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/Composer/DependencyResolver/SolverProblemsException.php b/src/Composer/DependencyResolver/SolverProblemsException.php index 9973f9d39..1dfc116f0 100644 --- a/src/Composer/DependencyResolver/SolverProblemsException.php +++ b/src/Composer/DependencyResolver/SolverProblemsException.php @@ -31,14 +31,23 @@ class SolverProblemsException extends \RuntimeException protected function createMessage() { $text = "\n"; + $hasExtensionProblems = false; foreach ($this->problems as $i => $problem) { $text .= " Problem ".($i + 1).$problem->getPrettyString($this->installedMap)."\n"; + + if (!$hasExtensionProblems && $this->hasExtensionProblems($problem->getReasons())) { + $hasExtensionProblems = true; + } } if (strpos($text, 'could not be found') || strpos($text, 'no matching package found')) { $text .= "\nPotential causes:\n - A typo in the package name\n - The package is not available in a stable-enough version according to your minimum-stability setting\n see for more details.\n\nRead for further common problems."; } + if ($hasExtensionProblems) { + $text .= $this->createExtensionHint(); + } + return $text; } @@ -46,4 +55,40 @@ class SolverProblemsException extends \RuntimeException { return $this->problems; } + + private function createExtensionHint() + { + $paths = array(); + + if (($iniPath = php_ini_loaded_file()) !== false) { + $paths[] = $iniPath; + } + + if (!defined('HHVM_VERSION') && $additionalIniPaths = php_ini_scanned_files()) { + $paths = array_merge($paths, array_map("trim", explode(",", $additionalIniPaths))); + } + + if (count($paths) === 0) { + return ''; + } + + $text = "\n Because of missing extensions, please verify whether they are enabled in those .ini files:\n - "; + $text .= implode("\n - ", $paths); + $text .= "\n You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode."; + + return $text; + } + + private function hasExtensionProblems(array $reasonSets) + { + foreach ($reasonSets as $reasonSet) { + foreach($reasonSet as $reason) { + if (isset($reason["rule"]) && 0 === strpos($reason["rule"]->getRequiredPackage(), 'ext-')) { + return true; + } + } + } + + return false; + } } From 73662c725ab072e6750077d1c4a856221bde2a5e Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 17 Jan 2016 19:15:06 +0000 Subject: [PATCH 02/28] Don't let PHP follow redirects it doesn't validate certificates --- src/Composer/Util/RemoteFilesystem.php | 78 +++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 3 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 4754e304b..b317a2399 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -38,6 +38,8 @@ class RemoteFilesystem private $lastHeaders; private $storeAuth; private $degradedMode = false; + private $redirects = 0; + private $maxRedirects = 20; /** * Constructor. @@ -293,6 +295,72 @@ class RemoteFilesystem $statusCode = $this->findStatusCode($http_response_header); } + if (!empty($http_response_header[0]) && preg_match('{^HTTP/\S+ (3\d\d)}i', $http_response_header[0], $match)) { + // TODO: Only follow if PHP is not set to follow. + foreach ($http_response_header as $header) { + if (preg_match('{^location: *(.+) *$}i', $header, $m)) { + if (parse_url($m[1], PHP_URL_SCHEME)) { + $targetUrl = $m[1]; + + break; + } + + if (parse_url($m[1], PHP_URL_HOST)) { + // Scheme relative; e.g. //example.com/foo + $targetUrl = $this->scheme.':'.$m[1]; + break; + } + + if ('/' === $m[1][0]) { + // Absolute path; e.g. /foo + throw new \Exception('todo'); + } + + throw new \Exception('todo'); + break; + } + } + + if ($targetUrl) { + $this->redirects++; + + if ($this->redirects > $this->maxRedirects) { + $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, too many redirects'); + $e->setHeaders($http_response_header); + $e->setResponse($result); + throw $e; + } + + if ('http' === parse_url($targetUrl, PHP_URL_SCHEME) && 'https' === $this->scheme) { + // Do not allow protocol downgrade. + // TODO: Currently this will fail if a request goes http -> https -> http + $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, not permitting protocol downgrade'); + $e->setHeaders($http_response_header); + $e->setResponse($result); + throw $e; + } + + if ($this->io->isDebug()) { + $this->io->writeError(sprintf('Following redirect (%u)', $this->redirects)); + } + + // TODO: Not so sure about preserving origin here... + $result = $this->get($this->originUrl, $targetUrl, $additionalOptions, $this->fileName, $this->progress); + + $this->redirects--; + + return $result; + } + + if (!$this->retry) { + $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, got redirect without Location ('.$http_response_header[0].')'); + $e->setHeaders($http_response_header); + $e->setResponse($result); + throw $e; + } + $result = false; + } + // fail 4xx and 5xx responses and capture the response if ($statusCode && $statusCode >= 400 && $statusCode <= 599) { if (!$this->retry) { @@ -529,9 +597,9 @@ class RemoteFilesystem $host = parse_url($this->fileUrl, PHP_URL_HOST); } - if ($host === 'github.com' || $host === 'api.github.com') { - $host = '*.github.com'; - } + // if ($host === 'github.com' || $host === 'api.github.com') { + // $host = '*.github.com'; + // } $tlsOptions['ssl']['CN_match'] = $host; $tlsOptions['ssl']['SNI_server_name'] = $host; @@ -551,6 +619,10 @@ class RemoteFilesystem $headers[] = 'Connection: close'; } + if (PHP_VERSION_ID >= 50304 && $this->disableTls === false) { + $options['http']['follow_location'] = 0; + } + if ($this->io->hasAuthentication($originUrl)) { $auth = $this->io->getAuthentication($originUrl); if ('github.com' === $originUrl && 'x-oauth-basic' === $auth['password']) { From ce1eda25f3b7895531a0a7845377fc8f9a17031c Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 17 Jan 2016 19:42:43 +0000 Subject: [PATCH 03/28] Follow redirects inside RFS only when required by PHP version --- src/Composer/Util/RemoteFilesystem.php | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index b317a2399..ba40517c4 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -221,6 +221,7 @@ class RemoteFilesystem } $options = $this->getOptionsForUrl($originUrl, $additionalOptions); + $userlandFollow = isset($options['http']['follow_location']) && !$options['http']['follow_location']; if ($this->io->isDebug()) { $this->io->writeError((substr($fileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $fileUrl); @@ -295,8 +296,7 @@ class RemoteFilesystem $statusCode = $this->findStatusCode($http_response_header); } - if (!empty($http_response_header[0]) && preg_match('{^HTTP/\S+ (3\d\d)}i', $http_response_header[0], $match)) { - // TODO: Only follow if PHP is not set to follow. + if ($userlandFollow && !empty($http_response_header[0]) && preg_match('{^HTTP/\S+ (3\d\d)}i', $http_response_header[0], $match)) { foreach ($http_response_header as $header) { if (preg_match('{^location: *(.+) *$}i', $header, $m)) { if (parse_url($m[1], PHP_URL_SCHEME)) { @@ -597,9 +597,20 @@ class RemoteFilesystem $host = parse_url($this->fileUrl, PHP_URL_HOST); } - // if ($host === 'github.com' || $host === 'api.github.com') { - // $host = '*.github.com'; - // } + if (PHP_VERSION_ID >= 50304) { + // Must manually follow when setting CN_match because this causes all + // redirects to be validated against the same CN_match value. + $userlandFollow = true; + } else { + // PHP < 5.3.4 does not support follow_location, for those people + // do some really nasty hard coded transformations. These will + // still breakdown if the site redirects to a domain we don't + // expect. + + if ($host === 'github.com' || $host === 'api.github.com') { + $host = '*.github.com'; + } + } $tlsOptions['ssl']['CN_match'] = $host; $tlsOptions['ssl']['SNI_server_name'] = $host; @@ -619,7 +630,7 @@ class RemoteFilesystem $headers[] = 'Connection: close'; } - if (PHP_VERSION_ID >= 50304 && $this->disableTls === false) { + if (isset($userlandFollow)) { $options['http']['follow_location'] = 0; } From ffab235edd5cc05ba7fe37d0394cd929dc270f65 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 17 Jan 2016 19:43:08 +0000 Subject: [PATCH 04/28] Remove code preventing protocol downgrades --- src/Composer/Util/RemoteFilesystem.php | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index ba40517c4..7ea71c2b0 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -331,14 +331,15 @@ class RemoteFilesystem throw $e; } - if ('http' === parse_url($targetUrl, PHP_URL_SCHEME) && 'https' === $this->scheme) { - // Do not allow protocol downgrade. - // TODO: Currently this will fail if a request goes http -> https -> http - $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, not permitting protocol downgrade'); - $e->setHeaders($http_response_header); - $e->setResponse($result); - throw $e; - } + // TODO: Disabled because this is (probably) different behaviour to PHP following for us. + // if ('http' === parse_url($targetUrl, PHP_URL_SCHEME) && 'https' === $this->scheme) { + // // Do not allow protocol downgrade. + // // TODO: Currently this will fail if a request goes http -> https -> http + // $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, not permitting protocol downgrade'); + // $e->setHeaders($http_response_header); + // $e->setResponse($result); + // throw $e; + // } if ($this->io->isDebug()) { $this->io->writeError(sprintf('Following redirect (%u)', $this->redirects)); From e830a611ec620237534822991675a3da3018bbf0 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 17 Jan 2016 21:17:52 +0000 Subject: [PATCH 05/28] Handle other path redirects --- src/Composer/Util/RemoteFilesystem.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 7ea71c2b0..ef2a91e26 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -313,10 +313,16 @@ class RemoteFilesystem if ('/' === $m[1][0]) { // Absolute path; e.g. /foo - throw new \Exception('todo'); + $urlHost = parse_url($this->fileUrl, PHP_URL_HOST); + + // Replace path using hostname as an anchor. + $targetUrl = preg_replace('{^(.+(?://|@)'.preg_quote($urlHost).')(?:[/\?].*)?$}', '\1'.$m[1], $this->fileUrl); } - throw new \Exception('todo'); + // Relative path; e.g. foo + // This actually differs from PHP which seems to add duplicate slashes. + $targetUrl = preg_replace('{^(.+/)[^/?]*(?:\?.*)?$}', '\1'.$m[1], $this->fileUrl); + break; } } From 33471e389f126de413619b53afc4520264ccda3a Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 17 Jan 2016 21:33:55 +0000 Subject: [PATCH 06/28] Pass redirect count using options Removing the risk it might be preserved between requests. --- src/Composer/Util/RemoteFilesystem.php | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index ef2a91e26..1216761ec 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -38,7 +38,7 @@ class RemoteFilesystem private $lastHeaders; private $storeAuth; private $degradedMode = false; - private $redirects = 0; + private $redirects; private $maxRedirects = 20; /** @@ -208,6 +208,7 @@ class RemoteFilesystem $this->lastProgress = null; $this->retryAuthFailure = true; $this->lastHeaders = array(); + $this->redirects = 1; // The first request counts. // capture username/password from URL if there is one if (preg_match('{^https?://(.+):(.+)@([^/]+)}i', $fileUrl, $match)) { @@ -220,6 +221,12 @@ class RemoteFilesystem unset($additionalOptions['retry-auth-failure']); } + if (isset($additionalOptions['redirects'])) { + $this->redirects = $additionalOptions['redirects']; + + unset($additionalOptions['redirects']); + } + $options = $this->getOptionsForUrl($originUrl, $additionalOptions); $userlandFollow = isset($options['http']['follow_location']) && !$options['http']['follow_location']; @@ -351,12 +358,10 @@ class RemoteFilesystem $this->io->writeError(sprintf('Following redirect (%u)', $this->redirects)); } + $additionalOptions['redirects'] = $this->redirects; + // TODO: Not so sure about preserving origin here... - $result = $this->get($this->originUrl, $targetUrl, $additionalOptions, $this->fileName, $this->progress); - - $this->redirects--; - - return $result; + return $this->get($this->originUrl, $targetUrl, $additionalOptions, $this->fileName, $this->progress); } if (!$this->retry) { From 8a8ec6fccc1cdfed76a30080811371966df2129e Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 17 Jan 2016 21:34:34 +0000 Subject: [PATCH 07/28] Too many redirects is not an error in PHP, return the latest response --- src/Composer/Util/RemoteFilesystem.php | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 1216761ec..82b8f400d 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -303,7 +303,7 @@ class RemoteFilesystem $statusCode = $this->findStatusCode($http_response_header); } - if ($userlandFollow && !empty($http_response_header[0]) && preg_match('{^HTTP/\S+ (3\d\d)}i', $http_response_header[0], $match)) { + if ($userlandFollow && !empty($http_response_header[0]) && preg_match('{^HTTP/\S+ (3\d\d)}i', $http_response_header[0], $match) && $this->redirects < $this->maxRedirects) { foreach ($http_response_header as $header) { if (preg_match('{^location: *(.+) *$}i', $header, $m)) { if (parse_url($m[1], PHP_URL_SCHEME)) { @@ -337,13 +337,6 @@ class RemoteFilesystem if ($targetUrl) { $this->redirects++; - if ($this->redirects > $this->maxRedirects) { - $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, too many redirects'); - $e->setHeaders($http_response_header); - $e->setResponse($result); - throw $e; - } - // TODO: Disabled because this is (probably) different behaviour to PHP following for us. // if ('http' === parse_url($targetUrl, PHP_URL_SCHEME) && 'https' === $this->scheme) { // // Do not allow protocol downgrade. From dd3216e93d43e48a0bd82c82fd629c6c761b8d66 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Tue, 19 Jan 2016 22:19:17 +0000 Subject: [PATCH 08/28] Refactor to use new helper methods for headers --- src/Composer/Util/RemoteFilesystem.php | 42 ++++++++++---------------- 1 file changed, 16 insertions(+), 26 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 82b8f400d..6ecc349db 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -303,38 +303,28 @@ class RemoteFilesystem $statusCode = $this->findStatusCode($http_response_header); } - if ($userlandFollow && !empty($http_response_header[0]) && preg_match('{^HTTP/\S+ (3\d\d)}i', $http_response_header[0], $match) && $this->redirects < $this->maxRedirects) { - foreach ($http_response_header as $header) { - if (preg_match('{^location: *(.+) *$}i', $header, $m)) { - if (parse_url($m[1], PHP_URL_SCHEME)) { - $targetUrl = $m[1]; - - break; - } - - if (parse_url($m[1], PHP_URL_HOST)) { - // Scheme relative; e.g. //example.com/foo - $targetUrl = $this->scheme.':'.$m[1]; - break; - } - - if ('/' === $m[1][0]) { - // Absolute path; e.g. /foo - $urlHost = parse_url($this->fileUrl, PHP_URL_HOST); - - // Replace path using hostname as an anchor. - $targetUrl = preg_replace('{^(.+(?://|@)'.preg_quote($urlHost).')(?:[/\?].*)?$}', '\1'.$m[1], $this->fileUrl); - } + if ($userlandFollow && $statusCode >= 300 && $statusCode <= 399 && $this->redirects < $this->maxRedirects) { + if ($locationHeader = $this->findHeaderValue($http_response_header, 'location')) { + if (parse_url($locationHeader, PHP_URL_SCHEME)) { + // Absolute URL; e.g. https://example.com/composer + $targetUrl = $locationHeader; + } elseif (parse_url($locationHeader, PHP_URL_HOST)) { + // Scheme relative; e.g. //example.com/foo + $targetUrl = $this->scheme.':'.$locationHeader; + } elseif ('/' === $locationHeader[0]) { + // Absolute path; e.g. /foo + $urlHost = parse_url($this->fileUrl, PHP_URL_HOST); + // Replace path using hostname as an anchor. + $targetUrl = preg_replace('{^(.+(?://|@)'.preg_quote($urlHost).')(?:[/\?].*)?$}', '\1'.$locationHeader, $this->fileUrl); + } else { // Relative path; e.g. foo // This actually differs from PHP which seems to add duplicate slashes. - $targetUrl = preg_replace('{^(.+/)[^/?]*(?:\?.*)?$}', '\1'.$m[1], $this->fileUrl); - - break; + $targetUrl = preg_replace('{^(.+/)[^/?]*(?:\?.*)?$}', '\1'.$locationHeader, $this->fileUrl); } } - if ($targetUrl) { + if (!empty($targetUrl)) { $this->redirects++; // TODO: Disabled because this is (probably) different behaviour to PHP following for us. From 34f1fcbdcb7316b356e41a6dc71dbd016c6a0b3f Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Fri, 22 Jan 2016 01:47:05 +0000 Subject: [PATCH 09/28] Drop downgrade warning --- src/Composer/Util/RemoteFilesystem.php | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 6ecc349db..e420fa3b7 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -327,16 +327,6 @@ class RemoteFilesystem if (!empty($targetUrl)) { $this->redirects++; - // TODO: Disabled because this is (probably) different behaviour to PHP following for us. - // if ('http' === parse_url($targetUrl, PHP_URL_SCHEME) && 'https' === $this->scheme) { - // // Do not allow protocol downgrade. - // // TODO: Currently this will fail if a request goes http -> https -> http - // $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, not permitting protocol downgrade'); - // $e->setHeaders($http_response_header); - // $e->setResponse($result); - // throw $e; - // } - if ($this->io->isDebug()) { $this->io->writeError(sprintf('Following redirect (%u)', $this->redirects)); } From 33f823146b52d5fe9b3826a1e7fad1e10f2037cf Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Fri, 22 Jan 2016 01:48:16 +0000 Subject: [PATCH 10/28] Account for ports in URL --- src/Composer/Util/RemoteFilesystem.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index e420fa3b7..adba6c46e 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -316,7 +316,7 @@ class RemoteFilesystem $urlHost = parse_url($this->fileUrl, PHP_URL_HOST); // Replace path using hostname as an anchor. - $targetUrl = preg_replace('{^(.+(?://|@)'.preg_quote($urlHost).')(?:[/\?].*)?$}', '\1'.$locationHeader, $this->fileUrl); + $targetUrl = preg_replace('{^(.+(?://|@)'.preg_quote($urlHost).'(?::\d+)?)(?:[/\?].*)?$}', '\1'.$locationHeader, $this->fileUrl); } else { // Relative path; e.g. foo // This actually differs from PHP which seems to add duplicate slashes. From 05c5aee1f1a453818b29ad58310e4ed4f810c915 Mon Sep 17 00:00:00 2001 From: Omar Shaban Date: Sat, 23 Jan 2016 20:50:43 +0200 Subject: [PATCH 11/28] Fix Broken Links in troubleshooting.md --- doc/articles/troubleshooting.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/articles/troubleshooting.md b/doc/articles/troubleshooting.md index 3edc793ba..f5b37a0ef 100644 --- a/doc/articles/troubleshooting.md +++ b/doc/articles/troubleshooting.md @@ -76,16 +76,16 @@ This is a list of common pitfalls on using Composer, and how to avoid them. ## I have a dependency which contains a "repositories" definition in its composer.json, but it seems to be ignored. -The [`repositories`](04-schema.md#repositories) configuration property is defined as [root-only] -(04-schema.md#root-package). It is not inherited. You can read more about the reasons behind this in the "[why can't -composer load repositories recursively?](articles/why-can't-composer-load-repositories-recursively.md)" article. +The [`repositories`](../04-schema.md#repositories) configuration property is defined as [root-only] +(../04-schema.md#root-package). It is not inherited. You can read more about the reasons behind this in the "[why can't +composer load repositories recursively?](../faqs/why-can't-composer-load-repositories-recursively.md)" article. The simplest work-around to this limitation, is moving or duplicating the `repositories` definition into your root composer.json. ## I have locked a dependency to a specific commit but get unexpected results. While Composer supports locking dependencies to a specific commit using the `#commit-ref` syntax, there are certain -caveats that one should take into account. The most important one is [documented](04-schema.md#package-links), but +caveats that one should take into account. The most important one is [documented](../04-schema.md#package-links), but frequently overlooked: > **Note:** While this is convenient at times, it should not be how you use From 7e2a015e9ba998ced1d7865cd4b5ff1193174ab2 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Tue, 19 Jan 2016 23:54:23 +0000 Subject: [PATCH 12/28] Provide support for subjectAltName on PHP < 5.6 --- src/Composer/Util/RemoteFilesystem.php | 157 +++++++++++++++++++++++++ 1 file changed, 157 insertions(+) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 9a8a25d81..b3bd6030f 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -33,6 +33,7 @@ class RemoteFilesystem private $progress; private $lastProgress; private $options = array(); + private $peerCertificateMap = array(); private $disableTls = false; private $retryAuthFailure; private $lastHeaders; @@ -252,6 +253,18 @@ class RemoteFilesystem }); try { $result = file_get_contents($fileUrl, false, $ctx); + + if (PHP_VERSION_ID < 50600 && !empty($options['ssl']['peer_fingerprint'])) { + // Emulate fingerprint validation on PHP < 5.6 + $params = stream_context_get_params($ctx); + $expectedPeerFingerprint = $options['ssl']['peer_fingerprint']; + $peerFingerprint = $this->getCertificateFingerprint($params['options']['ssl']['peer_certificate']); + + // Constant time compare??! + if ($expectedPeerFingerprint !== $peerFingerprint) { + throw new TransportException('Peer fingerprint did not match'); + } + } } catch (\Exception $e) { if ($e instanceof TransportException && !empty($http_response_header[0])) { $e->setHeaders($http_response_header); @@ -353,6 +366,32 @@ class RemoteFilesystem } } + if (false === $result && false !== strpos($errorMessage, 'Peer certificate') && PHP_VERSION_ID < 50600) { + // Certificate name error, PHP doesn't support subjectAltName on PHP < 5.6 + // The procedure to handle sAN for older PHP's is: + // + // 1. Open socket to remote server and fetch certificate (disabling peer + // validation because PHP errors without giving up the certificate.) + // + // 2. Verifying the domain in the URL against the names in the sAN field. + // If there is a match record the authority [host/port], certificate + // common name, and certificate fingerprint. + // + // 3. Retry the original request but changing the CN_match parameter to + // the common name extracted from the certificate in step 2. + // + // 4. To prevent any attempt at being hoodwinked by switching the + // certificate between steps 2 and 3 the fingerprint of the certificate + // presented in step 3 is compared against the one recorded in step 2. + $certDetails = $this->getCertificateCnAndFp($this->fileUrl, $options); + + if ($certDetails) { + $this->peerCertificateMap[$this->getUrlAuthority($this->fileUrl)] = $certDetails; + + $this->retry = true; + } + } + if ($this->retry) { $this->retry = false; @@ -529,6 +568,14 @@ class RemoteFilesystem $tlsOptions['ssl']['SNI_server_name'] = $host; } + if (isset($this->peerCertificateMap[$this->getUrlAuthority($originUrl)])) { + // Handle subjectAltName on lesser PHP's. + $certMap = $this->peerCertificateMap[$this->getUrlAuthority($originUrl)]; + + $tlsOptions['ssl']['CN_match'] = $certMap['cn']; + $tlsOptions['ssl']['peer_fingerprint'] = $certMap['fp']; + } + $headers = array(); if (extension_loaded('zlib')) { @@ -625,6 +672,7 @@ class RemoteFilesystem 'verify_peer' => true, 'verify_depth' => 7, 'SNI_enabled' => true, + 'capture_peer_cert' => true, ) ); @@ -800,4 +848,113 @@ class RemoteFilesystem unset($source, $target); } + + private function getCertificateCnAndFp($url, $options) + { + $context = StreamContextFactory::getContext($url, $options, array('options' => array( + 'ssl' => array( + 'capture_peer_cert' => true, + 'verify_peer' => false, // Yes this is fucking insane! But PHP is lame. + )) + )); + + if (false === $handle = @fopen($url, 'rb', false, $context)) { + return; + } + + // Close non authenticated connection without reading any content. + fclose($handle); + + $params = stream_context_get_params($context); + + if (!empty($params['options']['ssl']['peer_certificate'])) { + $peerCertificate = $params['options']['ssl']['peer_certificate']; + + $fp = $this->getCertificateFingerprint($peerCertificate); + $cert = openssl_x509_parse($peerCertificate, false); + $commonName = $cert['subject']['commonName']; + + $subjectAltName = preg_split('{\s*,\s*}', $cert['extensions']['subjectAltName']); + $subjectAltName = array_filter(array_map(function ($name) { + if (0 === strpos($name, 'DNS:')) { + return substr($name, 4); + } + }, $subjectAltName)); + + if (in_array(parse_url($url, PHP_URL_HOST), $subjectAltName, true)) { + return array( + 'cn' => $commonName, + 'fp' => $fp, + ); + } + + // TODO: Support wildcards. + } + } + + /** + * Get the certificate pin. + * + * By Kevin McArthur of StormTide Digital Studios Inc. + * @KevinSMcArthur / https://github.com/StormTide + * + * See http://tools.ietf.org/html/draft-ietf-websec-key-pinning-02 + * + * This method was adapted from Sslurp. + * https://github.com/EvanDotPro/Sslurp + * + * (c) Evan Coury + * + * For the full copyright and license information, please see below: + * + * Copyright (c) 2013, Evan Coury + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + private function getCertificateFingerprint($certificate) + { + $pubkeydetails = openssl_pkey_get_details(openssl_get_publickey($certificate)); + $pubkeypem = $pubkeydetails['key']; + //Convert PEM to DER before SHA1'ing + $start = '-----BEGIN PUBLIC KEY-----'; + $end = '-----END PUBLIC KEY-----'; + $pemtrim = substr($pubkeypem, (strpos($pubkeypem, $start) + strlen($start)), (strlen($pubkeypem) - strpos($pubkeypem, $end)) * (-1)); + $der = base64_decode($pemtrim); + + return sha1($der); + } + + private function getUrlAuthority($url) + { + $defaultPorts = array( + 'ftp' => 21, + 'http' => 80, + 'https' => 443, + ); + + $defaultPort = $defaultPorts[parse_url($this->fileUrl, PHP_URL_SCHEME)]; + $port = parse_url($this->fileUrl, PHP_URL_PORT) ?: $defaultPort; + + return parse_url($this->fileUrl, PHP_URL_HOST).':'.$port; + } } From 304c268c3bf6bfee2b5320be25bd43a329fd1192 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 24 Jan 2016 18:52:09 +0000 Subject: [PATCH 13/28] Tidy up and general improvement of sAN handling code * Move OpenSSL functions into a new TlsHelper class * Add error when sAN certificate cannot be verified due to CVE-2013-6420 * Throw exception if PHP >= 5.6 manages to use fallback code * Add support for wildcards in CN/sAN * Add tests for cert name validation * Check for backported security fix for CVE-2013-6420 using testcase from PHP tests. * Whitelist some disto PHP versions that have the CVE-2013-6420 fix backported. --- src/Composer/Util/RemoteFilesystem.php | 138 ++++------ src/Composer/Util/TlsHelper.php | 289 +++++++++++++++++++++ tests/Composer/Test/Util/TlsHelperTest.php | 76 ++++++ 3 files changed, 422 insertions(+), 81 deletions(-) create mode 100644 src/Composer/Util/TlsHelper.php create mode 100644 tests/Composer/Test/Util/TlsHelperTest.php diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index b3bd6030f..cee0670c0 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -258,7 +258,7 @@ class RemoteFilesystem // Emulate fingerprint validation on PHP < 5.6 $params = stream_context_get_params($ctx); $expectedPeerFingerprint = $options['ssl']['peer_fingerprint']; - $peerFingerprint = $this->getCertificateFingerprint($params['options']['ssl']['peer_certificate']); + $peerFingerprint = TlsHelper::getCertificateFingerprint($params['options']['ssl']['peer_certificate']); // Constant time compare??! if ($expectedPeerFingerprint !== $peerFingerprint) { @@ -383,12 +383,19 @@ class RemoteFilesystem // 4. To prevent any attempt at being hoodwinked by switching the // certificate between steps 2 and 3 the fingerprint of the certificate // presented in step 3 is compared against the one recorded in step 2. - $certDetails = $this->getCertificateCnAndFp($this->fileUrl, $options); + if (TlsHelper::isOpensslParseSafe()) { + $certDetails = $this->getCertificateCnAndFp($this->fileUrl, $options); - if ($certDetails) { - $this->peerCertificateMap[$this->getUrlAuthority($this->fileUrl)] = $certDetails; + if ($certDetails) { + $this->peerCertificateMap[$this->getUrlAuthority($this->fileUrl)] = $certDetails; - $this->retry = true; + $this->retry = true; + } + } else { + $this->io->writeError(sprintf( + 'Your version of PHP, %s, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.', + PHP_VERSION + )); } } @@ -566,14 +573,24 @@ class RemoteFilesystem $tlsOptions['ssl']['CN_match'] = $host; $tlsOptions['ssl']['SNI_server_name'] = $host; - } - if (isset($this->peerCertificateMap[$this->getUrlAuthority($originUrl)])) { - // Handle subjectAltName on lesser PHP's. - $certMap = $this->peerCertificateMap[$this->getUrlAuthority($originUrl)]; + $urlAuthority = $this->getUrlAuthority($this->fileUrl); - $tlsOptions['ssl']['CN_match'] = $certMap['cn']; - $tlsOptions['ssl']['peer_fingerprint'] = $certMap['fp']; + if (isset($this->peerCertificateMap[$urlAuthority])) { + // Handle subjectAltName on lesser PHP's. + $certMap = $this->peerCertificateMap[$urlAuthority]; + + if ($this->io->isDebug()) { + $this->io->writeError(sprintf( + 'Using %s as CN for subjectAltName enabled host %s', + $certMap['cn'], + $urlAuthority + )); + } + + $tlsOptions['ssl']['CN_match'] = $certMap['cn']; + $tlsOptions['ssl']['peer_fingerprint'] = $certMap['fp']; + } } $headers = array(); @@ -849,8 +866,20 @@ class RemoteFilesystem unset($source, $target); } + /** + * Fetch certificate common name and fingerprint for validation of SAN. + * + * @todo Remove when PHP 5.6 is minimum supported version. + */ private function getCertificateCnAndFp($url, $options) { + if (PHP_VERSION_ID >= 50600) { + throw new \BadMethodCallException(sprintf( + '%s must not be used on PHP >= 5.6', + __METHOD__ + )); + } + $context = StreamContextFactory::getContext($url, $options, array('options' => array( 'ssl' => array( 'capture_peer_cert' => true, @@ -858,92 +887,30 @@ class RemoteFilesystem )) )); + // Ideally this would just use stream_socket_client() to avoid sending a + // HTTP request but that does not capture the certificate. if (false === $handle = @fopen($url, 'rb', false, $context)) { return; } // Close non authenticated connection without reading any content. fclose($handle); + $handle = null; $params = stream_context_get_params($context); if (!empty($params['options']['ssl']['peer_certificate'])) { $peerCertificate = $params['options']['ssl']['peer_certificate']; - $fp = $this->getCertificateFingerprint($peerCertificate); - $cert = openssl_x509_parse($peerCertificate, false); - $commonName = $cert['subject']['commonName']; - - $subjectAltName = preg_split('{\s*,\s*}', $cert['extensions']['subjectAltName']); - $subjectAltName = array_filter(array_map(function ($name) { - if (0 === strpos($name, 'DNS:')) { - return substr($name, 4); - } - }, $subjectAltName)); - - if (in_array(parse_url($url, PHP_URL_HOST), $subjectAltName, true)) { + if (TlsHelper::checkCertificateHost($peerCertificate, parse_url($url, PHP_URL_HOST), $commonName)) { return array( 'cn' => $commonName, - 'fp' => $fp, + 'fp' => TlsHelper::getCertificateFingerprint($peerCertificate), ); } - - // TODO: Support wildcards. } } - /** - * Get the certificate pin. - * - * By Kevin McArthur of StormTide Digital Studios Inc. - * @KevinSMcArthur / https://github.com/StormTide - * - * See http://tools.ietf.org/html/draft-ietf-websec-key-pinning-02 - * - * This method was adapted from Sslurp. - * https://github.com/EvanDotPro/Sslurp - * - * (c) Evan Coury - * - * For the full copyright and license information, please see below: - * - * Copyright (c) 2013, Evan Coury - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - private function getCertificateFingerprint($certificate) - { - $pubkeydetails = openssl_pkey_get_details(openssl_get_publickey($certificate)); - $pubkeypem = $pubkeydetails['key']; - //Convert PEM to DER before SHA1'ing - $start = '-----BEGIN PUBLIC KEY-----'; - $end = '-----END PUBLIC KEY-----'; - $pemtrim = substr($pubkeypem, (strpos($pubkeypem, $start) + strlen($start)), (strlen($pubkeypem) - strpos($pubkeypem, $end)) * (-1)); - $der = base64_decode($pemtrim); - - return sha1($der); - } - private function getUrlAuthority($url) { $defaultPorts = array( @@ -952,9 +919,18 @@ class RemoteFilesystem 'https' => 443, ); - $defaultPort = $defaultPorts[parse_url($this->fileUrl, PHP_URL_SCHEME)]; - $port = parse_url($this->fileUrl, PHP_URL_PORT) ?: $defaultPort; + $scheme = parse_url($url, PHP_URL_SCHEME); - return parse_url($this->fileUrl, PHP_URL_HOST).':'.$port; + if (!isset($defaultPorts[$scheme])) { + throw new \InvalidArgumentException(sprintf( + 'Could not get default port for unknown scheme: %s', + $scheme + )); + } + + $defaultPort = $defaultPorts[$scheme]; + $port = parse_url($url, PHP_URL_PORT) ?: $defaultPort; + + return parse_url($url, PHP_URL_HOST).':'.$port; } } diff --git a/src/Composer/Util/TlsHelper.php b/src/Composer/Util/TlsHelper.php new file mode 100644 index 000000000..ce6738cdd --- /dev/null +++ b/src/Composer/Util/TlsHelper.php @@ -0,0 +1,289 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Util; + +use Symfony\Component\Process\PhpProcess; + +/** + * @author Chris Smith + */ +final class TlsHelper +{ + private static $useOpensslParse; + + /** + * Match hostname against a certificate. + * + * @param mixed $certificate X.509 certificate + * @param string $hostname Hostname in the URL + * @param string $cn Set to the common name of the certificate iff match found + * + * @return bool + */ + public static function checkCertificateHost($certificate, $hostname, &$cn = null) + { + $names = self::getCertificateNames($certificate); + + if (empty($names)) { + return false; + } + + $combinedNames = array_merge($names['san'], array($names['cn'])); + $hostname = strtolower($hostname); + + foreach ($combinedNames as $certName) { + $matcher = self::certNameMatcher($certName); + + if ($matcher && $matcher($hostname)) { + $cn = $names['cn']; + return true; + } + } + + return false; + } + + + /** + * Extract DNS names out of an X.509 certificate. + * + * @param mixed $certificate X.509 certificate + * + * @return array|null + */ + public static function getCertificateNames($certificate) + { + if (is_array($certificate)) { + $info = $certificate; + } elseif (self::isOpensslParseSafe()) { + $info = openssl_x509_parse($certificate, false); + } + + if (!isset($info['subject']['commonName'])) { + return; + } + + $commonName = strtolower($info['subject']['commonName']); + $subjectAltNames = array(); + + if (isset($info['extensions']['subjectAltName'])) { + $subjectAltNames = preg_split('{\s*,\s*}', $info['extensions']['subjectAltName']); + $subjectAltNames = array_filter(array_map(function ($name) { + if (0 === strpos($name, 'DNS:')) { + return strtolower(ltrim(substr($name, 4))); + } + }, $subjectAltNames)); + $subjectAltNames = array_values($subjectAltNames); + } + + return array( + 'cn' => $commonName, + 'san' => $subjectAltNames, + ); + } + + /** + * Get the certificate pin. + * + * By Kevin McArthur of StormTide Digital Studios Inc. + * @KevinSMcArthur / https://github.com/StormTide + * + * See http://tools.ietf.org/html/draft-ietf-websec-key-pinning-02 + * + * This method was adapted from Sslurp. + * https://github.com/EvanDotPro/Sslurp + * + * (c) Evan Coury + * + * For the full copyright and license information, please see below: + * + * Copyright (c) 2013, Evan Coury + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + public static function getCertificateFingerprint($certificate) + { + $pubkeydetails = openssl_pkey_get_details(openssl_get_publickey($certificate)); + $pubkeypem = $pubkeydetails['key']; + //Convert PEM to DER before SHA1'ing + $start = '-----BEGIN PUBLIC KEY-----'; + $end = '-----END PUBLIC KEY-----'; + $pemtrim = substr($pubkeypem, (strpos($pubkeypem, $start) + strlen($start)), (strlen($pubkeypem) - strpos($pubkeypem, $end)) * (-1)); + $der = base64_decode($pemtrim); + + return sha1($der); + } + + /** + * Test if it is safe to use the PHP function openssl_x509_parse(). + * + * This checks if OpenSSL extensions is vulnerable to remote code execution + * via the exploit documented as CVE-2013-6420. + * + * @return bool + */ + public static function isOpensslParseSafe() + { + if (null !== self::$useOpensslParse) { + return self::$useOpensslParse; + } + + if (PHP_VERSION_ID >= 50600) { + return self::$useOpensslParse = true; + } + + // Vulnerable: + // PHP 5.3.0 - PHP 5.3.27 + // PHP 5.4.0 - PHP 5.4.22 + // PHP 5.5.0 - PHP 5.5.6 + if ( + (PHP_VERSION_ID < 50400 && PHP_VERSION_ID >= 50328) + || (PHP_VERSION_ID < 50500 && PHP_VERSION_ID >= 50423) + || (PHP_VERSION_ID < 50600 && PHP_VERSION_ID >= 50507) + ) { + // This version of PHP has the fix for CVE-2013-6420 applied. + return self::$useOpensslParse = true; + } + + if ('\\' === DIRECTORY_SEPARATOR) { + // Windows is probably insecure in this case. + return self::$useOpensslParse = false; + } + + $compareDistroVersionPrefix = function ($prefix, $fixedVersion) { + $regex = '{^'.preg_quote($prefix).'([0-9]+)}$'; + + if (preg_match($regex, PHP_VERSION, $m)) { + return ((int) $m[1]) >= $fixedVersion; + } + + return false; + }; + + // Hard coded list of PHP distributions with the fix backported. + if ( + $compareDistroVersionPrefix('5.3.3-7+squeeze', 19) // Debian 6 (Squeeze) + || $compareDistroVersionPrefix('5.4.4-14+deb7u', 7) // Debian 7 (Wheezy) + || $compareDistroVersionPrefix('5.3.10-1ubuntu3.', 9) // Ubuntu 12.04 (Precise) + ) { + return self::$useOpensslParse = true; + } + + // This is where things get crazy, because distros backport security + // fixes the chances are on NIX systems the fix has been applied but + // it's not possible to verify that from the PHP version. + // + // To verify exec a new PHP process and run the issue testcase with + // known safe input that replicates the bug. + + // Based on testcase in https://github.com/php/php-src/commit/c1224573c773b6845e83505f717fbf820fc18415 + $cert = 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUVwRENDQTR5Z0F3SUJBZ0lKQUp6dThyNnU2ZUJjTUEwR0NTcUdTSWIzRFFFQkJRVUFNSUhETVFzd0NRWUQKVlFRR0V3SkVSVEVjTUJvR0ExVUVDQXdUVG05eVpISm9aV2x1TFZkbGMzUm1ZV3hsYmpFUU1BNEdBMVVFQnd3SApTOE9Ed3Jac2JqRVVNQklHQTFVRUNnd0xVMlZyZEdsdmJrVnBibk14SHpBZEJnTlZCQXNNRmsxaGJHbGphVzkxCmN5QkRaWEowSUZObFkzUnBiMjR4SVRBZkJnTlZCQU1NR0cxaGJHbGphVzkxY3k1elpXdDBhVzl1WldsdWN5NWsKWlRFcU1DZ0dDU3FHU0liM0RRRUpBUlliYzNSbFptRnVMbVZ6YzJWeVFITmxhM1JwYjI1bGFXNXpMbVJsTUhVWQpaREU1TnpBd01UQXhNREF3TURBd1dnQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUEKQUFBQUFBQVhEVEUwTVRFeU9ERXhNemt6TlZvd2djTXhDekFKQmdOVkJBWVRBa1JGTVJ3d0dnWURWUVFJREJOTwpiM0prY21obGFXNHRWMlZ6ZEdaaGJHVnVNUkF3RGdZRFZRUUhEQWRMdzRQQ3RteHVNUlF3RWdZRFZRUUtEQXRUClpXdDBhVzl1UldsdWN6RWZNQjBHQTFVRUN3d1dUV0ZzYVdOcGIzVnpJRU5sY25RZ1UyVmpkR2x2YmpFaE1COEcKQTFVRUF3d1liV0ZzYVdOcGIzVnpMbk5sYTNScGIyNWxhVzV6TG1SbE1Tb3dLQVlKS29aSWh2Y05BUWtCRmh0egpkR1ZtWVc0dVpYTnpaWEpBYzJWcmRHbHZibVZwYm5NdVpHVXdnZ0VpTUEwR0NTcUdTSWIzRFFFQkFRVUFBNElCCkR3QXdnZ0VLQW9JQkFRRERBZjNobDdKWTBYY0ZuaXlFSnBTU0RxbjBPcUJyNlFQNjV1c0pQUnQvOFBhRG9xQnUKd0VZVC9OYSs2ZnNnUGpDMHVLOURaZ1dnMnRIV1dvYW5TYmxBTW96NVBINlorUzRTSFJaN2UyZERJalBqZGhqaAowbUxnMlVNTzV5cDBWNzk3R2dzOWxOdDZKUmZIODFNTjJvYlhXczROdHp0TE11RDZlZ3FwcjhkRGJyMzRhT3M4CnBrZHVpNVVhd1Raa3N5NXBMUEhxNWNNaEZHbTA2djY1Q0xvMFYyUGQ5K0tBb2tQclBjTjVLTEtlYno3bUxwazYKU01lRVhPS1A0aWRFcXh5UTdPN2ZCdUhNZWRzUWh1K3ByWTNzaTNCVXlLZlF0UDVDWm5YMmJwMHdLSHhYMTJEWAoxbmZGSXQ5RGJHdkhUY3lPdU4rblpMUEJtM3ZXeG50eUlJdlZBZ01CQUFHalFqQkFNQWtHQTFVZEV3UUNNQUF3CkVRWUpZSVpJQVliNFFnRUJCQVFEQWdlQU1Bc0dBMVVkRHdRRUF3SUZvREFUQmdOVkhTVUVEREFLQmdnckJnRUYKQlFjREFqQU5CZ2txaGtpRzl3MEJBUVVGQUFPQ0FRRUFHMGZaWVlDVGJkajFYWWMrMVNub2FQUit2SThDOENhRAo4KzBVWWhkbnlVNGdnYTBCQWNEclk5ZTk0ZUVBdTZacXljRjZGakxxWFhkQWJvcHBXb2NyNlQ2R0QxeDMzQ2tsClZBcnpHL0t4UW9oR0QySmVxa2hJTWxEb214SE83a2EzOStPYThpMnZXTFZ5alU4QVp2V01BcnVIYTRFRU55RzcKbFcyQWFnYUZLRkNyOVRuWFRmcmR4R1ZFYnY3S1ZRNmJkaGc1cDVTanBXSDErTXEwM3VSM1pYUEJZZHlWODMxOQpvMGxWajFLRkkyRENML2xpV2lzSlJvb2YrMWNSMzVDdGQwd1lCY3BCNlRac2xNY09QbDc2ZHdLd0pnZUpvMlFnClpzZm1jMnZDMS9xT2xOdU5xLzBUenprVkd2OEVUVDNDZ2FVK1VYZTRYT1Z2a2NjZWJKbjJkZz09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K'; + $script = <<<'EOT' + +error_reporting(-1); +$info = openssl_x509_parse(base64_decode('%s')); +var_dump(PHP_VERSION, $info['issuer']['emailAddress'], $info['validFrom_time_t']); + +EOT; + $script = '<'."?php\n".sprintf($script, $cert); + + try { + $process = new PhpProcess($script); + $process->mustRun(); + } catch (\Exception $e) { + // In the case of any exceptions just accept it is not possible to + // determine the safety of openssl_x509_parse and bail out. + return self::$useOpensslParse = false; + } + + $output = preg_split('{\r?\n}', trim($process->getOutput())); + $errorOutput = trim($process->getErrorOutput()); + + if ( + count($output) === 3 + && $output[0] === sprintf('string(%d) "%s"', strlen(PHP_VERSION), PHP_VERSION) + && $output[1] === 'string(27) "stefan.esser@sektioneins.de"' + && $output[2] === 'int(-1)' + && preg_match('{openssl_x509_parse\(\): illegal length in timestamp in - on line \d+}', $errorOutput) + ) { + // This PHP has the fix backported probably by a distro security team. + return self::$useOpensslParse = true; + } + + return self::$useOpensslParse = false; + } + + /** + * Convert certificate name into matching function. + * + * @param $certName CN/SAN + * + * @return callable|null + */ + private static function certNameMatcher($certName) + { + $wildcards = substr_count($certName, '*'); + + if (0 === $wildcards) { + // Literal match. + return function ($hostname) use ($certName) { + return $hostname === $certName; + }; + } + + if (1 === $wildcards) { + $components = explode('.', $certName); + + if (3 > count($components)) { + // Must have 3+ components + return; + } + + $firstComponent = $components[0]; + + // Wildcard must be the last character. + if ('*' !== $firstComponent[strlen($firstComponent) - 1]) { + return; + } + + $wildcardRegex = preg_quote($certName); + $wildcardRegex = str_replace('\\*', '[a-z0-9-]+', $wildcardRegex); + $wildcardRegex = "{^{$wildcardRegex}$}"; + + return function ($hostname) use ($wildcardRegex) { + // var_dump($wildcardRegex); + return 1 === preg_match($wildcardRegex, $hostname); + }; + } + } +} diff --git a/tests/Composer/Test/Util/TlsHelperTest.php b/tests/Composer/Test/Util/TlsHelperTest.php new file mode 100644 index 000000000..b17c42ba0 --- /dev/null +++ b/tests/Composer/Test/Util/TlsHelperTest.php @@ -0,0 +1,76 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Test\Util; + +use Composer\Util\TlsHelper; + +class TlsHelperTest extends \PHPUnit_Framework_TestCase +{ + /** @dataProvider dataCheckCertificateHost */ + public function testCheckCertificateHost($expectedResult, $hostname, $certNames) + { + $certificate['subject']['commonName'] = $expectedCn = array_shift($certNames); + $certificate['extensions']['subjectAltName'] = $certNames ? 'DNS:'.implode(',DNS:', $certNames) : ''; + + $result = TlsHelper::checkCertificateHost($certificate, $hostname, $foundCn); + + if (true === $expectedResult) { + $this->assertTrue($result); + $this->assertSame($expectedCn, $foundCn); + } else { + $this->assertFalse($result); + $this->assertNull($foundCn); + } + } + + public function dataCheckCertificateHost() + { + return array( + array(true, 'getcomposer.org', array('getcomposer.org')), + array(true, 'getcomposer.org', array('getcomposer.org', 'packagist.org')), + array(true, 'getcomposer.org', array('packagist.org', 'getcomposer.org')), + array(true, 'foo.getcomposer.org', array('*.getcomposer.org')), + array(false, 'xyz.foo.getcomposer.org', array('*.getcomposer.org')), + array(true, 'foo.getcomposer.org', array('getcomposer.org', '*.getcomposer.org')), + array(true, 'foo.getcomposer.org', array('foo.getcomposer.org', 'foo*.getcomposer.org')), + array(true, 'foo1.getcomposer.org', array('foo.getcomposer.org', 'foo*.getcomposer.org')), + array(true, 'foo2.getcomposer.org', array('foo.getcomposer.org', 'foo*.getcomposer.org')), + array(false, 'foo2.another.getcomposer.org', array('foo.getcomposer.org', 'foo*.getcomposer.org')), + array(false, 'test.example.net', array('**.example.net', '**.example.net')), + array(false, 'test.example.net', array('t*t.example.net', 't*t.example.net')), + array(false, 'xyz.example.org', array('*z.example.org', '*z.example.org')), + array(false, 'foo.bar.example.com', array('foo.*.example.com', 'foo.*.example.com')), + array(false, 'example.com', array('example.*', 'example.*')), + array(true, 'localhost', array('localhost')), + array(false, 'localhost', array('*')), + array(false, 'localhost', array('local*')), + array(false, 'example.net', array('*.net', '*.org', 'ex*.net')), + array(true, 'example.net', array('*.net', '*.org', 'example.net')), + ); + } + + public function testGetCertificateNames() + { + $certificate['subject']['commonName'] = 'example.net'; + $certificate['extensions']['subjectAltName'] = 'DNS: example.com, IP: 127.0.0.1, DNS: getcomposer.org, Junk: blah, DNS: composer.example.org'; + + $names = TlsHelper::getCertificateNames($certificate); + + $this->assertSame('example.net', $names['cn']); + $this->assertSame(array( + 'example.com', + 'getcomposer.org', + 'composer.example.org', + ), $names['san']); + } +} From 74aa73e841f57694907fa81b0f5094a4f5e738a9 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 24 Jan 2016 19:09:35 +0000 Subject: [PATCH 14/28] The origin may not be the remote host --- src/Composer/Util/RemoteFilesystem.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index cee0670c0..afb942850 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -561,11 +561,7 @@ class RemoteFilesystem // Setup remaining TLS options - the matching may need monitoring, esp. www vs none in CN if ($this->disableTls === false && PHP_VERSION_ID < 50600) { - if (!preg_match('{^https?://}', $this->fileUrl)) { - $host = $originUrl; - } else { - $host = parse_url($this->fileUrl, PHP_URL_HOST); - } + $host = parse_url($this->fileUrl, PHP_URL_HOST); if ($host === 'github.com' || $host === 'api.github.com') { $host = '*.github.com'; From b32aad84394dbccef87c0aa114320a7d97873abc Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 24 Jan 2016 19:10:11 +0000 Subject: [PATCH 15/28] Do not set TLS options on local URLs --- src/Composer/Util/RemoteFilesystem.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index afb942850..09ab6188a 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -560,7 +560,7 @@ class RemoteFilesystem $tlsOptions = array(); // Setup remaining TLS options - the matching may need monitoring, esp. www vs none in CN - if ($this->disableTls === false && PHP_VERSION_ID < 50600) { + if ($this->disableTls === false && PHP_VERSION_ID < 50600 && !stream_is_local($this->fileUrl)) { $host = parse_url($this->fileUrl, PHP_URL_HOST); if ($host === 'github.com' || $host === 'api.github.com') { From bc8b7b0f78f68c0aceed500519e2492492828857 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 24 Jan 2016 19:41:14 +0000 Subject: [PATCH 16/28] Remove left behind debug code --- src/Composer/Util/TlsHelper.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Composer/Util/TlsHelper.php b/src/Composer/Util/TlsHelper.php index ce6738cdd..cfa209e83 100644 --- a/src/Composer/Util/TlsHelper.php +++ b/src/Composer/Util/TlsHelper.php @@ -281,7 +281,6 @@ EOT; $wildcardRegex = "{^{$wildcardRegex}$}"; return function ($hostname) use ($wildcardRegex) { - // var_dump($wildcardRegex); return 1 === preg_match($wildcardRegex, $hostname); }; } From e2e07a32c3fb45c7b63fc33017904b496bac9a2a Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Sun, 24 Jan 2016 20:54:43 +0000 Subject: [PATCH 17/28] Fixes to vuln detection --- src/Composer/Util/TlsHelper.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Composer/Util/TlsHelper.php b/src/Composer/Util/TlsHelper.php index cfa209e83..4aea24df6 100644 --- a/src/Composer/Util/TlsHelper.php +++ b/src/Composer/Util/TlsHelper.php @@ -181,7 +181,7 @@ final class TlsHelper } $compareDistroVersionPrefix = function ($prefix, $fixedVersion) { - $regex = '{^'.preg_quote($prefix).'([0-9]+)}$'; + $regex = '{^'.preg_quote($prefix).'([0-9]+)$}'; if (preg_match($regex, PHP_VERSION, $m)) { return ((int) $m[1]) >= $fixedVersion; @@ -192,7 +192,7 @@ final class TlsHelper // Hard coded list of PHP distributions with the fix backported. if ( - $compareDistroVersionPrefix('5.3.3-7+squeeze', 19) // Debian 6 (Squeeze) + $compareDistroVersionPrefix('5.3.3-7+squeeze', 18) // Debian 6 (Squeeze) || $compareDistroVersionPrefix('5.4.4-14+deb7u', 7) // Debian 7 (Wheezy) || $compareDistroVersionPrefix('5.3.10-1ubuntu3.', 9) // Ubuntu 12.04 (Precise) ) { @@ -207,6 +207,7 @@ final class TlsHelper // known safe input that replicates the bug. // Based on testcase in https://github.com/php/php-src/commit/c1224573c773b6845e83505f717fbf820fc18415 + // changes in https://github.com/php/php-src/commit/76a7fd893b7d6101300cc656058704a73254d593 $cert = 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUVwRENDQTR5Z0F3SUJBZ0lKQUp6dThyNnU2ZUJjTUEwR0NTcUdTSWIzRFFFQkJRVUFNSUhETVFzd0NRWUQKVlFRR0V3SkVSVEVjTUJvR0ExVUVDQXdUVG05eVpISm9aV2x1TFZkbGMzUm1ZV3hsYmpFUU1BNEdBMVVFQnd3SApTOE9Ed3Jac2JqRVVNQklHQTFVRUNnd0xVMlZyZEdsdmJrVnBibk14SHpBZEJnTlZCQXNNRmsxaGJHbGphVzkxCmN5QkRaWEowSUZObFkzUnBiMjR4SVRBZkJnTlZCQU1NR0cxaGJHbGphVzkxY3k1elpXdDBhVzl1WldsdWN5NWsKWlRFcU1DZ0dDU3FHU0liM0RRRUpBUlliYzNSbFptRnVMbVZ6YzJWeVFITmxhM1JwYjI1bGFXNXpMbVJsTUhVWQpaREU1TnpBd01UQXhNREF3TURBd1dnQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUEKQUFBQUFBQVhEVEUwTVRFeU9ERXhNemt6TlZvd2djTXhDekFKQmdOVkJBWVRBa1JGTVJ3d0dnWURWUVFJREJOTwpiM0prY21obGFXNHRWMlZ6ZEdaaGJHVnVNUkF3RGdZRFZRUUhEQWRMdzRQQ3RteHVNUlF3RWdZRFZRUUtEQXRUClpXdDBhVzl1UldsdWN6RWZNQjBHQTFVRUN3d1dUV0ZzYVdOcGIzVnpJRU5sY25RZ1UyVmpkR2x2YmpFaE1COEcKQTFVRUF3d1liV0ZzYVdOcGIzVnpMbk5sYTNScGIyNWxhVzV6TG1SbE1Tb3dLQVlKS29aSWh2Y05BUWtCRmh0egpkR1ZtWVc0dVpYTnpaWEpBYzJWcmRHbHZibVZwYm5NdVpHVXdnZ0VpTUEwR0NTcUdTSWIzRFFFQkFRVUFBNElCCkR3QXdnZ0VLQW9JQkFRRERBZjNobDdKWTBYY0ZuaXlFSnBTU0RxbjBPcUJyNlFQNjV1c0pQUnQvOFBhRG9xQnUKd0VZVC9OYSs2ZnNnUGpDMHVLOURaZ1dnMnRIV1dvYW5TYmxBTW96NVBINlorUzRTSFJaN2UyZERJalBqZGhqaAowbUxnMlVNTzV5cDBWNzk3R2dzOWxOdDZKUmZIODFNTjJvYlhXczROdHp0TE11RDZlZ3FwcjhkRGJyMzRhT3M4CnBrZHVpNVVhd1Raa3N5NXBMUEhxNWNNaEZHbTA2djY1Q0xvMFYyUGQ5K0tBb2tQclBjTjVLTEtlYno3bUxwazYKU01lRVhPS1A0aWRFcXh5UTdPN2ZCdUhNZWRzUWh1K3ByWTNzaTNCVXlLZlF0UDVDWm5YMmJwMHdLSHhYMTJEWAoxbmZGSXQ5RGJHdkhUY3lPdU4rblpMUEJtM3ZXeG50eUlJdlZBZ01CQUFHalFqQkFNQWtHQTFVZEV3UUNNQUF3CkVRWUpZSVpJQVliNFFnRUJCQVFEQWdlQU1Bc0dBMVVkRHdRRUF3SUZvREFUQmdOVkhTVUVEREFLQmdnckJnRUYKQlFjREFqQU5CZ2txaGtpRzl3MEJBUVVGQUFPQ0FRRUFHMGZaWVlDVGJkajFYWWMrMVNub2FQUit2SThDOENhRAo4KzBVWWhkbnlVNGdnYTBCQWNEclk5ZTk0ZUVBdTZacXljRjZGakxxWFhkQWJvcHBXb2NyNlQ2R0QxeDMzQ2tsClZBcnpHL0t4UW9oR0QySmVxa2hJTWxEb214SE83a2EzOStPYThpMnZXTFZ5alU4QVp2V01BcnVIYTRFRU55RzcKbFcyQWFnYUZLRkNyOVRuWFRmcmR4R1ZFYnY3S1ZRNmJkaGc1cDVTanBXSDErTXEwM3VSM1pYUEJZZHlWODMxOQpvMGxWajFLRkkyRENML2xpV2lzSlJvb2YrMWNSMzVDdGQwd1lCY3BCNlRac2xNY09QbDc2ZHdLd0pnZUpvMlFnClpzZm1jMnZDMS9xT2xOdU5xLzBUenprVkd2OEVUVDNDZ2FVK1VYZTRYT1Z2a2NjZWJKbjJkZz09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K'; $script = <<<'EOT' @@ -234,7 +235,7 @@ EOT; && $output[0] === sprintf('string(%d) "%s"', strlen(PHP_VERSION), PHP_VERSION) && $output[1] === 'string(27) "stefan.esser@sektioneins.de"' && $output[2] === 'int(-1)' - && preg_match('{openssl_x509_parse\(\): illegal length in timestamp in - on line \d+}', $errorOutput) + && preg_match('{openssl_x509_parse\(\): illegal (?:ASN1 data type for|length in) timestamp in - on line \d+}', $errorOutput) ) { // This PHP has the fix backported probably by a distro security team. return self::$useOpensslParse = true; From eb8df89cd5cfaab55e1ec2048f4987e1bf9910fd Mon Sep 17 00:00:00 2001 From: Bob4ever Date: Mon, 25 Jan 2016 14:29:37 +0100 Subject: [PATCH 18/28] Update custom-installers.md --- doc/articles/custom-installers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/articles/custom-installers.md b/doc/articles/custom-installers.md index 8b3536826..a3c937a5e 100644 --- a/doc/articles/custom-installers.md +++ b/doc/articles/custom-installers.md @@ -84,7 +84,7 @@ Example: "class": "phpDocumentor\\Composer\\TemplateInstallerPlugin" }, "require": { - "composer-plugin-api": "1.0.0" + "composer-plugin-api": "^1.0" } } ``` From 901e6f1d0ea72d3bde3af820de221f1f9ea874e6 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 25 Jan 2016 17:55:29 +0000 Subject: [PATCH 19/28] Fix output and handling of RFS::copy() and extract redirect code into its own method, refs #4783 --- src/Composer/Util/RemoteFilesystem.php | 97 ++++++++++++++------------ 1 file changed, 53 insertions(+), 44 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 4644e30f5..699a279fb 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -213,8 +213,10 @@ class RemoteFilesystem unset($additionalOptions['retry-auth-failure']); } + $isRedirect = false; if (isset($additionalOptions['redirects'])) { $this->redirects = $additionalOptions['redirects']; + $isRedirect = true; unset($additionalOptions['redirects']); } @@ -247,7 +249,7 @@ class RemoteFilesystem $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet'))); - if ($this->progress) { + if ($this->progress && !$isRedirect) { $this->io->writeError(" Downloading: Connecting...", false); } @@ -295,47 +297,9 @@ class RemoteFilesystem $statusCode = $this->findStatusCode($http_response_header); } - if ($userlandFollow && $statusCode >= 300 && $statusCode <= 399 && $this->redirects < $this->maxRedirects) { - if ($locationHeader = $this->findHeaderValue($http_response_header, 'location')) { - if (parse_url($locationHeader, PHP_URL_SCHEME)) { - // Absolute URL; e.g. https://example.com/composer - $targetUrl = $locationHeader; - } elseif (parse_url($locationHeader, PHP_URL_HOST)) { - // Scheme relative; e.g. //example.com/foo - $targetUrl = $this->scheme.':'.$locationHeader; - } elseif ('/' === $locationHeader[0]) { - // Absolute path; e.g. /foo - $urlHost = parse_url($this->fileUrl, PHP_URL_HOST); - - // Replace path using hostname as an anchor. - $targetUrl = preg_replace('{^(.+(?://|@)'.preg_quote($urlHost).'(?::\d+)?)(?:[/\?].*)?$}', '\1'.$locationHeader, $this->fileUrl); - } else { - // Relative path; e.g. foo - // This actually differs from PHP which seems to add duplicate slashes. - $targetUrl = preg_replace('{^(.+/)[^/?]*(?:\?.*)?$}', '\1'.$locationHeader, $this->fileUrl); - } - } - - if (!empty($targetUrl)) { - $this->redirects++; - - if ($this->io->isDebug()) { - $this->io->writeError(sprintf('Following redirect (%u)', $this->redirects)); - } - - $additionalOptions['redirects'] = $this->redirects; - - // TODO: Not so sure about preserving origin here... - return $this->get($this->originUrl, $targetUrl, $additionalOptions, $this->fileName, $this->progress); - } - - if (!$this->retry) { - $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, got redirect without Location ('.$http_response_header[0].')'); - $e->setHeaders($http_response_header); - $e->setResponse($result); - throw $e; - } - $result = false; + // handle 3xx redirects for php<5.6, 304 Not Modified is excluded + if ($userlandFollow && $statusCode >= 300 && $statusCode <= 399 && $statusCode !== 304 && $this->redirects < $this->maxRedirects) { + $result = $this->handleRedirect($http_response_header, $additionalOptions, $result); } // fail 4xx and 5xx responses and capture the response @@ -350,7 +314,7 @@ class RemoteFilesystem $result = false; } - if ($this->progress && !$this->retry) { + if ($this->progress && !$this->retry && !$isRedirect) { $this->io->overwriteError(" Downloading: 100%"); } @@ -387,7 +351,7 @@ class RemoteFilesystem } // handle copy command if download was successful - if (false !== $result && null !== $fileName) { + if (false !== $result && null !== $fileName && !$isRedirect) { if ('' === $result) { throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response'); } @@ -635,6 +599,51 @@ class RemoteFilesystem return $options; } + private function handleRedirect(array $http_response_header, array $additionalOptions, $result) + { + if ($locationHeader = $this->findHeaderValue($http_response_header, 'location')) { + if (parse_url($locationHeader, PHP_URL_SCHEME)) { + // Absolute URL; e.g. https://example.com/composer + $targetUrl = $locationHeader; + } elseif (parse_url($locationHeader, PHP_URL_HOST)) { + // Scheme relative; e.g. //example.com/foo + $targetUrl = $this->scheme.':'.$locationHeader; + } elseif ('/' === $locationHeader[0]) { + // Absolute path; e.g. /foo + $urlHost = parse_url($this->fileUrl, PHP_URL_HOST); + + // Replace path using hostname as an anchor. + $targetUrl = preg_replace('{^(.+(?://|@)'.preg_quote($urlHost).'(?::\d+)?)(?:[/\?].*)?$}', '\1'.$locationHeader, $this->fileUrl); + } else { + // Relative path; e.g. foo + // This actually differs from PHP which seems to add duplicate slashes. + $targetUrl = preg_replace('{^(.+/)[^/?]*(?:\?.*)?$}', '\1'.$locationHeader, $this->fileUrl); + } + } + + if (!empty($targetUrl)) { + $this->redirects++; + + if ($this->io->isDebug()) { + $this->io->writeError(sprintf('Following redirect (%u) %s', $this->redirects, $targetUrl)); + } + + $additionalOptions['redirects'] = $this->redirects; + + return $this->get($this->originUrl, $targetUrl, $additionalOptions, $this->fileName, $this->progress); + } + + if (!$this->retry) { + $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, got redirect without Location ('.$http_response_header[0].')'); + $e->setHeaders($http_response_header); + $e->setResponse($result); + + throw $e; + } + + return false; + } + /** * @param array $options * From e727f9f5feb3136e387ac6eeb22c92bd11f385bb Mon Sep 17 00:00:00 2001 From: Bilal Amarni Date: Fri, 22 Jan 2016 11:08:00 +0100 Subject: [PATCH 20/28] [Config command] allow to pass options when adding a repo --- doc/03-cli.md | 6 ++++++ src/Composer/Command/ConfigCommand.php | 15 ++++++++++++--- ...with-exampletld-repository-and-options.json | 15 +++++++++++++++ .../Test/Config/JsonConfigSourceTest.php | 18 ++++++++++++++++++ 4 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 tests/Composer/Test/Config/Fixtures/config/config-with-exampletld-repository-and-options.json diff --git a/doc/03-cli.md b/doc/03-cli.md index 8c855a286..cb47f7cc4 100644 --- a/doc/03-cli.md +++ b/doc/03-cli.md @@ -466,6 +466,12 @@ changes to the repositories section by using it the following way: php composer.phar config repositories.foo vcs https://github.com/foo/bar ``` +If your repository requires more configuration options, you can instead pass its JSON representation : + +```sh +php composer.phar config repositories.foo '{"type": "vcs", "url": "http://svn.example.org/my-project/", "trunk-path": "master"}' +``` + ## create-project You can use Composer to create new projects from an existing package. This is diff --git a/src/Composer/Command/ConfigCommand.php b/src/Composer/Command/ConfigCommand.php index 8378bc5b4..6faf5ae2d 100644 --- a/src/Composer/Command/ConfigCommand.php +++ b/src/Composer/Command/ConfigCommand.php @@ -434,9 +434,18 @@ EOT } if (1 === count($values)) { - $bool = strtolower($values[0]); - if (true === $booleanValidator($bool) && false === $booleanNormalizer($bool)) { - return $this->configSource->addRepository($matches[1], false); + $value = strtolower($values[0]); + if (true === $booleanValidator($value)) { + if (false === $booleanNormalizer($value)) { + return $this->configSource->addRepository($matches[1], false); + } + } else { + $value = json_decode($values[0], true); + if (JSON_ERROR_NONE !== json_last_error()) { + throw new \InvalidArgumentException(sprintf('%s is not valid JSON.', $values[0])); + } + + return $this->configSource->addRepository($matches[1], $value); } } diff --git a/tests/Composer/Test/Config/Fixtures/config/config-with-exampletld-repository-and-options.json b/tests/Composer/Test/Config/Fixtures/config/config-with-exampletld-repository-and-options.json new file mode 100644 index 000000000..c978851c6 --- /dev/null +++ b/tests/Composer/Test/Config/Fixtures/config/config-with-exampletld-repository-and-options.json @@ -0,0 +1,15 @@ +{ + "name": "my-vend/my-app", + "license": "MIT", + "repositories": { + "example_tld": { + "type": "composer", + "url": "https://example.tld", + "options": { + "ssl": { + "local_cert": "/home/composer/.ssl/composer.pem" + } + } + } + } +} diff --git a/tests/Composer/Test/Config/JsonConfigSourceTest.php b/tests/Composer/Test/Config/JsonConfigSourceTest.php index 529532263..819f12f2f 100644 --- a/tests/Composer/Test/Config/JsonConfigSourceTest.php +++ b/tests/Composer/Test/Config/JsonConfigSourceTest.php @@ -52,6 +52,24 @@ class JsonConfigSourceTest extends \PHPUnit_Framework_TestCase $this->assertFileEquals($this->fixturePath('config/config-with-exampletld-repository.json'), $config); } + public function testAddRepositoryWithOptions() + { + $config = $this->workingDir.'/composer.json'; + copy($this->fixturePath('composer-repositories.json'), $config); + $jsonConfigSource = new JsonConfigSource(new JsonFile($config)); + $jsonConfigSource->addRepository('example_tld', array( + 'type' => 'composer', + 'url' => 'https://example.tld', + 'options' => array( + 'ssl' => array( + 'local_cert' => '/home/composer/.ssl/composer.pem' + ) + ) + )); + + $this->assertFileEquals($this->fixturePath('config/config-with-exampletld-repository-and-options.json'), $config); + } + public function testRemoveRepository() { $config = $this->workingDir.'/composer.json'; From 78ffe0fd087e3e2941c7d85b71f294985a8007ad Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 25 Jan 2016 18:34:52 +0000 Subject: [PATCH 21/28] Avoid checking CA files several times --- src/Composer/Util/RemoteFilesystem.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 699a279fb..81f18fa19 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -842,6 +842,12 @@ class RemoteFilesystem */ private function validateCaFile($filename) { + static $files = array(); + + if (isset($files[$filename])) { + return $files[$filename]; + } + if ($this->io->isDebug()) { $this->io->writeError('Checking CA file '.realpath($filename)); } @@ -854,10 +860,10 @@ class RemoteFilesystem || (PHP_VERSION_ID >= 50400 && PHP_VERSION_ID < 50422) || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50506) ) { - return !empty($contents); + return $files[$filename] = !empty($contents); } - return (bool) openssl_x509_parse($contents); + return $files[$filename] = (bool) openssl_x509_parse($contents); } /** From bdb97e752713b4d492b7e0884e67fd51e81583df Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 25 Jan 2016 19:17:56 +0000 Subject: [PATCH 22/28] Reuse new TlsHelper for CA validation, refs #4798 --- src/Composer/Util/RemoteFilesystem.php | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 9fa54590e..b934bd145 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -383,6 +383,7 @@ class RemoteFilesystem } } + // Handle SSL cert match issues if (false === $result && false !== strpos($errorMessage, 'Peer certificate') && PHP_VERSION_ID < 50600) { // Certificate name error, PHP doesn't support subjectAltName on PHP < 5.6 // The procedure to handle sAN for older PHP's is: @@ -421,9 +422,11 @@ class RemoteFilesystem $result = $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); - $authHelper = new AuthHelper($this->io, $this->config); - $authHelper->storeAuth($this->originUrl, $this->storeAuth); - $this->storeAuth = false; + if (false !== $this->storeAuth) { + $authHelper = new AuthHelper($this->io, $this->config); + $authHelper->storeAuth($this->originUrl, $this->storeAuth); + $this->storeAuth = false; + } return $result; } @@ -734,7 +737,7 @@ class RemoteFilesystem 'DHE-DSS-AES256-SHA', 'DHE-RSA-AES256-SHA', 'AES128-GCM-SHA256', - 'AES256-GCM-SHA384', + 'AES256-GCM-SHA384', 'ECDHE-RSA-RC4-SHA', 'ECDHE-ECDSA-RC4-SHA', 'AES128', @@ -916,11 +919,12 @@ class RemoteFilesystem // assume the CA is valid if php is vulnerable to // https://www.sektioneins.de/advisories/advisory-012013-php-openssl_x509_parse-memory-corruption-vulnerability.html - if ( - PHP_VERSION_ID <= 50327 - || (PHP_VERSION_ID >= 50400 && PHP_VERSION_ID < 50422) - || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50506) - ) { + if (!TlsHelper::isOpensslParseSafe()) { + $this->io->writeError(sprintf( + 'Your version of PHP, %s, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.', + PHP_VERSION + )); + return $files[$filename] = !empty($contents); } From a9be7c83f13211f8edc2693e13c449e6efff5adb Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Sat, 16 Jan 2016 17:13:41 +0000 Subject: [PATCH 23/28] Add verification of signatures when running self-update --- src/Composer/Command/SelfUpdateCommand.php | 96 +++++++++++++++++++++- 1 file changed, 93 insertions(+), 3 deletions(-) diff --git a/src/Composer/Command/SelfUpdateCommand.php b/src/Composer/Command/SelfUpdateCommand.php index 581c45ab6..f227b22dc 100644 --- a/src/Composer/Command/SelfUpdateCommand.php +++ b/src/Composer/Command/SelfUpdateCommand.php @@ -14,7 +14,9 @@ namespace Composer\Command; use Composer\Composer; use Composer\Factory; +use Composer\Config; use Composer\Util\Filesystem; +use Composer\IO\IOInterface; use Composer\Util\RemoteFilesystem; use Composer\Downloader\FilesystemException; use Symfony\Component\Console\Input\InputInterface; @@ -44,6 +46,7 @@ class SelfUpdateCommand extends Command new InputOption('clean-backups', null, InputOption::VALUE_NONE, 'Delete old backups during an update. This makes the current version of composer the only backup available after the update'), new InputArgument('version', InputArgument::OPTIONAL, 'The version to update to'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), + new InputOption('update-keys', null, InputOption::VALUE_NONE, 'Prompt user for a key update'), )) ->setHelp(<<self-update command checks getcomposer.org for newer @@ -71,8 +74,13 @@ EOT $cacheDir = $config->get('cache-dir'); $rollbackDir = $config->get('data-dir'); + $home = $config->get('home'); $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0]; + if ($input->getOption('update-keys')) { + return $this->fetchKeys($io, $config); + } + // check if current dir is writable and if not try the cache dir from settings $tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir; @@ -112,15 +120,55 @@ EOT self::OLD_INSTALL_EXT ); - $io->writeError(sprintf("Updating to version %s.", $updateVersion)); - $remoteFilename = $baseUrl . (preg_match('{^[0-9a-f]{40}$}', $updateVersion) ? '/composer.phar' : "/download/{$updateVersion}/composer.phar"); + $updatingToTag = !preg_match('{^[0-9a-f]{40}$}', $updateVersion); + + $io->write(sprintf("Updating to version %s.", $updateVersion)); + $remoteFilename = $baseUrl . ($updatingToTag ? "/download/{$updateVersion}/composer.phar" : '/composer.phar'); + $signature = $remoteFilesystem->getContents(self::HOMEPAGE, $remoteFilename.'.sig', false); $remoteFilesystem->copy(self::HOMEPAGE, $remoteFilename, $tempFilename, !$input->getOption('no-progress')); - if (!file_exists($tempFilename)) { + if (!file_exists($tempFilename) || !$signature) { $io->writeError('The download of the new composer version failed for an unexpected reason'); return 1; } + // verify phar signature + if (!extension_loaded('openssl') && $config->get('disable-tls')) { + $io->writeError('Skipping phar signature verification as you have disabled OpenSSL via config.disable-tls'); + } else { + if (!extension_loaded('openssl')) { + throw new \RuntimeException('The openssl extension is required for phar signatures to be verified but it is not available. ' + . 'If you can not enable the openssl extension, you can disable this error, at your own risk, by setting the \'disable-tls\' option to true.'); + } + + $sigFile = 'file://'.$home.'/' . ($updatingToTag ? 'keys.tags.pub' : 'keys.dev.pub'); + if (!file_exists($sigFile)) { + $io->write('You are missing the public keys used to verify Composer phar file signatures'); + if (!$io->isInteractive() || getenv('CI') || getenv('CONTINUOUS_INTEGRATION')) { + $io->write('As this process is not interactive or you run on CI, it is allowed to run for now, but you should run "composer self-update --update-keys" to get them set up.'); + } else { + $this->fetchKeys($io, $config); + } + } + + // if still no file is present it means we are on CI/travis or + // not interactive so we skip the check for now + if (file_exists($sigFile)) { + $pubkeyid = openssl_pkey_get_public($sigFile); + $algo = defined('OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 : 'SHA384'; + if (!in_array('SHA384', openssl_get_md_methods())) { + throw new \RuntimeException('SHA384 is not supported by your openssl extension, could not verify the phar file integrity'); + } + $signature = json_decode($signature, true); + $signature = base64_decode($signature['sha384']); + $verified = 1 === openssl_verify(file_get_contents($tempFilename), $signature, $pubkeyid, $algo); + openssl_free_key($pubkeyid); + if (!$verified) { + throw new \RuntimeException('The phar signature did not match the file you downloaded, this means your public keys are outdated or that the phar file is corrupt/has been modified'); + } + } + } + // remove saved installations of composer if ($input->getOption('clean-backups')) { $finder = $this->getOldInstallationFinder($rollbackDir); @@ -147,6 +195,48 @@ EOT } } + protected function fetchKeys(IOInterface $io, Config $config) + { + if (!$io->isInteractive()) { + throw new \RuntimeException('Public keys are missing and can not be fetched in non-interactive mode, run this interactively or re-install composer using the installer to get the public keys set up'); + } + + $io->write('Open https://composer.github.io/pubkeys.html to find the latest keys'); + + $validator = function ($value) { + if (!preg_match('{^-----BEGIN PUBLIC KEY-----$}', trim($value))) { + throw new \UnexpectedValueException('Invalid input'); + } + return trim($value)."\n"; + }; + + $devKey = ''; + while (!preg_match('{(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)}s', $devKey, $match)) { + $devKey = $io->askAndValidate('Enter Dev / Snapshot Public Key (including lines with -----): ', $validator); + while ($line = $io->ask('')) { + $devKey .= trim($line)."\n"; + if (trim($line) === '-----END PUBLIC KEY-----') { + break; + } + } + } + file_put_contents($config->get('home').'/keys.dev.pub', $match[0]); + + $tagsKey = ''; + while (!preg_match('{(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)}s', $tagsKey, $match)) { + $tagsKey = $io->askAndValidate('Enter Tags Public Key (including lines with -----): ', $validator); + while ($line = $io->ask('')) { + $tagsKey .= trim($line)."\n"; + if (trim($line) === '-----END PUBLIC KEY-----') { + break; + } + } + } + file_put_contents($config->get('home').'/keys.tags.pub', $match[0]); + + $io->write('Public keys stored in '.$config->get('home')); + } + protected function rollback(OutputInterface $output, $rollbackDir, $localFilename) { $rollbackVersion = $this->getLastBackupVersion($rollbackDir); From 3ef22258e5f2674a4259b60e2eb0377ccd145d26 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Sun, 17 Jan 2016 14:49:58 +0000 Subject: [PATCH 24/28] Add key fingerprints for easier comparison and debugging via diagnose --- src/Composer/Command/DiagnoseCommand.php | 33 ++++++++++++++++++++++ src/Composer/Command/SelfUpdateCommand.php | 7 +++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/Composer/Command/DiagnoseCommand.php b/src/Composer/Command/DiagnoseCommand.php index faf537a10..b3ecb08bb 100644 --- a/src/Composer/Command/DiagnoseCommand.php +++ b/src/Composer/Command/DiagnoseCommand.php @@ -22,6 +22,7 @@ use Composer\Util\ConfigValidator; use Composer\Util\ProcessExecutor; use Composer\Util\RemoteFilesystem; use Composer\Util\StreamContextFactory; +use Composer\Util\Keys; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -133,6 +134,9 @@ EOT $io->write('Checking disk free space: ', false); $this->outputResult($this->checkDiskSpace($config)); + $io->write('Checking pubkeys: ', false); + $this->outputResult($this->checkPubKeys($config)); + $io->write('Checking composer version: ', false); $this->outputResult($this->checkVersion()); @@ -327,6 +331,35 @@ EOT return true; } + private function checkPubKeys($config) + { + $home = $config->get('home'); + $errors = []; + $io = $this->getIO(); + + if (file_exists($home.'/keys.tags.pub') && file_exists($home.'/keys.dev.pub')) { + $io->write(''); + } + + if (file_exists($home.'/keys.tags.pub')) { + $io->write('Tags Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.tags.pub')); + } else { + $errors[] = 'Missing pubkey for tags verification'; + } + + if (file_exists($home.'/keys.dev.pub')) { + $io->write('Dev Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.dev.pub')); + } else { + $errors[] = 'Missing pubkey for dev verification'; + } + + if ($errors) { + $errors[] = 'Run composer self-update --update-keys to set them up'; + } + + return $errors ?: true; + } + private function checkVersion() { $protocol = extension_loaded('openssl') ? 'https' : 'http'; diff --git a/src/Composer/Command/SelfUpdateCommand.php b/src/Composer/Command/SelfUpdateCommand.php index f227b22dc..3f456862c 100644 --- a/src/Composer/Command/SelfUpdateCommand.php +++ b/src/Composer/Command/SelfUpdateCommand.php @@ -16,6 +16,7 @@ use Composer\Composer; use Composer\Factory; use Composer\Config; use Composer\Util\Filesystem; +use Composer\Util\Keys; use Composer\IO\IOInterface; use Composer\Util\RemoteFilesystem; use Composer\Downloader\FilesystemException; @@ -220,7 +221,8 @@ EOT } } } - file_put_contents($config->get('home').'/keys.dev.pub', $match[0]); + file_put_contents($keyPath = $config->get('home').'/keys.dev.pub', $match[0]); + $io->write('Stored key with fingerprint: ' . Keys::fingerprint($keyPath)); $tagsKey = ''; while (!preg_match('{(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)}s', $tagsKey, $match)) { @@ -232,7 +234,8 @@ EOT } } } - file_put_contents($config->get('home').'/keys.tags.pub', $match[0]); + file_put_contents($keyPath = $config->get('home').'/keys.tags.pub', $match[0]); + $io->write('Stored key with fingerprint: ' . Keys::fingerprint($keyPath)); $io->write('Public keys stored in '.$config->get('home')); } From f4bcf7590b131332148de6df77ab452e47bb456e Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 18 Jan 2016 11:14:38 +0000 Subject: [PATCH 25/28] Fix array syntax --- src/Composer/Command/DiagnoseCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Composer/Command/DiagnoseCommand.php b/src/Composer/Command/DiagnoseCommand.php index b3ecb08bb..2306b138a 100644 --- a/src/Composer/Command/DiagnoseCommand.php +++ b/src/Composer/Command/DiagnoseCommand.php @@ -334,7 +334,7 @@ EOT private function checkPubKeys($config) { $home = $config->get('home'); - $errors = []; + $errors = array(); $io = $this->getIO(); if (file_exists($home.'/keys.tags.pub') && file_exists($home.'/keys.dev.pub')) { From 59975e3aaa1083c574ca934ee618ecd5bdbdfc96 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 18 Jan 2016 13:39:50 +0000 Subject: [PATCH 26/28] Add missing keys class --- src/Composer/Util/Keys.php | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/Composer/Util/Keys.php diff --git a/src/Composer/Util/Keys.php b/src/Composer/Util/Keys.php new file mode 100644 index 000000000..19628f5d3 --- /dev/null +++ b/src/Composer/Util/Keys.php @@ -0,0 +1,38 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Util; + +use Composer\Config; + +/** + * @author Jordi Boggiano + */ +class Keys +{ + public static function fingerprint($path) + { + $hash = strtoupper(hash('sha256', preg_replace('{\s}', '', file_get_contents($path)))); + + return implode(' ', [ + substr($hash, 0, 8), + substr($hash, 8, 8), + substr($hash, 16, 8), + substr($hash, 24, 8), + '', // Extra space + substr($hash, 32, 8), + substr($hash, 40, 8), + substr($hash, 48, 8), + substr($hash, 56, 8), + ]); + } +} From 5b41eaad3aecab692cbafc2b9cf720ed6bde74a0 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 25 Jan 2016 19:35:11 +0000 Subject: [PATCH 27/28] Bundle pubkeys and fail hard if validation can not happen --- src/Composer/Command/SelfUpdateCommand.php | 68 +++++++++++++++------- 1 file changed, 46 insertions(+), 22 deletions(-) diff --git a/src/Composer/Command/SelfUpdateCommand.php b/src/Composer/Command/SelfUpdateCommand.php index 3f456862c..7d868da06 100644 --- a/src/Composer/Command/SelfUpdateCommand.php +++ b/src/Composer/Command/SelfUpdateCommand.php @@ -144,29 +144,53 @@ EOT $sigFile = 'file://'.$home.'/' . ($updatingToTag ? 'keys.tags.pub' : 'keys.dev.pub'); if (!file_exists($sigFile)) { - $io->write('You are missing the public keys used to verify Composer phar file signatures'); - if (!$io->isInteractive() || getenv('CI') || getenv('CONTINUOUS_INTEGRATION')) { - $io->write('As this process is not interactive or you run on CI, it is allowed to run for now, but you should run "composer self-update --update-keys" to get them set up.'); - } else { - $this->fetchKeys($io, $config); - } + file_put_contents($home.'/keys.dev.pub', <<isInteractive()) { - throw new \RuntimeException('Public keys are missing and can not be fetched in non-interactive mode, run this interactively or re-install composer using the installer to get the public keys set up'); + throw new \RuntimeException('Public keys can not be fetched in non-interactive mode, please run Composer interactively'); } $io->write('Open https://composer.github.io/pubkeys.html to find the latest keys'); From e0ff9598c3a52468cf0dbbae386b883217552e31 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 25 Jan 2016 22:24:34 +0000 Subject: [PATCH 28/28] Tweak wording a bit, refs #3177 --- src/Composer/DependencyResolver/SolverProblemsException.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Composer/DependencyResolver/SolverProblemsException.php b/src/Composer/DependencyResolver/SolverProblemsException.php index 1dfc116f0..fcbb6a77b 100644 --- a/src/Composer/DependencyResolver/SolverProblemsException.php +++ b/src/Composer/DependencyResolver/SolverProblemsException.php @@ -72,7 +72,7 @@ class SolverProblemsException extends \RuntimeException return ''; } - $text = "\n Because of missing extensions, please verify whether they are enabled in those .ini files:\n - "; + $text = "\n To enable extensions, verify that they are enabled in those .ini files:\n - "; $text .= implode("\n - ", $paths); $text .= "\n You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.";