function get_raw_chain($host, $port = 443)
{
    global $timeout;
    $data = [];
    $stream = stream_context_create(array("ssl" => array("capture_peer_cert" => true, "capture_peer_cert_chain" => true, "verify_peer" => false, "peer_name" => $host, "verify_peer_name" => false, "allow_self_signed" => true, "capture_session_meta" => true, "sni_enabled" => true)));
    $read_stream = stream_socket_client("ssl://{$host}:{$port}", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $stream);
    if ($read_stream === false) {
        return false;
    } else {
        $context = stream_context_get_params($read_stream);
        $context_meta = stream_context_get_options($read_stream)['ssl']['session_meta'];
        $cert_data = openssl_x509_parse($context["options"]["ssl"]["peer_certificate"]);
        $chain_data = $context["options"]["ssl"]["peer_certificate_chain"];
        $chain_length = count($chain_data);
        if (isset($chain_data) && $chain_length < 10) {
            foreach ($chain_data as $key => $value) {
                $data["chain"][$key] = $value;
            }
        } else {
            $data["error"] = ["Chain too long."];
            return $data;
        }
    }
    return $data;
}
Esempio n. 2
0
 public function make_request()
 {
     $g = stream_context_create(array("ssl" => array("capture_peer_cert" => true)));
     set_error_handler(function () {
         return true;
     });
     $r = stream_socket_client("ssl://{$this->target}:{$this->target_port}", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $g);
     restore_error_handler();
     if (!$r) {
         return true;
     } else {
         $cont = stream_context_get_params($r);
         $cert = openssl_x509_read($cont["options"]["ssl"]["peer_certificate"]);
         $cert_data = openssl_x509_parse($cert);
         openssl_x509_export($cert, $out, FALSE);
         $signature_algorithm = null;
         if (preg_match('/^\\s+Signature Algorithm:\\s*(.*)\\s*$/m', $out, $match)) {
             $signature_algorithm = $match[1];
         }
         $this->sha_type = $signature_algorithm;
         $this->common_name = $cert_data['subject']['CN'];
         $this->alternative_names = $cert_data['extensions']['subjectAltName'];
         $this->issuer = $cert_data['issuer']['O'];
         $this->valid_from = date('m-d-Y H:i:s', strval($cert_data['validFrom_time_t']));
         $this->valid_to = date('m-d-Y H:i:s', strval($cert_data['validTo_time_t']));
         $this->parse_alternative_names();
     }
 }
Esempio n. 3
0
 function getParameters()
 {
     if (empty($this->Parameters)) {
         $this->Parameters->merge(stream_context_get_params($this->_resource));
     }
     return $this->Parameters;
 }
Esempio n. 4
0
 /**
  * Tests that create_context() does not set notification callback method if notification is empty.
  *
  * @covers Lunr\Network\StreamSocket::create_context
  */
 public function testCreateContextDoesNotSetNotificationCallbackIfNotificationIsNull()
 {
     $method = $this->get_accessible_reflection_method('create_context');
     $method->invoke($this->class);
     $params = stream_context_get_params($this->get_reflection_property_value('context'));
     $this->assertArrayNotHasKey('notification', $params);
 }
Esempio n. 5
0
 private function getCertifacateInformation($host)
 {
     $sslOptions = stream_context_create(array('ssl' => array('capture_peer_cert' => true)));
     $request = stream_socket_client('ssl://' . $host . ':443', $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $sslOptions);
     $content = stream_context_get_params($request);
     $certinfo = openssl_x509_parse($content['options']['ssl']['peer_certificate']);
     return $certinfo;
 }
 /**
  * @dataProvider dataGetContext
  */
 public function testGetContext($expectedOptions, $defaultOptions, $expectedParams, $defaultParams)
 {
     $context = StreamContextFactory::getContext($defaultOptions, $defaultParams);
     $options = stream_context_get_options($context);
     $params = stream_context_get_params($context);
     $this->assertEquals($expectedOptions, $options);
     $this->assertEquals($expectedParams, $params);
 }
