Php windows with openssl

Php windows with openssl

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

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

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

Сигнатура сертификата

Была добавлена поддержка извлечения и проверки сигнатуры сертификата. Для извлечения сигнатур сертификатов X.509 добавлена функция openssl_x509_fingerprint() . Также были добавлены две опции контекста потока SSL: capture_peer_cert для захвата узлового сертификата X.509, и peer_fingerprint для проверки сертификата на соответствие заданной сигнатуре.

Обновлены шифры по умолчанию

Список шифров по умолчанию, используемых PHP, был обновлён на более безопасный в соответствии с » рекомендациями по шифрам от Mozilla, с двумя дополнительными исключениями: анонимные шифры Диффи-Хеллмана и RC4.

Этот список доступен через новую константу OPENSSL_DEFAULT_STREAM_CIPHERS , и может быть переопределён (как и в предыдущих версиях PHP) установкой опцией контекста ciphers .

Сжатие запрещено по умолчанию

Сжатие SSL/TLS было запрещено по умолчанию для compression уменьшения вероятности атаки типа CRIME. В PHP 5.4.13 была добавлена опция контекста disable_compression для возможности запретить компрессию и теперь она по умолчанию установлена как true (то есть компрессия запрещена).

Разрешение серверу определять свой собственный порядок шифров

Была добавлена опция контекста honor_cipher_order , которая позволяет серверу обслуживающему зашифрованный поток самому определять шифры, которыми будет пользоваться клиент. Это позволить снизить риск атаки типа BEAST.

Доступ к согласованному протоколу и шифру

Протокол и шифр, согласованные для шифрованного потока, доступны с помощью функций stream_get_meta_data() или stream_context_get_options() , если опция контекста SSL capture_session_meta установлена как true .

= stream_context_create ([ ‘ssl’ => [
‘capture_session_meta’ => TRUE
]]);

