PHP SOAP SSL problems - php

I'm trying to connect to a secure SOAP server using NuSOAP. (I gave the built-in SOAP library a chance, but that was behaving strangely, so I switched to NuSOAP.)
Here's my code:
require('application/libraries/nusoap/nusoap.php');
$soap = new nusoap_client('https://ws.firstdataglobalgateway.com/fdggwsapi/services/order.wsdl', 'wsdl');
$soap->setCredentials('WS'.STORE_NUMBER.'._.1',
PASSWORD,
'certificate',
array(
'sslcertfile' => 'first_data/cert.pem',
'sslkeyfile' => 'first_data/key.pem',
'passphrase' => KEY_PASSPHRASE
)
);
if($err = $soap->getError()) {
die('Error: '.$err);
}
$result = $soap->call('fdggwsapi:FDGGWSApiOrderRequest', array('v1:Transaction' => '1'));
if($soap->fault) {
echo 'Fault! <pre>';
var_dump($result);
echo '</pre>';
} else {
if($err = $soap->getError()) {
die('Error: '.$err);
} else {
echo '<pre>';
var_dump($result);
die('</pre>');
}
}
I get the following error:
Error: wsdl error: Getting https://ws.firstdataglobalgateway.com/fdggwsapi/services/order.wsdl - HTTP ERROR: cURL ERROR: 56: SSL read: error:1409441B:SSL routines:SSL3_READ_BYTES:tlsv1 alert decrypt error, errno 0
url: https://ws.firstdataglobalgateway.com:443/fdggwsapi/services/order.wsdl
content_type:
http_code: 0
header_size: 0
request_size: 163
filetime: -1
ssl_verify_result: 0
redirect_count: 0
total_time: 0.531131
namelookup_time: 0.00121
connect_time: 0.070608
pretransfer_time: 0.305044
size_upload: 0
size_download: 0
speed_download: 0
speed_upload: 0
download_content_length: -1
upload_content_length: 0
starttransfer_time: 0
redirect_time: 0
What could be the possible problems? How could I debug this? I'm rather out of my league here.

Based on the error:
SSL read: error:1409441B:SSL routines:SSL3_READ_BYTES:tlsv1 alert
decrypt error, errno 0
It looks to me like the PHP library is having trouble reading your cert.pem and key.pem files. These files can come in different formats. Apache requires that these be in PKCS12 format and I would guess PHP is the same. You can use a tool called "Keystore Explorer 4.0.1" to verify and convert if necessary.
You can verify the validity of the format of the keys also, using openssl and this command:
C:\Temp> openssl pkcs12 -info -in ksb_cert.p12

With this settings my client working finally
$client = new nusoap_client($wsdlurl,'wdsl');
$client->setUseCURL(true);
$client->useHTTPPersistentConnection();
$client->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0);
$client->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0);
$client->setCurlOption(CURLOPT_RETURNTRANSFER, 1);
$client->setCurlOption(CURLOPT_SSLVERSION,3);

Related

Extracting zip file with php stream gives a "false positive" CRC error

I'm getting a "false positive" E_WARNING file_get_contents(): Zip stream error: CRC error
with the following code on Debian:
$context = stream_context_create(array('zip' => array('password' => '1234567890')));
$string = file_get_contents('zip://test.zip#test.csv', false, $context);
but the extracted data is ok, no crc error.

My PHP application dies with fastcgi: unexpected end-of-file