Esempio n. 7
0
function check_json($host, $ip, $port)
{
    global $timeout;
    $data = [];
    $stream = stream_context_create(array("ssl" => array("capture_peer_cert" => true, "capture_peer_cert_chain" => true, "verify_peer" => false, "peer_name" => $host, "verify_peer_name" => false, "allow_self_signed" => true, "capture_session_meta" => true, "sni_enabled" => true)));
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        $connect_ip = "[" . $ip . "]";
    } else {
        $connect_ip = $ip;
    }
    $read_stream = stream_socket_client("ssl://{$connect_ip}:{$port}", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $stream);
    if ($read_stream === false) {
        $data["error"] = ["Failed to connect: " . htmlspecialchars($errstr)];
        return $data;
    } else {
        $context = stream_context_get_params($read_stream);
        $context_meta = stream_context_get_options($read_stream)['ssl']['session_meta'];
        $cert_data = openssl_x509_parse($context["options"]["ssl"]["peer_certificate"]);
        $chain_data = $context["options"]["ssl"]["peer_certificate_chain"];
        $chain_length = count($chain_data);
        if (isset($chain_data) && $chain_length < 10) {
            $chain_length = count($chain_data);
            $chain_arr_keys = $chain_data;
            foreach (array_keys($chain_arr_keys) as $key) {
                $curr = $chain_data[$key];
                $next = $chain_data[$key + 1];
                $prev = $chain_data[$key - 1];
                $chain_key = (string) $key + 1;
                if ($key == 0) {
                    $data["connection"] = ssl_conn_metadata_json($host, $ip, $port, $read_stream, $chain_data);
                    $data["chain"][$chain_key] = cert_parse_json($curr, $next, $host, $ip, true);
                } else {
                    $data["chain"][$chain_key] = cert_parse_json($curr, $next, null, false);
                }
                // certificate transparency
                $ct_urls = ["https://ct.ws.symantec.com", "https://ct.googleapis.com/pilot", "https://ct.googleapis.com/aviator", "https://ct.googleapis.com/rocketeer", "https://ct1.digicert-ct.com/log", "https://ct.izenpe.com", "https://ctlog.api.venafi.com", "https://log.certly.io"];
                $data["certificate_transparency"] = [];
                foreach ($ct_urls as $ct_url) {
                    $submitToCT = submitCertToCT($data["chain"], $ct_url);
                    $ct_result = json_decode($submitToCT, TRUE);
                    if ($ct_result === null && json_last_error() !== JSON_ERROR_NONE) {
                        $result_ct = array('result' => $submitToCT);
                        $data["certificate_transparency"][$ct_url] = $result_ct;
                    } else {
                        $data["certificate_transparency"][$ct_url] = $ct_result;
                    }
                }
            }
        } else {
            $data["error"] = ["Chain too long."];
            return $data;
        }
    }
    return $data;
}
Esempio n. 8
0
 /**
  * Initializes observr collections by aliasing
  * stream_context_set_option and stream_context_set_params
  */
 private function initialize()
 {
     $this->options->merge(\stream_context_get_options($this->context));
     $this->options->attach('set', function ($sender, $e) {
         \stream_context_set_option($this->context, $this->wrapper, $e->offset, $e->value);
     });
     $this->data->merge(\stream_context_get_params($this->context));
     $this->data->attach('set', function ($sender, $e) {
         \stream_context_set_params($this->context, $this->data->toArray());
     });
 }
 /**
  * verifies if URL has SSL valid
  * @param string $url
  * @see http://stackoverflow.com/a/27706327/2324004
  * @return bool
  */
 public function verifySslUrl($url)
 {
     $stream = stream_context_create(['ssl' => ['capture_peer_cert' => true], 'http' => ['timeout' => self::HTTP_READ_TIMEOUT]]);
     $read = @fopen($url, 'rb', false, $stream);
     if (!$read) {
         return false;
     }
     $cont = stream_context_get_params($read);
     $var = !empty($cont['options']['ssl']['peer_certificate']);
     return $var;
 }
Esempio n. 10
0
 public function access($code, $options = array())
 {
     $type = isset($options['grant_type']) ? $options['grant_type'] : 'authorization_code';
     $params = array('client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'redirect_uri' => isset($options['redirect_uri']) ? $options['redirect_uri'] : $this->redirect_uri);
     switch ($type) {
         case 'authorization_code':
             $params['code'] = $code;
             $params['grant_type'] = $type;
             break;
         case 'refresh_token':
             $params['refresh_token'] = $code;
             $params['response_type'] = 'refresh_token';
             $params['UserID'] = $options['uid'];
             break;
     }
     $response = null;
     $url = $this->url_access_token();
     switch ($this->method) {
         case 'GET':
             // Need to switch to Request library, but need to test it on one that works
             $url .= '?' . http_build_query($params);
             $response = file_get_contents($url);
             $return = json_decode($response, true);
             break;
         case 'POST':
             $postdata = http_build_query($params);
             $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata));
             $_default_opts = stream_context_get_params(stream_context_get_default());
             $context = stream_context_create(array_merge_recursive($_default_opts['options'], $opts));
             $response = file_get_contents($url, false, $context);
             $return = json_decode($response, true);
             break;
         default:
             throw new Exception('Method \'' . $this->method . '\' must be either GET or POST');
     }
     if (isset($return['Error'])) {
         throw new Exception($return['Error'], $return['ErrorCode']);
     }
     // Converts keys to the equivalent
     $return['access_token'] = $return['AccessToken'];
     $return['expires'] = $return['Expires'];
     $return['refresh_token'] = $return['RefreshToken'];
     $return['uid'] = $return['UserID'];
     // Unsets no longer used indexes
     unset($return['AccessToken'], $return['Expires'], $return['RefreshToken'], $return['UserID']);
     switch ($type) {
         case 'authorization_code':
             return Token::factory('access', $return);
             break;
         case 'refresh_token':
             return Token::factory('refresh', $return);
             break;
     }
 }
 protected function getCertificateExpirationDate($socket)
 {
     $timeout = min(10, $this->getPingFrequency());
     $context = stream_context_create(['ssl' => ['capture_peer_cert' => TRUE]]);
     if (false === ($read = @stream_socket_client($socket, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context))) {
         throw new \RuntimeException($errstr);
     }
     $certificate = stream_context_get_params($read);
     $infos = openssl_x509_parse($certificate['options']['ssl']['peer_certificate']);
     return new \DateTime('@' . $infos['validTo_time_t']);
 }