$html = file_get_contents ( ‘https://google.com/’ , FALSE , $ctx );
$meta = stream_context_get_options ( $ctx )[ ‘ssl’ ][ ‘session_meta’ ];
var_dump ( $meta );
?>

Результат выполнения данного примера:

Новые возможности для совершенной прямой секретности (PFS) для серверов, обслуживающих шифрованные потоки

Шифрованные потоки клиента уже поддерживают совершенную прямую секретность, поскольку она, как правило, контролируется сервером. Серверы PHP, обслуживающие шифрованные потоки, использующие сертификаты поддерживающие совершенную прямую секретность не нуждаются в каких либо дополнительных действиях для включения PFS; однако, было добавлено некоторое количество новых опций контекста SSL для более точного контроля над PFS и для решения возможных проблем.

Эта опция позволяет выбрать кривую для использования в шифрах ECDH. Если не задано, то будет использоваться prime256v1 .

Путь к файлу, содержащему параметры для обмена ключами Диффи-Хеллмана, созданного, например, с помощью такой команды:

Если установлено как true , новая пара ключей будет создана, используя параметры Диффи-Хеллмана, тем самым улучшая прямую секретность.

Если установлено как true , новая пара ключей будет генерироваться всегда, при согласовании шифра ECDH. Это улучшает прямую секретность.

Выбор версии SSL/TLS

Теперь возможно выбирать конкретную версию SSL и TLS с помощью опции контекста crypto_method или указывая конкретный транспорт при создании обёртки потока (например с помощью вызова stream_socket_client() или stream_socket_server() ).

Опция контекста SSL crypto_method принимает битовую маску, перечисляющую допустимые протоколы, также как это задаётся в параметре crypto_type функции stream_socket_enable_crypto() .

Выбранная версия протокола и соответствующие опции

Протокол Флаг клиента Флаг сервера Транспорт
Любые версии TLS или SSL STREAM_CRYPTO_METHOD_ANY_CLIENT STREAM_CRYPTO_METHOD_ANY_SERVER ssl://
Любая версия TLS STREAM_CRYPTO_METHOD_TLS_CLIENT STREAM_CRYPTO_METHOD_TLS_SERVER tls://
TLS 1.0 STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT STREAM_CRYPTO_METHOD_TLSv1_0_SERVER tlsv1.0://
TLS 1.1 STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT STREAM_CRYPTO_METHOD_TLSv1_1_SERVER tlsv1.1://
TLS 1.2 STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT STREAM_CRYPTO_METHOD_TLSv1_2_SERVER tlsv1.2://
SSL 3 STREAM_CRYPTO_METHOD_SSLv3_CLIENT STREAM_CRYPTO_METHOD_SSLv3_SERVER sslv3://

// Требуется TLS 1.0 или выше для использования file_get_contents():
$ctx = stream_context_create ([
‘ssl’ => [
‘crypto_method’ => STREAM_CRYPTO_METHOD_TLS_CLIENT ,
],
]);
$html = file_get_contents ( ‘https://google.com/’ , false , $ctx );

// Требуется TLS 1.1 или 1.2:
$ctx = stream_context_create ([
‘ssl’ => [
‘crypto_method’ => STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT |
STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT ,
],
]);
$html = file_get_contents ( ‘https://google.com/’ , false , $ctx );

// Соединяемся с использованием транспорта потокового сокета tlsv1.2://
$sock = stream_socket_client ( ‘tlsv1.2://google.com:443/’ );

Добавлена функция openssl_get_cert_locations()

Была добавлена функция openssl_get_cert_locations() : она возвращает расположения, в которых PHP будет искать пакеты CA по умолчанию.

Php windows with openssl

Для поддержки OpenSSL в PHP вам необходимо скомпилировать его с опцией —with-openssl[=DIR].

Также библиотека OpenSSL имеет дополнительные требования для нормальной работы во время исполнения. Самое главное, OpenSSL требуется доступ к генераторам случайных и псевдослучайных чисел; на большинстве систем Unix/Linux, это означает доступ к устройствам /dev/urandom или /dev/random .

Начиная с PHP 5.6.3, доступна опция конфигурации —with-system-ciphers, которая заставляет PHP использовать системный список шифров вместо жёстко заданного по умолчанию.

Замечание: Замечания для пользователей Win32

Для работы этого расширения системной переменной Windows PATH должны быть доступны DLL -файлы. Чтобы узнать как этого достичь, обратитесь к разделу FAQ «Как добавить мою директорию с PHP в переменную Windows PATH». Хотя копирование DLL-файлов из директории PHP в системную папку Windows также решает проблему (потому что системная директория по умолчанию находится в переменной PATH ), это не рекомендуется. Этому расширению требуются следующие файлы в переменной PATH : libeay32.dll , либо, начиная с OpenSSL 1.1, libcrypto-*.dll .

Дополнительно, если вы собираетесь использовать функции генерации ключей и подписи сертификатов, вам придётся установить корректный файл openssl.cnf в вашей системе. Мы включили демонстрационный конфигурационный файл в бинарную поставку под win32. Он лежит в директории extras/openssl .

PHP будет искать openssl.cnf , используя следующую логику:

  • Переменная окружения OPENSSL_CONF . Если установлена, то должна содержать путь (включая имя файла) до конфигурационного файла.
  • переменная окружения SSLEAY_CONF . Если установлена, то должна содержать путь (включая имя файла) до конфигурационного файла.
  • Файл openssl.cnf будет искаться по стандартному пути для сертификатов, заданному при компиляции DLL. Обычно он задан как C:\Program Files\Common Files\SSL\openssl.cnf (x64) или C:\Program Files (x86)\Common Files\SSL\openssl.cnf (x86), или до PHP 7.4.0, как C:\usr\local\ssl\openssl.cnf .

При установке вы должны определить, установить ли файл по стандартному пути или хранить его в другом месте и задать путь к нему через переменные окружения, что полезно при использовании виртуальных хостов. Обратите внимание, что путь по умолчанию можно переопределить в скрипте используя параметр options функции, которой требуется этот файл.

Убедитесь, что непривилегированным пользователям не разрешено изменять openssl.cnf .

Список изменений

Версия Описание
7.4.0 Конфигурационный путь OpenSSL был изменён с C:\usr\local\ssl на C:\Program Files\Common Files\SSL или C:\Program Files (x86)\Common Files\SSL , соответственно.

User Contributed Notes 8 notes

Having recently installed Apache2.2 with PHP 5.2.17 on my Windows 7 development machine, I want to pass along my findings about how to set things up to load the correct versions of the OpenSSL DLLs. Many people have posted elsewhere about the «DLL Hell» that results if the a wrong version is loaded.

First, install Apache 2.2 and check its operation, then download the Windows binaries for PHP from http://windows.php.net/download/. Note that according to the sidebar on that page the recommended version of PHP for use with Apache2 is currently 5.2.17, even though it is back level. Plus, this version comes with all the DLLs you need to use OpenSSL — no need to recompile as the old PHP man page suggests.

Having verified the PHP installation, turn on the OpenSSL support by uncommenting the line

in php.ini, which you will find in the PHP directory (I’ll assume you made that c:/PHP). Next check the location of php_openssl.dll, which you should find in c:/PHP/ext. Also in php.ini find the key extension_dir, and change its value to c:/php/ext. Next, put this location on the end of your PATH (there’s no need to reboot).

At this point, when you start Apache it will attempt to load php_openssl.dll, but if your setup is anything like mine you will see an error. I prefer to start Apache manually, and the error appears in a dialog box: «The ordinal 4114 could not be located in the dynamic link library LIBEAY32.dll». (I’m not sure whether you would get this message if you started Apache as a service). The Apache log also contains an error message saying that php_openssl.dll cannot be loaded, though that message doesn’t name libeay32.dll. Welcome to DLL Hell.

Libeay32.dll enters the picture because php_openssl.dll depends on it (and also on ssleay32.dll). What I think happens is that Apache first tries to load php_openssl.dll programmatically from the path specified by the extension_dir key. But then, the loading of the so-called dependent DLLs is left to Windows’ default mechanism. If Windows finds an incompatible version of a dependent DLL, you get the error.

So clearly the fix is to ensure that the correct version of libeay32.dll is loaded. On my machine, at least three other processes have loaded various versions of this same DLL. They include the Mozy backup client, Windows Explorer (because Mozy installs support in Explorer) and the OpenOffice suite. My machine is quite different in this respect from a dedicated server on which one probably wants as few extraneous processes as possible. Presumably on a server one can follow advice that suggests copying the dlls to the system32 directory, for example. But I’m not about to mess with my other programs by making system-wide changes.

So what to do? I didn’t find the available information on how Windows searches for DLLs to be very useful, mainly because I didn’t understand it. But it does say that the first place Windows looks is «The directory from which the application loaded.»

To cut to the chase, after a lot of experimentation I came to a key realization — «the application» is APACHE, not PHP. So I copied libeay32.dll to the Apache2.2/bin directory. Problem solved. No error messages and running phpinfo confirms that OpenSSL is present and enabled.

OpenSSL

User Contributed Notes 3 notes

I was having a heck of a time finding help on making asynchronous encryption/decryption using private key/public key systems working, and I had to have it for creating a credit card module that uses recurring billing.

You’d be a fool to use normal, ‘synchronous’ or two-way encryption for this, so the whole mcrypt library won’t help.

But, it turns out OpenSSL is extremely easy to use. yet it is so sparsely documented that it seems it would be incredibly hard.

So I share my day of hacking with you — I hope you find it helpful!

if (isset( $_SERVER [ ‘HTTPS’ ]) )
<
echo «SECURE: This page is being accessed through a secure connection.

» ;
>
else
<
echo «UNSECURE: This page is being access through an unsecure connection.

// Create the keypair
$res = openssl_pkey_new ();

// Get private key
openssl_pkey_export ( $res , $privatekey );

// Get public key
$publickey = openssl_pkey_get_details ( $res );
$publickey = $publickey [ «key» ];

echo «Private Key:
$privatekey

Public Key:
$publickey

$cleartext = ‘1234 5678 9012 3456’ ;

echo «Clear text:
$cleartext

openssl_public_encrypt ( $cleartext , $crypttext , $publickey );

echo «Crypt text:
$crypttext

openssl_private_decrypt ( $crypttext , $decrypted , $privatekey );

echo «Decrypted text:
$decrypted

» ;
?>

Many thanks to other contributors in the docs for making this less painful.

Note that you will want to use these sorts of functions to generate a key ONCE — save your privatekey offline for decryption, and put your public key in your scripts/configuration file. If your data is compromised you don’t care about the encrypted stuff or the public key, it’s only the private key and cleartext that really matter.

For checking the status of a client certificate using OCSP, you can use this script:

// User variables:
$dir = ‘/path/to/temp/’ ; // Directory where apache has access to (chmod 777).
$RootCA = ‘/path/to/Root.cer’ ; // Points to the Root CA in PEM format.
$OCSPUrl = ‘http://ocsp.url’ ; //Points to the OCSP URL
// Script:
$a = rand ( 1000 , 99999 ); // Needed if you expect more page clicks in one second!
file_put_contents ( $dir . $a . ‘cert_i.pem’ , $_SERVER [ ‘SSL_CLIENT_CERT_CHAIN_0’ ]); // Issuer certificate.
file_put_contents ( $dir . $a . ‘cert_c.pem’ , $_SERVER [ ‘SSL_CLIENT_CERT’ ]); // Client (authentication) certificate.
$output = shell_exec ( ‘openssl ocsp -CAfile ‘ . $RootCA . ‘ -issuer ‘ . $dir . $a . ‘cert_i.pem -cert ‘ . $dir . $a . ‘cert_c.pem -url ‘ . $OCSPUrl );
$output2 = preg_split ( ‘/[\r\n]/’ , $output );
$output3 = preg_split ( ‘/: /’ , $output2 [ 0 ]);
$ocsp = $output3 [ 1 ];
echo «OCSP status: » . $ocsp ; // will be «good», «revoked», or «unknown»
unlink ( $dir . $a . ‘cert_i.pem’ );
unlink ( $dir . $a . ‘cert_c.pem’ );
?>

It can be ameliorated, but it’s just a beginning!

Normally, you can extract the ocsp url from the client certificate. Also, an OCSP request contains only the hash of the issuer name, the hash of the issuer’s key, and the serial number of the client certificate. All three can be extracted directly from the client certificate.

In regards to the comment above:

«After generating a key pair with OpenSSL, the public key can be stored in plain text format. I then encrypted the private key itself using regular mcrypt with the human-memorizable key of my choice and converted it to ACSII using base64_encode. Then to get the private key back, I just decrypted it with mcrypt. This way I could store the encrypted private key on the server without worrying about having things stored unencrypted. «

To anyone reading this that might not be all that familiar with public key cryptography; I haven’t the slightest idea what this person is talking about, but I can tell you its an absolutely horrible idea. He might have ended up with something that «looked like a private key» insofar as it was a base64 encoded string, but he did not have a private key. The parameters that make up a public/private key pair are EXTREMELY specific and in the case of RSA rely on very large co-primes plus an even larger moduli. Its not just a base64 encoded string; and just for the record. base64 encoding is not encryption.

One of two things happened; the more likely is the whatever program he needed the certificate for realized there was something wrong with the private key, and ignored it, reverting to either a default key, or null encryption or something. The worse outcome would be if it interpreted whatever was there as legitimate; and encrypted data as if it were a a proper certificate; encrypting this way would likely provide close to zero security and I’m not even sure you could decrypt the data once encrypted. Its not worth giving much thought.

Just please; don’t do this.

You can read about pki certificate structures and attribute frameworks by pasting «T-REC-X.509-201210-I» into your favorite interwebs search widget and following the result to the International Telecommunications Union webpage, or you can refer to the numerous RFCs; 6818, 5820 being good places to start. The Internet Engineering Task Force archives all RFCs, but there are other sources as well. «IETF RFC» should be enough to get you there.

. sorry, the «spam buster» was giving me all kinds of issues.

Читайте также:  Hklm software microsoft windows те currentversion productname
Оцените статью