Warning: stream_socket_enable_crypto(): SSL operation failed with code 1 - php

I have a problem with CSCart, it fails sending mail via google account.
To check if there is a problem in server config or in CSCart's scripts I installed clean library PHPMailer and tried to send test message using example script.
Result is the same:
Warning: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in [script path]/class.smtp.php on line 338
OpenSSL connection from console works good.
FreeBSD 10.0, Apache24, php5.6.
I could not find any information in google and for now I even do not know in which config file to search the issue root.

This is due to the new verify-by-default policy in PHP 5.6. It's not set in php.ini; it's an option you an provide to fopen wrappers or stream contexts. Have a look at the options here, especially verify_peer. PHPMailer allows you to set these params during the smtpConnect() method, but there is no option to pass options into the smtpSend() method, so you will need to subclass PHPMailer to get at that.
You may find the alternative simpler - don't try to use a self-signed or unverifiable certificate.

There is a lot of configs that makes this error come up, but more often it is that your system's configuration is not set up properly. To do it correctly, follow this:
Check if you have cacert.pem file for OPENSSL or not. If you don't, download proper version from of cacert.pem according to your php version and config your php.ini file as "2"
If you have this file then you have to lookup inside of your php.ini file and see if it has been set in it or not. To do so: lookup for line:
openssl.cafile ="example address..\cacert.pem"
If you find the line with an specific address, look for cacert.pem file in that address, if you find it, than it is all done with cacert.pem file. Else, you should use the correct address.

in laRAVEL 5.4 ERROR
C:\xampp\htdocs\itis_db\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php
and find out this function inside StreamBuffer.php
private function _establishSocketConnection()
and paste this two lines inside of this function
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
and reload your browser and try to run your project again. For me I put on like this:
private function _establishSocketConnection()
{
$host = $this->_params['host'];
if (!empty($this->_params['protocol'])) {
$host = $this->_params['protocol'].'://'.$host;
}
$timeout = 15;
if (!empty($this->_params['timeout'])) {
$timeout = $this->_params['timeout'];
}
$options = array();
if (!empty($this->_params['sourceIp'])) {
$options['socket']['bindto'] = $this->_params['sourceIp'].':0';
}
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
$this->_stream = #stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options));
if (false === $this->_stream) {
throw new Swift_TransportException(
'Connection could not be established with host '.$this->_params['host'].
' ['.$errstr.' #'.$errno.']'
);
}
if (!empty($this->_params['blocking'])) {
stream_set_blocking($this->_stream, 1);
} else {
stream_set_blocking($this->_stream, 0);
}
stream_set_timeout($this->_stream, $timeout);
$this->_in = &$this->_stream;
$this->_out = &$this->_stream;
}
Hope you will solve this problem.....

Related

Trying to connect SSL server using fsockopen()

