Curl ssl verification disable php

Stop turning off CURLOPT_SSL_VERIFYPEER and fix your PHP config

As Pádraic Brady points out in a recent article about PHP security, there’s a whole lot of misinformation about how to deal with the error “SSL certificate problem, verify that the CA cert is OK” from curl. Nearly everyone advises that you turn CURLOPT_SSL_VERIFYPEER off (in fact, countless comments on the PHP manual page for curl_setopt tell you this). This is bad, because it allows your nice, encrypted stream of confidential data to be silently highjacked by a bad guy. Don’t do that! Instead, just fix your PHP installation so that it doesn’t get that error.

The error is caused by not having an up-to-date bundle of CA root certificates. This is typically a text file with a bunch of cryptographic signatures that curl uses to verify a host’s SSL certificate. You need to make sure that your installation of PHP has one of these files, and that it’s up to date.

Anyone running a recent Linux distribution is probably already OK, because they get the curl libraries bundled in through their package managers and recent curl libraries come with the latest CA root certificate bundle from Mozilla.org. This means you can just turn CURLOPT_SSL_VERIFYPEER on and you won’t get any errors.

For a PHP installation that doesn’t come with this file, like the Windows PHP distribution, you need to download the CA root certificate bundle and tell PHP where to find it. Luckily this is really easy. The curl website has the latest CA root certificate bundle ready to go, just download the .pem and save it where your PHP installation can access it.

Читайте также:  Redirect html page to another html page

Then you just need to edit your php.ini file to tell curl where you saved the .pem file. On my Windows test VM, I have several PHP versions under c:\php, so I put the file into that folder and added this line to each php.ini file:

After restarting the web service, curl now has a valid CA root certificate bundle and it can verify the SSL certificates of remote servers just fine. If it does get an error, it’s because the certificate is invalid — and that’s what you want it to do.

© 2023 WebAware Pty Ltd | ABN 56 079 079 593

Источник

Использование curl в PHP для доступа к сайтам по Https(ssl/tls)

В Php для доступа к сайтам по http, https, FTP часто используется библиотека curl.

На практике, однако, наиболее часто используется протокол, HTTP особенно при соединении server-to-server . Curl же используется при таких методах доступа как

XML-RPC или REST для запроса ресурса. Либо же если производится соединение с сервером посредством какого-либо API. Ну и последним использованием curl в php можно назвать парсинг ресурсов.

Тем не менее, при попытке получить доступ к ресурсу по HTTPS, например, через API, могут возникнуть определенные проблемы в подключении, о которых и пойдет речь.

Основной проблемой при данном соединении с использованием Curl можно назвать невозможность библиотекой проверить недоверенный сертификат сайта. Смоделируем ситуацию.

Предположим мы используем следующий код

// Initialize session and set URL. $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // Set so curl_exec returns the result instead of outputting it. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Get the response and close the channel. $response = curl_exec($ch); curl_close($ch);

Если $url указывает на https ресурс как результат выполнения данного кода мы получим

Failed: Error Number: 60. Reason: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Это происходит потому, что Curl не был настроен доверять HTTPS сертификату сервера.

Понятия сертификаты и PKI вращается вокруг доверия сертификатов (CA), и по умолчанию, Curl настроен не доверять CA, таким образом, он не будет доверять сертификату любого веб-сервера. Так почему же не у нас не возникли проблемы посещения HTTPs сайтов через веб-браузер? Разработчики браузера включают в себя список корневых доверенных центров сертификации, у которых может быть приобретен сертификат сайта.

Таким образом необходимо либо разрешить Curl доверять нашему сертификату, либо запретить проверку доверия к сертификату при использовании библиотеки.

Обратимся к более простому решению – запретим Curl проверять сертификат, фактически настроив на доверие к любому полученному сертификату.

Читайте также:  Html element text content

Это не очень верное решение с точки зрения безопасности, но действенно. Для выполнения данной настройки перед вызовом curl curl_exec() достаточно вставить следующую строку

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Это заставляет библиотеку Curl принимать любые сертификаты, но если Вы обеспокоены, что у Вас принимаются все сертификаты без разбора необходимо сделать немного больше действий.

Оговоримся, что будем использовать такой параметр Curl CURLOPT_CAINFO и сертификат, полученный с сайта.

Давайте извлечем сертификат, используя наш броузер.

Откроем сайт и увидим следующую картинку в нижней части броузера.

1-2016

Нажмем «просмотреть сертификат»

2-2016

И далее в пункте «Детали» на странице сертификатов выберем наш сертификат. Это доверенный корневой сертификат.

3

Нам необходимо его экспортировать для дальнейшего использования Curl

4

Нажмем “Экспорт”, и сохраним наш корневой сертификат как X.509 Certificate (PEM).

Далее нам необходимо модифицировать настройки cURL для использования CA сертификата с параметром CURLOPT_CAINFO, где мы укажем место сохранения сертификата .

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/CAcerts/BuiltinObjectToken-EquifaxSecureCA.crt");

Failed: Error Number: 60. Reason: SSL certificate problem, verify that the CA cert is OK. Details:

error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Источник

Fix SSL certificate problem with PHP curl

Fix SSL certificate problem with PHP curl

In this article, I will show share with you a tip to fix SSL certificate problem with PHP curl when making HTTPS requests.

Making HTTPS requests

Before talking about the issue, let us try an old example by making HTTP request.

$url = "http://WEBSITE"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); if(curl_errno($ch)) < echo 'Error: '.curl_error($ch); >else < echo $result; >curl_close ($ch);

It is alright for HTTP site, but if we change the $url into a HTTPS url, ex. https://petehouston.com , does it work normally?

Читайте также:  Prepend python что это

No, it doesn’t. It shows this nagging error:

Error: SSL certificate problem: unable to get local issuer certificate

The error means we need to configure curl instance to deal with SSL-enabled websites.

Fix SSL certificate problem

There are two ways to fix SSL certificate problem with PHP curl module.

  1. Specify the valid CA certificate to curl client.
  2. Ignore SSL verification.

Solution 1: Use a valid CA certificate

I’m not going to explain what CA certificate is and why we need it to make requests.

You just need to download CA certificate provided by curl author, https://curl.haxx.se/docs/caextract.html, or click here to download.

Save the file somewhere in your computer, ex. ~/certs/cacert.pem if you’re on Linux or MacOS, D:\certs\cacert.pem if you’re using Windows.

Config the curl instance with CURLOPT_CAINFO to point to the cacert.pem file.

// for Linux/Mac curl_setopt($ch, CURLOPT_CAINFO, '/home/petehouston/certs/cacert.pem'); // for Windows curl_setopt($ch, CURLOPT_CAINFO, 'D:/certs/cacert.pem');

Try to execute the script again, it should work now!

You can also pre-configure the CA certificate by putting it into php.ini , so you don’t need to configure manually for each curl instance.

[curl] ; A default value for the CURLOPT_CAINFO option. This is required to be an ; absolute path. curl.cainfo = "/home/petehouston/certs/cacert.pem"

Solution 2: Ignore SSL verification

If you don’t really care about SSL verification, you can ignore it by disable the CURLOPT_SSL_VERIFYPEER key.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

It is just working as it with configured certificate.

Conclusion

So which one should I use, you ask?

Again, if you don’t care about the authenticity of the SSL then ignore it; otherwise, make sure you request to the right one.

That’s it! I’ve just shown you how to fix SSL certificate problem with PHP curl module.

Источник

Оцените статью