Openssl error 14090086

01 октября 2021 года я столкнулся с проблемой - в проекте на Wordpress и PHP 7.0 перестали работать все скрипты, которые получают что-то из вне по https с

OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate  file_get_contents(): Failed to enable crypto in

01 октября 2021 года я столкнулся с проблемой — в проекте на WordPress и PHP 7.0 перестали работать все скрипты, которые получают что-то из вне по https с помощью file_get_contents и wp_remote_get. C wp_remote_get все получилось решить просто:

wp_remote_get($url, [‘sslverify’ => false ]);

Но из используемой функции

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

В логах nginx ошибка file_get_contents(): Failed to enable crypto in

На все запросы через https. Полностью ошибка выглядела примерно так:

SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate

file_get_contents(): Failed to enable crypto in

error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /home/web/azzrael.ru/subscribeazzraelcodeyoutube.php on line 2

PHP message: PHP Warning:  file_get_contents(): Failed to enable crypto in /home/web/azzrael.ru/subscribeazzraelcodeyoutube.php on line 2

PHP message: PHP Warning:  file_get_contents([https://www.youtube.com/channel/UCf6kozNejHoQuFhBDB8cfxA.jpg](https://www.youtube.com/channel/UCf6kozNejHoQuFhBDB8cfxA.jpg)): failed to open stream: operation failed in /home/web/azzrael.ru/subscribe-azzrael-code-youtube.php on line 2

PHP message: PHP Fatal error:  Uncaught Exception: cant get file in /home/web/azzrael.ru/subscribeazzraelcodeyoutube.php:3

Stack trace:

#0 {main}

thrown in /home/web/azzrael.ru/subscribeazzraelcodeyoutube.php on line 3» while reading response header from upstream, client: 8.8.8.8, server: [azzrael.ru](http://azzrael.ru/), request: «GET /subscribeazzraelcodeyoutube.php HTTP/2.0«, upstream: «fastcgi://unix:/run/php/php7.0-fpm.sock:», host: «[azzrael.ru](http://azzrael.ru/)»

Упоминание OpenSSL и ssl3_get_server_certificate вместе сразу дало направление на гугление в сторону проблем с сертификатами. Так и оказалось.

Истечение корневых сертификатов Lets Encrypt

Вероятно сама проблема связана с истечением 30 сентября 2021 года корневых сертификатов Lets Encrypt. Возможно, также что проблема связана с версией PHP — на проекте используется довольно устаревшая PHP 7.0.

Решение проблемы

Есть несколько способов решения. Т.к. проблема касалась нескольких сайтов на сервере и имелся полный доступ к управлению сервером то я сделал следующее:

  • Пошел на https://curl.se/docs/caextract.html
  • Скачал cacert.pem
  • Положил cacert.pem в /etc/ssl/certs/cacert.pem

Затем в php.ini в раздел openssl прописал следующее:

[openssl]

openssl.cafile=/etc/ssl/certs/cacert.pem

Перезагрузил php

service php7.0fpm restart  и проблема исчезла.

Рано или поздно и этот сертификат протухнет. Но, судя по https://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt серт полученный в 2021 протухнет в 2028. Это приемлимо.

Had the same error with PHP 7 on XAMPP and OSX.

The above mentioned answer in https://stackoverflow.com/ is good, but it did not completely solve the problem for me. I had to provide the complete certificate chain to make file_get_contents() work again. That’s how I did it:

Get root / intermediate certificate

First of all I had to figure out what’s the root and the intermediate certificate.

The most convenient way is maybe an online cert-tool like the ssl-shopper

There I found three certificates, one server-certificate and two chain-certificates (one is the root, the other one apparantly the intermediate).

All I need to do is just search the internet for both of them. In my case, this is the root:

thawte DV SSL SHA256 CA

And it leads to his url thawte.com. So I just put this cert into a textfile and did the same for the intermediate. Done.

Get the host certificate

Next thing I had to to is to download my server cert. On Linux or OS X it can be done with openssl:

openssl s_client -showcerts -connect whatsyoururl.de:443 </dev/null 2>/dev/null|openssl x509 -outform PEM > /tmp/whatsyoururl.de.cert

Now bring them all together

Now just merge all of them into one file. (Maybe it’s good to just put them into one folder, I just merged them into one file). You can do it like this:

cat /tmp/thawteRoot.crt > /tmp/chain.crt
cat /tmp/thawteIntermediate.crt >> /tmp/chain.crt
cat /tmp/tmp/whatsyoururl.de.cert >> /tmp/chain.crt

tell PHP where to find the chain

There is this handy function openssl_get_cert_locations() that’ll tell you, where PHP is looking for cert files. And there is this parameter, that will tell file_get_contents() where to look for cert files. Maybe both ways will work. I preferred the parameter way. (Compared to the solution mentioned above).

So this is now my PHP-Code

$arrContextOptions=array(
    "ssl"=>array(
        "cafile" => "/Applications/XAMPP/xamppfiles/share/openssl/certs/chain.pem",
        "verify_peer"=> true,
        "verify_peer_name"=> true,
    ),
);

$response = file_get_contents($myHttpsURL, 0, stream_context_create($arrContextOptions));

That’s all. file_get_contents() is working again. Without CURL and hopefully without security flaws.

#################################################
# Sample OpenVPN 2.0 config file for #
# multi-client server. #
# #
# This file is for the server side #
# of a many-clients <-> one-server #
# OpenVPN configuration. #
# #
# OpenVPN also supports #
# single-machine <-> single-machine #
# configurations (See the Examples page #
# on the web site for more info). #
# #
# This config should work on Windows #
# or Linux/BSD systems. Remember on #
# Windows to quote pathnames and use #
# double backslashes, e.g.: #
# «C:\Program Files\OpenVPN\config\foo.key» #
# #
# Comments are preceded with ‘#’ or ‘;’ #
#################################################

# Which local IP address should OpenVPN
# listen on? (optional)
;local a.b.c.d

# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one. You will need to
# open up this port on your firewall.
port 1194

# TCP or UDP server?
;proto tcp
proto udp

# «dev tun» will create a routed IP tunnel,
# «dev tap» will create an ethernet tunnel.
# Use «dev tap0» if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use «dev-node» for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun

# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one. On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don’t need this.
;dev-node MyTap

# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key). Each client
# and the server must have their own cert and
# key file. The server and all clients will
# use the same ca file.
#
# See the «easy-rsa» directory for a series
# of scripts for generating RSA certificates
# and private keys. Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see «pkcs12» directive in man page).
ca «C:\Program Files\OpenVPN\config\ca.crt»
cert «C:\Program Files\OpenVPN\config\server.crt»
key «C:\Program Files\OpenVPN\config\server.key» # This file should be kept secret

# Diffie hellman parameters.
# Generate your own with:
# openssl dhparam -out dh2048.pem 2048
dh «C:\Program Files\OpenVPN\config\dh1024.pem»

# Network topology
# Should be subnet (addressing via IP)
# unless Windows clients v2.0.9 and lower have to
# be supported (then net30, i.e. a /30 per client)
# Defaults to net30 (not recommended)
;topology subnet

# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.8.0.0 255.255.255.0

# Maintain a record of client <-> virtual IP address
# associations in this file. If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.
ifconfig-pool-persist ipp.txt

# Configure server mode for ethernet bridging.
# You must first use your OS’s bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface. Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0. Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients. Leave this line commented
# out unless you are ethernet bridging.
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100

# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses. You must first use
# your OS’s bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge

# Push routes to the client to allow it
# to reach other private subnets behind
# the server. Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
push «route 10.200.1.0 255.0.0.0»

# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory «ccd» for client-specific
# configuration files (see man page for more info).

# EXAMPLE: Suppose the client
# having the certificate common name «Thelonious»
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
# iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious’ private subnet to
# access the VPN. This example will only work
# if you are routing, not bridging, i.e. you are
# using «dev tun» and «server» directives.

# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
# ifconfig-push 10.9.0.1 10.9.0.2

# Suppose that you want to enable different
# firewall access policies for different groups
# of clients. There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
# group, and firewall the TUN/TAP interface
# for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
# modify the firewall in response to access
# from different clients. See man
# page for more info on learn-address script.
;learn-address ./script

# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
;push «redirect-gateway def1 bypass-dhcp»

# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses. CAVEAT:
# http://openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
push «dhcp-option DNS 10.200.1.1»
push «dhcp-option DNS 8.8.4.4»

# Uncomment this directive to allow different
# clients to be able to «see» each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server’s TUN/TAP interface.
;client-to-client

# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names. This is recommended
# only for testing purposes. For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE «COMMON NAME»,
# UNCOMMENT THIS LINE OUT.
;duplicate-cn

# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
keepalive 10 300

# For extra security beyond that provided
# by SSL/TLS, create an «HMAC firewall»
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
# openvpn —genkey —secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be ‘0’
# on the server and ‘1’ on the clients.
;tls-auth ta.key 0 # This file is secret

# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
;cipher BF-CBC # Blowfish (default)
;cipher AES-128-CBC # AES
;cipher DES-EDE3-CBC # Triple-DES

# Enable compression on the VPN link.
# If you enable it here, you must also
# enable it in the client config file.
comp-lzo

# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100

# It’s a good idea to reduce the OpenVPN
# daemon’s privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
;user nobody
;group nobody

# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun

# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status openvpn-status.log

# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the «Program FilesOpenVPNlog» directory).
# Use log or log-append to override this default.
# «log» will truncate the log file on OpenVPN startup,
# while «log-append» will append to it. Use one
# or the other (but not both).
;log openvpn.log
;log-append openvpn.log

# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3

# Silence repeating messages. At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20

  • OnYourLips

На компе стоит сервер.

При таком раскладе

<?php
file_get_contents('https://vk.com');
?>

вот такая ошибка

Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in /Applications/AMPPS/www/pf.loc/test.php on line 2

Warning: file_get_contents(): Failed to enable crypto in /Applications/AMPPS/www/pf.loc/test.php on line 2

Warning: file_get_contents(https://vk.com): failed to open stream: operation failed in /Applications/AMPPS/www/pf.loc/test.php on line 2

Знаю, что такого быть не должно, так как на другом сервере все работало.

в php.ini стоит extension=openssl.so


  • Вопрос задан

    более трёх лет назад

  • 21042 просмотра

$arrContextOptions=array(
    "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ),
);  
$sw=file_get_contents(ЛИНК, false, stream_context_create($arrContextOptions));

Пользуюсь этим продуктом www.ampps.com . Сменил php с 5,6 на 5,5 и все нормально

Пригласить эксперта

function file_get_contents_curl( $url ) {

  $ch = curl_init();

  curl_setopt( $ch, CURLOPT_AUTOREFERER, TRUE );
  curl_setopt( $ch, CURLOPT_HEADER, 0 );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
  curl_setopt( $ch, CURLOPT_URL, $url );
  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE );

  $data = curl_exec( $ch );
  curl_close( $ch );

  return $data;

}

Затем просто используйте file_get_contents_curl вместо file_get_contents всякий раз, когда вы вызываете URL-адрес, начинающийся с https.


  • Показать ещё
    Загружается…

10 февр. 2023, в 01:33

1500 руб./за проект

10 февр. 2023, в 00:54

2000 руб./в час

10 февр. 2023, в 00:15

1000 руб./в час

Минуточку внимания

Было замечено, что я ряде случаев после обновления PHP до версии 5.6 возникают трудности с подключением к серверам средствами PHP, включая почтовые сервисы, HTTPS-сайты. Одной из возможных причин может быть ошибка при проверки валидности сертификатов SSL/TLS. При разборе можно натолкнуться на сообщение подобное одному из следующих:

SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

или

— fsockopen(): Failed to enable crypto

или

— fsockopen(): unable to connect to ssl://xx.xx.xx:443 (Unknown error)

Если ошибка одинаково возникает при подключении к хостам, которые 100% используют достоверные SSL сертификаты, и имя хоста для подключения совпадает с именем в таком сертификате, то проблема скорее всего кроется в том, что для PHP не указан или указан некорректно параметр openssl.cafile.

Из документации PHP 5.6

Все шифруемые клиентские потоки теперь по умолчанию включают проверку пиров. По умолчанию используется OpenSSL CA пакет для проверки сертификата пира. В большинстве случаев не требуется ничего делать для соединения с серверами с правильным SSL сертификатом, так как обычно OpenSSL уже настроен для использования хороших CA пакетов.

Стандартный CA пакет может быть переопределен глобально с помощью установки или openssl.cafile или openssl.capath строк конфигурации, или же на уровне каждого запроса используя опции контекста cafile или capath.

Хотя это и не рекомендуется, но можно отклчить проверку сертификата пира для запроса, установив verify_peer опцию контекста в FALSE, и можно отключить проверку имени пира, установив verify_peer_name в FALSE.

PHP: OpenSSL changes in PHP 5.6.x — Manual

Проверяем настройки

И так проверяем настройки:

# php -r 'print_r(openssl_get_cert_locations());' | grep '[default_cert_file]' | awk '{print $3}'

Результатом должна быть одна строка, указывающая на CA пакет (cafile):

/etc/pki/tls/cert.pem

Вариации

/usr/ssl/cert.pem
/usr/local/etc/ssl/cert.pem

В зависимости от используемой ОС и сборки PHP путь может отличаться. Главное здесь — убедиться, что указанный файл существует, и что он не пустой и соддержит корректную информацию.

Если файла нет или он поврежден, то восстановить его можно на CentOS с помощью (пере-)установки ca-certificates:

# yum reinstall ca-certificates

FreeBSD с пакетом security/ca_root_nss

# pkg install security/ca_root_nss

Или же скачать CA пакет целиком по ссылке http://curl.haxx.se/ca/cacert.pem

# wget http://curl.haxx.se/ca/cacert.pem -O 
`php -r 'print_r(openssl_get_cert_locations());' | grep '[default_cert_file]' | awk '{print $3}'`

Удачи!

Rinker

Сообщения: 7
Зарегистрирован: 30 ноя 2020, 13:35

Проблема с SSL сертификатом при попытке скачать страницу через file_get_contents

Всем привет. При попытке скачать страницу через php функцию file_get_contents() с сайта на https, возникает предупреждение (ошибка), связанная с сертификатом, и дальше скрипт не выполняется.

Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in test.php on line 10

Использую PHP 7.1 x64, Apache 2.4
В конфигурации php стоит настройка:

[openssl]
openssl.cafile="%sprogdir%/modules/php/%phpdriver%/cacert.pem"

Подскажите пожалуйста в чем может быть проблема?

AlexPavlov1991

Сообщения: 1
Зарегистрирован: 04 дек 2021, 14:32

Re: Проблема с SSL сертификатом при попытке скачать страницу через file_get_contents

Непрочитанное сообщение

AlexPavlov1991 » 04 дек 2021, 14:40

Максим писал(а): ↑30 ноя 2021, 18:45
Обновите файл cacert.pem и вообще проверьте что он есть у вас в папке с PHP (в последних версиях он лежит тут: /userdata/config/cacert.pem), перезапуститесь. Либо у вашего хоста реально неверный или устаревший сертификат, тогда вам поможет такой код:

<?php
$opt=array(
    "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ),
);  
$response = file_get_contents("https://xxx", false, stream_context_create($opt));
?>

Замена cacert.pem мне помогла при установке yii2 через composer. Но почему в самой свежей версии open server лежит устаревший сертификат?

vavyan

Сообщения: 5
Зарегистрирован: 07 янв 2022, 11:50

SagePointer

Сообщения: 308
Зарегистрирован: 27 ноя 2020, 20:52

Re: Проблема с SSL сертификатом при попытке скачать страницу через file_get_contents

Непрочитанное сообщение

SagePointer » 10 янв 2022, 18:42

vavyan писал(а): ↑10 янв 2022, 16:17
ещё такой вопрос антивирус может блокировать?

Если антивирус перехватывает и по пути проверяет зашифрованный трафик, то он подменяет при этом сертификаты на свои. В таком случае добавьте руками в cacert.pem корневой сертификат от антивируса, как это сделать — обратитесь к производителю антивируса за инструкциями и сертификатом в формате PEM.
Возможно, антивирус позволяет добавить в исключения проверку трафика отдельных процессов, в таком случае добавьте апач (в случае апача) или php-cgi.exe (в случае nginx)

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Opengl init error
  • Opengl error runtimeexception no opengl context found in the current thread что делать
  • Opengl error runtimeexception no opengl context found in the current thread minecraft error
  • Opengl error runtimeexception no opengl context found in the current thread gl caps
  • Opengl error nullfunctionerror attempt to call an undefined function glutinitdisplaymode

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии