Forráskód Böngészése

Merge remote-tracking branch 'cs278/san-support'

Jordi Boggiano 9 éve
szülő
commit
1ea810d40b

+ 135 - 6
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;
@@ -264,6 +265,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 = TlsHelper::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);
@@ -370,6 +383,39 @@ 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.
+            if (TlsHelper::isOpensslParseSafe()) {
+                $certDetails = $this->getCertificateCnAndFp($this->fileUrl, $options);
+
+                if ($certDetails) {
+                    $this->peerCertificateMap[$this->getUrlAuthority($this->fileUrl)] = $certDetails;
+
+                    $this->retry = true;
+                }
+            } else {
+                $this->io->writeError(sprintf(
+                    '<error>Your version of PHP, %s, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.</error>',
+                    PHP_VERSION
+                ));
+            }
+        }
+
         if ($this->retry) {
             $this->retry = false;
 
@@ -531,12 +577,8 @@ 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 (!preg_match('{^https?://}', $this->fileUrl)) {
-                $host = $originUrl;
-            } else {
-                $host = parse_url($this->fileUrl, PHP_URL_HOST);
-            }
+        if ($this->disableTls === false && PHP_VERSION_ID < 50600 && !stream_is_local($this->fileUrl)) {
+            $host = parse_url($this->fileUrl, PHP_URL_HOST);
 
             if (PHP_VERSION_ID >= 50304) {
                 // Must manually follow when setting CN_match because this causes all
@@ -555,6 +597,24 @@ class RemoteFilesystem
 
             $tlsOptions['ssl']['CN_match'] = $host;
             $tlsOptions['ssl']['SNI_server_name'] = $host;
+
+            $urlAuthority = $this->getUrlAuthority($this->fileUrl);
+
+            if (isset($this->peerCertificateMap[$urlAuthority])) {
+                // Handle subjectAltName on lesser PHP's.
+                $certMap = $this->peerCertificateMap[$urlAuthority];
+
+                if ($this->io->isDebug()) {
+                    $this->io->writeError(sprintf(
+                        'Using <info>%s</info> as CN for subjectAltName enabled host <info>%s</info>',
+                        $certMap['cn'],
+                        $urlAuthority
+                    ));
+                }
+
+                $tlsOptions['ssl']['CN_match'] = $certMap['cn'];
+                $tlsOptions['ssl']['peer_fingerprint'] = $certMap['fp'];
+            }
         }
 
         $headers = array();
@@ -702,6 +762,7 @@ class RemoteFilesystem
                 'verify_peer' => true,
                 'verify_depth' => 7,
                 'SNI_enabled' => true,
+                'capture_peer_cert' => true,
             )
         );
 
@@ -883,4 +944,72 @@ 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,
+                'verify_peer' => false, // Yes this is fucking insane! But PHP is lame.
+            ))
+        ));
+
+        // 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'];
+
+            if (TlsHelper::checkCertificateHost($peerCertificate, parse_url($url, PHP_URL_HOST), $commonName)) {
+                return array(
+                    'cn' => $commonName,
+                    'fp' => TlsHelper::getCertificateFingerprint($peerCertificate),
+                );
+            }
+        }
+    }
+
+    private function getUrlAuthority($url)
+    {
+        $defaultPorts = array(
+            'ftp' => 21,
+            'http' => 80,
+            'https' => 443,
+        );
+
+        $scheme = parse_url($url, PHP_URL_SCHEME);
+
+        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;
+    }
 }

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 210 - 0
src/Composer/Util/TlsHelper.php


+ 76 - 0
tests/Composer/Test/Util/TlsHelperTest.php

@@ -0,0 +1,76 @@
+<?php
+
+/*
+ * This file is part of Composer.
+ *
+ * (c) Nils Adermann <naderman@naderman.de>
+ *     Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * 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']);
+    }
+}

Nem az összes módosított fájl került megjelenítésre, mert túl sok fájl változott