PHP cURL 证书错误

PHP cURL certificate error

我正在尝试向我的 PHP cURL 请求添加自定义 cer 证书,但我不断收到此错误:

error setting certificate verify locations:
  CAfile: /path/to/my/cert.cer
  CApath: none

关于这个错误,我发现的是:

  1. 路径是相对的
    如您所见,我提供了一个绝对路径。

  2. 路径错误
    我试过var_dump(file_exists($certLocation));,结果是true,所以不是这样。

  3. 文件的权限不正确。
    出于调试目的,我已将权限设置为 777。错误仍然存​​在。

  4. 文件路径在链中某处没有 +x-权限。
    我也设置了这个,确保从 root 开始的整个路径都有 +x-permissions,但仍然没有运气。

我在这里不知所措,尝试了我能找到的一切,事实是,我什至不明白错误的实际含义。什么是 verify location?我能理解的是加载文件时出错。

不胜感激。请参阅下面的代码示例。

谢谢。

我使用的代码:

<?php

$oCurl = curl_init($this->baseUrl);
curl_setopt($oCurl, CURLOPT_FAILONERROR, 1);
curl_setopt($oCurl, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, $this->connectionTimeout);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($oCurl, CURLOPT_POST, 1);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($oCurl, CURLOPT_CAINFO, "/tmp/cert.cer");

错误:

error setting certificate verify locations:
  CAfile: /tmp/cert.cer
  CApath: none

如果您的 PHP 安装没有最新的 CA 根证书包,请在 curl 网站下载并保存在您的服务器上:

http://curl.haxx.se/docs/caextract.html

然后在您的 php.ini 文件中为其设置一个 path,例如在 Windows:

curl.cainfo=c:\php\cacert.pem

注意:
关闭 CURLOPT_SSL_VERIFYPEER 允许中间人 (MITM) 攻击,这是您不想要的!


SRC1 -
SRC2 - http://php.net/manual/en/function.curl-setopt.php#110457

CURLOPT_CAINFO is used in conjunction with CURLOPT_SSL_VERIFYPEER

CURLOPT_CAINFO 应设置为 PEM 格式的 CA 或 CA 捆绑包。我设法跟踪触发此错误的 curl 代码,这是我发现的:

curl/openssl.c中:

if(!SSL_CTX_load_verify_locations(connssl->ctx,
                                   data->set.str[STRING_SSL_CAFILE],
                                   data->set.str[STRING_SSL_CAPATH])) {
  if(data->set.ssl.verifypeer) {
    /* Fail if we insist on successfully verifying the server. */
    failf(data, "error setting certificate verify locations:\n"
          "  CAfile: %s\n  CApath: %s",
          data->set.str[STRING_SSL_CAFILE]?
          data->set.str[STRING_SSL_CAFILE]: "none",
          data->set.str[STRING_SSL_CAPATH]?
          data->set.str[STRING_SSL_CAPATH] : "none");
    return CURLE_SSL_CACERT_BADFILE;
  }
  ...

显然是对 SSL_CTX_load_verify_locations returns 0 的调用并结合将 CURLOPT_SSL_VERIFYPEER 设置为 1 的事实触发了错误。

SSL_CTX_load_verify_locations 是 openssl 库中的函数,根据文档(SSL_CTX_load_verify_locations documentation),应考虑以下语句:

"If CAfile is not NULL, it points to a file of CA certificates in PEM format."

"The CAfile is processed on execution of the SSL_CTX_load_verify_locations() function."

“0 - 操作失败,因为 CAfile 和 CApath 为 NULL 或在指定位置之一的处理失败。”在 RETURN VALUES 部分


您可以尝试使用以下命令将 cer 转换为 pem

openssl x509 -in /tmp/cert.cer -inform der -outform pem -out /tmp/cert.pem

但我不能保证这会起作用,因为我不确定您是否有合适的 CA 或 CA 捆绑文件。