PHP cURL证书错误

时间:2015-09-29 14:08:23

标签: php curl certificate

我尝试在我的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 - 权限,但仍然没有运气。

  5. 我在这里不知所措,尝试了我能找到的一切,事实是,我甚至不理解错误的实际含义。什么是{{ 1}?我所能理解的是加载文件时出错。

    非常感谢任何关于此的灯光。请参阅下面的代码示例。

    感谢。

    我使用的代码:

    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");
    

2 个答案:

答案 0 :(得分:2)

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

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

然后在path文件中为其设置php.ini,例如在Windows上:

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

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

SRC1 - https://stackoverflow.com/a/14064903/797495
SRC2 - http://php.net/manual/en/function.curl-setopt.php#110457

答案 1 :(得分:2)

CURLOPT_CAINFOCURLOPT_SSL_VERIFYPEER

一起使用

CURLOPT_CAINFO应设置为PEM格式的CA或CA-bundle。我设法跟踪触发此错误的卷曲代码,这就是我发现的:

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上的通话会返回0,并且结合将CURLOPT_SSL_VERIFYPEER设置为1的事实会触发错误。

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

“如果CAfile不为NULL,则它指向 PEM 格式的CA证书文件。”

“CAfile在执行SSL_CTX_load_verify_locations()函数时处理。”

“0 - 操作失败,因为CAfile和CApath为NULL或指定其中一个位置的处理失败。”在返回值部分

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

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

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