Esempio n. 12
0
 /**
  * @param $url String
  */
 public function init($url)
 {
     $parse = parse_url($url, PHP_URL_HOST);
     $get = stream_context_create(["ssl" => ["capture_peer_cert" => true]]);
     $read = stream_socket_client("ssl://" . $parse . ":443", $errno, $err, 30, STREAM_CLIENT_CONNECT, $get);
     $cert = stream_context_get_params($read);
     $this->certInfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
     if (!is_array($this->certInfo)) {
         throw new \InvalidArgumentException('cannot get ssl certificate information');
     }
 }
Esempio n. 13
0
 public function get_user_info(Access $token)
 {
     $opts = array('http' => array('method' => 'GET', 'header' => 'Authorization: OAuth ' . $token->access_token));
     $_default_opts = stream_context_get_params(stream_context_get_default());
     $opts = array_merge_recursive($_default_opts['options'], $opts);
     $context = stream_context_create($opts);
     $url = 'http://api-yaru.yandex.ru/me/?format=json';
     $user = json_decode(file_get_contents($url, false, $context));
     preg_match("/\\d+\$/", $user->id, $uid);
     return array('uid' => $uid[0], 'nickname' => isset($user->name) ? $user->name : null, 'name' => isset($user->name) ? $user->name : null, 'first_name' => isset($user->first_name) ? $user->first_name : null, 'last_name' => isset($user->last_name) ? $user->last_name : null, 'email' => isset($user->email) ? $user->email : null, 'location' => isset($user->hometown->name) ? $user->hometown->name : null, 'description' => isset($user->bio) ? $user->bio : null, 'image' => $user->links->userpic);
 }
Esempio n. 14
0
 /**
  * Preflight the SSL certificate presented by the backend. This isn't 100%
  * bulletproof, in that we're not actually validating the transport used to
  * communicate with Stripe, merely that the first attempt to does not use a
  * revoked certificate.
  *
  * Unfortunately the interface to OpenSSL doesn't make it easy to check the
  * certificate before sending potentially sensitive data on the wire. This
  * approach raises the bar for an attacker significantly.
  *
  * @param  string  $url
  *
  * @return bool
  */
 public function checkCert($url)
 {
     if (!$this->hasStreamExtensions()) {
         return $this->showStreamExtensionWarning();
     }
     $this->setUrl($url);
     list($result, $errorNo, $errorStr) = $this->streamSocketClient();
     $this->checkResult($result, $errorNo, $errorStr);
     openssl_x509_export(stream_context_get_params($result)['options']['ssl']['peer_certificate'], $pemCert);
     $this->checkBlackList($pemCert);
     return true;
 }
