Unable to set local cert chain file - php

I have trouble with establishing a SSL connection.
These warnings are displayed:
Warning: stream_socket_client() [function.stream-socket-client]: Unable to set local cert chain file `D:\path\cert.pem'; Check that your cafile/capath settings include details of your certificate and its issuer in D:\path\testSll.php on line 23
Warning: stream_socket_client() [function.stream-socket-client]: failed to create an SSL handle in D:\path\testSll.php on line 23
Warning: stream_socket_client() [function.stream-socket-client]: Failed to enable crypto in D:\path\testSll.php on line 23
Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://host.tld:700 (Unknown error) in D:\path\testSll.php on line 23
So I read all the question about the "Unable to set local cert chain file", but all the answer I found didn't work for me.
Here is the code I use :
$host = 'host.tld';
$port = 700;
$cert = dirname(__FILE__).'\\cert.pem'; //
$passe_phrase = 'pass';
$opts = array(
'ssl'=>array(
'local_cert' => $cert,
'passphrase' => $passe_phrase,
'verify_peer' => false
)
);
$context = stream_context_create($opts);
$fp = stream_socket_client('ssl://'.$host.':'.$port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
if ($fp) {
echo "OK";
} else {
echo "ERROR: $errno - $errstr<br />\n";
}
The certificate is the good one.
The script can access to the file cert.pem.
I cant find what I am missing here.
PHP version : 5.2.6

You should look at include details of your certificate and its issuer. In my case I accidentally deleted header of a file. When I return it back, the script is connecting successfully.
Before:
-----BEGIN CERTIFICATE-----
MIIFCBG+gAwIBAg...
After
Bag Attributes
friendlyName: ...
localKeyID: ...
subject=...
issuer=/C=US/... CN=Apple Worldwide Developer Relations Certification Authority
-----BEGIN CERTIFICATE-----
MIIFCBG+gAwIBAg...

Related

Sending Apple Push Notification via PHP: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out)

I have the following PHP code to send Apple Push Notifications to my app:
<?php
$body = '{"aps":{"alert":{"title":"test title","subtitle":"","body":"test body"},"badge":0,"sound":"default","additional_data":"test additional_data"}}';
$context = stream_context_create();
stream_context_set_option($context, "ssl", "local_cert", "certificate.pem");
stream_context_set_option($context, "ssl", "passphrase", "HERE_COMES_THE_PASSWORD_OF_THE_certificate.pem_FILE");
$socket = stream_socket_client("ssl://gateway.sandbox.push.apple.com:2195", $error, $errstr, 30, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $context);
$msg = chr(0) . chr(0) . chr(32) . pack("H*", "HERE_COMES_MY_APPLE_PUSH_TOKEN") . pack("n", strlen($body)) . $body;
$result = fwrite($socket, $msg, strlen($msg));
fclose($socket);
?>
This code is stored on my server together with the certificate file called certificate.pem.
I'm using this code unchanged since month without any problems. Today, I noticed, that I'm not getting push notifications any more.
The PHP error log shows the following:
[23-Mar-2022 11:39:45 UTC] PHP Warning: stream_socket_client(): unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out) in /home2/kd37875/public_html/test/index.php on line 7
[23-Mar-2022 11:39:45 UTC] PHP Warning: fwrite() expects parameter 1 to be resource, bool given in /home2/kd37875/public_html/test/index.php on line 9
[23-Mar-2022 11:39:45 UTC] PHP Warning: fclose() expects parameter 1 to be resource, bool given in /home2/kd37875/public_html/test/index.php on line 10
First, I thought, there's something wrong with the certificate file. Then, I found this: https://www.pushtry.com website. If I insert the Device Token, upload the certificate.pem file, insert the Bundle ID and a message, I'm successfully receiving a push message in my app. (There's a field for password on the website but it's also working if I don't insert it. No idea, why.) So this says me, that the certificate.pem must be okay.
Do you have any idea what I'm doing wrong? Why doesn't it work any more? Did Apple change something?
I finally solved my problem. Apple made a change to this about a year ago. No idea why it affected me only today.
This is the working code:
<?php
function sendHTTP2Push($http2_server, $apple_cert, $app_bundle_id, $message, $token) {
if(!defined('CURL_HTTP_VERSION_2_0')) {
define('CURL_HTTP_VERSION_2_0', 3);
}
$http2ch = curl_init();
curl_setopt($http2ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_setopt_array($http2ch, array(
CURLOPT_URL => "{$http2_server}/3/device/{$token}",
CURLOPT_PORT => 443,
CURLOPT_HTTPHEADER => array("apns-topic: {$app_bundle_id}"),
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $message,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSLCERT => realpath($apple_cert),
CURLOPT_HEADER => 1
));
$result = curl_exec($http2ch);
if($result === FALSE) {
throw new Exception('Curl failed with error: ' . curl_error($http2ch));
}
$status = curl_getinfo($http2ch, CURLINFO_HTTP_CODE);
return $status;
curl_close($http2ch);
}
$status = sendHTTP2Push('https://api.development.push.apple.com', 'certificate.pem', 'HERE_COMES_THE_APPS_BUNDLE_ID', '{"aps":{"alert":{"title":"test title","subtitle":"","body":"test body"},"badge":0,"sound":"default","additional_data":"test additional_data"}}', 'HERE_COMES_MY_APPLE_PUSH_TOKEN');
echo "Response code: ".$status;
?>
Source: https://gist.github.com/valfer/18e1052bd4b160fed86e6cbb426bb9fc

PHP stream_socket_client(): unable to connect to https

I've just noticed the new vulnerability discovered in Wordpress and I'm trying to fix it with the following code (but with any success
<?php
$url = 'https://mywebip/wp-login.php?action=lostpassword';
$data = 'user_login=admin&redirect_to=&wp-submit=Get+New+Password';
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Host: mailserver\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: ". strlen($data) ."\r\n",
'method' => 'POST',
'content' => $data,
'ssl'=>array('verify_peer'=>true, 'capath'=>'/etc/ssl/certs')
)
);
$context = stream_context_create($options);
//$result = file_get_contents($url, false, $context);
$fp = stream_socket_client($url, $errno, $errstr, 30);
//stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
$fp = fopen($url, 'r', false, $context);
if ($fp === FALSE) { /* Handle error */ }
var_dump($result);
?>
The error log I got is just like this:
PHP Warning: stream_socket_client(): unable to connect to https://mywebip/wp-login.php?action=lostpassword (Unable to find the socket transport "https" - did you forget to enable it when you configured PHP?) in /home/jorge/Escritorio/joomla.php on line 18
PHP Warning: fopen(): Peer certificate CN=`website` did not match expected CN=`mywebip' in /home/jorge/Escritorio/joomla.php on line 21
PHP Warning: fopen(): Failed to enable crypto in /home/jorge/Escritorio/joomla.php on line 21
PHP Warning: fopen(https://mywebip/wp-login.php?action=lostpassword): failed to open stream: operation failed in /home/jorge/Escritorio/joomla.php on line 21
Where mywebip represents the actual ip that hosts my website and website and mailserver the DNS directions of the services.
Thank you.
Via socket you do not specify a protocol.
http://php.net/stream_socket_client
First parameter:
remote_socket
Address to the socket to connect to.
Adress is only mywebip.
You should use CURL instead.
See http://php.net/manual/en/curl.examples.php
The other problem (with fopen(), which can handle streams with protocols!) is a malformed/wrong certificate issued by your webserver.
Use this service to debug problems with your webservers certificate:
https://www.ssllabs.com/ssltest/

Google reCaptcha with php validation

i'm trying to use reCaptcha v2.0 with php, in the server verification i use this code:
if(isset($_POST['Direccion_Email']) AND ($_POST['enviar'])) {
if(isset($_POST['g-recaptcha-response'])){
$mensaje_error = "";
include 'config-formulario.php';
require_once __DIR__ . '/recaptcha-master/src/autoload.php';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$mensaje_error .= "Control Anti SPAM no es vĂ¡lido <br />";
$errors = $resp->getErrorCodes();
} else {
//DO SOMETHING;
}
But when i try to send a simple contact me form with name, email and comments, it's return this warnings:
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 /home/diego/www/systec/scripts/recaptcha-master/src/ReCaptcha/RequestMethod/Post.php on line 68
Warning: file_get_contents(): Failed to enable crypto in /home/diego/www/systec/scripts/recaptcha-master/src/ReCaptcha/RequestMethod/Post.php on line 68
Warning: file_get_contents(https://www.google.com/recaptcha/api/siteverify): failed to open stream: operation failed in /home/diego/www/systec/scripts/recaptcha-master/src/ReCaptcha/RequestMethod/Post.php on line 68
I'm testing this on localhost.
Any suggestions.
Thanks.
Change
$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
To
$ch = curl_init("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$verify = curl_exec($ch);
The answer from #jww works form me:
For step (1), see How do you sign Certificate Signing Request with your Certification Authority?. For (2), see How to create a self-signed certificate with openssl?. The latter also shows you how to create a signing request (as opposed to a self signed certificate). They are the same steps - the only thing that differs is the lack of the -x509 option for a signing request.

PHP: sending apns inside socket server does not work?

This week i experimented with php sockets but there is one thing that does not appear to work.
I want to send a Apple push notification (apns) from within a socket server. The socket server works fine but opening another socket to send a message to apns does not work.
The server socket script i use is similar to the example of php.net. (http://www.php.net/manual/en/sockets.examples.php) The script i use to send a apns notification is the following function:
function sendToAPNS($data, $deviceTokens, $pem, $password, $debug=0)
{
$server = ($debug == 1) ? 'gateway.sandbox.push.apple.com' : 'gateway.push.apple.com';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', '/home/testing/pushNotifications/'.$pem);
stream_context_set_option($ctx, 'ssl', 'passphrase', $password);
$fp = stream_socket_client('ssl://'. $server .':2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
{
echo 'APNS error:'. $err .' '. $errstr ."\n";
return;
}
$body['aps'] = array('alert' => $data['message']);
foreach($data AS $key => $value)
{
if($key != 'message') $body['aps'][$key] = $value;
}
$payload = json_encode($body);
for($i = 0,$max=count($deviceTokens); $i < $max; $i++)
{
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceTokens[$i]) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
BPLog('Message['. $data['ID'] .'] not delivered to '. $deviceTokens[$i] .': '. PHP_EOL);
// ob_flush();
// flush();
}
fclose($fp);
return true;
}
The following warnings are displayed:
PHP Warning: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
error:14094410:SSL routines:func(148):reason(1040) in /home/testing/pushNotifications/index.php on line 162
Warning: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
error:14094410:SSL routines:func(148):reason(1040) in /home/testing/pushNotifications/index.php on line 162
PHP Warning: stream_socket_client(): Failed to enable crypto in /home/testing/pushNotifications/index.php on line 162
Warning: stream_socket_client(): Failed to enable crypto in /home/testing/pushNotifications/index.php on line 162
PHP Warning: stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195 (Unknown error) in /home/testing/pushNotifications/index.php on line 162
Warning: stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195 (Unknown error) in /home/testing/pushNotifications/index.php on line 162
The function works in an other environment though. I have tested it in a php file that can be called from the browser and it sends like it should. I use absolute paths for the certificates so that could not be the problem.
Maybe there is a difference in php since the socket server is called from the commandline. Or maybe it simply is not possible to open another socket stream from within a socket server?
Does anyone have an idea of what the problem can be?

Getting errors using APNS PHP

Here's the code I'm using
<?php
$deviceToken = 'my device key'; // not putting in for security
$payload['aps'] = array('alert' => 'This is the alert text', 'badge' => 1, 'sound' => 'default');
$payload = json_encode($payload);
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apns-dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
socket_close($apns);
fclose($apns);
?>
and I get these errors
Warning: stream_socket_client() [function.stream-socket-client]: Unable to set private key file `apns-dev.pem' in /home/bryan/sendpush.php on line 14
Warning: stream_socket_client() [function.stream-socket-client]: failed to create an SSL handle in /home/bryan/sendpush.php on line 14
Warning: stream_socket_client() [function.stream-socket-client]: Failed to enable crypto in /home/bryan/sendpush.php on line 14
Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error) in /home/bryan/sendpush.php on line 14
Warning: fwrite(): supplied argument is not a valid stream resource in /home/bryan/sendpush.php on line 17
Warning: socket_close() expects parameter 1 to be resource, boolean given in /home/bryan/sendpush.php on line 19
Warning: fclose(): supplied argument is not a valid stream resource in /home/bryan/sendpush.php on line 20
I actually now got it down to these errors
Warning: stream_socket_client() [function.stream-socket-client]: SSL operation failed with code 1. OpenSSL Error messages: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure in /home/bryan/PushService.php on line 27
Warning: stream_socket_client() [function.stream-socket-client]: Failed to enable crypto in /home/bryan/PushService.php on line 27
Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error) in /home/bryan/PushService.php on line
Use the absolute path for the private key instead of relative path.
Make sure the php user (or webserver user, depending.. www-data, apache, nginx, www...) is allowed to read it (chown, chmod).
I was getting this error also. found out that I had set up the permission wrong on the folder that had the certificate file. This worked for me:
chmod 755 your_folder_that_has_certificate_files

Categories