不推荐使用CN_match支持peer_name

时间:2017-11-28 22:23:37

标签: php ssl sslcontext

我正在尝试通过SSL在PHP中从一台服务器向另一台服务器发送POST请求。当我在我的上下文选项中使用CN_match时,它可以正常工作。但是我在错误日志中收到了弃用消息:

  

PHP已弃用:不推荐使用'CN_match'SSL上下文选项,而选择'peer_name'

问题在于,如果我按照建议将CN_match更改为peer_name,请求会完全失败,并显示以下消息:

  

无法打开流:HTTP请求失败! HTTP / 1.1 400错误请求。

使用peer_name的无效值会导致预期的错误:

  

同行证书CN ='localhost'与预期的CN ='test'

不匹配

当我指定'localhost'时,显然它正确匹配。我是否遗漏了使用peer_name而不是CN_match时需要的其他配置?

使用MAMP,PHP 5.6.27

$userdata = array(
    'action'            => 'add-user',
    'name'              => $name,
    'email'             => $email,
    'username'          => $username,
    'password'          => $password);

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($userdata)
    ),
    'ssl' => array(
        'verify_peer'       => true,
        'cafile'            => /path/to/file.pem,
        'verify_depth'      => 5,
        'allow_self_signed' => true,
        'peer_name'         => 'localhost'
    )
);

$context  = stream_context_create($options);
$data = file_get_contents('https://localhost/add-user.php', false, $context);

1 个答案:

答案 0 :(得分:1)

使用curl是我能​​找到的唯一解决方案:

$url = 'https://some.domain.com/file.php';
$pem_file = '/absolute/path/to/certificate.pem';

$userdata = array(
    'action'            => 'add-user',
    'name'              => $name,
    'email'             => $email,
    'username'          => $username,
    'password'          => $password);

$curl_req = curl_init();
curl_setopt($curl_req, CURLOPT_URL, $url);
curl_setopt($curl_req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_req, CURLOPT_POST, true);
curl_setopt($curl_req, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($curl_req, CURLOPT_POSTFIELDS, http_build_query($userdata));
curl_setopt($curl_req, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl_req, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl_req, CURLOPT_CAINFO, $pem_file);

$response = curl_exec($curl_req);
curl_close($curl_req);

此外,我花了一些时间来弄清楚如何构建certificate.pem文件。您需要堆叠从您的特定证书开始并通过任何中间证书并以CA证书结束的证书:

-----BEGIN CERTIFICATE-----
<your site certificate>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<intermediate certificate>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<CA certificate>
-----END CERTIFICATE-----