Esempio n. 15
0
function connectScan()
{
    $m = new MongoClient();
    $time = time();
    $out = "/var/log/httphunter.log";
    $file = fopen($out, 'a+') or die("Could not open log file for reading / writing\n");
    while (true) {
        $ip = long2ip(rand(0, "4294967295"));
        require_once "./sys/GeoIP/GeoIP.php";
        $curl = curl_init();
        curl_setopt_array($curl, array(CURLOPT_USERAGENT => md5(base64_encode(rand())), CURLOPT_HEADER => 1, CURLOPT_NOBODY => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 1.5, CURLOPT_URL => "http://{$ip}"));
        if (curl_exec($curl)) {
            $db = $m->httphunter;
            $collection = $db->results;
            $req_info = curl_getinfo($curl);
            $foundtime = time();
            $sslcheck = fsockopen("{$ip}", 443, $errno, $errstr, 3);
            if (!$sslcheck) {
                $results = array("ip" => $ip, "status" => $req_info['http_code'], "header" => curl_exec($curl), "request" => $req_info, "SSL" => "false", "SSL_DATA" => "false", "found" => $foundtime, "GeoIP" => array("country" => $geoip_country, "state" => $geoip_state, "Latitude" => $geoip_lat, "Longitude" => $geoip_lon));
            } else {
                $get_cert = stream_context_create(array("ssl" => array("capture_peer_cert" => true)));
                $connect_host = stream_socket_client("ssl://{$ip}:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get_cert);
                $ssl = stream_context_get_params($connect_host);
                $cert_info = json_encode(openssl_x509_parse($ssl["options"]["ssl"]["peer_certificate"]), true);
                $ssl_data = $cert_info;
                $results = array("ip" => $ip, "status" => $req_info['http_code'], "header" => curl_exec($curl), "request" => $req_info, "SSL" => true, "SSL_DATA" => $ssl_data, "found" => $foundtime, "GeoIP" => array("country" => $geoip_country, "state" => $geoip_state, "Latitude" => $geoip_lat, "Longitude" => $geoip_lon));
            }
            if ($req_info['http_code'] == 401) {
                $collection->insert($results);
                $output = "[" . date(DATE_RFC2822) . "] - {$ip} - 401 AUTH\n";
                flock($file, LOCK_SH);
                fwrite($file, $output);
                flock($file, LOCK_UN);
            } elseif ($req_info['http_code'] == 301) {
                $collection->insert($results);
                $output = "[" . date(DATE_RFC2822) . "] - {$ip} - 301 REDIRECT\n";
                flock($file, LOCK_SH);
                fwrite($file, $output);
                flock($file, LOCK_UN);
            } else {
                $collection->insert($results);
                $output = "[" . date(DATE_RFC2822) . "] - {$ip} - HTTP OK\n";
                flock($file, LOCK_SH);
                fwrite($file, $output);
                flock($file, LOCK_UN);
            }
            fclose($sslcheck);
        }
    }
}
Esempio n. 16
0
 public function get_user_info(OAuth2_Token_Access $token)
 {
     $url = 'https://api.renren.com/restserver.do';
     $params = array('access_token' => $token->access_token, 'format' => 'JSON', 'v' => '1.0', 'call_id' => time(), 'method' => 'users.getInfo');
     $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($params)));
     $_default_opts = stream_context_get_params(stream_context_get_default());
     $context = stream_context_create(array_merge_recursive($_default_opts['options'], $opts));
     $user = json_decode(file_get_contents($url, false, $context));
     if (!is_array($user) or !isset($user[0]) or !($user = $user[0]) or array_key_exists("error_code", $user)) {
         throw new OAuth2_Exception((array) $user);
     }
     // Create a response from the request
     return array('via' => 'renren', 'uid' => $user->uid, 'screen_name' => $user->name, 'name' => '', 'location' => '', 'description' => '', 'image' => $user->tinyurl, 'access_token' => $token->access_token, 'expire_at' => $token->expires, 'refresh_token' => $token->refresh_token);
 }
 /**
  * Loads SSL certificate for a given url
  *
  * @param   string  $url
  * @return  resource $certificateResource
  * @throws  Exception if loading fails
  */
 public function loadFromUrl($url)
 {
     $context = stream_context_create(array("ssl" => array("capture_peer_cert" => true)));
     $sslUrl = str_replace('https://', '', $url);
     $sslUrl = 'ssl://' . $sslUrl;
     $timeoutSeconds = 30;
     $streamResource = @stream_socket_client($sslUrl, $errorNr, $errorMessage, $timeoutSeconds, STREAM_CLIENT_CONNECT, $context);
     if (!is_resource($streamResource)) {
         throw new Exception('Failed loading SSL certificate: "' . $errorMessage . '"');
     }
     $contextParams = stream_context_get_params($streamResource);
     $certificateResource = $contextParams["options"]["ssl"]["peer_certificate"];
     return $certificateResource;
 }