I updated to PHP 7 at my localhost, but since then anytime i want to redirect from one page to another in my nette application, I'll receive error: 500 - Internal Server Error.
I was searching through stack overflow and found a problem that is quite similar to mine here: How to solve "mod_fastcgi.c.2566 unexpected end-of-file (perhaps the fastcgi process died)" when calling .php that takes long time to execute? . However, I don't work with large files and my connection dies immediately.
My /var/log/lighttpd/error.log
2016-03-06 10:54:11: (server.c.1456) [note] graceful shutdown started
2016-03-06 10:54:11: (server.c.1572) server stopped by UID = 0 PID = 351
2016-03-06 11:03:48: (log.c.194) server started
2016-03-06 11:07:17: (mod_fastcgi.c.2390) unexpected end-of-file (perhaps the fastcgi process died): pid: 21725 socket: unix:/run/lighttpd/php-fastcgi.sock-3
2016-03-06 11:07:17: (mod_fastcgi.c.3171) response not received, request sent: 1029 on socket: unix:/run/lighttpd/php-fastcgi.sock-3 for /~rost/lp/web/www/index.php?, closing connection
2016-03-06 11:09:01: (mod_fastcgi.c.2390) unexpected end-of-file (perhaps the fastcgi process died): pid: 21725 socket: unix:/run/lighttpd/php-fastcgi.sock-3
2016-03-06 11:09:01: (mod_fastcgi.c.3171) response not received, request sent: 1061 on socket: unix:/run/lighttpd/php-fastcgi.sock-3 for /~rost/lp/web/www/index.php?action=list&presenter=Campaign, closing connection
2016-03-06 11:09:06: (mod_fastcgi.c.2390) unexpected end-of-file (perhaps the fastcgi process died): pid: 21725 socket: unix:/run/lighttpd/php-fastcgi.sock-3
2016-03-06 11:09:06: (mod_fastcgi.c.3171) response not received, request sent: 942 on socket: unix:/run/lighttpd/php-fastcgi.sock-3 for /~rost/lp/web/www/index.php?, closing connection
2016-03-06 11:09:14: (mod_fastcgi.c.2390) unexpected end-of-file (perhaps the fastcgi process died): pid: 21725 socket: unix:/run/lighttpd/php-fastcgi.sock-3
2016-03-06 11:09:14: (mod_fastcgi.c.3171) response not received, request sent: 1051 on socket: unix:/run/lighttpd/php-fastcgi.sock-3 for /~rost/lp/web/www/index.php?action=out&presenter=Sign, closing connection
My /etc/lighttpd/lighttpd.conf
server.modules = ( "mod_userdir",
"mod_access",
"mod_accesslog",
"mod_fastcgi",
"mod_rewrite",
"mod_auth"
)
server.port = 80
server.username = "http"
server.groupname = "http"
server.document-root = "/srv/http"
server.errorlog = "/var/log/lighttpd/error.log"
dir-listing.activate = "enable"
index-file.names = ( "index.html" )
# Rewrite URL without dots to index.php
#url.rewrite-once = ( "/^[^.?]*$/" => "/index.php" )
mimetype.assign = ( ".html" => "text/html",
".htm" => "text/html",
".txt" => "text/plain",
".properties" => "text/plain",
".jpg" => "image/jpeg",
".png" => "image/png",
".svg" => "image/svg+xml",
".gif" => "image/gif",
".css" => "text/css",
".js" => "application/x-javascript",
"" => "application/octet-stream"
)
userdir.path = "public_html"
# Fast CGI
include "conf.d/fastcgi.conf"
My /etc/lighttpd/conf.d/fastcgi.conf
server.modules += ( "mod_fastcgi" )
#server.indexfiles += ( "index.php" ) #this is deprecated
index-file.names += ( "index.php" )
fastcgi.server = (
".php" => (
"localhost" => (
"bin-path" => "/usr/bin/php-cgi",
"socket" => "/run/lighttpd/php-fastcgi.sock",
"max-procs" => 4, # default value
"bin-environment" => (
"PHP_FCGI_CHILDREN" => "1", # default value
),
"broken-scriptfilename" => "enable"
))
)
Variables from /etc/php/php.ini
cat /etc/php/php.ini | grep max_execution_time
max_execution_time = 30
cat /etc/php/php.ini | grep default_socket_timeout
default_socket_timeout = 60
Update 7.3.2016
I switched from php fast cgi to php-fpm and interesting thing is that problem prevails, but is less often. Sometimes the redirect jump to 500 and sometimes not. And error log again:
2016-03-07 22:23:32: (mod_fastcgi.c.2390) unexpected end-of-file (perhaps the fastcgi process died): pid: 0 socket: unix:/run/php-fpm/php-fpm.sock
2016-03-07 22:23:32: (mod_fastcgi.c.3171) response not received, request sent: 1084 on socket: unix:/run/php-fpm/php-fpm.sock for /~rost/lp/web/www/index.php?action=out&presenter=Sign, closing connection
Also, try to delete Nette cache first.
I've finally found a solution. It is probably Nette / Cassandra related problem.
The error was appearing because of object Nette\Security\Identity, after I assigned user data into it:
public function authenticate(array $credentials) {
// Retrieve username and password
list($email, $passwd) = $credentials;
// Select user with given email from database
$usr = $this->daoManager->getDao("AppUser")->loadByEmail($email);
if ($usr == null || count($usr) == 0) {
$msg = 'The email is incorrect.';
$arg = self::IDENTITY_NOT_FOUND;
throw new Nette\Security\AuthenticationException($msg, $arg);
}
// TODO Check user password
// TODO Check verification
// Create identity - THE PROBLEM WAS HERE
return new Identity($email, $usr['role'], $usr);
}
It was caused by value 'registered' in $usr array which was of type Cassandra\Timestamp. Since then almost every redirect crashed with above mentioned error.
Following code fixed the issue:
return new Identity($email, $usr['role'], $this->fixUserArray($usr));
Where:
protected function fixUserArray(array $user) {
$result = array();
foreach ($user as $key => $val) {
if ($key === "registered") {
$result[$key] = $val->time();
} else {
$result[$key] = $val;
}
}
return $result;
}

