Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP stream_context_set_option SSL certificate as string

Tags:

php

curl

ssl

pem

I've got a weird issue. Basically, I need to do this:

 $handle = stream_context_create();
 stream_context_set_option($handle , 'ssl', 'local_cert', '/tmp/cert');

However. The certificate is not held as a file within the server. Rather it's an encrypted string held in a clustered database environment. So instead of the certificate being a file name pointer, its the physical content of the certificate. So instead of using the file name, I need to specify the content of the certificate instead.

For example:

 $cert = '-----BEGIN CERTIFICATE-----....
 upWbwmdMd61SjNCdtOpZcNW3YmzuT96Fr7GUPiDQ
 -----END CERTIFICATE-----';

Does anyone have any idea whatsoever how on earth I can do this? I'm scratching my head over this problem, but my gut instinct says it is doable.

Thanks in advance everyone!

like image 969
Roger Thomas Avatar asked Jul 09 '12 21:07

Roger Thomas


2 Answers

As Maerlyn said, it appears the only way to do this will be to write the certificate from memory to a temporary file, call the function, make the request, and then remove the temp file.

I looked at the PHP source code (relevant code here) and when you make a request that will use SSL, it checks to see if local_cert context option is set, and if so, ultimately calls the OpenSSL function SSL_CTX_use_PrivateKey_file which reads the certificate from a disk file.

Take note that the file doesn't get read until the request is performed, so you can't delete the temp file until after your request, as opposed to after calling stream_context_set_option.

like image 183
drew010 Avatar answered Sep 21 '22 18:09

drew010


I tried to use stream_wrapper (php://memory & custom stream wrapper) with no success :-(. At least, you can create a random temp file, register it to be deleted on shutdown, then run you code

$tmp_file = tempnam(sys_get_temp_dir(), "key");
register_shutdown_function("unlink",  $tmp_file);

//rest of your code go there
like image 37
131 Avatar answered Sep 23 '22 18:09

131