Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created November 17, 2012 20:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/4099807 to your computer and use it in GitHub Desktop.
Save xeoncross/4099807 to your computer and use it in GitHub Desktop.
Verify that an SSL certificate belongs to the server we are connecting too
<?php
//
// You need a CA cert bundle!
//
// Good
$host = 'www.google.com';
//$host = 'onlinessl.netlock.hu';
// Bad
//$host = 'google.com';
//$host = 'tv.eurosport.com';
$context = stream_context_create(array(
"ssl" => array("capture_peer_cert" => true)
));
$r = stream_socket_client("tcp://$host:443", $errno, $errstr, 20, STREAM_CLIENT_CONNECT, $context);
if( ! $r)
{
die("$host - $errstr ($errno)\n");
}
stream_context_set_option($r, 'ssl', 'verify_host', true);
stream_context_set_option($r, 'ssl', 'verify_peer', true);
stream_context_set_option($r, 'ssl', 'allow_self_signed', false);
stream_context_set_option($r, 'ssl', 'CN_match', $host);
stream_context_set_option($r, 'ssl', 'cafile', __DIR__ . '/cacert.pem');
$secure = stream_socket_enable_crypto($r, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
if( ! $secure)
{
die("failed to connect securely\n");
}
$meta = stream_context_get_params($r);
print_r($meta);
if(empty($meta["options"]["ssl"]))
{
die("Problem with cert\n");
}
$cert = openssl_x509_parse($meta["options"]["ssl"]["peer_certificate"]);
print_r($cert);
/*
if(isset($cert['subject']['CN']) AND $cert['subject']['CN'] == $host)
{
print "Valid cert for $host\n";
}
else
{
print "Invalid cert for $host\n";
}
*/
fclose($r);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment