如何在PHP中验证TLS SMTP证书是否有效?

Xeo*_*oss 17 php smtp ssl-certificate starttls

为了防止中间人攻击(假装是其他人的服务器),我想验证我通过SSL连接的SMTP服务器是否有一个有效的SSL证书,证明它是我认为的.

例如,在端口25上连接到SMTP服务器后,我可以切换到安全连接,如下所示:

<?php

$smtp = fsockopen( "tcp://mail.example.com", 25, $errno, $errstr ); 
fread( $smtp, 512 ); 

fwrite($smtp,"HELO mail.example.me\r\n"); // .me is client, .com is server
fread($smtp, 512); 

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

stream_socket_enable_crypto( $smtp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT ); 

fwrite($smtp,"HELO mail.example.me\r\n");
Run Code Online (Sandbox Code Playgroud)

但是,没有提到PHP检查SSL证书的位置.PHP有一个内置的根CA列表吗?它只是接受任何东西吗?

什么是验证证书有效的正确方法,以及SMTP服务器真的是我认为的那个?

更新

根据PHP.net上的这条评论,似乎我可以使用一些流选项进行SSL检查.最好的部分是stream_context_set_option接受上下文或流资源.因此,在TCP连接的某个时刻,您可以使用CA证书捆绑包切换到SSL .

$resource = fsockopen( "tcp://mail.example.com", 25, $errno, $errstr ); 

...

stream_set_blocking($resource, true);

stream_context_set_option($resource, 'ssl', 'verify_host', true);
stream_context_set_option($resource, 'ssl', 'verify_peer', true);
stream_context_set_option($resource, 'ssl', 'allow_self_signed', false);

stream_context_set_option($resource, 'ssl', 'cafile', __DIR__ . '/cacert.pem');

$secure = stream_socket_enable_crypto($resource, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
stream_set_blocking($resource, false);

if( ! $secure)
{
    die("failed to connect securely\n");
}
Run Code Online (Sandbox Code Playgroud)

另请参阅扩展SSL选项的上下文选项和参数.

但是,虽然这现在解决了主要问题 - 如何验证有效证书实际上属于我正在连接的域/ IP?

换句话说,我连接的服务器的证书也可能有一个有效的证书 - 但我怎么知道它对"example.com"有效,而不是另一台使用有效证书的服务器就像"example.com"一样?

更新2

您似乎可以使用steam context params 捕获SSL证书,并使用openssl_x509_parse解析它.

$cont = stream_context_get_params($r);
print_r(openssl_x509_parse($cont["options"]["ssl"]["peer_certificate"]));
Run Code Online (Sandbox Code Playgroud)

LSe*_*rni 8

更新:有更好的方法,请参阅评论.

您可以捕获证书并使用openssl过滤器与服务器进行对话.这样,您可以提取证书并在同一连接期间检查它.

这是一个不完整的实现(实际邮件发送的谈话是不存在的),这应该让你开始:

<?php
    $server = 'smtp.gmail.com';

    $pid    = proc_open("openssl s_client -connect $server:25 -starttls smtp",
                    array(
                            0 => array('pipe', 'r'),
                            1 => array('pipe', 'w'),
                            2 => array('pipe', 'r'),
                    ),
                    $pipes,
                    '/tmp',
                    array()
            );
    list($smtpout, $smtpin, $smtperr) = $pipes; unset($pipes);

    $stage  = 0;
    $cert   = 0;
    $certificate = '';
    while(($stage < 5) && (!feof($smtpin)))
    {
            $line = fgets($smtpin, 1024);
            switch(trim($line))
            {
                    case '-----BEGIN CERTIFICATE-----':
                            $cert   = 1;
                            break;
                    case '-----END CERTIFICATE-----':
                            $certificate .= $line;
                            $cert   = 0;
                            break;
                    case '---':
                            $stage++;
            }
            if ($cert)
                    $certificate .= $line;
    }
    fwrite($smtpout,"HELO mail.example.me\r\n"); // .me is client, .com is server
    print fgets($smtpin, 512);
    fwrite($smtpout,"QUIT\r\n");
    print fgets($smtpin, 512);

    fclose($smtpin);
    fclose($smtpout);
    fclose($smtperr);
    proc_close($pid);

    print $certificate;

    $par    = openssl_x509_parse($certificate);
?>
Run Code Online (Sandbox Code Playgroud)

当然,在向服务器发送任何有意义的内容之前,您将移动证书解析和检查.

$par数组中,您应该找到(在其余的)名称,同样解析为主题.

Array
(
    [name] => /C=US/ST=California/L=Mountain View/O=Google Inc/CN=smtp.gmail.com
    [subject] => Array
        (
            [C] => US
            [ST] => California
            [L] => Mountain View
            [O] => Google Inc
            [CN] => smtp.gmail.com
        )

    [hash] => 11e1af25
    [issuer] => Array
        (
            [C] => US
            [O] => Google Inc
            [CN] => Google Internet Authority
        )

    [version] => 2
    [serialNumber] => 280777854109761182656680
    [validFrom] => 120912115750Z
    [validTo] => 130607194327Z
    [validFrom_time_t] => 1347451070
    [validTo_time_t] => 1370634207
    ...
    [extensions] => Array
        (
            ...
            [subjectAltName] => DNS:smtp.gmail.com
        )
Run Code Online (Sandbox Code Playgroud)

要检查有效性,除了日期检查等,SSL本身执行哪些操作,您必须验证这些条件是否适用:

  • 实体的CN是您的DNS名称,例如"CN = smtp.your.server.com"

  • 定义了扩展,它们包含一个subjectAltName,它一旦爆炸explode(',', $subjectAltName),就会生成一个带有DNS:前缀的记录数组,其中至少有一个与您的DNS名称相匹配.如果不匹配,则拒绝证书.

PHP中的证书验证

验证主机在不同软件中的含义似乎充其量模糊的.

所以我决定深究这一点,并下载了OpenSSL的源代码(openssl-1.0.1c)并尝试自己查看.

我发现没有引用我期望的代码,即:

  • 尝试解析以冒号分隔的字符串
  • 引用subjectAltName(OpenSSL调用SN_subject_alt_name)
  • 使用"DNS [:]"作为分隔符

OpenSSL似乎将所有证书详细信息放入一个结构中,对其中一些进行非常基本的测试,但大多数"人类可读"的字段都是单独存在的.这是有道理的:可以说,名称检查比证书签名检查更高

然后我还下载了最新的cURL和最新的PHP tarball.

在PHP源代码中我什么都没找到; 显然任何选项都只是传递下去,否则就会被忽略.此代码运行时没有警告:

    stream_context_set_option($smtp, 'ssl', 'I-want-a-banana', True);
Run Code Online (Sandbox Code Playgroud)

然后stream_context_get_options尽职尽责地检索

    [ssl] => Array
        (
            [I-want-a-banana] => 1
            ...
Run Code Online (Sandbox Code Playgroud)

这也是有道理的:PHP在"上下文选项设置"环境中无法知道将使用哪些选项.

同样,证书解析代码解析证书并提取OpenSSL放在那里的信息,但它不验证相同的信息.

所以我挖得更深一点,最后在cURL中找到了证书验证码,这里:

// curl-7.28.0/lib/ssluse.c

static CURLcode verifyhost(struct connectdata *conn,
                       X509 *server_cert)
{
Run Code Online (Sandbox Code Playgroud)

它按照我的预期执行:它查找subjectAltNames,它检查所有这些是否合理并运行它们过去hostmatch,运行hello.example.com ==*.example.com之类的检查.还有额外的健全性检查:"我们需要至少2个点模式,以避免过于宽泛的通配符匹配." 和xn--检查.

总而言之,OpenSSL运行一些简单的检查,并将其余的检查留给调用者.调用OpenSSL的cURL实现了更多检查.PHP也会在CN上运行一些检查verify_peer,但subjectAltName单独留下.这些检查并不能说服我太多; 见下文"测试".

由于缺乏访问cURL函数的能力,最好的替代方法是重新实现 PHP中的函数.

例如,可变通配符域匹配可以通过点扩展实际域和证书域来完成,从而反转两个阵列

com.example.site.my
com.example.*
Run Code Online (Sandbox Code Playgroud)

并验证相应的项目是否相等,或证书一个是*; 如果发生这种情况,我们必须已经检查了至少两个组件,在这里comexample.

我相信如果您想一次性检查证书,上面的解决方案是最好的解决方案之一.更好的是能够直接打开流而不求助于openssl客户端 - 这是可能的 ; 看评论.

测试

我有一份来自Thawte的优质,有效且完全信任的证书,发给"mail.eve.com".

然后,在Alice上运行的上述代码将安全地连接mail.eve.com,并且按预期连接.

现在我安装相同的证书mail.bob.com,或以其他方式我说服DNS我的服务器是Bob,而它实际上仍然是夏娃.

我希望SSL连接仍然有效(证书有效和可信的),但该证书不颁发给鲍勃-它发放给夏娃.所以有人必须做最后一次检查,并警告爱丽丝,鲍勃实际上被夏娃模仿(或者等效地说,鲍勃正在使用夏娃的被盗证书).

我使用下面的代码:

    $smtp = fsockopen( "tcp://mail.bob.com", 25, $errno, $errstr );
    fread( $smtp, 512 );
    fwrite($smtp,"HELO alice\r\n");
    fread($smtp, 512);
    fwrite($smtp,"STARTTLS\r\n");
    fread($smtp, 512);
    stream_set_blocking($smtp, true);
    stream_context_set_option($smtp, 'ssl', 'verify_host', 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', 'cafile', '/etc/ssl/cacert.pem');
    $secure = stream_socket_enable_crypto($smtp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
    stream_set_blocking($smtp, false);
    print_r(stream_context_get_options($smtp));
    if( ! $secure)
            die("failed to connect securely\n");
    print "Success!\n";
Run Code Online (Sandbox Code Playgroud)

和:

  • 如果证书无法通过受信任的机构进行验证:
    • verify_host什么都不做
    • verify_peer TRUE导致错误
    • verify_peer FALSE允许连接
    • allow_self_signed什么都不做
  • 如果证书已过期:
    • 我收到一个错误.
  • 如果证书可以核实:
    • 连接被允许"mail.eve.com"冒充"mail.bob.com",我得到一个"成功!" 信息.

我认为这意味着,除非我犯了一些愚蠢的错误,否则PHP本身不会根据名称检查证书.

使用本文proc_open开头的代码,我再次可以连接,但这次我可以访问,subjectAltName因此可以自己检查,检测模仿.


LSe*_*rni 3

为了不加载已经过长的内容,并且不再过多地讨论主题,请用更多文本来回答,我将其留给处理原因和原因的部分,在这里我将描述如何

我针对 Google 和其他几个服务器测试了这段代码;有什么注释,嗯,代码中的注释。

<?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 on SMTP port 25
    $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...
Run Code Online (Sandbox Code Playgroud)