I'm running the next script from my local host and the production server, and Im getting different outputs. Anyone knows why am I getting that false from my localhost?
<?php
$host = 'ssl://mail.companyname.org';
$port = 993;
$error = 0;
$errorString = "";
var_dump(fsockopen($host, $port, $error, $errorString, 30));
var_dump($errorString);
var_dump($error);
Local host output:
bool(false)
Production server output:
resource(4) of type (stream)
UPDATE: after the comments/answer I have modified the code and now Im getting this output on my local host:
PHP Warning: fsockopen(): SSL operation failed with code 1. OpenSSL
Error messages: error:1416F086:SSL
routines:tls_process_server_certificate:certificate verify failed in
/tmp/test.php on line 7 PHP Warning: fsockopen(): Failed to enable
crypto in /tmp/test.php on line 7 PHP Warning: fsockopen(): unable to
connect to ssl://mail.twmdata.org:993 (Unknown error) in /tmp/test.php
on line 7 bool(false) string(0) "" int(0)
it seems this is problem with server certificate :
first you can check if your server certificate and its chains are valid by this:
https://www.sslshopper.com/ssl-checker.htm
if somethings were wrong in ssl-checker?
you can try to correct SSL certificate configs in companyname.org
if you succeed and error was persists ?
you have to add Certificate files manually.
if you have a self-signed certificate:
you have to add Certificate files manually.
if you dont have certificate nor you dont care about man-in-the-middle attack,
you can still use SSL without Certificate.
turn off php fsock Certificate check (not recommended)
its recommended to have a certificate at least a self-signed. if you have a self-signed try 1 solution.
I have found the Problem
You have exposed your Domain name in your PHP Warning Log, so i have checked your domain SSL.
after i check your company`s domain certificate using this tool:
https://www.sslshopper.com/ssl-checker.html#hostname=twmdata.org
it had 2 errors with your certificates:
This certificate has expired (0 days ago). Renew now.
None of the common names in the certificate match the name that was entered (twmdata.org). You may receive an error when accessing this site in a web browser.
so it seems you have to renew your certificate first
Update:
i have found this answer maybe helpful
https://stackoverflow.com/a/40962061/9287628
it suggested to use
stream_context_create(['ssl' => [
'ciphers' => 'RC4-MD5'
]])
as #ChrisHaas suggested connecting with stream_context_create and stream_socket_client brings you a lot of option if you want to dictate the cert directory or you want to turn off certificate check.
Per the documentation for fsockopen
The function stream_socket_client() is similar but provides a richer set of options, including non-blocking connection and the ability to provide a stream context.
Basically, fsockopen is very low-level but without many options, or, arguably, "sane defaults".
Instead, you can switch to stream_socket_client which will allow you to specify a context as the last parameter, and that object has many options, including a dedicated one with over a dozen options specific to SSL. The object created from this function is compatible with fwrite and other functions, so it should do everything you are hoping for.
$context = stream_context_create([/*Options here*/]);
$connection = stream_socket_client($host, $errno, $errorString, 30, null, $context);
Now, what options should you use?
The worst option that might work is probably verify_peer. I say "worst" because you are throwing away the verifiability part of SSL/TLS and only using it for encryption, and doing this will make you susceptible to MitM attacks. However, there's a place and time for this, so you could try it if the other options are too complicated.
$context = stream_context_create(['ssl' => ['verify_peer' => false]]);
$connection = stream_socket_client($host, $errno, $errorString, 30, null, $context);
Instead, I'd recommend using either cafile or capath which do the same thing except the former is for a file while the latter is for a directory.
$context = stream_context_create(['ssl' => ['verify_peer' => true, 'cafile' => '/path/to/file']]);
$connection = stream_socket_client($host, $errno, $errorString, 30, null, $context);
What certs should you use? We use this library to pull in recent CA files on a periodic basis, very convenient. There's a little bit of setup that's per-project but once you get it it goes pretty fast. See this for pulling in a CA file at a well-known location.
One other last option is local_cert which you can use with a PEM file that holds the certificate and private key from the server, if you have access to that.
EDIT
The cert on mail.twmdata.org:993 is different than the web server's cert that other people are talking about, which is generally a best practice. You can inspect that cert using:
openssl s_client -connect mail.twmdata.org:993 -servername mail.twmdata.org
If you do that, you'll see that the server has a self-signed cert which you can get around by setting the verify_peer option to false.
Remove the # symbol. You are hiding error messages that might tell you what the problem is. You should also set a variable in the errorno argument to fsockopen() and echo it for debugging.
My guess would be that you haven't installed PHP with SSL support on your local server. See here.
Companyname.org might also block requests from your local server that are allowed from the production server.

PHP Warning: stream_socket_enable_crypto(): SSL operation failed with code 1

I am getting the following warning when trying to configure and send mail using PHPMailer:
PHP Warning: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:
error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed
I have looked around at the other solutions, and none of them work. Here are some particulars:
My cert (from letsencrypt) is valid, at least in my Nginx config. My WordPress site serves securely with no errors. My PHP version is 7.0.xx
I have tried adding the cert file location to php.ini, but it warns of a failure to load stream, even though the address is correct. Here is what I have tried (among others):
openssl.capath = "/etc/letsencrypt/live/example.org/" This results in
exactly the same error as above.
I have also tried:
openssl.cafile = "/etc/letsencrypt/live/example.org/fullchain.pem" but get warning: PHP Warning:failed loading cafile stream
My PHP mailer config (that is inside my wordpress functions file) looks like this:
$phpmailer->Host = 'mail.example.org';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 587;
$phpmailer->Username = 'myadminaccount#example.org';
$phpmailer->Password = 'mypassword';
$phpmailer->SMTPSecure = "tls";
$phpmailer->From = "myadminaccount#example.org";
$phpmailer->FromName = "MY Admin Account";
As I said, I have tried the various solutions elsewhere on the site, and none of them work. And I am baffled because my local cert (and the cert of the mail server for that matter) are both valid.
I don't really want to turn off peer verification as suggested elsewhere, but if I have to I guess I will.
UGH the solution was rather simple, and outside of what I wrote above. I was using a switch case to check to make sure my server was correct, like so:
switch ($_SERVER['HTTP_HOST']) {
case 'https://example1.org':
// Set the hostname of the mail server
$phpmailer->Host = 'mail.example1.org';
And I needed to leave out the https. So changing it to:
switch ($_SERVER['HTTP_HOST']) {
case 'example1.org':
// Set the hostname of the mail server
$phpmailer->Host = 'mail.example1.org';
got it working! I feel like a bonehead, but I hope this helps someone else.

SwiftMailer not working, connection could not be established [#0]

I'm trying to set up a mailer script using Silex and SwiftMailer. However, I haven't managed to get the mail sent so far. When setting swiftmailer.use_spool to false, I don't get errors but don't receive emails either. When instead flushing the spool transport queue like this...
if ($app['mailer.initialized']) {
$app['swiftmailer.spooltransport']
->getSpool()
->flushQueue($app['swiftmailer.transport']);
}
...I get the following exception:
Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host abc.xyz [ #0]'
I haven't found any documentation for this exception so far. I'm sure all SMTP settings and credentials are valid (I also tried another host, same problem). I can also ping the host and the port I use is open, and php_openssl is enabled.
It looks like it's failing on Swift\Transport\StreamBuffer.php:269 because stream_socket_client returns 0:
$this->_stream = #stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext);
if (false === $this->_stream) {
throw new Swift_TransportException(
'Connection could not be established with host '.$this->_params['host'].
' ['.$errstr.' #'.$errno.']'
);
}
Update #1
I forgot to have a look at the error log, now I see it says:
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php5/20121212/php_openssl.dll' - /usr/lib/php5/20121212/php_openssl.dll: cannot open shared object file: No such file or directory in Unknown on line 0
So it seems PHP fails to load the php_openssl extension, although phpinfo() says the module is enabled? Where should it be located, or how should I get it?
Update #2
I believe I may have mistakenly tried to enable the php_openssl.dll extension while it's meant for Windows environments. When I remove it, the error is obviously gone from the error log, but the main issue persists. Back to square one..
What could I be doing wrong?

socket connection fails in php script while it works in terminal

That is the script I have
<?php
$timeout = 10;
$target = "tls://testbed-epp.nominet.org.uk:700";
$result = stream_socket_client($target, $errno, $errstr, 30, STREAM_CLIENT_CONNECT);
if ($result === False) {
throw new Exception("Error connecting to $target: $errstr (code $errno)");
}
echo "Connected";
And it throws an exception
Error connecting to tls://testbed-epp.nominet.org.uk:700: (code 0)
There is also a warning
WARNING: stream_socket_client(): Failed to enable crypto
At the same time running
openssl s_client -connect testbed-epp.nominet.org.uk:700
in a terminal connects flawlessly.
Any ideas will be appreciated
Try this instead:
$result = stream_socket_client("testbed-epp.nominet.org.uk:700", $errno, $errstr);
EDIT: also you can setup secure connection via stream_socket_enable_crypto() function, but you should note that it must be used AFTER initialization of socket connection.
Well, i tested your code on my apache server, and it is working fine. Can you check your apache configs. In the configs there is a parameter called "Registered Stream Socket Transports ". Just check if tls exists as a value over there, else there is some other problem, but it definitely isn't your script
$timeout =- 10;
^----
You're setting $timeout to be negative 10 seconds. e.g. you're killing the connection attempt before it can EVER get started.

PHP : file_get_contents($loc) fails

I just moved a project from localhost over to my remote server, and noticed that some of my scripts stopped working. Most importantly was one that relied upon file_get_contents() to fetch JSON values from another script.
PHP Version is 5.2.4
allow_url_fopen is ON
Warning: file_get_contents() [function.file-get-contents]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/html/2009/functions/functions.products.php on line 5
Warning: file_get_contents(http://data.example.com/new-data.php) [function.file-get-contents]: failed to open stream: Success in /var/www/html/2009/functions/functions.products.php on line 5
The script is being ran from: http://www.example.com
The location passed into the function is http://data.example.com/new-data.php
Note: Same domain name, but two different servers.
function getData() {
$location = "http://data.mysite.com/new-data.php";
$contents = file_get_contents($location);
$jsonVars = json_decode($contents);
return $jsonVars
}
Name or service not known
DNS is broke. Can you ping data.mysite.com from a shell on the machine (assuming you have one)?
Try replacing data.mysite.com with a fixed IP address for now.
Also you can try curl:
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, 'http://url.url');
$result = curl_exec($curl);
curl_close($curl);
And you get what you want in $result.
Look at your /etc/hosts on the remote server. If it's empty, you need to add '127.0.0.1 localhost' to it.
Unless it's one of the varieties of VPS where the loopback interface hits the outer machine; on those, you need to use your VPS's IP number instead of 127.0.0.1.
If you are sure it is not a DNS issue, try restarting Apache. This solved it for me after 20 minutes of head scratching.
Please include more information, does $contents contain anything? Remember to do json_decode($contents, true) if you want it as a php array otherwise its a stdClass that gets returned.
Could it have a problem resolving the hostname? is data.mysite.com the same machine as mysite.com?

Categories