使用PHP中的Openssl验证SSL证书

时间:2013-11-26 03:31:03

标签: php ssl openssl certificate

我正在处理下面的事情:

Generate CSR(Certificate Signing Request)
Upload SSL Certificates

要生成SSL证书,我使用的是:

        $privkey = openssl_pkey_new();
        $csr = openssl_csr_new($dn, $privkey);
        $sscert = openssl_csr_sign($csr, null, $privkey, $days);
        openssl_csr_export($csr, $csrout);
        openssl_pkey_export($privkey, $pkeyout, $_POST['password']);
        openssl_pkey_export_to_file($privkey, "<path/to/store/server.key>");
        openssl_csr_export_to_file($csr, "/tmp/".<domain-name>.".csr");

现在使用该CSR请求,我可以生成(domain-name.cer),(DigitalCert.cer)。

现在,一旦我上传了这个(.cer)证书,我就需要验证这些证书。

原因:某人在“a.com”上生成了这些证书,并尝试在“b.com”上传。这不应该发生,所以我想验证上传的SSL证书。

在PHP中,我们有

$ ok = openssl_verify($ data,$ signature,$ pubkeyid);

但我无法根据上述证书生成过程得到什么东西被视为$ data,$ signature和$ pubkeyid。

5 个答案:

答案 0 :(得分:2)

检查一下: Verify SMTP in PHP

<?php
$server   = "smtp.gmail.com";        // Who I connect to
$myself   = "my_server.example.com"; // Who I am
$cabundle = '/etc/ssl/cacert.pem';   // Where my root certificates are

// Verify server. There's not much we can do, if we suppose that an attacker
// has taken control of the DNS. The most we can hope for is that there will
// be discrepancies between the expected responses to the following code and
// the answers from the subverted DNS server.

// To detect these discrepancies though, implies we knew the proper response
// and saved it in the code. At that point we might as well save the IP, and
// decouple from the DNS altogether.

$match1   = false;
$addrs    = gethostbynamel($server);
foreach($addrs as $addr)
{
    $name = gethostbyaddr($addr);
    if ($name == $server)
    {
        $match1 = true;
        break;
    }
}
// Here we must decide what to do if $match1 is false.
// Which may happen often and for legitimate reasons.
print "Test 1: " . ($match1 ? "PASSED" : "FAILED") . "\n";

$match2   = false;
$domain   = explode('.', $server);
array_shift($domain);
$domain = implode('.', $domain);
getmxrr($domain, $mxhosts);
foreach($mxhosts as $mxhost)
{
    $tests = gethostbynamel($mxhost);
    if (0 != count(array_intersect($addrs, $tests)))
    {
        // One of the instances of $server is a MX for its domain
        $match2 = true;
        break;
    }
}
// Again here we must decide what to do if $match2 is false.
// Most small ISP pass test 2; very large ISPs and Google fail.
print "Test 2: " . ($match2 ? "PASSED" : "FAILED") . "\n";
// On the other hand, if you have a PASS on a server you use,
// it's unlikely to become a FAIL anytime soon.

// End of maybe-they-help-maybe-they-don't checks.

// Establish the connection
$smtp = fsockopen( "tcp://$server", 25, $errno, $errstr );
fread( $smtp, 512 );

// Here you can check the usual banner from $server (or in general,
// check whether it contains $server's domain name, or whether the
// domain it advertises has $server among its MX's.
// But yet again, Google fails both these tests.

fwrite($smtp,"HELO $myself\r\n");
fread($smtp, 512);

// Switch to TLS
fwrite($smtp,"STARTTLS\r\n");
fread($smtp, 512);
stream_set_blocking($smtp, true);
stream_context_set_option($smtp, 'ssl', 'verify_peer', true);
stream_context_set_option($smtp, 'ssl', 'allow_self_signed', false);
stream_context_set_option($smtp, 'ssl', 'capture_peer_cert', true);
stream_context_set_option($smtp, 'ssl', 'cafile', $cabundle);
$secure = stream_socket_enable_crypto($smtp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
stream_set_blocking($smtp, false);
$opts = stream_context_get_options($smtp);
if (!isset($opts["ssl"]["peer_certificate"]))
    $secure = false;
else
{
    $cert = openssl_x509_parse($opts["ssl"]["peer_certificate"]);
    $names = '';
    if ('' != $cert)
    {
        if (isset($cert['extensions']))
            $names = $cert['extensions']['subjectAltName'];
        elseif (isset($cert['subject']))
        {
            if (isset($cert['subject']['CN']))
                $names = 'DNS:' . $cert['subject']['CN'];
            else
                $secure = false; // No exts, subject without CN
        }
        else
            $secure = false; // No exts, no subject
    }
    $checks = explode(',', $names);

    // At least one $check must match $server
    $tmp    = explode('.', $server);
    $fles   = array_reverse($tmp);
    $okay   = false;
    foreach($checks as $check)
    {
        $tmp = explode(':', $check);
        if ('DNS' != $tmp[0])    continue;  // candidates must start with DNS:
        if (!isset($tmp[1]))     continue;  // and have something afterwards
        $tmp  = explode('.', $tmp[1]);
        if (count($tmp) < 3)     continue;  // "*.com" is not a valid match
        $cand = array_reverse($tmp);
        $okay = true;
        foreach($cand as $i => $item)
        {
            if (!isset($fles[$i]))
            {
                // We connected to www.example.com and certificate is for *.www.example.com -- bad.
                $okay = false;
                break;
            }
            if ($fles[$i] == $item)
                continue;
            if ($item == '*')
                break;
        }
        if ($okay)
            break;
    }
    if (!$okay)
        $secure = false; // No hosts matched our server.
}

if (!$secure)
        die("failed to connect securely\n");
print "Success!\n";
// Continue with connection...
?>

答案 1 :(得分:0)

这就是我的表现......

system('openssl x509 -noout -modulus -in '.$crt.' | openssl md5', $crt_md5);
system('openssl rsa  -noout -modulus -in '.$key.' | openssl md5', $key_md5);

if($crt_md5 != $key_md5){
echo 'BAD';
}

答案 2 :(得分:0)

这对我有用

$crt_md5=exec('openssl x509 -noout -modulus -in /path/to/domain.crt/ | openssl md5 | sed "s/^.* //"');
$key_md5=exec('openssl rsa -noout -modulus -in /path/to/server.key | openssl md5 | sed "s/^.* //"');

if($crt_md5 != $key_md5){
   echo 'BAD';
}
else{
     echo "GOOD";
}
  

sed“s /^.* //” - 将从输出中删除(stdin)= thing,这样   你得到确切的md5字符串

答案 3 :(得分:0)

尝试openssl_x509_check_private_key($ crt,$ key)它返回布尔值

ref http://php.net/manual/en/function.openssl-x509-check-private-key.php

答案 4 :(得分:0)

警告: openssl_x509_check_private_key 在某些情况下不起作用。

示例:

SSL 证书喜欢这个:

-----BEGIN CERTIFICATE-----
xxxx
-----END CERTIFICATE-----

-----BEGIN CERTIFICATE-----
xxxx
xxxx

这个证书没有以-----END CERTIFICATE-----结尾,但是它仍然可以通过这个函数的检查。它会返回 true 告诉您它是正确的,但实际上并非如此。如果你把这个证书上传到你的应用中,比如 Nginx ,Nginx 会告诉你一个错误。

这似乎不是只出现在 PHP 中的错误。如果你在命令行中检查 openssl 函数,它会告诉你同样的结果。

所以我觉得最好的办法就是你需要检查一下证书的段落是否完整。

确认格式正确后,使用该函数验证证书和私钥。

相关问题