Esempio n. 18
0
function sock_open(&$sock, $host, $port)
{
    global $TOTAL_SOCKETS;
    $TOTAL_SOCKETS++;
    $sock->error = "";
    $sock->errno = 0;
    if (substr($host, 0, 7) != 'unix://') {
        $host = "tcp://{$host}:{$port}";
    }
    $sock->socket = @stream_socket_client($host, $sock->errno, $sock->error, 1, STREAM_CLIENT_CONNECT);
    if ($sock->socket !== false) {
        stream_set_timeout($sock->socket, $sock->timeout);
        if ($sock->ssl_enabled) {
            if ($sock->ssl_ca !== false) {
                stream_context_set_option($sock->socket, 'ssl', 'verify_peer', true);
                stream_context_set_option($sock->socket, 'ssl', 'cafile', $sock->ssl_ca);
            }
            if ($sock->ssl_cn !== false) {
                // only PHP 5.6 provides common name validation, so lets do this by ourselves
                stream_context_set_option($sock->socket, 'ssl', 'capture_peer_cert', true);
            }
            if (stream_socket_enable_crypto($sock->socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT)) {
                if ($sock->ssl_cn !== false) {
                    $parameters = stream_context_get_params($sock->socket);
                    $certificate = openssl_x509_parse($parameters["options"]["ssl"]["peer_certificate"]);
                    $common_name = $certificate["subject"]["CN"];
                    if (fnmatch($common_name, $sock->ssl_cn, FNM_CASEFOLD) || fnmatch($sock->ssl_cn, $common_name, FNM_CASEFOLD)) {
                        return true;
                    } else {
                        sock_close($sock);
                        $sock->error = "SSL handshake error";
                        $sock->errno = 0;
                        return false;
                    }
                }
                return true;
            } else {
                sock_close($sock);
                $sock->error = "SSL handshake error";
                $sock->errno = 0;
                return false;
            }
        } else {
            return true;
        }
    } else {
        return false;
    }
}
Esempio n. 19
0
 /**
  * @param $url
  * @return Certificate
  * @throws Exception
  */
 public function readFromUrl($url)
 {
     $urlHost = parse_url($url, PHP_URL_HOST);
     if ($urlHost === null) {
         $urlHost = $url;
     }
     $streamContext = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE, "verify_peer" => FALSE, "verify_peer_name" => FALSE)));
     $stream = @stream_socket_client("ssl://" . $urlHost . ":443", $errorNumber, $errorString, self::CONNECTION_TIMEOUT, STREAM_CLIENT_CONNECT, $streamContext);
     if ($stream) {
         $streamParams = stream_context_get_params($stream);
         $certResource = $streamParams['options']['ssl']['peer_certificate'];
         return new Certificate($this->certResourceToString($certResource));
     } else {
         throw new Exception(sprintf("Unable to connect to %s", $urlHost), Exception::CONNECTION_PROBLEM);
     }
 }
Esempio n. 20
0
/**
 * Mock the global function for this test.
 *
 * @param $filename
 * @param null $flags
 * @param null $context
 * @param null $offset
 * @param null $maxlen
 *
 * @return string mocked response
 */
function file_get_contents($filename, $flags = null, $context = null, $offset = null, $maxlen = null)
{
    $context = \stream_context_get_params($context);
    $header_str = $context['options']['http']['header'];
    preg_match('/user_key:\\s*(.+)\\s*\\r\\n/', $header_str, $out);
    // we borrow the user_key field for testing
    $test_file = $out[1];
    // prepare mocked response content
    $response_data = \file_get_contents(ApiTest::$responseDir . $test_file . '.json');
    $response_data = json_encode(json_decode($response_data, true));
    // necessary to get a valid json string
    if (strlen($response_data) > 200) {
        // test gzip encoding for longer response
        $response_data = gzencode($response_data);
    }
    return $response_data;
}
Esempio n. 21
0
 public static function downloadCertificateFromUrl(string $url, int $timeout = 30) : array
 {
     $hostName = (new Url($url))->getHostName();
     $streamContext = stream_context_create(['ssl' => ['capture_peer_cert' => true]]);
     try {
         $client = stream_socket_client("ssl://{$hostName}:443", $errorNumber, $errorDescription, $timeout, STREAM_CLIENT_CONNECT, $streamContext);
     } catch (Throwable $thrown) {
         if (str_contains($thrown->getMessage(), 'getaddrinfo failed')) {
             throw CouldNotDownloadCertificate::hostDoesNotExist($hostName);
         }
         if (str_contains($thrown->getMessage(), 'error:14090086')) {
             throw CouldNotDownloadCertificate::noCertificateInstalled($hostName);
         }
         throw CouldNotDownloadCertificate::unknownError($hostName, $thrown->getMessage());
     }
     $response = stream_context_get_params($client);
     return openssl_x509_parse($response['options']['ssl']['peer_certificate']);
 }