APNS certificate .pem

I am trying to create the server side connection for apple push notifications.
First, I ask from the user (who probably will be an ios dev) to give the .cer and .p12 files that Apple provides in order to make it a .pem file.
Below is the .pem certificate creation.
$dir = $this->directory.'/certificates';
$password = 'a_user_password';
$certificate = $dir.'/certificate.cer';
$key_password = $dir.'/key.p12';
exec('openssl x509 -inform der -in '.$certificate.' -out '.$dir.'/certificate.pem');
exec('openssl pkcs12 -nocerts -out '.$dir.'/key.pem -in '.$key_password.' -passout pass:'.$password.' -passin pass:'.$password);
$filename = $key_password;
$results = array();
$worked = openssl_pkcs12_read(file_get_contents($filename), $results, $obj->password);
if($worked) {
$current = file_get_contents($dir.'/key.pem');
$current .= $results['pkey'];
file_put_contents($dir.'/key.pem', $current);
} else {
echo openssl_error_string();
}
exec('cat '.$dir.'/certificate.pem '.$dir.'/key.pem > '.$dir.'/apns_certificate.pem');
So far, so good. I have tested that the above generated apns_certificate.pem is successful with apple through command line via:
s_client -connect gateway.sandbox.push.apple.com:2195 -cert certificate.pem -key key.pem
However,
When I try to connect with apns through PHP I cannot. Follows the last php code that I have tried and I have seen that for others has worked:
$this->certificate = ROOT.'/certificates/apns_certificate.pem';
$this->socket = 'ssl://gateway.push.apple.com:2195';
if (!file_exists($this->certificate)) {
$this->error = 'Certificate file not found';
return false;
}
$this->stream_context = stream_context_create();
$this->stream_options = array(
'ssl' => array(
'local_cert' => $this->certificate,
'passphrase' => 'a_user_password', //same with the one used in my previous code
)
);
$success = stream_context_set_option($this->stream_context, $this->stream_options);
if ($success == false) {
$this->error = 'Secure connection failed';
return false;
}
$this->socket_client = stream_socket_client($this->socket, $con_error, $con_error_string, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context);
if ($this->socket_client === false) {
$this->error = $con_error_string;
return false;
} else {
return true;
}
The above code returns me an error:
Warning: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages: error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown
Warning: stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195
Thank you in advance for your help!
The above code is correct. There was an error with the certification .p12 . Also I changed the exec for .p12 convertion file to:
exec('openssl pkcs12 -out '.$dir.'/key.pem -in '.$key_password.' -passout pass:'.$password.' -passin pass:'.$password.' -nodes');

Call to undefined function cur_init()