Esempio n. 22
0
function check_json($host, $ip, $port)
{
    global $timeout;
    $data = [];
    $stream = stream_context_create(array("ssl" => array("capture_peer_cert" => true, "capture_peer_cert_chain" => true, "verify_peer" => false, "peer_name" => $host, "verify_peer_name" => false, "allow_self_signed" => true, "capture_session_meta" => true, "sni_enabled" => true)));
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        $connect_ip = "[" . $ip . "]";
    } else {
        $connect_ip = $ip;
    }
    $read_stream = stream_socket_client("ssl://{$connect_ip}:{$port}", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $stream);
    if ($read_stream === false) {
        $data["error"] = ["Failed to connect: " . htmlspecialchars($errstr)];
        return $data;
    } else {
        $context = stream_context_get_params($read_stream);
        $context_meta = stream_context_get_options($read_stream)['ssl']['session_meta'];
        $cert_data = openssl_x509_parse($context["options"]["ssl"]["peer_certificate"]);
        $chain_data = $context["options"]["ssl"]["peer_certificate_chain"];
        $chain_length = count($chain_data);
        if (isset($chain_data) && $chain_length < 10) {
            $chain_length = count($chain_data);
            $chain_arr_keys = $chain_data;
            foreach (array_keys($chain_arr_keys) as $key) {
                $curr = $chain_data[$key];
                $next = $chain_data[$key + 1];
                $prev = $chain_data[$key - 1];
                $chain_key = (string) $key + 1;
                if ($key == 0) {
                    $data["connection"] = ssl_conn_metadata_json($host, $ip, $port, $read_stream, $chain_data);
                    $data["chain"][$chain_key] = cert_parse_json($curr, $next, $host, $ip, true);
                } else {
                    $data["chain"][$chain_key] = cert_parse_json($curr, $next, null, false);
                }
            }
        } else {
            $data["error"] = ["Chain too long."];
            return $data;
        }
    }
    return $data;
}
Esempio n. 23
0
 public static function getCertFromServer($host, $port = 443)
 {
     $options = array();
     $options['ssl']['capture_peer_cert_chain'] = true;
     $options['ssl']['capture_peer_cert'] = true;
     $context = stream_context_create($options);
     $timeout = defined('CERTAIN_TIMEOUT') && is_numeric(CERTAIN_TIMEOUT) ? CERTAIN_TIMEOUT : 30;
     $uri = 'ssl://' . $host . ':' . $port;
     $stream = @stream_socket_client($uri, $errorNumber, $errorString, $timeout, STREAM_CLIENT_CONNECT, $context);
     if ($stream == false) {
         throw new \RuntimeException('Error getting chain from server: ' . $errorNumber . ' ' . $errorString);
     }
     $params = stream_context_get_params($stream);
     $sslParms = $params['options']['ssl'];
     if (!isset($sslParms['peer_certificate_chain']) || count($sslParms['peer_certificate_chain']) < 1) {
         $chain = array($params['options']['ssl']['peer_certificate']);
     } else {
         $chain = $params['options']['ssl']['peer_certificate_chain'];
     }
     $cert = static::getCertFromChain($chain);
     $cert->setHost($host);
     return $cert;
 }
Esempio n. 24
0
 /**
  * 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))));
     // 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));
         }
     }
 }
 /**
  * Preflight the SSL certificate presented by the backend. This isn't 100%
  * bulletproof, in that we're not actually validating the transport used to
  * communicate with Divido, merely that the first attempt to does not use a
  * revoked certificate.
  *
  * Unfortunately the interface to OpenSSL doesn't make it easy to check the
  * certificate before sending potentially sensitive data on the wire. This
  * approach raises the bar for an attacker significantly.
  */
 private function checkSslCert($url)
 {
     return true;
     if (version_compare(PHP_VERSION, '5.3.0', '<')) {
         error_log('Warning: This version of PHP is too old to check SSL certificates ' . 'correctly. Divido cannot guarantee that the server has a ' . 'certificate which is not blacklisted');
         return true;
     }
     if (strpos(PHP_VERSION, 'hiphop') !== false) {
         error_log('Warning: HHVM does not support Divido\'s SSL certificate ' . 'verification. (See http://docs.hhvm.com/manual/en/context.ssl.php) ' . 'Divido cannot guarantee that the server has a certificate which is ' . 'not blacklisted');
         return true;
     }
     $url = parse_url($url);
     $port = isset($url["port"]) ? $url["port"] : 443;
     $url = "ssl://{$url["host"]}:{$port}";
     $sslContext = stream_context_create(array('ssl' => array('capture_peer_cert' => true, 'verify_peer' => true, 'cafile' => $this->caBundle())));
     $result = stream_socket_client($url, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $sslContext);
     if ($errno !== 0) {
         $apiBase = Divido::$apiBase;
         throw new Divido_ApiConnectionError('Could not connect to Divido (' . $apiBase . ').  Please check your ' . 'internet connection and try again.  If this problem persists, ' . 'you should check Divido\'s service status at ' . 'https://twitter.com/dividostatus. Reason was: ' . $errstr);
     }
     $params = stream_context_get_params($result);
     $cert = $params['options']['ssl']['peer_certificate'];
     openssl_x509_export($cert, $pemCert);
     if (self::isBlackListed($pemCert)) {
         throw new Divido_ApiConnectionError('Invalid server certificate. You tried to connect to a server that ' . 'has a revoked SSL certificate, which means we cannot securely send ' . 'data to that server.  Please email support@divido.com if you need ' . 'help connecting to the correct API server.');
     }
     return true;
 }