I've seen plenty of these both here on stackoverflow and in other places - by try as I might i am still getting this error.
Any way - useful information
The Code I am trying to execute is as follows
<?php
function getOAuthToken ( $grantCode, $grant_type ) {
global $client_id;
global $client_secret;
global $refresh_token;
try {
ini_set('display_errors', '1');
error_reporting(E_ALL);
$oauth2token_uri = "https://accounts.google.com/o/oauth2/token";
$clienttoken_post = array(
"client_id" => $client_id,
"client_secret" => $client_secret
);
if ($grant_type === "online") {
$clienttoken_post["code"] = $grantCode;
$clienttoken_post["redirect_uri"] = $refresh_token;
$clienttoken_post["grant_type"] = "authorization_code";
}
if ($grant_type == "offline") {
$clienttoken_post["refresh_token"] = $grantCode;
$clienttoken_post["grant_type"] = "refresh_token";
}
$curl = cur_init($oauth2token_uri);
}
catch ( Exception $e )
{
echo 'Message: ' .$e->getMessage();
}
};
session_start();
if (isset($_GET['code'])) {
try
{
$accessToken = getOAuthToken($_GET['code'],'online');
}
catch (Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
}
?>
Windows 7 (64bit) IIS Express
PHP.INI
executing phpInfo() gives the following information.
Php Version 5.3.24
Loaded Configuration File C:\Program Files (x86)\php\php.ini
cURL support enabled
cURL Information 7.29.0
Age 3
Features
AsynchDNS Yes
Debug No
GSS-Negotiate Yes
IDN No
IPv6 Yes
Largefile Yes
NTLM Yes
SPNEGO Yes
SSL Yes
SSPI Yes
krb4 No
libz Yes
CharConv No
Protocols dict, file, ftp, ftps, gopher, http, https, imap, imaps, ldap, pop3, pop3s, rtsp, scp, sftp, smtp, smtps, telnet, tftp
Host i386-pc-win32
SSL Version OpenSSL/0.9.8y
ZLib Version 1.2.7
libSSH Version libssh2/1.4.2
Executing the following code;
<?php
$ci=#curl_version(); $cv=$ci["version_number"]; if($cv) echo "curl
installed"; else echo "curl is not installed";
?>
Shows curl installed
Libcurl.dll (v7.13) installed in Windows\System32 C:\Windows\SysWOW64
Extensions directory is given as C:\Program Files (x86)\php\v5.3\ext
this contains php_curl.dll (ver 5.3.24)
in the php.ini file the line
extension=php_curl.dll
has no semi-colon in front of it
The DLL ssleay32.dll (ver 0.9.8y) has been copied into c:\windows\System32 and C:\Windows\SysWOW64
the DLL libeay32.dll (ver 1.0.1e) has been copied into c:\windows\System32 and c:\windows\sysWOW64
Which I think covers all the answers I have been able to find but still have the ' Call to undefined function cur_init() ' error and have no idea what to try next.
should be
$curl = curl_init($oauth2token_uri);
and not
$curl = cur_init($oauth2token_uri);

Specifying input format type when calling openssl_pkcs7_verify in PHP

I have a crypto/php question, I was hoping someone could help me with.
My issue is that I have a signed PKCS7 block that I am trying to verify in PHP.
However, when I run the following PHP command:
openssl_pkcs7_verify($myfile, PKCS7_BINARY | PKCS7_NOVERIFY, $signers_file);
I get the following error:
PKCS7 routines:SMIME_read_PKCS7:no content type
If I do it using ruby like so:
p7container = OpenSSL::PKCS7.new(file_contents);
mystore = OpenSSL::X509::Store.new
p7container.verify(nil, store, nil, OpenSSL::PKCS7::NOVERIFY)
It works.
Also, if I run it through the OpenSSL commandline:
openssl smime -verify -inform der -in my_data_file -noverify
It also works. However, if I run the following:
openssl smime -verify -in my_data_file -noverify
Which is the same command, but without specifying the inform parameter, it fails with the same error message specified before, regarding the "no content type", which makes it seem I need to specify the input file format. Any ideas how I can do that through PHP?
Thanks in advance for your help,
I got around that problem by calling openssl directly from PHP (using the exec function). Be sure to add 2>&1 to the command to redirect stderr to stdout as the message "Verification successful" is sent to stderr.
function verify($signedData, &$data = null) {
#mkdir("tmp");
$random = randomString(32);
$signedFile = "tmp/" . $random . ".pem";
$file = "tmp/" . $random . ".dat";
file_put_contents($signedFile, $signedData);
$output = exec("openssl smime -verify -in $signedFile -inform DER -noverify -out $file 2>&1");
if ($output == "Verification successful") {
$data = file_get_contents($file);
$result = true;
} else {
$result = false;
}
#unlink($signedFile);
#unlink($file);
return $result;
}

Categories