Esempio n. 26
0
 /**
  * Path Parser
  *
  * Extract a path from a URI and actually connect to an SSH server if appropriate
  *
  * If "notification" is set as a context parameter the message code for successful login is
  * NET_SSH2_MSG_USERAUTH_SUCCESS. For a failed login it's NET_SSH2_MSG_USERAUTH_FAILURE.
  *
  * @param String $path
  * @return String
  * @access private
  */
 function _parse_path($path)
 {
     extract(parse_url($path) + array('port' => 22));
     if (!isset($host)) {
         return false;
     }
     if (isset($this->context)) {
         $context = stream_context_get_params($this->context);
         if (isset($context['notification'])) {
             $this->notification = $context['notification'];
         }
     }
     if ($host[0] == '$') {
         $host = substr($host, 1);
         global ${$host};
         if (!is_object(${$host}) || get_class(${$host}) != 'Net_SFTP') {
             return false;
         }
         $this->sftp = ${$host};
     } else {
         if (isset($this->context)) {
             $context = stream_context_get_options($this->context);
         }
         if (isset($context[$scheme]['session'])) {
             $sftp = $context[$scheme]['session'];
         }
         if (isset($context[$scheme]['sftp'])) {
             $sftp = $context[$scheme]['sftp'];
         }
         if (isset($sftp) && is_object($sftp) && get_class($sftp) == 'Net_SFTP') {
             $this->sftp = $sftp;
             return $path;
         }
         if (isset($context[$scheme]['username'])) {
             $user = $context[$scheme]['username'];
         }
         if (isset($context[$scheme]['password'])) {
             $pass = $context[$scheme]['password'];
         }
         if (isset($context[$scheme]['privkey']) && is_object($context[$scheme]['privkey']) && get_Class($context[$scheme]['privkey']) == 'Crypt_RSA') {
             $pass = $context[$scheme]['privkey'];
         }
         if (!isset($user) || !isset($pass)) {
             return false;
         }
         // casting $pass to a string is necessary in the event that it's a Crypt_RSA object
         if (isset(self::$instances[$host][$port][$user][(string) $pass])) {
             $this->sftp = self::$instances[$host][$port][$user][(string) $pass];
         } else {
             $this->sftp = new Net_SFTP($host, $port);
             $this->sftp->disableStatCache();
             if (isset($this->notification) && is_callable($this->notification)) {
                 /* if !is_callable($this->notification) we could do this:
                 
                                        user_error('fopen(): failed to call user notifier', E_USER_WARNING);
                 
                                        the ftp wrapper gives errors like that when the notifier isn't callable.
                                        i've opted not to do that, however, since the ftp wrapper gives the line
                                        on which the fopen occurred as the line number - not the line that the
                                        user_error is on.
                                     */
                 call_user_func($this->notification, STREAM_NOTIFY_CONNECT, STREAM_NOTIFY_SEVERITY_INFO, '', 0, 0, 0);
                 call_user_func($this->notification, STREAM_NOTIFY_AUTH_REQUIRED, STREAM_NOTIFY_SEVERITY_INFO, '', 0, 0, 0);
                 if (!$this->sftp->login($user, $pass)) {
                     call_user_func($this->notification, STREAM_NOTIFY_AUTH_RESULT, STREAM_NOTIFY_SEVERITY_ERR, 'Login Failure', NET_SSH2_MSG_USERAUTH_FAILURE, 0, 0);
                     return false;
                 }
                 call_user_func($this->notification, STREAM_NOTIFY_AUTH_RESULT, STREAM_NOTIFY_SEVERITY_INFO, 'Login Success', NET_SSH2_MSG_USERAUTH_SUCCESS, 0, 0);
             } else {
                 if (!$this->sftp->login($user, $pass)) {
                     return false;
                 }
             }
             self::$instances[$host][$port][$user][(string) $pass] = $this->sftp;
         }
     }
     return $path;
 }
Esempio n. 27
0
 /**
  * Path Parser
  *
  * Extract a path from a URI and actually connect to an SSH server if appropriate
  *
  * If "notification" is set as a context parameter the message code for successful login is
  * NET_SSH2_MSG_USERAUTH_SUCCESS. For a failed login it's NET_SSH2_MSG_USERAUTH_FAILURE.
  *
  * @param string $path
  * @return string
  * @access private
  */
 function _parse_path($path)
 {
     $orig = $path;
     extract(parse_url($path) + array('port' => 22));
     if (isset($query)) {
         $path .= '?' . $query;
     } elseif (preg_match('/(\\?|\\?#)$/', $orig)) {
         $path .= '?';
     }
     if (isset($fragment)) {
         $path .= '#' . $fragment;
     } elseif ($orig[strlen($orig) - 1] == '#') {
         $path .= '#';
     }
     if (!isset($host)) {
         return false;
     }
     if (isset($this->context)) {
         $context = stream_context_get_params($this->context);
         if (isset($context['notification'])) {
             $this->notification = $context['notification'];
         }
     }
     if (preg_match('/^{[a-z0-9]+}$/i', $host)) {
         $host = SSH2::getConnectionByResourceId($host);
         if ($host === false) {
             return false;
         }
         $this->sftp = $host;
     } else {
         if (isset($this->context)) {
             $context = stream_context_get_options($this->context);
         }
         if (isset($context[$scheme]['session'])) {
             $sftp = $context[$scheme]['session'];
         }
         if (isset($context[$scheme]['sftp'])) {
             $sftp = $context[$scheme]['sftp'];
         }
         if (isset($sftp) && $sftp instanceof SFTP) {
             $this->sftp = $sftp;
             return $path;
         }
         if (isset($context[$scheme]['username'])) {
             $user = $context[$scheme]['username'];
         }
         if (isset($context[$scheme]['password'])) {
             $pass = $context[$scheme]['password'];
         }
         if (isset($context[$scheme]['privkey']) && $context[$scheme]['privkey'] instanceof RSA) {
             $pass = $context[$scheme]['privkey'];
         }
         if (!isset($user) || !isset($pass)) {
             return false;
         }
         // casting $pass to a string is necessary in the event that it's a \phpseclib\Crypt\RSA object
         if (isset(self::$instances[$host][$port][$user][(string) $pass])) {
             $this->sftp = self::$instances[$host][$port][$user][(string) $pass];
         } else {
             $this->sftp = new SFTP($host, $port);
             $this->sftp->disableStatCache();
             if (isset($this->notification) && is_callable($this->notification)) {
                 /* if !is_callable($this->notification) we could do this:
                 
                                        user_error('fopen(): failed to call user notifier', E_USER_WARNING);
                 
                                        the ftp wrapper gives errors like that when the notifier isn't callable.
                                        i've opted not to do that, however, since the ftp wrapper gives the line
                                        on which the fopen occurred as the line number - not the line that the
                                        user_error is on.
                                     */
                 call_user_func($this->notification, STREAM_NOTIFY_CONNECT, STREAM_NOTIFY_SEVERITY_INFO, '', 0, 0, 0);
                 call_user_func($this->notification, STREAM_NOTIFY_AUTH_REQUIRED, STREAM_NOTIFY_SEVERITY_INFO, '', 0, 0, 0);
                 if (!$this->sftp->login($user, $pass)) {
                     call_user_func($this->notification, STREAM_NOTIFY_AUTH_RESULT, STREAM_NOTIFY_SEVERITY_ERR, 'Login Failure', NET_SSH2_MSG_USERAUTH_FAILURE, 0, 0);
                     return false;
                 }
                 call_user_func($this->notification, STREAM_NOTIFY_AUTH_RESULT, STREAM_NOTIFY_SEVERITY_INFO, 'Login Success', NET_SSH2_MSG_USERAUTH_SUCCESS, 0, 0);
             } else {
                 if (!$this->sftp->login($user, $pass)) {
                     return false;
                 }
             }
             self::$instances[$host][$port][$user][(string) $pass] = $this->sftp;
         }
     }
     return $path;
 }
Esempio n. 28
0
 public function access($code, $options = array())
 {
     $params = array('client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'grant_type' => isset($options['grant_type']) ? $options['grant_type'] : 'authorization_code');
     $params = array_merge($params, $this->params);
     switch ($params['grant_type']) {
         case 'authorization_code':
             $params['code'] = $code;
             $params['redirect_uri'] = isset($options['redirect_uri']) ? $options['redirect_uri'] : $this->redirect_uri;
             break;
         case 'refresh_token':
             $params['refresh_token'] = $code;
             break;
     }
     $response = null;
     $url = $this->accessTokenUrl();
     switch ($this->method) {
         case 'GET':
             // Need to switch to Request library, but need to test it on one that works
             $url .= '?' . http_build_query($params);
             $response = file_get_contents($url);
             parse_str($response, $return);
             break;
         case 'POST':
             $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($params)));
             $_default_opts = stream_context_get_params(stream_context_get_default());
             $context = stream_context_create(array_merge_recursive($_default_opts['options'], $opts));
             $response = file_get_contents($url, false, $context);
             $return = json_decode($response, true);
             break;
         default:
             throw new \OutOfBoundsException("Method '{$this->method}' must be either GET or POST");
     }
     if (!empty($return['error'])) {
         throw new Exception($return);
     }
     switch ($params['grant_type']) {
         case 'authorization_code':
             return new Access($return);
             break;
         case 'refresh_token':
             return new Refresh($return);
             break;
     }
 }
Esempio n. 29
0
 /**
  * @return array|bool
  */
 public function StreamContextParams()
 {
     return \is_resource($this->rConnect) && \MailSo\Base\Utils::FunctionExistsAndEnabled('stream_context_get_options') ? \stream_context_get_params($this->rConnect) : false;
 }
 protected function downloadCertificate($urlParts)
 {
     $streamContext = stream_context_create(["ssl" => ["capture_peer_cert" => TRUE]]);
     $streamClient = stream_socket_client("ssl://{$urlParts['host']}:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $streamContext);
     $certificateContext = stream_context_get_params($streamClient);
     return openssl_x509_parse($certificateContext['options']['ssl']['peer_certificate']);
 }