PageRenderTime 79ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/ext/openssl/openssl.c

http://github.com/php/php-src
C | 6595 lines | 5257 code | 868 blank | 470 comment | 1492 complexity | fc00f3cc45b888f17bb7d4e0a60efcd8 MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-2.1
  1. /*
  2. +----------------------------------------------------------------------+
  3. | Copyright (c) The PHP Group |
  4. +----------------------------------------------------------------------+
  5. | This source file is subject to version 3.01 of the PHP license, |
  6. | that is bundled with this package in the file LICENSE, and is |
  7. | available through the world-wide-web at the following url: |
  8. | http://www.php.net/license/3_01.txt |
  9. | If you did not receive a copy of the PHP license and are unable to |
  10. | obtain it through the world-wide-web, please send a note to |
  11. | license@php.net so we can mail you a copy immediately. |
  12. +----------------------------------------------------------------------+
  13. | Authors: Stig Venaas <venaas@php.net> |
  14. | Wez Furlong <wez@thebrainroom.com> |
  15. | Sascha Kettler <kettler@gmx.net> |
  16. | Pierre-Alain Joye <pierre@php.net> |
  17. | Marc Delling <delling@silpion.de> (PKCS12 functions) |
  18. | Jakub Zelenka <bukka@php.net> |
  19. +----------------------------------------------------------------------+
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include "config.h"
  23. #endif
  24. #include "php.h"
  25. #include "php_ini.h"
  26. #include "php_openssl.h"
  27. #include "zend_exceptions.h"
  28. /* PHP Includes */
  29. #include "ext/standard/file.h"
  30. #include "ext/standard/info.h"
  31. #include "ext/standard/php_fopen_wrappers.h"
  32. #include "ext/standard/md5.h"
  33. #include "ext/standard/base64.h"
  34. #ifdef PHP_WIN32
  35. # include "win32/winutil.h"
  36. #endif
  37. /* OpenSSL includes */
  38. #include <openssl/evp.h>
  39. #include <openssl/bn.h>
  40. #include <openssl/rsa.h>
  41. #include <openssl/dsa.h>
  42. #include <openssl/dh.h>
  43. #include <openssl/x509.h>
  44. #include <openssl/x509v3.h>
  45. #include <openssl/crypto.h>
  46. #include <openssl/pem.h>
  47. #include <openssl/err.h>
  48. #include <openssl/conf.h>
  49. #include <openssl/rand.h>
  50. #include <openssl/ssl.h>
  51. #include <openssl/pkcs12.h>
  52. /* Common */
  53. #include <time.h>
  54. #if (defined(PHP_WIN32) && defined(_MSC_VER) && _MSC_VER >= 1900)
  55. #define timezone _timezone /* timezone is called _timezone in LibC */
  56. #endif
  57. #define MIN_KEY_LENGTH 384
  58. #define OPENSSL_ALGO_SHA1 1
  59. #define OPENSSL_ALGO_MD5 2
  60. #define OPENSSL_ALGO_MD4 3
  61. #ifdef HAVE_OPENSSL_MD2_H
  62. #define OPENSSL_ALGO_MD2 4
  63. #endif
  64. #if PHP_OPENSSL_API_VERSION < 0x10100
  65. #define OPENSSL_ALGO_DSS1 5
  66. #endif
  67. #define OPENSSL_ALGO_SHA224 6
  68. #define OPENSSL_ALGO_SHA256 7
  69. #define OPENSSL_ALGO_SHA384 8
  70. #define OPENSSL_ALGO_SHA512 9
  71. #define OPENSSL_ALGO_RMD160 10
  72. #define DEBUG_SMIME 0
  73. #if !defined(OPENSSL_NO_EC) && defined(EVP_PKEY_EC)
  74. #define HAVE_EVP_PKEY_EC 1
  75. #endif
  76. #include "openssl_arginfo.h"
  77. ZEND_DECLARE_MODULE_GLOBALS(openssl)
  78. /* FIXME: Use the openssl constants instead of
  79. * enum. It is now impossible to match real values
  80. * against php constants. Also sorry to break the
  81. * enum principles here, BC...
  82. */
  83. enum php_openssl_key_type {
  84. OPENSSL_KEYTYPE_RSA,
  85. OPENSSL_KEYTYPE_DSA,
  86. OPENSSL_KEYTYPE_DH,
  87. OPENSSL_KEYTYPE_DEFAULT = OPENSSL_KEYTYPE_RSA,
  88. #ifdef HAVE_EVP_PKEY_EC
  89. OPENSSL_KEYTYPE_EC = OPENSSL_KEYTYPE_DH +1
  90. #endif
  91. };
  92. enum php_openssl_cipher_type {
  93. PHP_OPENSSL_CIPHER_RC2_40,
  94. PHP_OPENSSL_CIPHER_RC2_128,
  95. PHP_OPENSSL_CIPHER_RC2_64,
  96. PHP_OPENSSL_CIPHER_DES,
  97. PHP_OPENSSL_CIPHER_3DES,
  98. PHP_OPENSSL_CIPHER_AES_128_CBC,
  99. PHP_OPENSSL_CIPHER_AES_192_CBC,
  100. PHP_OPENSSL_CIPHER_AES_256_CBC,
  101. PHP_OPENSSL_CIPHER_DEFAULT = PHP_OPENSSL_CIPHER_RC2_40
  102. };
  103. /* {{{ openssl_module_entry
  104. */
  105. zend_module_entry openssl_module_entry = {
  106. STANDARD_MODULE_HEADER,
  107. "openssl",
  108. ext_functions,
  109. PHP_MINIT(openssl),
  110. PHP_MSHUTDOWN(openssl),
  111. NULL,
  112. NULL,
  113. PHP_MINFO(openssl),
  114. PHP_OPENSSL_VERSION,
  115. PHP_MODULE_GLOBALS(openssl),
  116. PHP_GINIT(openssl),
  117. PHP_GSHUTDOWN(openssl),
  118. NULL,
  119. STANDARD_MODULE_PROPERTIES_EX
  120. };
  121. /* }}} */
  122. #ifdef COMPILE_DL_OPENSSL
  123. ZEND_GET_MODULE(openssl)
  124. #endif
  125. /* {{{ OpenSSL compatibility functions and macros */
  126. #if PHP_OPENSSL_API_VERSION < 0x10100
  127. #define EVP_PKEY_get0_RSA(_pkey) _pkey->pkey.rsa
  128. #define EVP_PKEY_get0_DH(_pkey) _pkey->pkey.dh
  129. #define EVP_PKEY_get0_DSA(_pkey) _pkey->pkey.dsa
  130. #define EVP_PKEY_get0_EC_KEY(_pkey) _pkey->pkey.ec
  131. static int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d)
  132. {
  133. r->n = n;
  134. r->e = e;
  135. r->d = d;
  136. return 1;
  137. }
  138. static int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q)
  139. {
  140. r->p = p;
  141. r->q = q;
  142. return 1;
  143. }
  144. static int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp)
  145. {
  146. r->dmp1 = dmp1;
  147. r->dmq1 = dmq1;
  148. r->iqmp = iqmp;
  149. return 1;
  150. }
  151. static void RSA_get0_key(const RSA *r, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
  152. {
  153. *n = r->n;
  154. *e = r->e;
  155. *d = r->d;
  156. }
  157. static void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q)
  158. {
  159. *p = r->p;
  160. *q = r->q;
  161. }
  162. static void RSA_get0_crt_params(const RSA *r, const BIGNUM **dmp1, const BIGNUM **dmq1, const BIGNUM **iqmp)
  163. {
  164. *dmp1 = r->dmp1;
  165. *dmq1 = r->dmq1;
  166. *iqmp = r->iqmp;
  167. }
  168. static void DH_get0_pqg(const DH *dh, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g)
  169. {
  170. *p = dh->p;
  171. *q = dh->q;
  172. *g = dh->g;
  173. }
  174. static int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
  175. {
  176. dh->p = p;
  177. dh->q = q;
  178. dh->g = g;
  179. return 1;
  180. }
  181. static void DH_get0_key(const DH *dh, const BIGNUM **pub_key, const BIGNUM **priv_key)
  182. {
  183. *pub_key = dh->pub_key;
  184. *priv_key = dh->priv_key;
  185. }
  186. static int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key)
  187. {
  188. dh->pub_key = pub_key;
  189. dh->priv_key = priv_key;
  190. return 1;
  191. }
  192. static void DSA_get0_pqg(const DSA *d, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g)
  193. {
  194. *p = d->p;
  195. *q = d->q;
  196. *g = d->g;
  197. }
  198. int DSA_set0_pqg(DSA *d, BIGNUM *p, BIGNUM *q, BIGNUM *g)
  199. {
  200. d->p = p;
  201. d->q = q;
  202. d->g = g;
  203. return 1;
  204. }
  205. static void DSA_get0_key(const DSA *d, const BIGNUM **pub_key, const BIGNUM **priv_key)
  206. {
  207. *pub_key = d->pub_key;
  208. *priv_key = d->priv_key;
  209. }
  210. int DSA_set0_key(DSA *d, BIGNUM *pub_key, BIGNUM *priv_key)
  211. {
  212. d->pub_key = pub_key;
  213. d->priv_key = priv_key;
  214. return 1;
  215. }
  216. static const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1)
  217. {
  218. return M_ASN1_STRING_data(asn1);
  219. }
  220. #if PHP_OPENSSL_API_VERSION < 0x10002
  221. static int X509_get_signature_nid(const X509 *x)
  222. {
  223. return OBJ_obj2nid(x->sig_alg->algorithm);
  224. }
  225. #endif
  226. #define OpenSSL_version SSLeay_version
  227. #define OPENSSL_VERSION SSLEAY_VERSION
  228. #define X509_getm_notBefore X509_get_notBefore
  229. #define X509_getm_notAfter X509_get_notAfter
  230. #define EVP_CIPHER_CTX_reset EVP_CIPHER_CTX_cleanup
  231. #endif
  232. /* }}} */
  233. /* number conversion flags checks */
  234. #define PHP_OPENSSL_CHECK_NUMBER_CONVERSION(_cond, _name) \
  235. do { \
  236. if (_cond) { \
  237. php_error_docref(NULL, E_WARNING, #_name" is too long"); \
  238. RETURN_FALSE; \
  239. } \
  240. } while(0)
  241. /* number conversion flags checks */
  242. #define PHP_OPENSSL_CHECK_NUMBER_CONVERSION_NORET(_cond, _name) \
  243. do { \
  244. if (_cond) { \
  245. php_error_docref(NULL, E_WARNING, #_name" is too long"); \
  246. return NULL; \
  247. } \
  248. } while(0)
  249. /* check if size_t can be safely casted to int */
  250. #define PHP_OPENSSL_CHECK_SIZE_T_TO_INT(_var, _name) \
  251. PHP_OPENSSL_CHECK_NUMBER_CONVERSION(ZEND_SIZE_T_INT_OVFL(_var), _name)
  252. /* check if size_t can be safely casted to int */
  253. #define PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(_var, _name) \
  254. PHP_OPENSSL_CHECK_NUMBER_CONVERSION_NORET(ZEND_SIZE_T_INT_OVFL(_var), _name)
  255. /* check if size_t can be safely casted to unsigned int */
  256. #define PHP_OPENSSL_CHECK_SIZE_T_TO_UINT(_var, _name) \
  257. PHP_OPENSSL_CHECK_NUMBER_CONVERSION(ZEND_SIZE_T_UINT_OVFL(_var), _name)
  258. /* check if long can be safely casted to int */
  259. #define PHP_OPENSSL_CHECK_LONG_TO_INT(_var, _name) \
  260. PHP_OPENSSL_CHECK_NUMBER_CONVERSION(ZEND_LONG_EXCEEDS_INT(_var), _name)
  261. /* check if long can be safely casted to int */
  262. #define PHP_OPENSSL_CHECK_LONG_TO_INT_NORET(_var, _name) \
  263. PHP_OPENSSL_CHECK_NUMBER_CONVERSION_NORET(ZEND_LONG_EXCEEDS_INT(_var), _name)
  264. /* {{{ php_openssl_store_errors */
  265. void php_openssl_store_errors()
  266. {
  267. struct php_openssl_errors *errors;
  268. int error_code = ERR_get_error();
  269. if (!error_code) {
  270. return;
  271. }
  272. if (!OPENSSL_G(errors)) {
  273. OPENSSL_G(errors) = pecalloc(1, sizeof(struct php_openssl_errors), 1);
  274. }
  275. errors = OPENSSL_G(errors);
  276. do {
  277. errors->top = (errors->top + 1) % ERR_NUM_ERRORS;
  278. if (errors->top == errors->bottom) {
  279. errors->bottom = (errors->bottom + 1) % ERR_NUM_ERRORS;
  280. }
  281. errors->buffer[errors->top] = error_code;
  282. } while ((error_code = ERR_get_error()));
  283. }
  284. /* }}} */
  285. static int le_key;
  286. static int le_x509;
  287. static int le_csr;
  288. static int ssl_stream_data_index;
  289. int php_openssl_get_x509_list_id(void) /* {{{ */
  290. {
  291. return le_x509;
  292. }
  293. /* }}} */
  294. /* {{{ resource destructors */
  295. static void php_openssl_pkey_free(zend_resource *rsrc)
  296. {
  297. EVP_PKEY *pkey = (EVP_PKEY *)rsrc->ptr;
  298. assert(pkey != NULL);
  299. EVP_PKEY_free(pkey);
  300. }
  301. static void php_openssl_x509_free(zend_resource *rsrc)
  302. {
  303. X509 *x509 = (X509 *)rsrc->ptr;
  304. X509_free(x509);
  305. }
  306. static void php_openssl_csr_free(zend_resource *rsrc)
  307. {
  308. X509_REQ * csr = (X509_REQ*)rsrc->ptr;
  309. X509_REQ_free(csr);
  310. }
  311. /* }}} */
  312. /* {{{ openssl open_basedir check */
  313. inline static int php_openssl_open_base_dir_chk(char *filename)
  314. {
  315. if (php_check_open_basedir(filename)) {
  316. return -1;
  317. }
  318. return 0;
  319. }
  320. /* }}} */
  321. php_stream* php_openssl_get_stream_from_ssl_handle(const SSL *ssl)
  322. {
  323. return (php_stream*)SSL_get_ex_data(ssl, ssl_stream_data_index);
  324. }
  325. int php_openssl_get_ssl_stream_data_index()
  326. {
  327. return ssl_stream_data_index;
  328. }
  329. /* openssl -> PHP "bridging" */
  330. /* true global; readonly after module startup */
  331. static char default_ssl_conf_filename[MAXPATHLEN];
  332. struct php_x509_request { /* {{{ */
  333. LHASH_OF(CONF_VALUE) * global_config; /* Global SSL config */
  334. LHASH_OF(CONF_VALUE) * req_config; /* SSL config for this request */
  335. const EVP_MD * md_alg;
  336. const EVP_MD * digest;
  337. char * section_name,
  338. * config_filename,
  339. * digest_name,
  340. * extensions_section,
  341. * request_extensions_section;
  342. int priv_key_bits;
  343. int priv_key_type;
  344. int priv_key_encrypt;
  345. #ifdef HAVE_EVP_PKEY_EC
  346. int curve_name;
  347. #endif
  348. EVP_PKEY * priv_key;
  349. const EVP_CIPHER * priv_key_encrypt_cipher;
  350. };
  351. /* }}} */
  352. static X509 * php_openssl_x509_from_zval(zval * val, int makeresource, zend_resource **resourceval);
  353. static EVP_PKEY * php_openssl_evp_from_zval(
  354. zval * val, int public_key, char *passphrase, size_t passphrase_len,
  355. int makeresource, zend_resource **resourceval);
  356. static int php_openssl_is_private_key(EVP_PKEY* pkey);
  357. static X509_STORE * php_openssl_setup_verify(zval * calist);
  358. static STACK_OF(X509) * php_openssl_load_all_certs_from_file(char *certfile);
  359. static X509_REQ * php_openssl_csr_from_zval(zval * val, int makeresource, zend_resource ** resourceval);
  360. static EVP_PKEY * php_openssl_generate_private_key(struct php_x509_request * req);
  361. static void php_openssl_add_assoc_name_entry(zval * val, char * key, X509_NAME * name, int shortname) /* {{{ */
  362. {
  363. zval *data;
  364. zval subitem, tmp;
  365. int i;
  366. char *sname;
  367. int nid;
  368. X509_NAME_ENTRY * ne;
  369. ASN1_STRING * str = NULL;
  370. ASN1_OBJECT * obj;
  371. if (key != NULL) {
  372. array_init(&subitem);
  373. } else {
  374. ZVAL_COPY_VALUE(&subitem, val);
  375. }
  376. for (i = 0; i < X509_NAME_entry_count(name); i++) {
  377. const unsigned char *to_add = NULL;
  378. int to_add_len = 0;
  379. unsigned char *to_add_buf = NULL;
  380. ne = X509_NAME_get_entry(name, i);
  381. obj = X509_NAME_ENTRY_get_object(ne);
  382. nid = OBJ_obj2nid(obj);
  383. if (shortname) {
  384. sname = (char *) OBJ_nid2sn(nid);
  385. } else {
  386. sname = (char *) OBJ_nid2ln(nid);
  387. }
  388. str = X509_NAME_ENTRY_get_data(ne);
  389. if (ASN1_STRING_type(str) != V_ASN1_UTF8STRING) {
  390. /* ASN1_STRING_to_UTF8(3): The converted data is copied into a newly allocated buffer */
  391. to_add_len = ASN1_STRING_to_UTF8(&to_add_buf, str);
  392. to_add = to_add_buf;
  393. } else {
  394. /* ASN1_STRING_get0_data(3): Since this is an internal pointer it should not be freed or modified in any way */
  395. to_add = ASN1_STRING_get0_data(str);
  396. to_add_len = ASN1_STRING_length(str);
  397. }
  398. if (to_add_len != -1) {
  399. if ((data = zend_hash_str_find(Z_ARRVAL(subitem), sname, strlen(sname))) != NULL) {
  400. if (Z_TYPE_P(data) == IS_ARRAY) {
  401. add_next_index_stringl(data, (const char *)to_add, to_add_len);
  402. } else if (Z_TYPE_P(data) == IS_STRING) {
  403. array_init(&tmp);
  404. add_next_index_str(&tmp, zend_string_copy(Z_STR_P(data)));
  405. add_next_index_stringl(&tmp, (const char *)to_add, to_add_len);
  406. zend_hash_str_update(Z_ARRVAL(subitem), sname, strlen(sname), &tmp);
  407. }
  408. } else {
  409. /* it might be better to expand it and pass zval from ZVAL_STRING
  410. * to zend_symtable_str_update so we do not silently drop const
  411. * but we need a test to cover this part first */
  412. add_assoc_stringl(&subitem, sname, (char *)to_add, to_add_len);
  413. }
  414. } else {
  415. php_openssl_store_errors();
  416. }
  417. if (to_add_buf != NULL) {
  418. OPENSSL_free(to_add_buf);
  419. }
  420. }
  421. if (key != NULL) {
  422. zend_hash_str_update(Z_ARRVAL_P(val), key, strlen(key), &subitem);
  423. }
  424. }
  425. /* }}} */
  426. static void php_openssl_add_assoc_asn1_string(zval * val, char * key, ASN1_STRING * str) /* {{{ */
  427. {
  428. add_assoc_stringl(val, key, (char *)str->data, str->length);
  429. }
  430. /* }}} */
  431. static time_t php_openssl_asn1_time_to_time_t(ASN1_UTCTIME * timestr) /* {{{ */
  432. {
  433. /*
  434. This is how the time string is formatted:
  435. snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100,
  436. ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec);
  437. */
  438. time_t ret;
  439. struct tm thetime;
  440. char * strbuf;
  441. char * thestr;
  442. long gmadjust = 0;
  443. size_t timestr_len;
  444. if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME && ASN1_STRING_type(timestr) != V_ASN1_GENERALIZEDTIME) {
  445. php_error_docref(NULL, E_WARNING, "Illegal ASN1 data type for timestamp");
  446. return (time_t)-1;
  447. }
  448. timestr_len = (size_t)ASN1_STRING_length(timestr);
  449. if (timestr_len != strlen((const char *)ASN1_STRING_get0_data(timestr))) {
  450. php_error_docref(NULL, E_WARNING, "Illegal length in timestamp");
  451. return (time_t)-1;
  452. }
  453. if (timestr_len < 13 && timestr_len != 11) {
  454. php_error_docref(NULL, E_WARNING, "Unable to parse time string %s correctly", timestr->data);
  455. return (time_t)-1;
  456. }
  457. if (ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME && timestr_len < 15) {
  458. php_error_docref(NULL, E_WARNING, "Unable to parse time string %s correctly", timestr->data);
  459. return (time_t)-1;
  460. }
  461. strbuf = estrdup((const char *)ASN1_STRING_get0_data(timestr));
  462. memset(&thetime, 0, sizeof(thetime));
  463. /* we work backwards so that we can use atoi more easily */
  464. thestr = strbuf + timestr_len - 3;
  465. if (timestr_len == 11) {
  466. thetime.tm_sec = 0;
  467. } else {
  468. thetime.tm_sec = atoi(thestr);
  469. *thestr = '\0';
  470. thestr -= 2;
  471. }
  472. thetime.tm_min = atoi(thestr);
  473. *thestr = '\0';
  474. thestr -= 2;
  475. thetime.tm_hour = atoi(thestr);
  476. *thestr = '\0';
  477. thestr -= 2;
  478. thetime.tm_mday = atoi(thestr);
  479. *thestr = '\0';
  480. thestr -= 2;
  481. thetime.tm_mon = atoi(thestr)-1;
  482. *thestr = '\0';
  483. if( ASN1_STRING_type(timestr) == V_ASN1_UTCTIME ) {
  484. thestr -= 2;
  485. thetime.tm_year = atoi(thestr);
  486. if (thetime.tm_year < 68) {
  487. thetime.tm_year += 100;
  488. }
  489. } else if( ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME ) {
  490. thestr -= 4;
  491. thetime.tm_year = atoi(thestr) - 1900;
  492. }
  493. thetime.tm_isdst = -1;
  494. ret = mktime(&thetime);
  495. #if HAVE_STRUCT_TM_TM_GMTOFF
  496. gmadjust = thetime.tm_gmtoff;
  497. #else
  498. /*
  499. ** If correcting for daylight savings time, we set the adjustment to
  500. ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and
  501. ** set the adjustment to the main timezone + 3600 seconds.
  502. */
  503. gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone);
  504. #endif
  505. ret += gmadjust;
  506. efree(strbuf);
  507. return ret;
  508. }
  509. /* }}} */
  510. static inline int php_openssl_config_check_syntax(const char * section_label, const char * config_filename, const char * section, LHASH_OF(CONF_VALUE) * config) /* {{{ */
  511. {
  512. X509V3_CTX ctx;
  513. X509V3_set_ctx_test(&ctx);
  514. X509V3_set_conf_lhash(&ctx, config);
  515. if (!X509V3_EXT_add_conf(config, &ctx, (char *)section, NULL)) {
  516. php_openssl_store_errors();
  517. php_error_docref(NULL, E_WARNING, "Error loading %s section %s of %s",
  518. section_label,
  519. section,
  520. config_filename);
  521. return FAILURE;
  522. }
  523. return SUCCESS;
  524. }
  525. /* }}} */
  526. static int php_openssl_add_oid_section(struct php_x509_request * req) /* {{{ */
  527. {
  528. char * str;
  529. STACK_OF(CONF_VALUE) * sktmp;
  530. CONF_VALUE * cnf;
  531. int i;
  532. str = CONF_get_string(req->req_config, NULL, "oid_section");
  533. if (str == NULL) {
  534. php_openssl_store_errors();
  535. return SUCCESS;
  536. }
  537. sktmp = CONF_get_section(req->req_config, str);
  538. if (sktmp == NULL) {
  539. php_openssl_store_errors();
  540. php_error_docref(NULL, E_WARNING, "Problem loading oid section %s", str);
  541. return FAILURE;
  542. }
  543. for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
  544. cnf = sk_CONF_VALUE_value(sktmp, i);
  545. if (OBJ_sn2nid(cnf->name) == NID_undef && OBJ_ln2nid(cnf->name) == NID_undef &&
  546. OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
  547. php_openssl_store_errors();
  548. php_error_docref(NULL, E_WARNING, "Problem creating object %s=%s", cnf->name, cnf->value);
  549. return FAILURE;
  550. }
  551. }
  552. return SUCCESS;
  553. }
  554. /* }}} */
  555. #define PHP_SSL_REQ_INIT(req) memset(req, 0, sizeof(*req))
  556. #define PHP_SSL_REQ_DISPOSE(req) php_openssl_dispose_config(req)
  557. #define PHP_SSL_REQ_PARSE(req, zval) php_openssl_parse_config(req, zval)
  558. #define PHP_SSL_CONFIG_SYNTAX_CHECK(var) if (req->var && php_openssl_config_check_syntax(#var, \
  559. req->config_filename, req->var, req->req_config) == FAILURE) return FAILURE
  560. #define SET_OPTIONAL_STRING_ARG(key, varname, defval) \
  561. do { \
  562. if (optional_args && (item = zend_hash_str_find(Z_ARRVAL_P(optional_args), key, sizeof(key)-1)) != NULL && Z_TYPE_P(item) == IS_STRING) { \
  563. varname = Z_STRVAL_P(item); \
  564. } else { \
  565. varname = defval; \
  566. if (varname == NULL) { \
  567. php_openssl_store_errors(); \
  568. } \
  569. } \
  570. } while(0)
  571. #define SET_OPTIONAL_LONG_ARG(key, varname, defval) \
  572. if (optional_args && (item = zend_hash_str_find(Z_ARRVAL_P(optional_args), key, sizeof(key)-1)) != NULL && Z_TYPE_P(item) == IS_LONG) \
  573. varname = (int)Z_LVAL_P(item); \
  574. else \
  575. varname = defval
  576. static const EVP_CIPHER * php_openssl_get_evp_cipher_from_algo(zend_long algo);
  577. /* {{{ strip line endings from spkac */
  578. static int php_openssl_spki_cleanup(const char *src, char *dest)
  579. {
  580. int removed = 0;
  581. while (*src) {
  582. if (*src != '\n' && *src != '\r') {
  583. *dest++ = *src;
  584. } else {
  585. ++removed;
  586. }
  587. ++src;
  588. }
  589. *dest = 0;
  590. return removed;
  591. }
  592. /* }}} */
  593. static int php_openssl_parse_config(struct php_x509_request * req, zval * optional_args) /* {{{ */
  594. {
  595. char * str;
  596. zval * item;
  597. SET_OPTIONAL_STRING_ARG("config", req->config_filename, default_ssl_conf_filename);
  598. SET_OPTIONAL_STRING_ARG("config_section_name", req->section_name, "req");
  599. req->global_config = CONF_load(NULL, default_ssl_conf_filename, NULL);
  600. if (req->global_config == NULL) {
  601. php_openssl_store_errors();
  602. }
  603. req->req_config = CONF_load(NULL, req->config_filename, NULL);
  604. if (req->req_config == NULL) {
  605. php_openssl_store_errors();
  606. return FAILURE;
  607. }
  608. /* read in the oids */
  609. str = CONF_get_string(req->req_config, NULL, "oid_file");
  610. if (str == NULL) {
  611. php_openssl_store_errors();
  612. } else if (!php_openssl_open_base_dir_chk(str)) {
  613. BIO *oid_bio = BIO_new_file(str, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY));
  614. if (oid_bio) {
  615. OBJ_create_objects(oid_bio);
  616. BIO_free(oid_bio);
  617. php_openssl_store_errors();
  618. }
  619. }
  620. if (php_openssl_add_oid_section(req) == FAILURE) {
  621. return FAILURE;
  622. }
  623. SET_OPTIONAL_STRING_ARG("digest_alg", req->digest_name,
  624. CONF_get_string(req->req_config, req->section_name, "default_md"));
  625. SET_OPTIONAL_STRING_ARG("x509_extensions", req->extensions_section,
  626. CONF_get_string(req->req_config, req->section_name, "x509_extensions"));
  627. SET_OPTIONAL_STRING_ARG("req_extensions", req->request_extensions_section,
  628. CONF_get_string(req->req_config, req->section_name, "req_extensions"));
  629. SET_OPTIONAL_LONG_ARG("private_key_bits", req->priv_key_bits,
  630. CONF_get_number(req->req_config, req->section_name, "default_bits"));
  631. SET_OPTIONAL_LONG_ARG("private_key_type", req->priv_key_type, OPENSSL_KEYTYPE_DEFAULT);
  632. if (optional_args && (item = zend_hash_str_find(Z_ARRVAL_P(optional_args), "encrypt_key", sizeof("encrypt_key")-1)) != NULL) {
  633. req->priv_key_encrypt = Z_TYPE_P(item) == IS_TRUE ? 1 : 0;
  634. } else {
  635. str = CONF_get_string(req->req_config, req->section_name, "encrypt_rsa_key");
  636. if (str == NULL) {
  637. str = CONF_get_string(req->req_config, req->section_name, "encrypt_key");
  638. /* it is sure that there are some errors as str was NULL for encrypt_rsa_key */
  639. php_openssl_store_errors();
  640. }
  641. if (str != NULL && strcmp(str, "no") == 0) {
  642. req->priv_key_encrypt = 0;
  643. } else {
  644. req->priv_key_encrypt = 1;
  645. }
  646. }
  647. if (req->priv_key_encrypt &&
  648. optional_args &&
  649. (item = zend_hash_str_find(Z_ARRVAL_P(optional_args), "encrypt_key_cipher", sizeof("encrypt_key_cipher")-1)) != NULL &&
  650. Z_TYPE_P(item) == IS_LONG
  651. ) {
  652. zend_long cipher_algo = Z_LVAL_P(item);
  653. const EVP_CIPHER* cipher = php_openssl_get_evp_cipher_from_algo(cipher_algo);
  654. if (cipher == NULL) {
  655. php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm for private key.");
  656. return FAILURE;
  657. } else {
  658. req->priv_key_encrypt_cipher = cipher;
  659. }
  660. } else {
  661. req->priv_key_encrypt_cipher = NULL;
  662. }
  663. /* digest alg */
  664. if (req->digest_name == NULL) {
  665. req->digest_name = CONF_get_string(req->req_config, req->section_name, "default_md");
  666. }
  667. if (req->digest_name != NULL) {
  668. req->digest = req->md_alg = EVP_get_digestbyname(req->digest_name);
  669. } else {
  670. php_openssl_store_errors();
  671. }
  672. if (req->md_alg == NULL) {
  673. req->md_alg = req->digest = EVP_sha1();
  674. php_openssl_store_errors();
  675. }
  676. PHP_SSL_CONFIG_SYNTAX_CHECK(extensions_section);
  677. #ifdef HAVE_EVP_PKEY_EC
  678. /* set the ec group curve name */
  679. req->curve_name = NID_undef;
  680. if (optional_args && (item = zend_hash_str_find(Z_ARRVAL_P(optional_args), "curve_name", sizeof("curve_name")-1)) != NULL
  681. && Z_TYPE_P(item) == IS_STRING) {
  682. req->curve_name = OBJ_sn2nid(Z_STRVAL_P(item));
  683. if (req->curve_name == NID_undef) {
  684. php_error_docref(NULL, E_WARNING, "Unknown elliptic curve (short) name %s", Z_STRVAL_P(item));
  685. return FAILURE;
  686. }
  687. }
  688. #endif
  689. /* set the string mask */
  690. str = CONF_get_string(req->req_config, req->section_name, "string_mask");
  691. if (str == NULL) {
  692. php_openssl_store_errors();
  693. } else if (!ASN1_STRING_set_default_mask_asc(str)) {
  694. php_error_docref(NULL, E_WARNING, "Invalid global string mask setting %s", str);
  695. return FAILURE;
  696. }
  697. PHP_SSL_CONFIG_SYNTAX_CHECK(request_extensions_section);
  698. return SUCCESS;
  699. }
  700. /* }}} */
  701. static void php_openssl_dispose_config(struct php_x509_request * req) /* {{{ */
  702. {
  703. if (req->priv_key) {
  704. EVP_PKEY_free(req->priv_key);
  705. req->priv_key = NULL;
  706. }
  707. if (req->global_config) {
  708. CONF_free(req->global_config);
  709. req->global_config = NULL;
  710. }
  711. if (req->req_config) {
  712. CONF_free(req->req_config);
  713. req->req_config = NULL;
  714. }
  715. }
  716. /* }}} */
  717. #if defined(PHP_WIN32) || PHP_OPENSSL_API_VERSION >= 0x10100
  718. #define PHP_OPENSSL_RAND_ADD_TIME() ((void) 0)
  719. #else
  720. #define PHP_OPENSSL_RAND_ADD_TIME() php_openssl_rand_add_timeval()
  721. static inline void php_openssl_rand_add_timeval() /* {{{ */
  722. {
  723. struct timeval tv;
  724. gettimeofday(&tv, NULL);
  725. RAND_add(&tv, sizeof(tv), 0.0);
  726. }
  727. /* }}} */
  728. #endif
  729. static int php_openssl_load_rand_file(const char * file, int *egdsocket, int *seeded) /* {{{ */
  730. {
  731. char buffer[MAXPATHLEN];
  732. *egdsocket = 0;
  733. *seeded = 0;
  734. if (file == NULL) {
  735. file = RAND_file_name(buffer, sizeof(buffer));
  736. #ifdef HAVE_RAND_EGD
  737. } else if (RAND_egd(file) > 0) {
  738. /* if the given filename is an EGD socket, don't
  739. * write anything back to it */
  740. *egdsocket = 1;
  741. return SUCCESS;
  742. #endif
  743. }
  744. if (file == NULL || !RAND_load_file(file, -1)) {
  745. if (RAND_status() == 0) {
  746. php_openssl_store_errors();
  747. php_error_docref(NULL, E_WARNING, "Unable to load random state; not enough random data!");
  748. return FAILURE;
  749. }
  750. return FAILURE;
  751. }
  752. *seeded = 1;
  753. return SUCCESS;
  754. }
  755. /* }}} */
  756. static int php_openssl_write_rand_file(const char * file, int egdsocket, int seeded) /* {{{ */
  757. {
  758. char buffer[MAXPATHLEN];
  759. if (egdsocket || !seeded) {
  760. /* if we did not manage to read the seed file, we should not write
  761. * a low-entropy seed file back */
  762. return FAILURE;
  763. }
  764. if (file == NULL) {
  765. file = RAND_file_name(buffer, sizeof(buffer));
  766. }
  767. PHP_OPENSSL_RAND_ADD_TIME();
  768. if (file == NULL || !RAND_write_file(file)) {
  769. php_openssl_store_errors();
  770. php_error_docref(NULL, E_WARNING, "Unable to write random state");
  771. return FAILURE;
  772. }
  773. return SUCCESS;
  774. }
  775. /* }}} */
  776. static EVP_MD * php_openssl_get_evp_md_from_algo(zend_long algo) { /* {{{ */
  777. EVP_MD *mdtype;
  778. switch (algo) {
  779. case OPENSSL_ALGO_SHA1:
  780. mdtype = (EVP_MD *) EVP_sha1();
  781. break;
  782. case OPENSSL_ALGO_MD5:
  783. mdtype = (EVP_MD *) EVP_md5();
  784. break;
  785. case OPENSSL_ALGO_MD4:
  786. mdtype = (EVP_MD *) EVP_md4();
  787. break;
  788. #ifdef HAVE_OPENSSL_MD2_H
  789. case OPENSSL_ALGO_MD2:
  790. mdtype = (EVP_MD *) EVP_md2();
  791. break;
  792. #endif
  793. #if PHP_OPENSSL_API_VERSION < 0x10100
  794. case OPENSSL_ALGO_DSS1:
  795. mdtype = (EVP_MD *) EVP_dss1();
  796. break;
  797. #endif
  798. case OPENSSL_ALGO_SHA224:
  799. mdtype = (EVP_MD *) EVP_sha224();
  800. break;
  801. case OPENSSL_ALGO_SHA256:
  802. mdtype = (EVP_MD *) EVP_sha256();
  803. break;
  804. case OPENSSL_ALGO_SHA384:
  805. mdtype = (EVP_MD *) EVP_sha384();
  806. break;
  807. case OPENSSL_ALGO_SHA512:
  808. mdtype = (EVP_MD *) EVP_sha512();
  809. break;
  810. case OPENSSL_ALGO_RMD160:
  811. mdtype = (EVP_MD *) EVP_ripemd160();
  812. break;
  813. default:
  814. return NULL;
  815. break;
  816. }
  817. return mdtype;
  818. }
  819. /* }}} */
  820. static const EVP_CIPHER * php_openssl_get_evp_cipher_from_algo(zend_long algo) { /* {{{ */
  821. switch (algo) {
  822. #ifndef OPENSSL_NO_RC2
  823. case PHP_OPENSSL_CIPHER_RC2_40:
  824. return EVP_rc2_40_cbc();
  825. break;
  826. case PHP_OPENSSL_CIPHER_RC2_64:
  827. return EVP_rc2_64_cbc();
  828. break;
  829. case PHP_OPENSSL_CIPHER_RC2_128:
  830. return EVP_rc2_cbc();
  831. break;
  832. #endif
  833. #ifndef OPENSSL_NO_DES
  834. case PHP_OPENSSL_CIPHER_DES:
  835. return EVP_des_cbc();
  836. break;
  837. case PHP_OPENSSL_CIPHER_3DES:
  838. return EVP_des_ede3_cbc();
  839. break;
  840. #endif
  841. #ifndef OPENSSL_NO_AES
  842. case PHP_OPENSSL_CIPHER_AES_128_CBC:
  843. return EVP_aes_128_cbc();
  844. break;
  845. case PHP_OPENSSL_CIPHER_AES_192_CBC:
  846. return EVP_aes_192_cbc();
  847. break;
  848. case PHP_OPENSSL_CIPHER_AES_256_CBC:
  849. return EVP_aes_256_cbc();
  850. break;
  851. #endif
  852. default:
  853. return NULL;
  854. break;
  855. }
  856. }
  857. /* }}} */
  858. /* {{{ INI Settings */
  859. PHP_INI_BEGIN()
  860. PHP_INI_ENTRY("openssl.cafile", NULL, PHP_INI_PERDIR, NULL)
  861. PHP_INI_ENTRY("openssl.capath", NULL, PHP_INI_PERDIR, NULL)
  862. PHP_INI_END()
  863. /* }}} */
  864. /* {{{ PHP_MINIT_FUNCTION
  865. */
  866. PHP_MINIT_FUNCTION(openssl)
  867. {
  868. char * config_filename;
  869. le_key = zend_register_list_destructors_ex(php_openssl_pkey_free, NULL, "OpenSSL key", module_number);
  870. le_x509 = zend_register_list_destructors_ex(php_openssl_x509_free, NULL, "OpenSSL X.509", module_number);
  871. le_csr = zend_register_list_destructors_ex(php_openssl_csr_free, NULL, "OpenSSL X.509 CSR", module_number);
  872. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined (LIBRESSL_VERSION_NUMBER)
  873. OPENSSL_config(NULL);
  874. SSL_library_init();
  875. OpenSSL_add_all_ciphers();
  876. OpenSSL_add_all_digests();
  877. OpenSSL_add_all_algorithms();
  878. #if !defined(OPENSSL_NO_AES) && defined(EVP_CIPH_CCM_MODE) && OPENSSL_VERSION_NUMBER < 0x100020000
  879. EVP_add_cipher(EVP_aes_128_ccm());
  880. EVP_add_cipher(EVP_aes_192_ccm());
  881. EVP_add_cipher(EVP_aes_256_ccm());
  882. #endif
  883. SSL_load_error_strings();
  884. #else
  885. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
  886. #endif
  887. /* register a resource id number with OpenSSL so that we can map SSL -> stream structures in
  888. * OpenSSL callbacks */
  889. ssl_stream_data_index = SSL_get_ex_new_index(0, "PHP stream index", NULL, NULL, NULL);
  890. REGISTER_STRING_CONSTANT("OPENSSL_VERSION_TEXT", OPENSSL_VERSION_TEXT, CONST_CS|CONST_PERSISTENT);
  891. REGISTER_LONG_CONSTANT("OPENSSL_VERSION_NUMBER", OPENSSL_VERSION_NUMBER, CONST_CS|CONST_PERSISTENT);
  892. /* purposes for cert purpose checking */
  893. REGISTER_LONG_CONSTANT("X509_PURPOSE_SSL_CLIENT", X509_PURPOSE_SSL_CLIENT, CONST_CS|CONST_PERSISTENT);
  894. REGISTER_LONG_CONSTANT("X509_PURPOSE_SSL_SERVER", X509_PURPOSE_SSL_SERVER, CONST_CS|CONST_PERSISTENT);
  895. REGISTER_LONG_CONSTANT("X509_PURPOSE_NS_SSL_SERVER", X509_PURPOSE_NS_SSL_SERVER, CONST_CS|CONST_PERSISTENT);
  896. REGISTER_LONG_CONSTANT("X509_PURPOSE_SMIME_SIGN", X509_PURPOSE_SMIME_SIGN, CONST_CS|CONST_PERSISTENT);
  897. REGISTER_LONG_CONSTANT("X509_PURPOSE_SMIME_ENCRYPT", X509_PURPOSE_SMIME_ENCRYPT, CONST_CS|CONST_PERSISTENT);
  898. REGISTER_LONG_CONSTANT("X509_PURPOSE_CRL_SIGN", X509_PURPOSE_CRL_SIGN, CONST_CS|CONST_PERSISTENT);
  899. #ifdef X509_PURPOSE_ANY
  900. REGISTER_LONG_CONSTANT("X509_PURPOSE_ANY", X509_PURPOSE_ANY, CONST_CS|CONST_PERSISTENT);
  901. #endif
  902. /* signature algorithm constants */
  903. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA1", OPENSSL_ALGO_SHA1, CONST_CS|CONST_PERSISTENT);
  904. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_MD5", OPENSSL_ALGO_MD5, CONST_CS|CONST_PERSISTENT);
  905. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_MD4", OPENSSL_ALGO_MD4, CONST_CS|CONST_PERSISTENT);
  906. #ifdef HAVE_OPENSSL_MD2_H
  907. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_MD2", OPENSSL_ALGO_MD2, CONST_CS|CONST_PERSISTENT);
  908. #endif
  909. #if PHP_OPENSSL_API_VERSION < 0x10100
  910. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_DSS1", OPENSSL_ALGO_DSS1, CONST_CS|CONST_PERSISTENT);
  911. #endif
  912. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA224", OPENSSL_ALGO_SHA224, CONST_CS|CONST_PERSISTENT);
  913. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA256", OPENSSL_ALGO_SHA256, CONST_CS|CONST_PERSISTENT);
  914. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA384", OPENSSL_ALGO_SHA384, CONST_CS|CONST_PERSISTENT);
  915. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA512", OPENSSL_ALGO_SHA512, CONST_CS|CONST_PERSISTENT);
  916. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_RMD160", OPENSSL_ALGO_RMD160, CONST_CS|CONST_PERSISTENT);
  917. /* flags for S/MIME */
  918. REGISTER_LONG_CONSTANT("PKCS7_DETACHED", PKCS7_DETACHED, CONST_CS|CONST_PERSISTENT);
  919. REGISTER_LONG_CONSTANT("PKCS7_TEXT", PKCS7_TEXT, CONST_CS|CONST_PERSISTENT);
  920. REGISTER_LONG_CONSTANT("PKCS7_NOINTERN", PKCS7_NOINTERN, CONST_CS|CONST_PERSISTENT);
  921. REGISTER_LONG_CONSTANT("PKCS7_NOVERIFY", PKCS7_NOVERIFY, CONST_CS|CONST_PERSISTENT);
  922. REGISTER_LONG_CONSTANT("PKCS7_NOCHAIN", PKCS7_NOCHAIN, CONST_CS|CONST_PERSISTENT);
  923. REGISTER_LONG_CONSTANT("PKCS7_NOCERTS", PKCS7_NOCERTS, CONST_CS|CONST_PERSISTENT);
  924. REGISTER_LONG_CONSTANT("PKCS7_NOATTR", PKCS7_NOATTR, CONST_CS|CONST_PERSISTENT);
  925. REGISTER_LONG_CONSTANT("PKCS7_BINARY", PKCS7_BINARY, CONST_CS|CONST_PERSISTENT);
  926. REGISTER_LONG_CONSTANT("PKCS7_NOSIGS", PKCS7_NOSIGS, CONST_CS|CONST_PERSISTENT);
  927. REGISTER_LONG_CONSTANT("OPENSSL_PKCS1_PADDING", RSA_PKCS1_PADDING, CONST_CS|CONST_PERSISTENT);
  928. REGISTER_LONG_CONSTANT("OPENSSL_SSLV23_PADDING", RSA_SSLV23_PADDING, CONST_CS|CONST_PERSISTENT);
  929. REGISTER_LONG_CONSTANT("OPENSSL_NO_PADDING", RSA_NO_PADDING, CONST_CS|CONST_PERSISTENT);
  930. REGISTER_LONG_CONSTANT("OPENSSL_PKCS1_OAEP_PADDING", RSA_PKCS1_OAEP_PADDING, CONST_CS|CONST_PERSISTENT);
  931. /* Informational stream wrapper constants */
  932. REGISTER_STRING_CONSTANT("OPENSSL_DEFAULT_STREAM_CIPHERS", OPENSSL_DEFAULT_STREAM_CIPHERS, CONST_CS|CONST_PERSISTENT);
  933. /* Ciphers */
  934. #ifndef OPENSSL_NO_RC2
  935. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_RC2_40", PHP_OPENSSL_CIPHER_RC2_40, CONST_CS|CONST_PERSISTENT);
  936. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_RC2_128", PHP_OPENSSL_CIPHER_RC2_128, CONST_CS|CONST_PERSISTENT);
  937. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_RC2_64", PHP_OPENSSL_CIPHER_RC2_64, CONST_CS|CONST_PERSISTENT);
  938. #endif
  939. #ifndef OPENSSL_NO_DES
  940. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_DES", PHP_OPENSSL_CIPHER_DES, CONST_CS|CONST_PERSISTENT);
  941. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_3DES", PHP_OPENSSL_CIPHER_3DES, CONST_CS|CONST_PERSISTENT);
  942. #endif
  943. #ifndef OPENSSL_NO_AES
  944. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_AES_128_CBC", PHP_OPENSSL_CIPHER_AES_128_CBC, CONST_CS|CONST_PERSISTENT);
  945. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_AES_192_CBC", PHP_OPENSSL_CIPHER_AES_192_CBC, CONST_CS|CONST_PERSISTENT);
  946. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_AES_256_CBC", PHP_OPENSSL_CIPHER_AES_256_CBC, CONST_CS|CONST_PERSISTENT);
  947. #endif
  948. /* Values for key types */
  949. REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_RSA", OPENSSL_KEYTYPE_RSA, CONST_CS|CONST_PERSISTENT);
  950. #ifndef NO_DSA
  951. REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_DSA", OPENSSL_KEYTYPE_DSA, CONST_CS|CONST_PERSISTENT);
  952. #endif
  953. REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_DH", OPENSSL_KEYTYPE_DH, CONST_CS|CONST_PERSISTENT);
  954. #ifdef HAVE_EVP_PKEY_EC
  955. REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_EC", OPENSSL_KEYTYPE_EC, CONST_CS|CONST_PERSISTENT);
  956. #endif
  957. REGISTER_LONG_CONSTANT("OPENSSL_RAW_DATA", OPENSSL_RAW_DATA, CONST_CS|CONST_PERSISTENT);
  958. REGISTER_LONG_CONSTANT("OPENSSL_ZERO_PADDING", OPENSSL_ZERO_PADDING, CONST_CS|CONST_PERSISTENT);
  959. REGISTER_LONG_CONSTANT("OPENSSL_DONT_ZERO_PAD_KEY", OPENSSL_DONT_ZERO_PAD_KEY, CONST_CS|CONST_PERSISTENT);
  960. #ifndef OPENSSL_NO_TLSEXT
  961. /* SNI support included */
  962. REGISTER_LONG_CONSTANT("OPENSSL_TLSEXT_SERVER_NAME", 1, CONST_CS|CONST_PERSISTENT);
  963. #endif
  964. /* Determine default SSL configuration file */
  965. config_filename = getenv("OPENSSL_CONF");
  966. if (config_filename == NULL) {
  967. config_filename = getenv("SSLEAY_CONF");
  968. }
  969. /* default to 'openssl.cnf' if no environment variable is set */
  970. if (config_filename == NULL) {
  971. snprintf(default_ssl_conf_filename, sizeof(default_ssl_conf_filename), "%s/%s",
  972. X509_get_default_cert_area(),
  973. "openssl.cnf");
  974. } else {
  975. strlcpy(default_ssl_conf_filename, config_filename, sizeof(default_ssl_conf_filename));
  976. }
  977. php_stream_xport_register("ssl", php_openssl_ssl_socket_factory);
  978. #ifndef OPENSSL_NO_SSL3
  979. php_stream_xport_register("sslv3", php_openssl_ssl_socket_factory);
  980. #endif
  981. php_stream_xport_register("tls", php_openssl_ssl_socket_factory);
  982. php_stream_xport_register("tlsv1.0", php_openssl_ssl_socket_factory);
  983. php_stream_xport_register("tlsv1.1", php_openssl_ssl_socket_factory);
  984. php_stream_xport_register("tlsv1.2", php_openssl_ssl_socket_factory);
  985. #if OPENSSL_VERSION_NUMBER >= 0x10101000
  986. php_stream_xport_register("tlsv1.3", php_openssl_ssl_socket_factory);
  987. #endif
  988. /* override the default tcp socket provider */
  989. php_stream_xport_register("tcp", php_openssl_ssl_socket_factory);
  990. php_register_url_stream_wrapper("https", &php_stream_http_wrapper);
  991. php_register_url_stream_wrapper("ftps", &php_stream_ftp_wrapper);
  992. REGISTER_INI_ENTRIES();
  993. return SUCCESS;
  994. }
  995. /* }}} */
  996. /* {{{ PHP_GINIT_FUNCTION
  997. */
  998. PHP_GINIT_FUNCTION(openssl)
  999. {
  1000. #if defined(COMPILE_DL_OPENSSL) && defined(ZTS)
  1001. ZEND_TSRMLS_CACHE_UPDATE();
  1002. #endif
  1003. openssl_globals->errors = NULL;
  1004. }
  1005. /* }}} */
  1006. /* {{{ PHP_GSHUTDOWN_FUNCTION
  1007. */
  1008. PHP_GSHUTDOWN_FUNCTION(openssl)
  1009. {
  1010. if (openssl_globals->errors) {
  1011. pefree(openssl_globals->errors, 1);
  1012. }
  1013. }
  1014. /* }}} */
  1015. /* {{{ PHP_MINFO_FUNCTION
  1016. */
  1017. PHP_MINFO_FUNCTION(openssl)
  1018. {
  1019. php_info_print_table_start();
  1020. php_info_print_table_row(2, "OpenSSL support", "enabled");
  1021. php_info_print_table_row(2, "OpenSSL Library Version", OpenSSL_version(OPENSSL_VERSION));
  1022. php_info_print_table_row(2, "OpenSSL Header Version", OPENSSL_VERSION_TEXT);
  1023. php_info_print_table_row(2, "Openssl default config", default_ssl_conf_filename);
  1024. php_info_print_table_end();
  1025. DISPLAY_INI_ENTRIES();
  1026. }
  1027. /* }}} */
  1028. /* {{{ PHP_MSHUTDOWN_FUNCTION
  1029. */
  1030. PHP_MSHUTDOWN_FUNCTION(openssl)
  1031. {
  1032. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined (LIBRESSL_VERSION_NUMBER)
  1033. EVP_cleanup();
  1034. /* prevent accessing locking callback from unloaded extension */
  1035. CRYPTO_set_locking_callback(NULL);
  1036. /* free allocated error strings */
  1037. ERR_free_strings();
  1038. CONF_modules_free();
  1039. #endif
  1040. php_unregister_url_stream_wrapper("https");
  1041. php_unregister_url_stream_wrapper("ftps");
  1042. php_stream_xport_unregister("ssl");
  1043. #ifndef OPENSSL_NO_SSL3
  1044. php_stream_xport_unregister("sslv3");
  1045. #endif
  1046. php_stream_xport_unregister("tls");
  1047. php_stream_xport_unregister("tlsv1.0");
  1048. php_stream_xport_unregister("tlsv1.1");
  1049. php_stream_xport_unregister("tlsv1.2");
  1050. #if OPENSSL_VERSION_NUMBER >= 0x10101000
  1051. php_stream_xport_unregister("tlsv1.3");
  1052. #endif
  1053. /* reinstate the default tcp handler */
  1054. php_stream_xport_register("tcp", php_stream_generic_socket_factory);
  1055. UNREGISTER_INI_ENTRIES();
  1056. return SUCCESS;
  1057. }
  1058. /* }}} */
  1059. /* {{{ x509 cert functions */
  1060. /* {{{ proto array openssl_get_cert_locations(void)
  1061. Retrieve an array mapping available certificate locations */
  1062. PHP_FUNCTION(openssl_get_cert_locations)
  1063. {
  1064. if (zend_parse_parameters_none() == FAILURE) {
  1065. RETURN_THROWS();
  1066. }
  1067. array_init(return_value);
  1068. add_assoc_string(return_value, "default_cert_file", (char *) X509_get_default_cert_file());
  1069. add_assoc_string(return_value, "default_cert_file_env", (char *) X509_get_default_cert_file_env());
  1070. add_assoc_string(return_value, "default_cert_dir", (char *) X509_get_default_cert_dir());
  1071. add_assoc_string(return_value, "default_cert_dir_env", (char *) X509_get_default_cert_dir_env());
  1072. add_assoc_string(return_value, "default_private_dir", (char *) X509_get_default_private_dir());
  1073. add_assoc_string(return_value, "default_default_cert_area", (char *) X509_get_default_cert_area());
  1074. add_assoc_string(return_value, "ini_cafile",
  1075. zend_ini_string("openssl.cafile", sizeof("openssl.cafile")-1, 0));
  1076. add_assoc_string(return_value, "ini_capath",
  1077. zend_ini_string("openssl.capath", sizeof("openssl.capath")-1, 0));
  1078. }
  1079. /* }}} */
  1080. /* {{{ php_openssl_x509_from_zval
  1081. Given a zval, coerce it into an X509 object.
  1082. The zval can be:
  1083. . X509 resource created using openssl_read_x509()
  1084. . if it starts with file:// then it will be interpreted as the path to that cert
  1085. . it will be interpreted as the cert data
  1086. If you supply makeresource, the result will be registered as an x509 resource and
  1087. it's value returned in makeresource.
  1088. */
  1089. static X509 * php_openssl_x509_from_zval(zval * val, int makeresource, zend_resource **resourceval)
  1090. {
  1091. X509 *cert = NULL;
  1092. BIO *in;
  1093. if (resourceval) {
  1094. *resourceval = NULL;
  1095. }
  1096. if (Z_TYPE_P(val) == IS_RESOURCE) {
  1097. /* is it an x509 resource ? */
  1098. void * what;
  1099. zend_resource *res = Z_RES_P(val);
  1100. what = zend_fetch_resource(res, "OpenSSL X.509", le_x509);
  1101. if (!what) {
  1102. return NULL;
  1103. }
  1104. if (resourceval) {
  1105. *resourceval = res;
  1106. if (makeresource) {
  1107. Z_ADDREF_P(val);
  1108. }
  1109. }
  1110. return (X509*)what;
  1111. }
  1112. if (!(Z_TYPE_P(val) == IS_STRING || Z_TYPE_P(val) == IS_OBJECT)) {
  1113. return NULL;
  1114. }
  1115. /* force it to be a string and check if it refers to a file */
  1116. if (!try_convert_to_string(val)) {
  1117. return NULL;
  1118. }
  1119. if (Z_STRLEN_P(val) > 7 && memcmp(Z_STRVAL_P(val), "file://", sizeof("file://") - 1) == 0) {
  1120. if (php_openssl_open_base_dir_chk(Z_STRVAL_P(val) + (sizeof("file://") - 1))) {
  1121. return NULL;
  1122. }
  1123. in = BIO_new_file(Z_STRVAL_P(val) + (sizeof("file://") - 1), PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY));
  1124. if (in == NULL) {
  1125. php_openssl_store_errors();
  1126. return NULL;
  1127. }
  1128. cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
  1129. } else {
  1130. in = BIO_new_mem_buf(Z_STRVAL_P(val), (int)Z_STRLEN_P(val));
  1131. if (in == NULL) {
  1132. php_openssl_store_errors();
  1133. return NULL;
  1134. }
  1135. #ifdef TYPEDEF_D2I_OF
  1136. cert = (X509 *) PEM_ASN1_read_bio((d2i_of_void *)d2i_X509, PEM_STRING_X509, in, NULL, NULL, NULL);
  1137. #else
  1138. cert = (X509 *) PEM_ASN1_read_bio((char *(*)())d2i_X509, PEM_STRING_X509, in, NULL, NULL, NULL);
  1139. #endif
  1140. }
  1141. if (!BIO_free(in)) {
  1142. php_openssl_store_errors();
  1143. }
  1144. if (cert == NULL) {
  1145. php_openssl_store_errors();
  1146. return NULL;
  1147. }
  1148. if (makeresource && resourceval) {
  1149. *resourceval = zend_register_resource(cert, le_x509);
  1150. }
  1151. return cert;
  1152. }
  1153. /* }}} */
  1154. /* {{{ proto bool openssl_x509_export_to_file(mixed x509, string outfilename [, bool notext = true])
  1155. Exports a CERT to file or a var */
  1156. PHP_FUNCTION(openssl_x509_export_to_file)
  1157. {
  1158. X509 * cert;
  1159. zval * zcert;
  1160. zend_bool notext = 1;
  1161. BIO * bio_out;
  1162. char * filename;
  1163. size_t filename_len;
  1164. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zp|b", &zcert, &filename, &filename_len, &notext) == FAILURE) {
  1165. RETURN_THROWS();
  1166. }
  1167. RETVAL_FALSE;
  1168. cert = php_openssl_x509_from_zval(zcert, 0, NULL);
  1169. if (cert == NULL) {
  1170. php_error_docref(NULL, E_WARNING, "Cannot get cert from parameter 1");
  1171. return;
  1172. }
  1173. if (php_openssl_open_base_dir_chk(filename)) {
  1174. return;
  1175. }
  1176. bio_out = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY));
  1177. if (bio_out) {
  1178. if (!notext && !X509_print(bio_out, cert)) {
  1179. php_openssl_store_errors();
  1180. }
  1181. if (!PEM_write_bio_X509(bio_out, cert)) {
  1182. php_openssl_store_errors();
  1183. }
  1184. RETVAL_TRUE;
  1185. } else {
  1186. php_openssl_store_errors();
  1187. php_error_docref(NULL, E_WARNING, "Error opening file %s", filename);
  1188. }
  1189. if (Z_TYPE_P(zcert) != IS_RESOURCE) {
  1190. X509_free(cert);
  1191. }
  1192. if (!BIO_free(bio_out)) {
  1193. php_openssl_store_errors();
  1194. }
  1195. }
  1196. /* }}} */
  1197. /* {{{ proto string openssl_spki_new(mixed zpkey, string challenge [, mixed method])
  1198. Creates new private key (or uses existing) and creates a new spki cert
  1199. outputting results to var */
  1200. PHP_FUNCTION(openssl_spki_new)
  1201. {
  1202. size_t challenge_len;
  1203. char * challenge = NULL, * spkstr = NULL;
  1204. zend_string * s = NULL;
  1205. zend_resource *keyresource = NULL;
  1206. const char *spkac = "SPKAC=";
  1207. zend_long algo = OPENSSL_ALGO_MD5;
  1208. zval * zpkey = NULL;
  1209. EVP_PKEY * pkey = NULL;
  1210. NETSCAPE_SPKI *spki=NULL;
  1211. const EVP_MD *mdtype;
  1212. if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|l", &zpkey, &challenge, &challenge_len, &algo) == FAILURE) {
  1213. RETURN_THROWS();
  1214. }
  1215. RETVAL_FALSE;
  1216. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(challenge_len, challenge);
  1217. pkey = php_openssl_evp_from_zval(zpkey, 0, challenge, challenge_len, 1, &keyresource);
  1218. if (pkey == NULL) {
  1219. if (!EG(exception)) {
  1220. php_error_docref(NULL, E_WARNING, "Unable to use supplied private key");
  1221. }
  1222. goto cleanup;
  1223. }
  1224. mdtype = php_openssl_get_evp_md_from_algo(algo);
  1225. if (!mdtype) {
  1226. php_error_docref(NULL, E_WARNING, "Unknown signature algorithm");
  1227. goto cleanup;
  1228. }
  1229. if ((spki = NETSCAPE_SPKI_new()) == NULL) {
  1230. php_openssl_store_errors();
  1231. php_error_docref(NULL, E_WARNING, "Unable to create new SPKAC");
  1232. goto cleanup;
  1233. }
  1234. if (challenge) {
  1235. if (!ASN1_STRING_set(spki->spkac->challenge, challenge, (int)challenge_len)) {
  1236. php_openssl_store_errors();
  1237. php_error_docref(NULL, E_WARNING, "Unable to set challenge data");
  1238. goto cleanup;
  1239. }
  1240. }
  1241. if (!NETSCAPE_SPKI_set_pubkey(spki, pkey)) {
  1242. php_openssl_store_errors();
  1243. php_error_docref(NULL, E_WARNING, "Unable to embed public key");
  1244. goto cleanup;
  1245. }
  1246. if (!NETSCAPE_SPKI_sign(spki, pkey, mdtype)) {
  1247. php_openssl_store_errors();
  1248. php_error_docref(NULL, E_WARNING, "Unable to sign with specified algorithm");
  1249. goto cleanup;
  1250. }
  1251. spkstr = NETSCAPE_SPKI_b64_encode(spki);
  1252. if (!spkstr){
  1253. php_openssl_store_errors();
  1254. php_error_docref(NULL, E_WARNING, "Unable to encode SPKAC");
  1255. goto cleanup;
  1256. }
  1257. s = zend_string_alloc(strlen(spkac) + strlen(spkstr), 0);
  1258. sprintf(ZSTR_VAL(s), "%s%s", spkac, spkstr);
  1259. ZSTR_LEN(s) = strlen(ZSTR_VAL(s));
  1260. OPENSSL_free(spkstr);
  1261. RETVAL_STR(s);
  1262. goto cleanup;
  1263. cleanup:
  1264. if (spki != NULL) {
  1265. NETSCAPE_SPKI_free(spki);
  1266. }
  1267. if (keyresource == NULL && pkey != NULL) {
  1268. EVP_PKEY_free(pkey);
  1269. }
  1270. if (s && ZSTR_LEN(s) <= 0) {
  1271. RETVAL_FALSE;
  1272. }
  1273. if (keyresource == NULL && s != NULL) {
  1274. zend_string_release_ex(s, 0);
  1275. }
  1276. }
  1277. /* }}} */
  1278. /* {{{ proto bool openssl_spki_verify(string spki)
  1279. Verifies spki returns boolean */
  1280. PHP_FUNCTION(openssl_spki_verify)
  1281. {
  1282. size_t spkstr_len;
  1283. int i = 0, spkstr_cleaned_len = 0;
  1284. char *spkstr, * spkstr_cleaned = NULL;
  1285. EVP_PKEY *pkey = NULL;
  1286. NETSCAPE_SPKI *spki = NULL;
  1287. if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &spkstr, &spkstr_len) == FAILURE) {
  1288. RETURN_THROWS();
  1289. }
  1290. RETVAL_FALSE;
  1291. spkstr_cleaned = emalloc(spkstr_len + 1);
  1292. spkstr_cleaned_len = (int)(spkstr_len - php_openssl_spki_cleanup(spkstr, spkstr_cleaned));
  1293. if (spkstr_cleaned_len == 0) {
  1294. php_error_docref(NULL, E_WARNING, "Invalid SPKAC");
  1295. goto cleanup;
  1296. }
  1297. spki = NETSCAPE_SPKI_b64_decode(spkstr_cleaned, spkstr_cleaned_len);
  1298. if (spki == NULL) {
  1299. php_openssl_store_errors();
  1300. php_error_docref(NULL, E_WARNING, "Unable to decode supplied SPKAC");
  1301. goto cleanup;
  1302. }
  1303. pkey = X509_PUBKEY_get(spki->spkac->pubkey);
  1304. if (pkey == NULL) {
  1305. php_openssl_store_errors();
  1306. php_error_docref(NULL, E_WARNING, "Unable to acquire signed public key");
  1307. goto cleanup;
  1308. }
  1309. i = NETSCAPE_SPKI_verify(spki, pkey);
  1310. goto cleanup;
  1311. cleanup:
  1312. if (spki != NULL) {
  1313. NETSCAPE_SPKI_free(spki);
  1314. }
  1315. if (pkey != NULL) {
  1316. EVP_PKEY_free(pkey);
  1317. }
  1318. if (spkstr_cleaned != NULL) {
  1319. efree(spkstr_cleaned);
  1320. }
  1321. if (i > 0) {
  1322. RETVAL_TRUE;
  1323. } else {
  1324. php_openssl_store_errors();
  1325. }
  1326. }
  1327. /* }}} */
  1328. /* {{{ proto string openssl_spki_export(string spki)
  1329. Exports public key from existing spki to var */
  1330. PHP_FUNCTION(openssl_spki_export)
  1331. {
  1332. size_t spkstr_len;
  1333. char *spkstr, * spkstr_cleaned = NULL, * s = NULL;
  1334. int spkstr_cleaned_len;
  1335. EVP_PKEY *pkey = NULL;
  1336. NETSCAPE_SPKI *spki = NULL;
  1337. BIO *out = NULL;
  1338. if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &spkstr, &spkstr_len) == FAILURE) {
  1339. RETURN_THROWS();
  1340. }
  1341. RETVAL_FALSE;
  1342. spkstr_cleaned = emalloc(spkstr_len + 1);
  1343. spkstr_cleaned_len = (int)(spkstr_len - php_openssl_spki_cleanup(spkstr, spkstr_cleaned));
  1344. if (spkstr_cleaned_len == 0) {
  1345. php_error_docref(NULL, E_WARNING, "Invalid SPKAC");
  1346. goto cleanup;
  1347. }
  1348. spki = NETSCAPE_SPKI_b64_decode(spkstr_cleaned, spkstr_cleaned_len);
  1349. if (spki == NULL) {
  1350. php_openssl_store_errors();
  1351. php_error_docref(NULL, E_WARNING, "Unable to decode supplied SPKAC");
  1352. goto cleanup;
  1353. }
  1354. pkey = X509_PUBKEY_get(spki->spkac->pubkey);
  1355. if (pkey == NULL) {
  1356. php_openssl_store_errors();
  1357. php_error_docref(NULL, E_WARNING, "Unable to acquire signed public key");
  1358. goto cleanup;
  1359. }
  1360. out = BIO_new(BIO_s_mem());
  1361. if (out && PEM_write_bio_PUBKEY(out, pkey)) {
  1362. BUF_MEM *bio_buf;
  1363. BIO_get_mem_ptr(out, &bio_buf);
  1364. RETVAL_STRINGL((char *)bio_buf->data, bio_buf->length);
  1365. } else {
  1366. php_openssl_store_errors();
  1367. }
  1368. goto cleanup;
  1369. cleanup:
  1370. if (spki != NULL) {
  1371. NETSCAPE_SPKI_free(spki);
  1372. }
  1373. if (out != NULL) {
  1374. BIO_free_all(out);
  1375. }
  1376. if (pkey != NULL) {
  1377. EVP_PKEY_free(pkey);
  1378. }
  1379. if (spkstr_cleaned != NULL) {
  1380. efree(spkstr_cleaned);
  1381. }
  1382. if (s != NULL) {
  1383. efree(s);
  1384. }
  1385. }
  1386. /* }}} */
  1387. /* {{{ proto string openssl_spki_export_challenge(string spki)
  1388. Exports spkac challenge from existing spki to var */
  1389. PHP_FUNCTION(openssl_spki_export_challenge)
  1390. {
  1391. size_t spkstr_len;
  1392. char *spkstr, * spkstr_cleaned = NULL;
  1393. int spkstr_cleaned_len;
  1394. NETSCAPE_SPKI *spki = NULL;
  1395. if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &spkstr, &spkstr_len) == FAILURE) {
  1396. RETURN_THROWS();
  1397. }
  1398. RETVAL_FALSE;
  1399. spkstr_cleaned = emalloc(spkstr_len + 1);
  1400. spkstr_cleaned_len = (int)(spkstr_len - php_openssl_spki_cleanup(spkstr, spkstr_cleaned));
  1401. if (spkstr_cleaned_len == 0) {
  1402. php_error_docref(NULL, E_WARNING, "Invalid SPKAC");
  1403. goto cleanup;
  1404. }
  1405. spki = NETSCAPE_SPKI_b64_decode(spkstr_cleaned, spkstr_cleaned_len);
  1406. if (spki == NULL) {
  1407. php_openssl_store_errors();
  1408. php_error_docref(NULL, E_WARNING, "Unable to decode SPKAC");
  1409. goto cleanup;
  1410. }
  1411. RETVAL_STRING((const char *)ASN1_STRING_get0_data(spki->spkac->challenge));
  1412. goto cleanup;
  1413. cleanup:
  1414. if (spkstr_cleaned != NULL) {
  1415. efree(spkstr_cleaned);
  1416. }
  1417. if (spki) {
  1418. NETSCAPE_SPKI_free(spki);
  1419. }
  1420. }
  1421. /* }}} */
  1422. /* {{{ proto bool openssl_x509_export(mixed x509, string &out [, bool notext = true])
  1423. Exports a CERT to file or a var */
  1424. PHP_FUNCTION(openssl_x509_export)
  1425. {
  1426. X509 * cert;
  1427. zval * zcert, *zout;
  1428. zend_bool notext = 1;
  1429. BIO * bio_out;
  1430. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz|b", &zcert, &zout, &notext) == FAILURE) {
  1431. RETURN_THROWS();
  1432. }
  1433. RETVAL_FALSE;
  1434. cert = php_openssl_x509_from_zval(zcert, 0, NULL);
  1435. if (cert == NULL) {
  1436. php_error_docref(NULL, E_WARNING, "Cannot get cert from parameter 1");
  1437. return;
  1438. }
  1439. bio_out = BIO_new(BIO_s_mem());
  1440. if (!bio_out) {
  1441. php_openssl_store_errors();
  1442. goto cleanup;
  1443. }
  1444. if (!notext && !X509_print(bio_out, cert)) {
  1445. php_openssl_store_errors();
  1446. }
  1447. if (PEM_write_bio_X509(bio_out, cert)) {
  1448. BUF_MEM *bio_buf;
  1449. BIO_get_mem_ptr(bio_out, &bio_buf);
  1450. ZEND_TRY_ASSIGN_REF_STRINGL(zout, bio_buf->data, bio_buf->length);
  1451. RETVAL_TRUE;
  1452. } else {
  1453. php_openssl_store_errors();
  1454. }
  1455. BIO_free(bio_out);
  1456. cleanup:
  1457. if (Z_TYPE_P(zcert) != IS_RESOURCE) {
  1458. X509_free(cert);
  1459. }
  1460. }
  1461. /* }}} */
  1462. zend_string* php_openssl_x509_fingerprint(X509 *peer, const char *method, zend_bool raw)
  1463. {
  1464. unsigned char md[EVP_MAX_MD_SIZE];
  1465. const EVP_MD *mdtype;
  1466. unsigned int n;
  1467. zend_string *ret;
  1468. if (!(mdtype = EVP_get_digestbyname(method))) {
  1469. php_error_docref(NULL, E_WARNING, "Unknown signature algorithm");
  1470. return NULL;
  1471. } else if (!X509_digest(peer, mdtype, md, &n)) {
  1472. php_openssl_store_errors();
  1473. php_error_docref(NULL, E_ERROR, "Could not generate signature");
  1474. return NULL;
  1475. }
  1476. if (raw) {
  1477. ret = zend_string_init((char*)md, n, 0);
  1478. } else {
  1479. ret = zend_string_alloc(n * 2, 0);
  1480. make_digest_ex(ZSTR_VAL(ret), md, n);
  1481. ZSTR_VAL(ret)[n * 2] = '\0';
  1482. }
  1483. return ret;
  1484. }
  1485. PHP_FUNCTION(openssl_x509_fingerprint)
  1486. {
  1487. X509 *cert;
  1488. zval *zcert;
  1489. zend_bool raw_output = 0;
  1490. char *method = "sha1";
  1491. size_t method_len;
  1492. zend_string *fingerprint;
  1493. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|sb", &zcert, &method, &method_len, &raw_output) == FAILURE) {
  1494. RETURN_THROWS();
  1495. }
  1496. cert = php_openssl_x509_from_zval(zcert, 0, NULL);
  1497. if (cert == NULL) {
  1498. php_error_docref(NULL, E_WARNING, "Cannot get cert from parameter 1");
  1499. RETURN_FALSE;
  1500. }
  1501. fingerprint = php_openssl_x509_fingerprint(cert, method, raw_output);
  1502. if (fingerprint) {
  1503. RETVAL_STR(fingerprint);
  1504. } else {
  1505. RETVAL_FALSE;
  1506. }
  1507. if (Z_TYPE_P(zcert) != IS_RESOURCE) {
  1508. X509_free(cert);
  1509. }
  1510. }
  1511. /* {{{ proto bool openssl_x509_check_private_key(mixed cert, mixed key)
  1512. Checks if a private key corresponds to a CERT */
  1513. PHP_FUNCTION(openssl_x509_check_private_key)
  1514. {
  1515. zval * zcert, *zkey;
  1516. X509 * cert = NULL;
  1517. EVP_PKEY * key = NULL;
  1518. zend_resource *keyresource = NULL;
  1519. RETVAL_FALSE;
  1520. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zcert, &zkey) == FAILURE) {
  1521. RETURN_THROWS();
  1522. }
  1523. cert = php_openssl_x509_from_zval(zcert, 0, NULL);
  1524. if (cert == NULL) {
  1525. RETURN_FALSE;
  1526. }
  1527. key = php_openssl_evp_from_zval(zkey, 0, "", 0, 1, &keyresource);
  1528. if (key) {
  1529. RETVAL_BOOL(X509_check_private_key(cert, key));
  1530. }
  1531. if (keyresource == NULL && key) {
  1532. EVP_PKEY_free(key);
  1533. }
  1534. if (Z_TYPE_P(zcert) != IS_RESOURCE) {
  1535. X509_free(cert);
  1536. }
  1537. }
  1538. /* }}} */
  1539. /* {{{ proto int openssl_x509_verify(mixed cert, mixed key)
  1540. Verifies the signature of certificate cert using public key key */
  1541. PHP_FUNCTION(openssl_x509_verify)
  1542. {
  1543. zval * zcert, *zkey;
  1544. X509 * cert = NULL;
  1545. EVP_PKEY * key = NULL;
  1546. zend_resource *keyresource = NULL;
  1547. int err = -1;
  1548. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zcert, &zkey) == FAILURE) {
  1549. RETURN_THROWS();
  1550. }
  1551. cert = php_openssl_x509_from_zval(zcert, 0, NULL);
  1552. if (cert == NULL) {
  1553. RETURN_LONG(err);
  1554. }
  1555. key = php_openssl_evp_from_zval(zkey, 1, NULL, 0, 0, &keyresource);
  1556. if (key == NULL) {
  1557. X509_free(cert);
  1558. RETURN_LONG(err);
  1559. }
  1560. err = X509_verify(cert, key);
  1561. if (err < 0) {
  1562. php_openssl_store_errors();
  1563. }
  1564. if (keyresource == NULL && key) {
  1565. EVP_PKEY_free(key);
  1566. }
  1567. if (Z_TYPE_P(zcert) != IS_RESOURCE) {
  1568. X509_free(cert);
  1569. }
  1570. RETURN_LONG(err);
  1571. }
  1572. /* }}} */
  1573. /* Special handling of subjectAltName, see CVE-2013-4073
  1574. * Christian Heimes
  1575. */
  1576. static int openssl_x509v3_subjectAltName(BIO *bio, X509_EXTENSION *extension)
  1577. {
  1578. GENERAL_NAMES *names;
  1579. const X509V3_EXT_METHOD *method = NULL;
  1580. ASN1_OCTET_STRING *extension_data;
  1581. long i, length, num;
  1582. const unsigned char *p;
  1583. method = X509V3_EXT_get(extension);
  1584. if (method == NULL) {
  1585. return -1;
  1586. }
  1587. extension_data = X509_EXTENSION_get_data(extension);
  1588. p = extension_data->data;
  1589. length = extension_data->length;
  1590. if (method->it) {
  1591. names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL, &p, length,
  1592. ASN1_ITEM_ptr(method->it)));
  1593. } else {
  1594. names = (GENERAL_NAMES*) (method->d2i(NULL, &p, length));
  1595. }
  1596. if (names == NULL) {
  1597. php_openssl_store_errors();
  1598. return -1;
  1599. }
  1600. num = sk_GENERAL_NAME_num(names);
  1601. for (i = 0; i < num; i++) {
  1602. GENERAL_NAME *name;
  1603. ASN1_STRING *as;
  1604. name = sk_GENERAL_NAME_value(names, i);
  1605. switch (name->type) {
  1606. case GEN_EMAIL:
  1607. BIO_puts(bio, "email:");
  1608. as = name->d.rfc822Name;
  1609. BIO_write(bio, ASN1_STRING_get0_data(as),
  1610. ASN1_STRING_length(as));
  1611. break;
  1612. case GEN_DNS:
  1613. BIO_puts(bio, "DNS:");
  1614. as = name->d.dNSName;
  1615. BIO_write(bio, ASN1_STRING_get0_data(as),
  1616. ASN1_STRING_length(as));
  1617. break;
  1618. case GEN_URI:
  1619. BIO_puts(bio, "URI:");
  1620. as = name->d.uniformResourceIdentifier;
  1621. BIO_write(bio, ASN1_STRING_get0_data(as),
  1622. ASN1_STRING_length(as));
  1623. break;
  1624. default:
  1625. /* use builtin print for GEN_OTHERNAME, GEN_X400,
  1626. * GEN_EDIPARTY, GEN_DIRNAME, GEN_IPADD and GEN_RID
  1627. */
  1628. GENERAL_NAME_print(bio, name);
  1629. }
  1630. /* trailing ', ' except for last element */
  1631. if (i < (num - 1)) {
  1632. BIO_puts(bio, ", ");
  1633. }
  1634. }
  1635. sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
  1636. return 0;
  1637. }
  1638. /* {{{ proto array openssl_x509_parse(mixed x509 [, bool shortnames=true])
  1639. Returns an array of the fields/values of the CERT */
  1640. PHP_FUNCTION(openssl_x509_parse)
  1641. {
  1642. zval * zcert;
  1643. X509 * cert = NULL;
  1644. int i, sig_nid;
  1645. zend_bool useshortnames = 1;
  1646. char * tmpstr;
  1647. zval subitem;
  1648. X509_EXTENSION *extension;
  1649. X509_NAME *subject_name;
  1650. char *cert_name;
  1651. char *extname;
  1652. BIO *bio_out;
  1653. BUF_MEM *bio_buf;
  1654. ASN1_INTEGER *asn1_serial;
  1655. BIGNUM *bn_serial;
  1656. char *str_serial;
  1657. char *hex_serial;
  1658. char buf[256];
  1659. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|b", &zcert, &useshortnames) == FAILURE) {
  1660. RETURN_THROWS();
  1661. }
  1662. cert = php_openssl_x509_from_zval(zcert, 0, NULL);
  1663. if (cert == NULL) {
  1664. RETURN_FALSE;
  1665. }
  1666. array_init(return_value);
  1667. subject_name = X509_get_subject_name(cert);
  1668. cert_name = X509_NAME_oneline(subject_name, NULL, 0);
  1669. add_assoc_string(return_value, "name", cert_name);
  1670. OPENSSL_free(cert_name);
  1671. php_openssl_add_assoc_name_entry(return_value, "subject", subject_name, useshortnames);
  1672. /* hash as used in CA directories to lookup cert by subject name */
  1673. {
  1674. char buf[32];
  1675. snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert));
  1676. add_assoc_string(return_value, "hash", buf);
  1677. }
  1678. php_openssl_add_assoc_name_entry(return_value, "issuer", X509_get_issuer_name(cert), useshortnames);
  1679. add_assoc_long(return_value, "version", X509_get_version(cert));
  1680. asn1_serial = X509_get_serialNumber(cert);
  1681. bn_serial = ASN1_INTEGER_to_BN(asn1_serial, NULL);
  1682. /* Can return NULL on error or memory allocation failure */
  1683. if (!bn_serial) {
  1684. php_openssl_store_errors();
  1685. RETURN_FALSE;
  1686. }
  1687. hex_serial = BN_bn2hex(bn_serial);
  1688. BN_free(bn_serial);
  1689. /* Can return NULL on error or memory allocation failure */
  1690. if (!hex_serial) {
  1691. php_openssl_store_errors();
  1692. RETURN_FALSE;
  1693. }
  1694. str_serial = i2s_ASN1_INTEGER(NULL, asn1_serial);
  1695. add_assoc_string(return_value, "serialNumber", str_serial);
  1696. OPENSSL_free(str_serial);
  1697. /* Return the hex representation of the serial number, as defined by OpenSSL */
  1698. add_assoc_string(return_value, "serialNumberHex", hex_serial);
  1699. OPENSSL_free(hex_serial);
  1700. php_openssl_add_assoc_asn1_string(return_value, "validFrom", X509_getm_notBefore(cert));
  1701. php_openssl_add_assoc_asn1_string(return_value, "validTo", X509_getm_notAfter(cert));
  1702. add_assoc_long(return_value, "validFrom_time_t", php_openssl_asn1_time_to_time_t(X509_getm_notBefore(cert)));
  1703. add_assoc_long(return_value, "validTo_time_t", php_openssl_asn1_time_to_time_t(X509_getm_notAfter(cert)));
  1704. tmpstr = (char *)X509_alias_get0(cert, NULL);
  1705. if (tmpstr) {
  1706. add_assoc_string(return_value, "alias", tmpstr);
  1707. }
  1708. sig_nid = X509_get_signature_nid(cert);
  1709. add_assoc_string(return_value, "signatureTypeSN", (char*)OBJ_nid2sn(sig_nid));
  1710. add_assoc_string(return_value, "signatureTypeLN", (char*)OBJ_nid2ln(sig_nid));
  1711. add_assoc_long(return_value, "signatureTypeNID", sig_nid);
  1712. array_init(&subitem);
  1713. /* NOTE: the purposes are added as integer keys - the keys match up to the X509_PURPOSE_SSL_XXX defines
  1714. in x509v3.h */
  1715. for (i = 0; i < X509_PURPOSE_get_count(); i++) {
  1716. int id, purpset;
  1717. char * pname;
  1718. X509_PURPOSE * purp;
  1719. zval subsub;
  1720. array_init(&subsub);
  1721. purp = X509_PURPOSE_get0(i);
  1722. id = X509_PURPOSE_get_id(purp);
  1723. purpset = X509_check_purpose(cert, id, 0);
  1724. add_index_bool(&subsub, 0, purpset);
  1725. purpset = X509_check_purpose(cert, id, 1);
  1726. add_index_bool(&subsub, 1, purpset);
  1727. pname = useshortnames ? X509_PURPOSE_get0_sname(purp) : X509_PURPOSE_get0_name(purp);
  1728. add_index_string(&subsub, 2, pname);
  1729. /* NOTE: if purpset > 1 then it's a warning - we should mention it ? */
  1730. add_index_zval(&subitem, id, &subsub);
  1731. }
  1732. add_assoc_zval(return_value, "purposes", &subitem);
  1733. array_init(&subitem);
  1734. for (i = 0; i < X509_get_ext_count(cert); i++) {
  1735. int nid;
  1736. extension = X509_get_ext(cert, i);
  1737. nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension));
  1738. if (nid != NID_undef) {
  1739. extname = (char *)OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(extension)));
  1740. } else {
  1741. OBJ_obj2txt(buf, sizeof(buf)-1, X509_EXTENSION_get_object(extension), 1);
  1742. extname = buf;
  1743. }
  1744. bio_out = BIO_new(BIO_s_mem());
  1745. if (bio_out == NULL) {
  1746. php_openssl_store_errors();
  1747. RETURN_FALSE;
  1748. }
  1749. if (nid == NID_subject_alt_name) {
  1750. if (openssl_x509v3_subjectAltName(bio_out, extension) == 0) {
  1751. BIO_get_mem_ptr(bio_out, &bio_buf);
  1752. add_assoc_stringl(&subitem, extname, bio_buf->data, bio_buf->length);
  1753. } else {
  1754. zend_array_destroy(Z_ARR_P(return_value));
  1755. BIO_free(bio_out);
  1756. if (Z_TYPE_P(zcert) != IS_RESOURCE) {
  1757. X509_free(cert);
  1758. }
  1759. RETURN_FALSE;
  1760. }
  1761. }
  1762. else if (X509V3_EXT_print(bio_out, extension, 0, 0)) {
  1763. BIO_get_mem_ptr(bio_out, &bio_buf);
  1764. add_assoc_stringl(&subitem, extname, bio_buf->data, bio_buf->length);
  1765. } else {
  1766. php_openssl_add_assoc_asn1_string(&subitem, extname, X509_EXTENSION_get_data(extension));
  1767. }
  1768. BIO_free(bio_out);
  1769. }
  1770. add_assoc_zval(return_value, "extensions", &subitem);
  1771. if (Z_TYPE_P(zcert) != IS_RESOURCE) {
  1772. X509_free(cert);
  1773. }
  1774. }
  1775. /* }}} */
  1776. /* {{{ php_openssl_load_all_certs_from_file */
  1777. static STACK_OF(X509) *php_openssl_load_all_certs_from_file(char *certfile)
  1778. {
  1779. STACK_OF(X509_INFO) *sk=NULL;
  1780. STACK_OF(X509) *stack=NULL, *ret=NULL;
  1781. BIO *in=NULL;
  1782. X509_INFO *xi;
  1783. if(!(stack = sk_X509_new_null())) {
  1784. php_openssl_store_errors();
  1785. php_error_docref(NULL, E_ERROR, "Memory allocation failure");
  1786. goto end;
  1787. }
  1788. if (php_openssl_open_base_dir_chk(certfile)) {
  1789. sk_X509_free(stack);
  1790. goto end;
  1791. }
  1792. if (!(in=BIO_new_file(certfile, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY)))) {
  1793. php_openssl_store_errors();
  1794. php_error_docref(NULL, E_WARNING, "Error opening the file, %s", certfile);
  1795. sk_X509_free(stack);
  1796. goto end;
  1797. }
  1798. /* This loads from a file, a stack of x509/crl/pkey sets */
  1799. if (!(sk=PEM_X509_INFO_read_bio(in, NULL, NULL, NULL))) {
  1800. php_openssl_store_errors();
  1801. php_error_docref(NULL, E_WARNING, "Error reading the file, %s", certfile);
  1802. sk_X509_free(stack);
  1803. goto end;
  1804. }
  1805. /* scan over it and pull out the certs */
  1806. while (sk_X509_INFO_num(sk)) {
  1807. xi=sk_X509_INFO_shift(sk);
  1808. if (xi->x509 != NULL) {
  1809. sk_X509_push(stack,xi->x509);
  1810. xi->x509=NULL;
  1811. }
  1812. X509_INFO_free(xi);
  1813. }
  1814. if (!sk_X509_num(stack)) {
  1815. php_error_docref(NULL, E_WARNING, "No certificates in file, %s", certfile);
  1816. sk_X509_free(stack);
  1817. goto end;
  1818. }
  1819. ret = stack;
  1820. end:
  1821. BIO_free(in);
  1822. sk_X509_INFO_free(sk);
  1823. return ret;
  1824. }
  1825. /* }}} */
  1826. /* {{{ check_cert */
  1827. static int check_cert(X509_STORE *ctx, X509 *x, STACK_OF(X509) *untrustedchain, int purpose)
  1828. {
  1829. int ret=0;
  1830. X509_STORE_CTX *csc;
  1831. csc = X509_STORE_CTX_new();
  1832. if (csc == NULL) {
  1833. php_openssl_store_errors();
  1834. php_error_docref(NULL, E_ERROR, "Memory allocation failure");
  1835. return 0;
  1836. }
  1837. if (!X509_STORE_CTX_init(csc, ctx, x, untrustedchain)) {
  1838. php_openssl_store_errors();
  1839. php_error_docref(NULL, E_WARNING, "Certificate store initialization failed");
  1840. return 0;
  1841. }
  1842. if (purpose >= 0 && !X509_STORE_CTX_set_purpose(csc, purpose)) {
  1843. php_openssl_store_errors();
  1844. }
  1845. ret = X509_verify_cert(csc);
  1846. if (ret < 0) {
  1847. php_openssl_store_errors();
  1848. }
  1849. X509_STORE_CTX_free(csc);
  1850. return ret;
  1851. }
  1852. /* }}} */
  1853. /* {{{ proto int openssl_x509_checkpurpose(mixed x509cert, int purpose, array cainfo [, string untrustedfile])
  1854. Checks the CERT to see if it can be used for the purpose in purpose. cainfo holds information about trusted CAs */
  1855. PHP_FUNCTION(openssl_x509_checkpurpose)
  1856. {
  1857. zval * zcert, * zcainfo = NULL;
  1858. X509_STORE * cainfo = NULL;
  1859. X509 * cert = NULL;
  1860. STACK_OF(X509) * untrustedchain = NULL;
  1861. zend_long purpose;
  1862. char * untrusted = NULL;
  1863. size_t untrusted_len = 0;
  1864. int ret;
  1865. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zl|a!s", &zcert, &purpose, &zcainfo, &untrusted, &untrusted_len) == FAILURE) {
  1866. RETURN_THROWS();
  1867. }
  1868. RETVAL_LONG(-1);
  1869. if (untrusted) {
  1870. untrustedchain = php_openssl_load_all_certs_from_file(untrusted);
  1871. if (untrustedchain == NULL) {
  1872. goto clean_exit;
  1873. }
  1874. }
  1875. cainfo = php_openssl_setup_verify(zcainfo);
  1876. if (cainfo == NULL) {
  1877. goto clean_exit;
  1878. }
  1879. cert = php_openssl_x509_from_zval(zcert, 0, NULL);
  1880. if (cert == NULL) {
  1881. goto clean_exit;
  1882. }
  1883. ret = check_cert(cainfo, cert, untrustedchain, (int)purpose);
  1884. if (ret != 0 && ret != 1) {
  1885. RETVAL_LONG(ret);
  1886. } else {
  1887. RETVAL_BOOL(ret);
  1888. }
  1889. if (Z_TYPE_P(zcert) != IS_RESOURCE) {
  1890. X509_free(cert);
  1891. }
  1892. clean_exit:
  1893. if (cainfo) {
  1894. X509_STORE_free(cainfo);
  1895. }
  1896. if (untrustedchain) {
  1897. sk_X509_pop_free(untrustedchain, X509_free);
  1898. }
  1899. }
  1900. /* }}} */
  1901. /* {{{ php_openssl_setup_verify
  1902. * calist is an array containing file and directory names. create a
  1903. * certificate store and add those certs to it for use in verification.
  1904. */
  1905. static X509_STORE *php_openssl_setup_verify(zval *calist)
  1906. {
  1907. X509_STORE *store;
  1908. X509_LOOKUP * dir_lookup, * file_lookup;
  1909. int ndirs = 0, nfiles = 0;
  1910. zval * item;
  1911. zend_stat_t sb;
  1912. store = X509_STORE_new();
  1913. if (store == NULL) {
  1914. php_openssl_store_errors();
  1915. return NULL;
  1916. }
  1917. if (calist && (Z_TYPE_P(calist) == IS_ARRAY)) {
  1918. ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(calist), item) {
  1919. zend_string *str = zval_try_get_string(item);
  1920. if (UNEXPECTED(!str)) {
  1921. return NULL;
  1922. }
  1923. if (VCWD_STAT(ZSTR_VAL(str), &sb) == -1) {
  1924. php_error_docref(NULL, E_WARNING, "Unable to stat %s", ZSTR_VAL(str));
  1925. zend_string_release(str);
  1926. continue;
  1927. }
  1928. if ((sb.st_mode & S_IFREG) == S_IFREG) {
  1929. file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
  1930. if (file_lookup == NULL || !X509_LOOKUP_load_file(file_lookup, ZSTR_VAL(str), X509_FILETYPE_PEM)) {
  1931. php_openssl_store_errors();
  1932. php_error_docref(NULL, E_WARNING, "Error loading file %s", ZSTR_VAL(str));
  1933. } else {
  1934. nfiles++;
  1935. }
  1936. file_lookup = NULL;
  1937. } else {
  1938. dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
  1939. if (dir_lookup == NULL || !X509_LOOKUP_add_dir(dir_lookup, ZSTR_VAL(str), X509_FILETYPE_PEM)) {
  1940. php_openssl_store_errors();
  1941. php_error_docref(NULL, E_WARNING, "Error loading directory %s", ZSTR_VAL(str));
  1942. } else {
  1943. ndirs++;
  1944. }
  1945. dir_lookup = NULL;
  1946. }
  1947. zend_string_release(str);
  1948. } ZEND_HASH_FOREACH_END();
  1949. }
  1950. if (nfiles == 0) {
  1951. file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
  1952. if (file_lookup == NULL || !X509_LOOKUP_load_file(file_lookup, NULL, X509_FILETYPE_DEFAULT)) {
  1953. php_openssl_store_errors();
  1954. }
  1955. }
  1956. if (ndirs == 0) {
  1957. dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
  1958. if (dir_lookup == NULL || !X509_LOOKUP_add_dir(dir_lookup, NULL, X509_FILETYPE_DEFAULT)) {
  1959. php_openssl_store_errors();
  1960. }
  1961. }
  1962. return store;
  1963. }
  1964. /* }}} */
  1965. /* {{{ proto resource openssl_x509_read(mixed cert)
  1966. Reads X.509 certificates */
  1967. PHP_FUNCTION(openssl_x509_read)
  1968. {
  1969. zval *cert;
  1970. X509 *x509;
  1971. zend_resource *res;
  1972. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &cert) == FAILURE) {
  1973. RETURN_THROWS();
  1974. }
  1975. x509 = php_openssl_x509_from_zval(cert, 1, &res);
  1976. ZVAL_RES(return_value, res);
  1977. if (x509 == NULL) {
  1978. php_error_docref(NULL, E_WARNING, "Supplied parameter cannot be coerced into an X509 certificate!");
  1979. RETURN_FALSE;
  1980. }
  1981. }
  1982. /* }}} */
  1983. /* {{{ proto void openssl_x509_free(resource x509)
  1984. Frees X.509 certificates */
  1985. PHP_FUNCTION(openssl_x509_free)
  1986. {
  1987. zval *x509;
  1988. X509 *cert;
  1989. if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &x509) == FAILURE) {
  1990. RETURN_THROWS();
  1991. }
  1992. if ((cert = (X509 *)zend_fetch_resource(Z_RES_P(x509), "OpenSSL X.509", le_x509)) == NULL) {
  1993. RETURN_THROWS();
  1994. }
  1995. zend_list_close(Z_RES_P(x509));
  1996. }
  1997. /* }}} */
  1998. /* }}} */
  1999. /* Pop all X509 from Stack and free them, free the stack afterwards */
  2000. static void php_sk_X509_free(STACK_OF(X509) * sk) /* {{{ */
  2001. {
  2002. for (;;) {
  2003. X509* x = sk_X509_pop(sk);
  2004. if (!x) break;
  2005. X509_free(x);
  2006. }
  2007. sk_X509_free(sk);
  2008. }
  2009. /* }}} */
  2010. static STACK_OF(X509) * php_array_to_X509_sk(zval * zcerts) /* {{{ */
  2011. {
  2012. zval * zcertval;
  2013. STACK_OF(X509) * sk = NULL;
  2014. X509 * cert;
  2015. zend_resource *certresource;
  2016. sk = sk_X509_new_null();
  2017. /* get certs */
  2018. if (Z_TYPE_P(zcerts) == IS_ARRAY) {
  2019. ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(zcerts), zcertval) {
  2020. cert = php_openssl_x509_from_zval(zcertval, 0, &certresource);
  2021. if (cert == NULL) {
  2022. goto clean_exit;
  2023. }
  2024. if (certresource != NULL) {
  2025. cert = X509_dup(cert);
  2026. if (cert == NULL) {
  2027. php_openssl_store_errors();
  2028. goto clean_exit;
  2029. }
  2030. }
  2031. sk_X509_push(sk, cert);
  2032. } ZEND_HASH_FOREACH_END();
  2033. } else {
  2034. /* a single certificate */
  2035. cert = php_openssl_x509_from_zval(zcerts, 0, &certresource);
  2036. if (cert == NULL) {
  2037. goto clean_exit;
  2038. }
  2039. if (certresource != NULL) {
  2040. cert = X509_dup(cert);
  2041. if (cert == NULL) {
  2042. php_openssl_store_errors();
  2043. goto clean_exit;
  2044. }
  2045. }
  2046. sk_X509_push(sk, cert);
  2047. }
  2048. clean_exit:
  2049. return sk;
  2050. }
  2051. /* }}} */
  2052. /* {{{ proto bool openssl_pkcs12_export_to_file(mixed x509, string filename, mixed priv_key, string pass[, array args])
  2053. Creates and exports a PKCS to file */
  2054. PHP_FUNCTION(openssl_pkcs12_export_to_file)
  2055. {
  2056. X509 * cert = NULL;
  2057. BIO * bio_out = NULL;
  2058. PKCS12 * p12 = NULL;
  2059. char * filename;
  2060. char * friendly_name = NULL;
  2061. size_t filename_len;
  2062. char * pass;
  2063. size_t pass_len;
  2064. zval *zcert = NULL, *zpkey = NULL, *args = NULL;
  2065. EVP_PKEY *priv_key = NULL;
  2066. zend_resource *keyresource;
  2067. zval * item;
  2068. STACK_OF(X509) *ca = NULL;
  2069. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zpzs|a", &zcert, &filename, &filename_len, &zpkey, &pass, &pass_len, &args) == FAILURE)
  2070. RETURN_THROWS();
  2071. RETVAL_FALSE;
  2072. cert = php_openssl_x509_from_zval(zcert, 0, NULL);
  2073. if (cert == NULL) {
  2074. php_error_docref(NULL, E_WARNING, "Cannot get cert from parameter 1");
  2075. return;
  2076. }
  2077. priv_key = php_openssl_evp_from_zval(zpkey, 0, "", 0, 1, &keyresource);
  2078. if (priv_key == NULL) {
  2079. if (!EG(exception)) {
  2080. php_error_docref(NULL, E_WARNING, "Cannot get private key from parameter 3");
  2081. }
  2082. goto cleanup;
  2083. }
  2084. if (!X509_check_private_key(cert, priv_key)) {
  2085. php_openssl_store_errors();
  2086. php_error_docref(NULL, E_WARNING, "Private key does not correspond to cert");
  2087. goto cleanup;
  2088. }
  2089. if (php_openssl_open_base_dir_chk(filename)) {
  2090. goto cleanup;
  2091. }
  2092. /* parse extra config from args array, promote this to an extra function */
  2093. if (args &&
  2094. (item = zend_hash_str_find(Z_ARRVAL_P(args), "friendly_name", sizeof("friendly_name")-1)) != NULL &&
  2095. Z_TYPE_P(item) == IS_STRING
  2096. ) {
  2097. friendly_name = Z_STRVAL_P(item);
  2098. }
  2099. /* certpbe (default RC2-40)
  2100. keypbe (default 3DES)
  2101. friendly_caname
  2102. */
  2103. if (args && (item = zend_hash_str_find(Z_ARRVAL_P(args), "extracerts", sizeof("extracerts")-1)) != NULL) {
  2104. ca = php_array_to_X509_sk(item);
  2105. }
  2106. /* end parse extra config */
  2107. /*PKCS12 *PKCS12_create(char *pass, char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca,
  2108. int nid_key, int nid_cert, int iter, int mac_iter, int keytype);*/
  2109. p12 = PKCS12_create(pass, friendly_name, priv_key, cert, ca, 0, 0, 0, 0, 0);
  2110. if (p12 != NULL) {
  2111. bio_out = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY));
  2112. if (bio_out != NULL) {
  2113. i2d_PKCS12_bio(bio_out, p12);
  2114. BIO_free(bio_out);
  2115. RETVAL_TRUE;
  2116. } else {
  2117. php_openssl_store_errors();
  2118. php_error_docref(NULL, E_WARNING, "Error opening file %s", filename);
  2119. }
  2120. PKCS12_free(p12);
  2121. } else {
  2122. php_openssl_store_errors();
  2123. }
  2124. php_sk_X509_free(ca);
  2125. cleanup:
  2126. if (keyresource == NULL && priv_key) {
  2127. EVP_PKEY_free(priv_key);
  2128. }
  2129. if (Z_TYPE_P(zcert) != IS_RESOURCE) {
  2130. X509_free(cert);
  2131. }
  2132. }
  2133. /* }}} */
  2134. /* {{{ proto bool openssl_pkcs12_export(mixed x509, string &out, mixed priv_key, string pass[, array args])
  2135. Creates and exports a PKCS12 to a var */
  2136. PHP_FUNCTION(openssl_pkcs12_export)
  2137. {
  2138. X509 * cert = NULL;
  2139. BIO * bio_out;
  2140. PKCS12 * p12 = NULL;
  2141. zval * zcert = NULL, *zout = NULL, *zpkey, *args = NULL;
  2142. EVP_PKEY *priv_key = NULL;
  2143. zend_resource *keyresource;
  2144. char * pass;
  2145. size_t pass_len;
  2146. char * friendly_name = NULL;
  2147. zval * item;
  2148. STACK_OF(X509) *ca = NULL;
  2149. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zzzs|a", &zcert, &zout, &zpkey, &pass, &pass_len, &args) == FAILURE) {
  2150. RETURN_THROWS();
  2151. }
  2152. RETVAL_FALSE;
  2153. cert = php_openssl_x509_from_zval(zcert, 0, NULL);
  2154. if (cert == NULL) {
  2155. php_error_docref(NULL, E_WARNING, "Cannot get cert from parameter 1");
  2156. return;
  2157. }
  2158. priv_key = php_openssl_evp_from_zval(zpkey, 0, "", 0, 1, &keyresource);
  2159. if (priv_key == NULL) {
  2160. if (!EG(exception)) {
  2161. php_error_docref(NULL, E_WARNING, "Cannot get private key from parameter 3");
  2162. }
  2163. goto cleanup;
  2164. }
  2165. if (!X509_check_private_key(cert, priv_key)) {
  2166. php_error_docref(NULL, E_WARNING, "Private key does not correspond to cert");
  2167. goto cleanup;
  2168. }
  2169. /* parse extra config from args array, promote this to an extra function */
  2170. if (args &&
  2171. (item = zend_hash_str_find(Z_ARRVAL_P(args), "friendly_name", sizeof("friendly_name")-1)) != NULL &&
  2172. Z_TYPE_P(item) == IS_STRING
  2173. ) {
  2174. friendly_name = Z_STRVAL_P(item);
  2175. }
  2176. if (args && (item = zend_hash_str_find(Z_ARRVAL_P(args), "extracerts", sizeof("extracerts")-1)) != NULL) {
  2177. ca = php_array_to_X509_sk(item);
  2178. }
  2179. /* end parse extra config */
  2180. p12 = PKCS12_create(pass, friendly_name, priv_key, cert, ca, 0, 0, 0, 0, 0);
  2181. if (p12 != NULL) {
  2182. bio_out = BIO_new(BIO_s_mem());
  2183. if (i2d_PKCS12_bio(bio_out, p12)) {
  2184. BUF_MEM *bio_buf;
  2185. BIO_get_mem_ptr(bio_out, &bio_buf);
  2186. ZEND_TRY_ASSIGN_REF_STRINGL(zout, bio_buf->data, bio_buf->length);
  2187. RETVAL_TRUE;
  2188. } else {
  2189. php_openssl_store_errors();
  2190. }
  2191. BIO_free(bio_out);
  2192. PKCS12_free(p12);
  2193. } else {
  2194. php_openssl_store_errors();
  2195. }
  2196. php_sk_X509_free(ca);
  2197. cleanup:
  2198. if (keyresource == NULL && priv_key) {
  2199. EVP_PKEY_free(priv_key);
  2200. }
  2201. if (Z_TYPE_P(zcert) != IS_RESOURCE) {
  2202. X509_free(cert);
  2203. }
  2204. }
  2205. /* }}} */
  2206. /* {{{ proto bool openssl_pkcs12_read(string PKCS12, array &certs, string pass)
  2207. Parses a PKCS12 to an array */
  2208. PHP_FUNCTION(openssl_pkcs12_read)
  2209. {
  2210. zval *zout = NULL, zextracerts, zcert, zpkey;
  2211. char *pass, *zp12;
  2212. size_t pass_len, zp12_len;
  2213. PKCS12 * p12 = NULL;
  2214. EVP_PKEY * pkey = NULL;
  2215. X509 * cert = NULL;
  2216. STACK_OF(X509) * ca = NULL;
  2217. BIO * bio_in = NULL;
  2218. int i;
  2219. if (zend_parse_parameters(ZEND_NUM_ARGS(), "szs", &zp12, &zp12_len, &zout, &pass, &pass_len) == FAILURE) {
  2220. RETURN_THROWS();
  2221. }
  2222. RETVAL_FALSE;
  2223. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(zp12_len, pkcs12);
  2224. bio_in = BIO_new(BIO_s_mem());
  2225. if (0 >= BIO_write(bio_in, zp12, (int)zp12_len)) {
  2226. php_openssl_store_errors();
  2227. goto cleanup;
  2228. }
  2229. if (d2i_PKCS12_bio(bio_in, &p12) && PKCS12_parse(p12, pass, &pkey, &cert, &ca)) {
  2230. BIO * bio_out;
  2231. int cert_num;
  2232. zout = zend_try_array_init(zout);
  2233. if (!zout) {
  2234. goto cleanup;
  2235. }
  2236. if (cert) {
  2237. bio_out = BIO_new(BIO_s_mem());
  2238. if (PEM_write_bio_X509(bio_out, cert)) {
  2239. BUF_MEM *bio_buf;
  2240. BIO_get_mem_ptr(bio_out, &bio_buf);
  2241. ZVAL_STRINGL(&zcert, bio_buf->data, bio_buf->length);
  2242. add_assoc_zval(zout, "cert", &zcert);
  2243. } else {
  2244. php_openssl_store_errors();
  2245. }
  2246. BIO_free(bio_out);
  2247. }
  2248. if (pkey) {
  2249. bio_out = BIO_new(BIO_s_mem());
  2250. if (PEM_write_bio_PrivateKey(bio_out, pkey, NULL, NULL, 0, 0, NULL)) {
  2251. BUF_MEM *bio_buf;
  2252. BIO_get_mem_ptr(bio_out, &bio_buf);
  2253. ZVAL_STRINGL(&zpkey, bio_buf->data, bio_buf->length);
  2254. add_assoc_zval(zout, "pkey", &zpkey);
  2255. } else {
  2256. php_openssl_store_errors();
  2257. }
  2258. BIO_free(bio_out);
  2259. }
  2260. cert_num = sk_X509_num(ca);
  2261. if (ca && cert_num) {
  2262. array_init(&zextracerts);
  2263. for (i = 0; i < cert_num; i++) {
  2264. zval zextracert;
  2265. X509* aCA = sk_X509_pop(ca);
  2266. if (!aCA) break;
  2267. bio_out = BIO_new(BIO_s_mem());
  2268. if (PEM_write_bio_X509(bio_out, aCA)) {
  2269. BUF_MEM *bio_buf;
  2270. BIO_get_mem_ptr(bio_out, &bio_buf);
  2271. ZVAL_STRINGL(&zextracert, bio_buf->data, bio_buf->length);
  2272. add_index_zval(&zextracerts, i, &zextracert);
  2273. }
  2274. X509_free(aCA);
  2275. BIO_free(bio_out);
  2276. }
  2277. sk_X509_free(ca);
  2278. add_assoc_zval(zout, "extracerts", &zextracerts);
  2279. }
  2280. RETVAL_TRUE;
  2281. } else {
  2282. php_openssl_store_errors();
  2283. }
  2284. cleanup:
  2285. if (bio_in) {
  2286. BIO_free(bio_in);
  2287. }
  2288. if (pkey) {
  2289. EVP_PKEY_free(pkey);
  2290. }
  2291. if (cert) {
  2292. X509_free(cert);
  2293. }
  2294. if (p12) {
  2295. PKCS12_free(p12);
  2296. }
  2297. }
  2298. /* }}} */
  2299. /* {{{ x509 CSR functions */
  2300. /* {{{ php_openssl_make_REQ */
  2301. static int php_openssl_make_REQ(struct php_x509_request * req, X509_REQ * csr, zval * dn, zval * attribs)
  2302. {
  2303. STACK_OF(CONF_VALUE) * dn_sk, *attr_sk = NULL;
  2304. char * str, *dn_sect, *attr_sect;
  2305. dn_sect = CONF_get_string(req->req_config, req->section_name, "distinguished_name");
  2306. if (dn_sect == NULL) {
  2307. php_openssl_store_errors();
  2308. return FAILURE;
  2309. }
  2310. dn_sk = CONF_get_section(req->req_config, dn_sect);
  2311. if (dn_sk == NULL) {
  2312. php_openssl_store_errors();
  2313. return FAILURE;
  2314. }
  2315. attr_sect = CONF_get_string(req->req_config, req->section_name, "attributes");
  2316. if (attr_sect == NULL) {
  2317. php_openssl_store_errors();
  2318. attr_sk = NULL;
  2319. } else {
  2320. attr_sk = CONF_get_section(req->req_config, attr_sect);
  2321. if (attr_sk == NULL) {
  2322. php_openssl_store_errors();
  2323. return FAILURE;
  2324. }
  2325. }
  2326. /* setup the version number: version 1 */
  2327. if (X509_REQ_set_version(csr, 0L)) {
  2328. int i, nid;
  2329. char * type;
  2330. CONF_VALUE * v;
  2331. X509_NAME * subj;
  2332. zval * item;
  2333. zend_string * strindex = NULL;
  2334. subj = X509_REQ_get_subject_name(csr);
  2335. /* apply values from the dn hash */
  2336. ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(dn), strindex, item) {
  2337. if (strindex) {
  2338. int nid = OBJ_txt2nid(ZSTR_VAL(strindex));
  2339. if (nid != NID_undef) {
  2340. zend_string *str_item = zval_try_get_string(item);
  2341. if (UNEXPECTED(!str_item)) {
  2342. return FAILURE;
  2343. }
  2344. if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_UTF8,
  2345. (unsigned char*)ZSTR_VAL(str_item), -1, -1, 0))
  2346. {
  2347. php_openssl_store_errors();
  2348. php_error_docref(NULL, E_WARNING,
  2349. "dn: add_entry_by_NID %d -> %s (failed; check error"
  2350. " queue and value of string_mask OpenSSL option "
  2351. "if illegal characters are reported)",
  2352. nid, ZSTR_VAL(str_item));
  2353. zend_string_release(str_item);
  2354. return FAILURE;
  2355. }
  2356. zend_string_release(str_item);
  2357. } else {
  2358. php_error_docref(NULL, E_WARNING, "dn: %s is not a recognized name", ZSTR_VAL(strindex));
  2359. }
  2360. }
  2361. } ZEND_HASH_FOREACH_END();
  2362. /* Finally apply defaults from config file */
  2363. for(i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
  2364. size_t len;
  2365. char buffer[200 + 1]; /*200 + \0 !*/
  2366. v = sk_CONF_VALUE_value(dn_sk, i);
  2367. type = v->name;
  2368. len = strlen(type);
  2369. if (len < sizeof("_default")) {
  2370. continue;
  2371. }
  2372. len -= sizeof("_default") - 1;
  2373. if (strcmp("_default", type + len) != 0) {
  2374. continue;
  2375. }
  2376. if (len > 200) {
  2377. len = 200;
  2378. }
  2379. memcpy(buffer, type, len);
  2380. buffer[len] = '\0';
  2381. type = buffer;
  2382. /* Skip past any leading X. X: X, etc to allow for multiple
  2383. * instances */
  2384. for (str = type; *str; str++) {
  2385. if (*str == ':' || *str == ',' || *str == '.') {
  2386. str++;
  2387. if (*str) {
  2388. type = str;
  2389. }
  2390. break;
  2391. }
  2392. }
  2393. /* if it is already set, skip this */
  2394. nid = OBJ_txt2nid(type);
  2395. if (X509_NAME_get_index_by_NID(subj, nid, -1) >= 0) {
  2396. continue;
  2397. }
  2398. if (!X509_NAME_add_entry_by_txt(subj, type, MBSTRING_UTF8, (unsigned char*)v->value, -1, -1, 0)) {
  2399. php_openssl_store_errors();
  2400. php_error_docref(NULL, E_WARNING, "add_entry_by_txt %s -> %s (failed)", type, v->value);
  2401. return FAILURE;
  2402. }
  2403. if (!X509_NAME_entry_count(subj)) {
  2404. php_error_docref(NULL, E_WARNING, "No objects specified in config file");
  2405. return FAILURE;
  2406. }
  2407. }
  2408. if (attribs) {
  2409. ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(attribs), strindex, item) {
  2410. int nid;
  2411. if (NULL == strindex) {
  2412. php_error_docref(NULL, E_WARNING, "dn: numeric fild names are not supported");
  2413. continue;
  2414. }
  2415. nid = OBJ_txt2nid(ZSTR_VAL(strindex));
  2416. if (nid != NID_undef) {
  2417. zend_string *str_item = zval_try_get_string(item);
  2418. if (UNEXPECTED(!str_item)) {
  2419. return FAILURE;
  2420. }
  2421. if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_UTF8, (unsigned char*)ZSTR_VAL(str_item), -1, -1, 0)) {
  2422. php_openssl_store_errors();
  2423. php_error_docref(NULL, E_WARNING, "attribs: add_entry_by_NID %d -> %s (failed)", nid, ZSTR_VAL(str_item));
  2424. zend_string_release(str_item);
  2425. return FAILURE;
  2426. }
  2427. zend_string_release(str_item);
  2428. } else {
  2429. php_error_docref(NULL, E_WARNING, "dn: %s is not a recognized name", ZSTR_VAL(strindex));
  2430. }
  2431. } ZEND_HASH_FOREACH_END();
  2432. for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
  2433. v = sk_CONF_VALUE_value(attr_sk, i);
  2434. /* if it is already set, skip this */
  2435. nid = OBJ_txt2nid(v->name);
  2436. if (X509_REQ_get_attr_by_NID(csr, nid, -1) >= 0) {
  2437. continue;
  2438. }
  2439. if (!X509_REQ_add1_attr_by_txt(csr, v->name, MBSTRING_UTF8, (unsigned char*)v->value, -1)) {
  2440. php_openssl_store_errors();
  2441. php_error_docref(NULL, E_WARNING,
  2442. "add1_attr_by_txt %s -> %s (failed; check error queue "
  2443. "and value of string_mask OpenSSL option if illegal "
  2444. "characters are reported)",
  2445. v->name, v->value);
  2446. return FAILURE;
  2447. }
  2448. }
  2449. }
  2450. } else {
  2451. php_openssl_store_errors();
  2452. }
  2453. if (!X509_REQ_set_pubkey(csr, req->priv_key)) {
  2454. php_openssl_store_errors();
  2455. }
  2456. return SUCCESS;
  2457. }
  2458. /* }}} */
  2459. /* {{{ php_openssl_csr_from_zval */
  2460. static X509_REQ * php_openssl_csr_from_zval(zval * val, int makeresource, zend_resource **resourceval)
  2461. {
  2462. X509_REQ * csr = NULL;
  2463. char * filename = NULL;
  2464. BIO * in;
  2465. if (resourceval) {
  2466. *resourceval = NULL;
  2467. }
  2468. if (Z_TYPE_P(val) == IS_RESOURCE) {
  2469. void * what;
  2470. zend_resource *res = Z_RES_P(val);
  2471. what = zend_fetch_resource(res, "OpenSSL X.509 CSR", le_csr);
  2472. if (what) {
  2473. if (resourceval) {
  2474. *resourceval = res;
  2475. if (makeresource) {
  2476. Z_ADDREF_P(val);
  2477. }
  2478. }
  2479. return (X509_REQ*)what;
  2480. }
  2481. return NULL;
  2482. } else if (Z_TYPE_P(val) != IS_STRING) {
  2483. return NULL;
  2484. }
  2485. if (Z_STRLEN_P(val) > 7 && memcmp(Z_STRVAL_P(val), "file://", sizeof("file://") - 1) == 0) {
  2486. filename = Z_STRVAL_P(val) + (sizeof("file://") - 1);
  2487. }
  2488. if (filename) {
  2489. if (php_openssl_open_base_dir_chk(filename)) {
  2490. return NULL;
  2491. }
  2492. in = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY));
  2493. } else {
  2494. in = BIO_new_mem_buf(Z_STRVAL_P(val), (int)Z_STRLEN_P(val));
  2495. }
  2496. if (in == NULL) {
  2497. php_openssl_store_errors();
  2498. return NULL;
  2499. }
  2500. csr = PEM_read_bio_X509_REQ(in, NULL,NULL,NULL);
  2501. if (csr == NULL) {
  2502. php_openssl_store_errors();
  2503. }
  2504. BIO_free(in);
  2505. return csr;
  2506. }
  2507. /* }}} */
  2508. /* {{{ proto bool openssl_csr_export_to_file(resource csr, string outfilename [, bool notext=true])
  2509. Exports a CSR to file */
  2510. PHP_FUNCTION(openssl_csr_export_to_file)
  2511. {
  2512. X509_REQ * csr;
  2513. zval * zcsr = NULL;
  2514. zend_bool notext = 1;
  2515. char * filename = NULL;
  2516. size_t filename_len;
  2517. BIO * bio_out;
  2518. zend_resource *csr_resource;
  2519. if (zend_parse_parameters(ZEND_NUM_ARGS(), "rp|b", &zcsr, &filename, &filename_len, &notext) == FAILURE) {
  2520. RETURN_THROWS();
  2521. }
  2522. RETVAL_FALSE;
  2523. csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource);
  2524. if (csr == NULL) {
  2525. if (!EG(exception)) {
  2526. php_error_docref(NULL, E_WARNING, "Cannot get CSR from parameter 1");
  2527. }
  2528. return;
  2529. }
  2530. if (php_openssl_open_base_dir_chk(filename)) {
  2531. return;
  2532. }
  2533. bio_out = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY));
  2534. if (bio_out != NULL) {
  2535. if (!notext && !X509_REQ_print(bio_out, csr)) {
  2536. php_openssl_store_errors();
  2537. }
  2538. if (!PEM_write_bio_X509_REQ(bio_out, csr)) {
  2539. php_error_docref(NULL, E_WARNING, "Error writing PEM to file %s", filename);
  2540. php_openssl_store_errors();
  2541. } else {
  2542. RETVAL_TRUE;
  2543. }
  2544. BIO_free(bio_out);
  2545. } else {
  2546. php_openssl_store_errors();
  2547. php_error_docref(NULL, E_WARNING, "Error opening file %s", filename);
  2548. }
  2549. if (csr_resource == NULL && csr != NULL) {
  2550. X509_REQ_free(csr);
  2551. }
  2552. }
  2553. /* }}} */
  2554. /* {{{ proto bool openssl_csr_export(resource csr, string &out [, bool notext=true])
  2555. Exports a CSR to file or a var */
  2556. PHP_FUNCTION(openssl_csr_export)
  2557. {
  2558. X509_REQ * csr;
  2559. zval * zcsr = NULL, *zout=NULL;
  2560. zend_bool notext = 1;
  2561. BIO * bio_out;
  2562. zend_resource *csr_resource;
  2563. if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz|b", &zcsr, &zout, &notext) == FAILURE) {
  2564. RETURN_THROWS();
  2565. }
  2566. RETVAL_FALSE;
  2567. csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource);
  2568. if (csr == NULL) {
  2569. if (!EG(exception)) {
  2570. php_error_docref(NULL, E_WARNING, "Cannot get CSR from parameter 1");
  2571. }
  2572. return;
  2573. }
  2574. /* export to a var */
  2575. bio_out = BIO_new(BIO_s_mem());
  2576. if (!notext && !X509_REQ_print(bio_out, csr)) {
  2577. php_openssl_store_errors();
  2578. }
  2579. if (PEM_write_bio_X509_REQ(bio_out, csr)) {
  2580. BUF_MEM *bio_buf;
  2581. BIO_get_mem_ptr(bio_out, &bio_buf);
  2582. ZEND_TRY_ASSIGN_REF_STRINGL(zout, bio_buf->data, bio_buf->length);
  2583. RETVAL_TRUE;
  2584. } else {
  2585. php_openssl_store_errors();
  2586. }
  2587. if (csr_resource == NULL && csr) {
  2588. X509_REQ_free(csr);
  2589. }
  2590. BIO_free(bio_out);
  2591. }
  2592. /* }}} */
  2593. /* {{{ proto resource openssl_csr_sign(mixed csr, mixed x509, mixed priv_key, int days [, array config_args [, int serial]])
  2594. Signs a cert with another CERT */
  2595. PHP_FUNCTION(openssl_csr_sign)
  2596. {
  2597. zval * zcert = NULL, *zcsr, *zpkey, *args = NULL;
  2598. zend_long num_days;
  2599. zend_long serial = Z_L(0);
  2600. X509 * cert = NULL, *new_cert = NULL;
  2601. X509_REQ * csr;
  2602. EVP_PKEY * key = NULL, *priv_key = NULL;
  2603. zend_resource *csr_resource, *certresource = NULL, *keyresource = NULL;
  2604. int i;
  2605. struct php_x509_request req;
  2606. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz!zl|a!l", &zcsr, &zcert, &zpkey, &num_days, &args, &serial) == FAILURE) {
  2607. RETURN_THROWS();
  2608. }
  2609. RETVAL_FALSE;
  2610. PHP_SSL_REQ_INIT(&req);
  2611. csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource);
  2612. if (csr == NULL) {
  2613. if (!EG(exception)) {
  2614. php_error_docref(NULL, E_WARNING, "Cannot get CSR from parameter 1");
  2615. }
  2616. return;
  2617. }
  2618. if (zcert) {
  2619. cert = php_openssl_x509_from_zval(zcert, 0, &certresource);
  2620. if (cert == NULL) {
  2621. php_error_docref(NULL, E_WARNING, "Cannot get cert from parameter 2");
  2622. goto cleanup;
  2623. }
  2624. }
  2625. priv_key = php_openssl_evp_from_zval(zpkey, 0, "", 0, 1, &keyresource);
  2626. if (priv_key == NULL) {
  2627. if (!EG(exception)) {
  2628. php_error_docref(NULL, E_WARNING, "Cannot get private key from parameter 3");
  2629. }
  2630. goto cleanup;
  2631. }
  2632. if (cert && !X509_check_private_key(cert, priv_key)) {
  2633. php_openssl_store_errors();
  2634. php_error_docref(NULL, E_WARNING, "Private key does not correspond to signing cert");
  2635. goto cleanup;
  2636. }
  2637. if (PHP_SSL_REQ_PARSE(&req, args) == FAILURE) {
  2638. goto cleanup;
  2639. }
  2640. /* Check that the request matches the signature */
  2641. key = X509_REQ_get_pubkey(csr);
  2642. if (key == NULL) {
  2643. php_openssl_store_errors();
  2644. php_error_docref(NULL, E_WARNING, "Error unpacking public key");
  2645. goto cleanup;
  2646. }
  2647. i = X509_REQ_verify(csr, key);
  2648. if (i < 0) {
  2649. php_openssl_store_errors();
  2650. php_error_docref(NULL, E_WARNING, "Signature verification problems");
  2651. goto cleanup;
  2652. }
  2653. else if (i == 0) {
  2654. php_error_docref(NULL, E_WARNING, "Signature did not match the certificate request");
  2655. goto cleanup;
  2656. }
  2657. /* Now we can get on with it */
  2658. new_cert = X509_new();
  2659. if (new_cert == NULL) {
  2660. php_openssl_store_errors();
  2661. php_error_docref(NULL, E_WARNING, "No memory");
  2662. goto cleanup;
  2663. }
  2664. /* Version 3 cert */
  2665. if (!X509_set_version(new_cert, 2)) {
  2666. goto cleanup;
  2667. }
  2668. ASN1_INTEGER_set(X509_get_serialNumber(new_cert), (long)serial);
  2669. X509_set_subject_name(new_cert, X509_REQ_get_subject_name(csr));
  2670. if (cert == NULL) {
  2671. cert = new_cert;
  2672. }
  2673. if (!X509_set_issuer_name(new_cert, X509_get_subject_name(cert))) {
  2674. php_openssl_store_errors();
  2675. goto cleanup;
  2676. }
  2677. X509_gmtime_adj(X509_getm_notBefore(new_cert), 0);
  2678. X509_gmtime_adj(X509_getm_notAfter(new_cert), 60*60*24*(long)num_days);
  2679. i = X509_set_pubkey(new_cert, key);
  2680. if (!i) {
  2681. php_openssl_store_errors();
  2682. goto cleanup;
  2683. }
  2684. if (req.extensions_section) {
  2685. X509V3_CTX ctx;
  2686. X509V3_set_ctx(&ctx, cert, new_cert, csr, NULL, 0);
  2687. X509V3_set_conf_lhash(&ctx, req.req_config);
  2688. if (!X509V3_EXT_add_conf(req.req_config, &ctx, req.extensions_section, new_cert)) {
  2689. php_openssl_store_errors();
  2690. goto cleanup;
  2691. }
  2692. }
  2693. /* Now sign it */
  2694. if (!X509_sign(new_cert, priv_key, req.digest)) {
  2695. php_openssl_store_errors();
  2696. php_error_docref(NULL, E_WARNING, "Failed to sign it");
  2697. goto cleanup;
  2698. }
  2699. /* Succeeded; lets return the cert */
  2700. ZVAL_RES(return_value, zend_register_resource(new_cert, le_x509));
  2701. new_cert = NULL;
  2702. cleanup:
  2703. if (cert == new_cert) {
  2704. cert = NULL;
  2705. }
  2706. PHP_SSL_REQ_DISPOSE(&req);
  2707. if (keyresource == NULL && priv_key) {
  2708. EVP_PKEY_free(priv_key);
  2709. }
  2710. if (key) {
  2711. EVP_PKEY_free(key);
  2712. }
  2713. if (csr_resource == NULL && csr) {
  2714. X509_REQ_free(csr);
  2715. }
  2716. if (zcert && certresource == NULL && cert) {
  2717. X509_free(cert);
  2718. }
  2719. if (new_cert) {
  2720. X509_free(new_cert);
  2721. }
  2722. }
  2723. /* }}} */
  2724. /* {{{ proto bool openssl_csr_new(array dn, resource &privkey [, array configargs [, array extraattribs]])
  2725. Generates a privkey and CSR */
  2726. PHP_FUNCTION(openssl_csr_new)
  2727. {
  2728. struct php_x509_request req;
  2729. zval * args = NULL, * dn, *attribs = NULL;
  2730. zval * out_pkey;
  2731. X509_REQ * csr = NULL;
  2732. int we_made_the_key = 1;
  2733. zend_resource *key_resource;
  2734. if (zend_parse_parameters(ZEND_NUM_ARGS(), "az|a!a!", &dn, &out_pkey, &args, &attribs) == FAILURE) {
  2735. RETURN_THROWS();
  2736. }
  2737. RETVAL_FALSE;
  2738. PHP_SSL_REQ_INIT(&req);
  2739. if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) {
  2740. zval *out_pkey_val = out_pkey;
  2741. ZVAL_DEREF(out_pkey_val);
  2742. /* Generate or use a private key */
  2743. if (Z_TYPE_P(out_pkey_val) != IS_NULL) {
  2744. req.priv_key = php_openssl_evp_from_zval(out_pkey_val, 0, NULL, 0, 0, &key_resource);
  2745. if (req.priv_key != NULL) {
  2746. we_made_the_key = 0;
  2747. }
  2748. }
  2749. if (req.priv_key == NULL) {
  2750. php_openssl_generate_private_key(&req);
  2751. }
  2752. if (req.priv_key == NULL) {
  2753. php_error_docref(NULL, E_WARNING, "Unable to generate a private key");
  2754. } else {
  2755. csr = X509_REQ_new();
  2756. if (csr) {
  2757. if (php_openssl_make_REQ(&req, csr, dn, attribs) == SUCCESS) {
  2758. X509V3_CTX ext_ctx;
  2759. X509V3_set_ctx(&ext_ctx, NULL, NULL, csr, NULL, 0);
  2760. X509V3_set_conf_lhash(&ext_ctx, req.req_config);
  2761. /* Add extensions */
  2762. if (req.request_extensions_section && !X509V3_EXT_REQ_add_conf(req.req_config,
  2763. &ext_ctx, req.request_extensions_section, csr))
  2764. {
  2765. php_openssl_store_errors();
  2766. php_error_docref(NULL, E_WARNING, "Error loading extension section %s", req.request_extensions_section);
  2767. } else {
  2768. RETVAL_TRUE;
  2769. if (X509_REQ_sign(csr, req.priv_key, req.digest)) {
  2770. ZVAL_RES(return_value, zend_register_resource(csr, le_csr));
  2771. csr = NULL;
  2772. } else {
  2773. php_openssl_store_errors();
  2774. php_error_docref(NULL, E_WARNING, "Error signing request");
  2775. }
  2776. if (we_made_the_key) {
  2777. /* and a resource for the private key */
  2778. ZEND_TRY_ASSIGN_REF_RES(out_pkey, zend_register_resource(req.priv_key, le_key));
  2779. req.priv_key = NULL; /* make sure the cleanup code doesn't zap it! */
  2780. } else if (key_resource != NULL) {
  2781. req.priv_key = NULL; /* make sure the cleanup code doesn't zap it! */
  2782. }
  2783. }
  2784. }
  2785. else {
  2786. if (!we_made_the_key) {
  2787. /* if we have not made the key we are not supposed to zap it by calling dispose! */
  2788. req.priv_key = NULL;
  2789. }
  2790. }
  2791. } else {
  2792. php_openssl_store_errors();
  2793. }
  2794. }
  2795. }
  2796. if (csr) {
  2797. X509_REQ_free(csr);
  2798. }
  2799. PHP_SSL_REQ_DISPOSE(&req);
  2800. }
  2801. /* }}} */
  2802. /* {{{ proto mixed openssl_csr_get_subject(mixed csr [, bool use_shortnames = TRUE])
  2803. Returns the subject of a CERT or FALSE on error */
  2804. PHP_FUNCTION(openssl_csr_get_subject)
  2805. {
  2806. zval * zcsr;
  2807. zend_bool use_shortnames = 1;
  2808. zend_resource *csr_resource;
  2809. X509_NAME * subject;
  2810. X509_REQ * csr;
  2811. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|b", &zcsr, &use_shortnames) == FAILURE) {
  2812. RETURN_THROWS();
  2813. }
  2814. csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource);
  2815. if (csr == NULL) {
  2816. RETURN_FALSE;
  2817. }
  2818. subject = X509_REQ_get_subject_name(csr);
  2819. array_init(return_value);
  2820. php_openssl_add_assoc_name_entry(return_value, NULL, subject, use_shortnames);
  2821. if (!csr_resource) {
  2822. X509_REQ_free(csr);
  2823. }
  2824. }
  2825. /* }}} */
  2826. /* {{{ proto mixed openssl_csr_get_public_key(mixed csr [, bool use_shortnames = TRUE])
  2827. Returns the subject of a CERT or FALSE on error */
  2828. PHP_FUNCTION(openssl_csr_get_public_key)
  2829. {
  2830. zval * zcsr;
  2831. zend_bool use_shortnames = 1;
  2832. zend_resource *csr_resource;
  2833. X509_REQ *orig_csr, *csr;
  2834. EVP_PKEY *tpubkey;
  2835. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|b", &zcsr, &use_shortnames) == FAILURE) {
  2836. RETURN_THROWS();
  2837. }
  2838. orig_csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource);
  2839. if (orig_csr == NULL) {
  2840. RETURN_FALSE;
  2841. }
  2842. #if PHP_OPENSSL_API_VERSION >= 0x10100
  2843. /* Due to changes in OpenSSL 1.1 related to locking when decoding CSR,
  2844. * the pub key is not changed after assigning. It means if we pass
  2845. * a private key, it will be returned including the private part.
  2846. * If we duplicate it, then we get just the public part which is
  2847. * the same behavior as for OpenSSL 1.0 */
  2848. csr = X509_REQ_dup(orig_csr);
  2849. #else
  2850. csr = orig_csr;
  2851. #endif
  2852. /* Retrieve the public key from the CSR */
  2853. tpubkey = X509_REQ_get_pubkey(csr);
  2854. if (csr != orig_csr) {
  2855. /* We need to free the duplicated CSR */
  2856. X509_REQ_free(csr);
  2857. }
  2858. if (!csr_resource) {
  2859. /* We also need to free the original CSR if it was freshly created */
  2860. X509_REQ_free(orig_csr);
  2861. }
  2862. if (tpubkey == NULL) {
  2863. php_openssl_store_errors();
  2864. RETURN_FALSE;
  2865. }
  2866. RETURN_RES(zend_register_resource(tpubkey, le_key));
  2867. }
  2868. /* }}} */
  2869. /* }}} */
  2870. /* {{{ EVP Public/Private key functions */
  2871. struct php_openssl_pem_password {
  2872. char *key;
  2873. int len;
  2874. };
  2875. /* {{{ php_openssl_pem_password_cb */
  2876. static int php_openssl_pem_password_cb(char *buf, int size, int rwflag, void *userdata)
  2877. {
  2878. struct php_openssl_pem_password *password = userdata;
  2879. if (password == NULL || password->key == NULL) {
  2880. return -1;
  2881. }
  2882. size = (password->len > size) ? size : password->len;
  2883. memcpy(buf, password->key, size);
  2884. return size;
  2885. }
  2886. /* }}} */
  2887. /* {{{ php_openssl_evp_from_zval
  2888. Given a zval, coerce it into a EVP_PKEY object.
  2889. It can be:
  2890. 1. private key resource from openssl_get_privatekey()
  2891. 2. X509 resource -> public key will be extracted from it
  2892. 3. if it starts with file:// interpreted as path to key file
  2893. 4. interpreted as the data from the cert/key file and interpreted in same way as openssl_get_privatekey()
  2894. 5. an array(0 => [items 2..4], 1 => passphrase)
  2895. 6. if val is a string (possibly starting with file:///) and it is not an X509 certificate, then interpret as public key
  2896. NOTE: If you are requesting a private key but have not specified a passphrase, you should use an
  2897. empty string rather than NULL for the passphrase - NULL causes a passphrase prompt to be emitted in
  2898. the Apache error log!
  2899. */
  2900. static EVP_PKEY * php_openssl_evp_from_zval(
  2901. zval * val, int public_key, char *passphrase, size_t passphrase_len,
  2902. int makeresource, zend_resource **resourceval)
  2903. {
  2904. EVP_PKEY * key = NULL;
  2905. X509 * cert = NULL;
  2906. int free_cert = 0;
  2907. zend_resource *cert_res = NULL;
  2908. char * filename = NULL;
  2909. zval tmp;
  2910. ZVAL_NULL(&tmp);
  2911. #define TMP_CLEAN \
  2912. if (Z_TYPE(tmp) == IS_STRING) {\
  2913. zval_ptr_dtor_str(&tmp); \
  2914. } \
  2915. return NULL;
  2916. if (resourceval) {
  2917. *resourceval = NULL;
  2918. }
  2919. if (Z_TYPE_P(val) == IS_ARRAY) {
  2920. zval * zphrase;
  2921. /* get passphrase */
  2922. if ((zphrase = zend_hash_index_find(Z_ARRVAL_P(val), 1)) == NULL) {
  2923. php_error_docref(NULL, E_WARNING, "Key array must be of the form array(0 => key, 1 => phrase)");
  2924. return NULL;
  2925. }
  2926. if (Z_TYPE_P(zphrase) == IS_STRING) {
  2927. passphrase = Z_STRVAL_P(zphrase);
  2928. passphrase_len = Z_STRLEN_P(zphrase);
  2929. } else {
  2930. ZVAL_COPY(&tmp, zphrase);
  2931. if (!try_convert_to_string(&tmp)) {
  2932. return NULL;
  2933. }
  2934. passphrase = Z_STRVAL(tmp);
  2935. passphrase_len = Z_STRLEN(tmp);
  2936. }
  2937. /* now set val to be the key param and continue */
  2938. if ((val = zend_hash_index_find(Z_ARRVAL_P(val), 0)) == NULL) {
  2939. php_error_docref(NULL, E_WARNING, "Key array must be of the form array(0 => key, 1 => phrase)");
  2940. TMP_CLEAN;
  2941. }
  2942. }
  2943. if (Z_TYPE_P(val) == IS_RESOURCE) {
  2944. void * what;
  2945. zend_resource * res = Z_RES_P(val);
  2946. what = zend_fetch_resource2(res, "OpenSSL X.509/key", le_x509, le_key);
  2947. if (!what) {
  2948. TMP_CLEAN;
  2949. }
  2950. if (resourceval) {
  2951. *resourceval = res;
  2952. Z_ADDREF_P(val);
  2953. }
  2954. if (res->type == le_x509) {
  2955. /* extract key from cert, depending on public_key param */
  2956. cert = (X509*)what;
  2957. free_cert = 0;
  2958. } else if (res->type == le_key) {
  2959. int is_priv;
  2960. is_priv = php_openssl_is_private_key((EVP_PKEY*)what);
  2961. /* check whether it is actually a private key if requested */
  2962. if (!public_key && !is_priv) {
  2963. php_error_docref(NULL, E_WARNING, "Supplied key param is a public key");
  2964. TMP_CLEAN;
  2965. }
  2966. if (public_key && is_priv) {
  2967. php_error_docref(NULL, E_WARNING, "Don't know how to get public key from this private key");
  2968. TMP_CLEAN;
  2969. } else {
  2970. if (Z_TYPE(tmp) == IS_STRING) {
  2971. zval_ptr_dtor_str(&tmp);
  2972. }
  2973. /* got the key - return it */
  2974. return (EVP_PKEY*)what;
  2975. }
  2976. } else {
  2977. /* other types could be used here - eg: file pointers and read in the data from them */
  2978. TMP_CLEAN;
  2979. }
  2980. } else {
  2981. /* force it to be a string and check if it refers to a file */
  2982. /* passing non string values leaks, object uses toString, it returns NULL
  2983. * See bug38255.phpt
  2984. */
  2985. if (!(Z_TYPE_P(val) == IS_STRING || Z_TYPE_P(val) == IS_OBJECT)) {
  2986. TMP_CLEAN;
  2987. }
  2988. if (!try_convert_to_string(val)) {
  2989. TMP_CLEAN;
  2990. }
  2991. if (Z_STRLEN_P(val) > 7 && memcmp(Z_STRVAL_P(val), "file://", sizeof("file://") - 1) == 0) {
  2992. filename = Z_STRVAL_P(val) + (sizeof("file://") - 1);
  2993. if (php_openssl_open_base_dir_chk(filename)) {
  2994. TMP_CLEAN;
  2995. }
  2996. }
  2997. /* it's an X509 file/cert of some kind, and we need to extract the data from that */
  2998. if (public_key) {
  2999. cert = php_openssl_x509_from_zval(val, 0, &cert_res);
  3000. free_cert = (cert_res == NULL);
  3001. /* actual extraction done later */
  3002. if (!cert) {
  3003. /* not a X509 certificate, try to retrieve public key */
  3004. BIO* in;
  3005. if (filename) {
  3006. in = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY));
  3007. } else {
  3008. in = BIO_new_mem_buf(Z_STRVAL_P(val), (int)Z_STRLEN_P(val));
  3009. }
  3010. if (in == NULL) {
  3011. php_openssl_store_errors();
  3012. TMP_CLEAN;
  3013. }
  3014. key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL);
  3015. BIO_free(in);
  3016. }
  3017. } else {
  3018. /* we want the private key */
  3019. BIO *in;
  3020. if (filename) {
  3021. in = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY));
  3022. } else {
  3023. in = BIO_new_mem_buf(Z_STRVAL_P(val), (int)Z_STRLEN_P(val));
  3024. }
  3025. if (in == NULL) {
  3026. TMP_CLEAN;
  3027. }
  3028. if (passphrase == NULL) {
  3029. key = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
  3030. } else {
  3031. struct php_openssl_pem_password password;
  3032. password.key = passphrase;
  3033. password.len = passphrase_len;
  3034. key = PEM_read_bio_PrivateKey(in, NULL, php_openssl_pem_password_cb, &password);
  3035. }
  3036. BIO_free(in);
  3037. }
  3038. }
  3039. if (key == NULL) {
  3040. php_openssl_store_errors();
  3041. if (public_key && cert) {
  3042. /* extract public key from X509 cert */
  3043. key = (EVP_PKEY *) X509_get_pubkey(cert);
  3044. if (key == NULL) {
  3045. php_openssl_store_errors();
  3046. }
  3047. }
  3048. }
  3049. if (free_cert && cert) {
  3050. X509_free(cert);
  3051. }
  3052. if (key && makeresource && resourceval) {
  3053. *resourceval = zend_register_resource(key, le_key);
  3054. }
  3055. if (Z_TYPE(tmp) == IS_STRING) {
  3056. zval_ptr_dtor_str(&tmp);
  3057. }
  3058. return key;
  3059. }
  3060. /* }}} */
  3061. /* {{{ php_openssl_generate_private_key */
  3062. static EVP_PKEY * php_openssl_generate_private_key(struct php_x509_request * req)
  3063. {
  3064. char * randfile = NULL;
  3065. int egdsocket, seeded;
  3066. EVP_PKEY * return_val = NULL;
  3067. if (req->priv_key_bits < MIN_KEY_LENGTH) {
  3068. php_error_docref(NULL, E_WARNING, "Private key length is too short; it needs to be at least %d bits, not %d",
  3069. MIN_KEY_LENGTH, req->priv_key_bits);
  3070. return NULL;
  3071. }
  3072. randfile = CONF_get_string(req->req_config, req->section_name, "RANDFILE");
  3073. if (randfile == NULL) {
  3074. php_openssl_store_errors();
  3075. }
  3076. php_openssl_load_rand_file(randfile, &egdsocket, &seeded);
  3077. if ((req->priv_key = EVP_PKEY_new()) != NULL) {
  3078. switch(req->priv_key_type) {
  3079. case OPENSSL_KEYTYPE_RSA:
  3080. {
  3081. RSA* rsaparam;
  3082. #if OPENSSL_VERSION_NUMBER < 0x10002000L
  3083. /* OpenSSL 1.0.2 deprecates RSA_generate_key */
  3084. PHP_OPENSSL_RAND_ADD_TIME();
  3085. rsaparam = (RSA*)RSA_generate_key(req->priv_key_bits, RSA_F4, NULL, NULL);
  3086. #else
  3087. {
  3088. BIGNUM *bne = (BIGNUM *)BN_new();
  3089. if (BN_set_word(bne, RSA_F4) != 1) {
  3090. BN_free(bne);
  3091. php_error_docref(NULL, E_WARNING, "Failed setting exponent");
  3092. return NULL;
  3093. }
  3094. rsaparam = RSA_new();
  3095. PHP_OPENSSL_RAND_ADD_TIME();
  3096. if (rsaparam == NULL || !RSA_generate_key_ex(rsaparam, req->priv_key_bits, bne, NULL)) {
  3097. php_openssl_store_errors();
  3098. }
  3099. BN_free(bne);
  3100. }
  3101. #endif
  3102. if (rsaparam && EVP_PKEY_assign_RSA(req->priv_key, rsaparam)) {
  3103. return_val = req->priv_key;
  3104. } else {
  3105. php_openssl_store_errors();
  3106. }
  3107. }
  3108. break;
  3109. #if !defined(NO_DSA)
  3110. case OPENSSL_KEYTYPE_DSA:
  3111. PHP_OPENSSL_RAND_ADD_TIME();
  3112. {
  3113. DSA *dsaparam = DSA_new();
  3114. if (dsaparam && DSA_generate_parameters_ex(dsaparam, req->priv_key_bits, NULL, 0, NULL, NULL, NULL)) {
  3115. DSA_set_method(dsaparam, DSA_get_default_method());
  3116. if (DSA_generate_key(dsaparam)) {
  3117. if (EVP_PKEY_assign_DSA(req->priv_key, dsaparam)) {
  3118. return_val = req->priv_key;
  3119. } else {
  3120. php_openssl_store_errors();
  3121. }
  3122. } else {
  3123. php_openssl_store_errors();
  3124. DSA_free(dsaparam);
  3125. }
  3126. } else {
  3127. php_openssl_store_errors();
  3128. }
  3129. }
  3130. break;
  3131. #endif
  3132. #if !defined(NO_DH)
  3133. case OPENSSL_KEYTYPE_DH:
  3134. PHP_OPENSSL_RAND_ADD_TIME();
  3135. {
  3136. int codes = 0;
  3137. DH *dhparam = DH_new();
  3138. if (dhparam && DH_generate_parameters_ex(dhparam, req->priv_key_bits, 2, NULL)) {
  3139. DH_set_method(dhparam, DH_get_default_method());
  3140. if (DH_check(dhparam, &codes) && codes == 0 && DH_generate_key(dhparam)) {
  3141. if (EVP_PKEY_assign_DH(req->priv_key, dhparam)) {
  3142. return_val = req->priv_key;
  3143. } else {
  3144. php_openssl_store_errors();
  3145. }
  3146. } else {
  3147. php_openssl_store_errors();
  3148. DH_free(dhparam);
  3149. }
  3150. } else {
  3151. php_openssl_store_errors();
  3152. }
  3153. }
  3154. break;
  3155. #endif
  3156. #ifdef HAVE_EVP_PKEY_EC
  3157. case OPENSSL_KEYTYPE_EC:
  3158. {
  3159. EC_KEY *eckey;
  3160. if (req->curve_name == NID_undef) {
  3161. php_error_docref(NULL, E_WARNING, "Missing configuration value: 'curve_name' not set");
  3162. return NULL;
  3163. }
  3164. eckey = EC_KEY_new_by_curve_name(req->curve_name);
  3165. if (eckey) {
  3166. EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE);
  3167. if (EC_KEY_generate_key(eckey) &&
  3168. EVP_PKEY_assign_EC_KEY(req->priv_key, eckey)) {
  3169. return_val = req->priv_key;
  3170. } else {
  3171. EC_KEY_free(eckey);
  3172. }
  3173. }
  3174. }
  3175. break;
  3176. #endif
  3177. default:
  3178. php_error_docref(NULL, E_WARNING, "Unsupported private key type");
  3179. }
  3180. } else {
  3181. php_openssl_store_errors();
  3182. }
  3183. php_openssl_write_rand_file(randfile, egdsocket, seeded);
  3184. if (return_val == NULL) {
  3185. EVP_PKEY_free(req->priv_key);
  3186. req->priv_key = NULL;
  3187. return NULL;
  3188. }
  3189. return return_val;
  3190. }
  3191. /* }}} */
  3192. /* {{{ php_openssl_is_private_key
  3193. Check whether the supplied key is a private key by checking if the secret prime factors are set */
  3194. static int php_openssl_is_private_key(EVP_PKEY* pkey)
  3195. {
  3196. assert(pkey != NULL);
  3197. switch (EVP_PKEY_id(pkey)) {
  3198. case EVP_PKEY_RSA:
  3199. case EVP_PKEY_RSA2:
  3200. {
  3201. RSA *rsa = EVP_PKEY_get0_RSA(pkey);
  3202. if (rsa != NULL) {
  3203. const BIGNUM *p, *q;
  3204. RSA_get0_factors(rsa, &p, &q);
  3205. if (p == NULL || q == NULL) {
  3206. return 0;
  3207. }
  3208. }
  3209. }
  3210. break;
  3211. case EVP_PKEY_DSA:
  3212. case EVP_PKEY_DSA1:
  3213. case EVP_PKEY_DSA2:
  3214. case EVP_PKEY_DSA3:
  3215. case EVP_PKEY_DSA4:
  3216. {
  3217. DSA *dsa = EVP_PKEY_get0_DSA(pkey);
  3218. if (dsa != NULL) {
  3219. const BIGNUM *p, *q, *g, *pub_key, *priv_key;
  3220. DSA_get0_pqg(dsa, &p, &q, &g);
  3221. if (p == NULL || q == NULL) {
  3222. return 0;
  3223. }
  3224. DSA_get0_key(dsa, &pub_key, &priv_key);
  3225. if (priv_key == NULL) {
  3226. return 0;
  3227. }
  3228. }
  3229. }
  3230. break;
  3231. case EVP_PKEY_DH:
  3232. {
  3233. DH *dh = EVP_PKEY_get0_DH(pkey);
  3234. if (dh != NULL) {
  3235. const BIGNUM *p, *q, *g, *pub_key, *priv_key;
  3236. DH_get0_pqg(dh, &p, &q, &g);
  3237. if (p == NULL) {
  3238. return 0;
  3239. }
  3240. DH_get0_key(dh, &pub_key, &priv_key);
  3241. if (priv_key == NULL) {
  3242. return 0;
  3243. }
  3244. }
  3245. }
  3246. break;
  3247. #ifdef HAVE_EVP_PKEY_EC
  3248. case EVP_PKEY_EC:
  3249. {
  3250. EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
  3251. if (ec != NULL && NULL == EC_KEY_get0_private_key(ec)) {
  3252. return 0;
  3253. }
  3254. }
  3255. break;
  3256. #endif
  3257. default:
  3258. php_error_docref(NULL, E_WARNING, "Key type not supported in this PHP build!");
  3259. break;
  3260. }
  3261. return 1;
  3262. }
  3263. /* }}} */
  3264. #define OPENSSL_GET_BN(_array, _bn, _name) do { \
  3265. if (_bn != NULL) { \
  3266. int len = BN_num_bytes(_bn); \
  3267. zend_string *str = zend_string_alloc(len, 0); \
  3268. BN_bn2bin(_bn, (unsigned char*)ZSTR_VAL(str)); \
  3269. ZSTR_VAL(str)[len] = 0; \
  3270. add_assoc_str(&_array, #_name, str); \
  3271. } \
  3272. } while (0);
  3273. #define OPENSSL_PKEY_GET_BN(_type, _name) OPENSSL_GET_BN(_type, _name, _name)
  3274. #define OPENSSL_PKEY_SET_BN(_data, _name) do { \
  3275. zval *bn; \
  3276. if ((bn = zend_hash_str_find(Z_ARRVAL_P(_data), #_name, sizeof(#_name)-1)) != NULL && \
  3277. Z_TYPE_P(bn) == IS_STRING) { \
  3278. _name = BN_bin2bn( \
  3279. (unsigned char*)Z_STRVAL_P(bn), \
  3280. (int)Z_STRLEN_P(bn), NULL); \
  3281. } else { \
  3282. _name = NULL; \
  3283. } \
  3284. } while (0);
  3285. /* {{{ php_openssl_pkey_init_rsa */
  3286. static zend_bool php_openssl_pkey_init_and_assign_rsa(EVP_PKEY *pkey, RSA *rsa, zval *data)
  3287. {
  3288. BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp;
  3289. OPENSSL_PKEY_SET_BN(data, n);
  3290. OPENSSL_PKEY_SET_BN(data, e);
  3291. OPENSSL_PKEY_SET_BN(data, d);
  3292. if (!n || !d || !RSA_set0_key(rsa, n, e, d)) {
  3293. return 0;
  3294. }
  3295. OPENSSL_PKEY_SET_BN(data, p);
  3296. OPENSSL_PKEY_SET_BN(data, q);
  3297. if ((p || q) && !RSA_set0_factors(rsa, p, q)) {
  3298. return 0;
  3299. }
  3300. OPENSSL_PKEY_SET_BN(data, dmp1);
  3301. OPENSSL_PKEY_SET_BN(data, dmq1);
  3302. OPENSSL_PKEY_SET_BN(data, iqmp);
  3303. if ((dmp1 || dmq1 || iqmp) && !RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp)) {
  3304. return 0;
  3305. }
  3306. if (!EVP_PKEY_assign_RSA(pkey, rsa)) {
  3307. php_openssl_store_errors();
  3308. return 0;
  3309. }
  3310. return 1;
  3311. }
  3312. /* {{{ php_openssl_pkey_init_dsa */
  3313. static zend_bool php_openssl_pkey_init_dsa(DSA *dsa, zval *data)
  3314. {
  3315. BIGNUM *p, *q, *g, *priv_key, *pub_key;
  3316. const BIGNUM *priv_key_const, *pub_key_const;
  3317. OPENSSL_PKEY_SET_BN(data, p);
  3318. OPENSSL_PKEY_SET_BN(data, q);
  3319. OPENSSL_PKEY_SET_BN(data, g);
  3320. if (!p || !q || !g || !DSA_set0_pqg(dsa, p, q, g)) {
  3321. return 0;
  3322. }
  3323. OPENSSL_PKEY_SET_BN(data, pub_key);
  3324. OPENSSL_PKEY_SET_BN(data, priv_key);
  3325. if (pub_key) {
  3326. return DSA_set0_key(dsa, pub_key, priv_key);
  3327. }
  3328. /* generate key */
  3329. PHP_OPENSSL_RAND_ADD_TIME();
  3330. if (!DSA_generate_key(dsa)) {
  3331. php_openssl_store_errors();
  3332. return 0;
  3333. }
  3334. /* if BN_mod_exp return -1, then DSA_generate_key succeed for failed key
  3335. * so we need to double check that public key is created */
  3336. DSA_get0_key(dsa, &pub_key_const, &priv_key_const);
  3337. if (!pub_key_const || BN_is_zero(pub_key_const)) {
  3338. return 0;
  3339. }
  3340. /* all good */
  3341. return 1;
  3342. }
  3343. /* }}} */
  3344. /* {{{ php_openssl_dh_pub_from_priv */
  3345. static BIGNUM *php_openssl_dh_pub_from_priv(BIGNUM *priv_key, BIGNUM *g, BIGNUM *p)
  3346. {
  3347. BIGNUM *pub_key, *priv_key_const_time;
  3348. BN_CTX *ctx;
  3349. pub_key = BN_new();
  3350. if (pub_key == NULL) {
  3351. php_openssl_store_errors();
  3352. return NULL;
  3353. }
  3354. priv_key_const_time = BN_new();
  3355. if (priv_key_const_time == NULL) {
  3356. BN_free(pub_key);
  3357. php_openssl_store_errors();
  3358. return NULL;
  3359. }
  3360. ctx = BN_CTX_new();
  3361. if (ctx == NULL) {
  3362. BN_free(pub_key);
  3363. BN_free(priv_key_const_time);
  3364. php_openssl_store_errors();
  3365. return NULL;
  3366. }
  3367. BN_with_flags(priv_key_const_time, priv_key, BN_FLG_CONSTTIME);
  3368. if (!BN_mod_exp_mont(pub_key, g, priv_key_const_time, p, ctx, NULL)) {
  3369. BN_free(pub_key);
  3370. php_openssl_store_errors();
  3371. pub_key = NULL;
  3372. }
  3373. BN_free(priv_key_const_time);
  3374. BN_CTX_free(ctx);
  3375. return pub_key;
  3376. }
  3377. /* }}} */
  3378. /* {{{ php_openssl_pkey_init_dh */
  3379. static zend_bool php_openssl_pkey_init_dh(DH *dh, zval *data)
  3380. {
  3381. BIGNUM *p, *q, *g, *priv_key, *pub_key;
  3382. OPENSSL_PKEY_SET_BN(data, p);
  3383. OPENSSL_PKEY_SET_BN(data, q);
  3384. OPENSSL_PKEY_SET_BN(data, g);
  3385. if (!p || !g || !DH_set0_pqg(dh, p, q, g)) {
  3386. return 0;
  3387. }
  3388. OPENSSL_PKEY_SET_BN(data, priv_key);
  3389. OPENSSL_PKEY_SET_BN(data, pub_key);
  3390. if (pub_key) {
  3391. return DH_set0_key(dh, pub_key, priv_key);
  3392. }
  3393. if (priv_key) {
  3394. pub_key = php_openssl_dh_pub_from_priv(priv_key, g, p);
  3395. if (pub_key == NULL) {
  3396. return 0;
  3397. }
  3398. return DH_set0_key(dh, pub_key, priv_key);
  3399. }
  3400. /* generate key */
  3401. PHP_OPENSSL_RAND_ADD_TIME();
  3402. if (!DH_generate_key(dh)) {
  3403. php_openssl_store_errors();
  3404. return 0;
  3405. }
  3406. /* all good */
  3407. return 1;
  3408. }
  3409. /* }}} */
  3410. /* {{{ proto mixed openssl_pkey_new([array configargs])
  3411. Generates a new private key */
  3412. PHP_FUNCTION(openssl_pkey_new)
  3413. {
  3414. struct php_x509_request req;
  3415. zval * args = NULL;
  3416. zval *data;
  3417. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a!", &args) == FAILURE) {
  3418. RETURN_THROWS();
  3419. }
  3420. RETVAL_FALSE;
  3421. if (args && Z_TYPE_P(args) == IS_ARRAY) {
  3422. EVP_PKEY *pkey;
  3423. if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "rsa", sizeof("rsa")-1)) != NULL &&
  3424. Z_TYPE_P(data) == IS_ARRAY) {
  3425. pkey = EVP_PKEY_new();
  3426. if (pkey) {
  3427. RSA *rsa = RSA_new();
  3428. if (rsa) {
  3429. if (php_openssl_pkey_init_and_assign_rsa(pkey, rsa, data)) {
  3430. RETURN_RES(zend_register_resource(pkey, le_key));
  3431. }
  3432. RSA_free(rsa);
  3433. } else {
  3434. php_openssl_store_errors();
  3435. }
  3436. EVP_PKEY_free(pkey);
  3437. } else {
  3438. php_openssl_store_errors();
  3439. }
  3440. RETURN_FALSE;
  3441. } else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "dsa", sizeof("dsa") - 1)) != NULL &&
  3442. Z_TYPE_P(data) == IS_ARRAY) {
  3443. pkey = EVP_PKEY_new();
  3444. if (pkey) {
  3445. DSA *dsa = DSA_new();
  3446. if (dsa) {
  3447. if (php_openssl_pkey_init_dsa(dsa, data)) {
  3448. if (EVP_PKEY_assign_DSA(pkey, dsa)) {
  3449. RETURN_RES(zend_register_resource(pkey, le_key));
  3450. } else {
  3451. php_openssl_store_errors();
  3452. }
  3453. }
  3454. DSA_free(dsa);
  3455. } else {
  3456. php_openssl_store_errors();
  3457. }
  3458. EVP_PKEY_free(pkey);
  3459. } else {
  3460. php_openssl_store_errors();
  3461. }
  3462. RETURN_FALSE;
  3463. } else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "dh", sizeof("dh") - 1)) != NULL &&
  3464. Z_TYPE_P(data) == IS_ARRAY) {
  3465. pkey = EVP_PKEY_new();
  3466. if (pkey) {
  3467. DH *dh = DH_new();
  3468. if (dh) {
  3469. if (php_openssl_pkey_init_dh(dh, data)) {
  3470. if (EVP_PKEY_assign_DH(pkey, dh)) {
  3471. ZVAL_COPY_VALUE(return_value, zend_list_insert(pkey, le_key));
  3472. return;
  3473. } else {
  3474. php_openssl_store_errors();
  3475. }
  3476. }
  3477. DH_free(dh);
  3478. } else {
  3479. php_openssl_store_errors();
  3480. }
  3481. EVP_PKEY_free(pkey);
  3482. } else {
  3483. php_openssl_store_errors();
  3484. }
  3485. RETURN_FALSE;
  3486. #ifdef HAVE_EVP_PKEY_EC
  3487. } else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "ec", sizeof("ec") - 1)) != NULL &&
  3488. Z_TYPE_P(data) == IS_ARRAY) {
  3489. EC_KEY *eckey = NULL;
  3490. EC_GROUP *group = NULL;
  3491. EC_POINT *pnt = NULL;
  3492. BIGNUM *d = NULL;
  3493. pkey = EVP_PKEY_new();
  3494. if (pkey) {
  3495. eckey = EC_KEY_new();
  3496. if (eckey) {
  3497. EC_GROUP *group = NULL;
  3498. zval *bn;
  3499. zval *x;
  3500. zval *y;
  3501. if ((bn = zend_hash_str_find(Z_ARRVAL_P(data), "curve_name", sizeof("curve_name") - 1)) != NULL &&
  3502. Z_TYPE_P(bn) == IS_STRING) {
  3503. int nid = OBJ_sn2nid(Z_STRVAL_P(bn));
  3504. if (nid != NID_undef) {
  3505. group = EC_GROUP_new_by_curve_name(nid);
  3506. if (!group) {
  3507. php_openssl_store_errors();
  3508. goto clean_exit;
  3509. }
  3510. EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
  3511. EC_GROUP_set_point_conversion_form(group, POINT_CONVERSION_UNCOMPRESSED);
  3512. if (!EC_KEY_set_group(eckey, group)) {
  3513. php_openssl_store_errors();
  3514. goto clean_exit;
  3515. }
  3516. }
  3517. }
  3518. if (group == NULL) {
  3519. php_error_docref(NULL, E_WARNING, "Unknown curve_name");
  3520. goto clean_exit;
  3521. }
  3522. // The public key 'pnt' can be calculated from 'd' or is defined by 'x' and 'y'
  3523. if ((bn = zend_hash_str_find(Z_ARRVAL_P(data), "d", sizeof("d") - 1)) != NULL &&
  3524. Z_TYPE_P(bn) == IS_STRING) {
  3525. d = BN_bin2bn((unsigned char*) Z_STRVAL_P(bn), Z_STRLEN_P(bn), NULL);
  3526. if (!EC_KEY_set_private_key(eckey, d)) {
  3527. php_openssl_store_errors();
  3528. goto clean_exit;
  3529. }
  3530. // Calculate the public key by multiplying the Point Q with the public key
  3531. // P = d * Q
  3532. pnt = EC_POINT_new(group);
  3533. if (!pnt || !EC_POINT_mul(group, pnt, d, NULL, NULL, NULL)) {
  3534. php_openssl_store_errors();
  3535. goto clean_exit;
  3536. }
  3537. BN_free(d);
  3538. } else if ((x = zend_hash_str_find(Z_ARRVAL_P(data), "x", sizeof("x") - 1)) != NULL &&
  3539. Z_TYPE_P(x) == IS_STRING &&
  3540. (y = zend_hash_str_find(Z_ARRVAL_P(data), "y", sizeof("y") - 1)) != NULL &&
  3541. Z_TYPE_P(y) == IS_STRING) {
  3542. pnt = EC_POINT_new(group);
  3543. if (pnt == NULL) {
  3544. php_openssl_store_errors();
  3545. goto clean_exit;
  3546. }
  3547. if (!EC_POINT_set_affine_coordinates_GFp(
  3548. group, pnt, BN_bin2bn((unsigned char*) Z_STRVAL_P(x), Z_STRLEN_P(x), NULL),
  3549. BN_bin2bn((unsigned char*) Z_STRVAL_P(y), Z_STRLEN_P(y), NULL), NULL)) {
  3550. php_openssl_store_errors();
  3551. goto clean_exit;
  3552. }
  3553. }
  3554. if (pnt != NULL) {
  3555. if (!EC_KEY_set_public_key(eckey, pnt)) {
  3556. php_openssl_store_errors();
  3557. goto clean_exit;
  3558. }
  3559. EC_POINT_free(pnt);
  3560. pnt = NULL;
  3561. }
  3562. if (!EC_KEY_check_key(eckey)) {
  3563. PHP_OPENSSL_RAND_ADD_TIME();
  3564. EC_KEY_generate_key(eckey);
  3565. php_openssl_store_errors();
  3566. }
  3567. if (EC_KEY_check_key(eckey) && EVP_PKEY_assign_EC_KEY(pkey, eckey)) {
  3568. EC_GROUP_free(group);
  3569. RETURN_RES(zend_register_resource(pkey, le_key));
  3570. } else {
  3571. php_openssl_store_errors();
  3572. }
  3573. } else {
  3574. php_openssl_store_errors();
  3575. }
  3576. } else {
  3577. php_openssl_store_errors();
  3578. }
  3579. clean_exit:
  3580. if (d != NULL) {
  3581. BN_free(d);
  3582. }
  3583. if (pnt != NULL) {
  3584. EC_POINT_free(pnt);
  3585. }
  3586. if (group != NULL) {
  3587. EC_GROUP_free(group);
  3588. }
  3589. if (eckey != NULL) {
  3590. EC_KEY_free(eckey);
  3591. }
  3592. if (pkey != NULL) {
  3593. EVP_PKEY_free(pkey);
  3594. }
  3595. RETURN_FALSE;
  3596. #endif
  3597. }
  3598. }
  3599. PHP_SSL_REQ_INIT(&req);
  3600. if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) {
  3601. if (php_openssl_generate_private_key(&req)) {
  3602. /* pass back a key resource */
  3603. RETVAL_RES(zend_register_resource(req.priv_key, le_key));
  3604. /* make sure the cleanup code doesn't zap it! */
  3605. req.priv_key = NULL;
  3606. }
  3607. }
  3608. PHP_SSL_REQ_DISPOSE(&req);
  3609. }
  3610. /* }}} */
  3611. /* {{{ proto bool openssl_pkey_export_to_file(mixed key, string outfilename [, string passphrase [, array config_args]])
  3612. Gets an exportable representation of a key into a file */
  3613. PHP_FUNCTION(openssl_pkey_export_to_file)
  3614. {
  3615. struct php_x509_request req;
  3616. zval * zpkey, * args = NULL;
  3617. char * passphrase = NULL;
  3618. size_t passphrase_len = 0;
  3619. char * filename = NULL;
  3620. size_t filename_len = 0;
  3621. zend_resource *key_resource = NULL;
  3622. int pem_write = 0;
  3623. EVP_PKEY * key;
  3624. BIO * bio_out = NULL;
  3625. const EVP_CIPHER * cipher;
  3626. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zp|s!a!", &zpkey, &filename, &filename_len, &passphrase, &passphrase_len, &args) == FAILURE) {
  3627. RETURN_THROWS();
  3628. }
  3629. RETVAL_FALSE;
  3630. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(passphrase_len, passphrase);
  3631. key = php_openssl_evp_from_zval(zpkey, 0, passphrase, passphrase_len, 0, &key_resource);
  3632. if (key == NULL) {
  3633. if (!EG(exception)) {
  3634. php_error_docref(NULL, E_WARNING, "Cannot get key from parameter 1");
  3635. }
  3636. RETURN_FALSE;
  3637. }
  3638. if (php_openssl_open_base_dir_chk(filename)) {
  3639. RETURN_FALSE;
  3640. }
  3641. PHP_SSL_REQ_INIT(&req);
  3642. if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) {
  3643. bio_out = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY));
  3644. if (bio_out == NULL) {
  3645. php_openssl_store_errors();
  3646. goto clean_exit;
  3647. }
  3648. if (passphrase && req.priv_key_encrypt) {
  3649. if (req.priv_key_encrypt_cipher) {
  3650. cipher = req.priv_key_encrypt_cipher;
  3651. } else {
  3652. cipher = (EVP_CIPHER *) EVP_des_ede3_cbc();
  3653. }
  3654. } else {
  3655. cipher = NULL;
  3656. }
  3657. switch (EVP_PKEY_base_id(key)) {
  3658. #ifdef HAVE_EVP_PKEY_EC
  3659. case EVP_PKEY_EC:
  3660. pem_write = PEM_write_bio_ECPrivateKey(
  3661. bio_out, EVP_PKEY_get0_EC_KEY(key), cipher,
  3662. (unsigned char *)passphrase, (int)passphrase_len, NULL, NULL);
  3663. break;
  3664. #endif
  3665. default:
  3666. pem_write = PEM_write_bio_PrivateKey(
  3667. bio_out, key, cipher,
  3668. (unsigned char *)passphrase, (int)passphrase_len, NULL, NULL);
  3669. break;
  3670. }
  3671. if (pem_write) {
  3672. /* Success!
  3673. * If returning the output as a string, do so now */
  3674. RETVAL_TRUE;
  3675. } else {
  3676. php_openssl_store_errors();
  3677. }
  3678. }
  3679. clean_exit:
  3680. PHP_SSL_REQ_DISPOSE(&req);
  3681. if (key_resource == NULL && key) {
  3682. EVP_PKEY_free(key);
  3683. }
  3684. if (bio_out) {
  3685. BIO_free(bio_out);
  3686. }
  3687. }
  3688. /* }}} */
  3689. /* {{{ proto bool openssl_pkey_export(mixed key, &mixed out [, string passphrase [, array config_args]])
  3690. Gets an exportable representation of a key into a string or file */
  3691. PHP_FUNCTION(openssl_pkey_export)
  3692. {
  3693. struct php_x509_request req;
  3694. zval * zpkey, * args = NULL, *out;
  3695. char * passphrase = NULL; size_t passphrase_len = 0;
  3696. int pem_write = 0;
  3697. zend_resource *key_resource = NULL;
  3698. EVP_PKEY * key;
  3699. BIO * bio_out = NULL;
  3700. const EVP_CIPHER * cipher;
  3701. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz|s!a!", &zpkey, &out, &passphrase, &passphrase_len, &args) == FAILURE) {
  3702. RETURN_THROWS();
  3703. }
  3704. RETVAL_FALSE;
  3705. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(passphrase_len, passphrase);
  3706. key = php_openssl_evp_from_zval(zpkey, 0, passphrase, passphrase_len, 0, &key_resource);
  3707. if (key == NULL) {
  3708. if (!EG(exception)) {
  3709. php_error_docref(NULL, E_WARNING, "Cannot get key from parameter 1");
  3710. }
  3711. RETURN_FALSE;
  3712. }
  3713. PHP_SSL_REQ_INIT(&req);
  3714. if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) {
  3715. bio_out = BIO_new(BIO_s_mem());
  3716. if (passphrase && req.priv_key_encrypt) {
  3717. if (req.priv_key_encrypt_cipher) {
  3718. cipher = req.priv_key_encrypt_cipher;
  3719. } else {
  3720. cipher = (EVP_CIPHER *) EVP_des_ede3_cbc();
  3721. }
  3722. } else {
  3723. cipher = NULL;
  3724. }
  3725. switch (EVP_PKEY_base_id(key)) {
  3726. #ifdef HAVE_EVP_PKEY_EC
  3727. case EVP_PKEY_EC:
  3728. pem_write = PEM_write_bio_ECPrivateKey(
  3729. bio_out, EVP_PKEY_get0_EC_KEY(key), cipher,
  3730. (unsigned char *)passphrase, (int)passphrase_len, NULL, NULL);
  3731. break;
  3732. #endif
  3733. default:
  3734. pem_write = PEM_write_bio_PrivateKey(
  3735. bio_out, key, cipher,
  3736. (unsigned char *)passphrase, (int)passphrase_len, NULL, NULL);
  3737. break;
  3738. }
  3739. if (pem_write) {
  3740. /* Success!
  3741. * If returning the output as a string, do so now */
  3742. char * bio_mem_ptr;
  3743. long bio_mem_len;
  3744. RETVAL_TRUE;
  3745. bio_mem_len = BIO_get_mem_data(bio_out, &bio_mem_ptr);
  3746. ZEND_TRY_ASSIGN_REF_STRINGL(out, bio_mem_ptr, bio_mem_len);
  3747. } else {
  3748. php_openssl_store_errors();
  3749. }
  3750. }
  3751. PHP_SSL_REQ_DISPOSE(&req);
  3752. if (key_resource == NULL && key) {
  3753. EVP_PKEY_free(key);
  3754. }
  3755. if (bio_out) {
  3756. BIO_free(bio_out);
  3757. }
  3758. }
  3759. /* }}} */
  3760. /* {{{ proto mixed openssl_pkey_get_public(mixed cert)
  3761. Gets public key from X.509 certificate */
  3762. PHP_FUNCTION(openssl_pkey_get_public)
  3763. {
  3764. zval *cert;
  3765. EVP_PKEY *pkey;
  3766. zend_resource *res;
  3767. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &cert) == FAILURE) {
  3768. RETURN_THROWS();
  3769. }
  3770. pkey = php_openssl_evp_from_zval(cert, 1, NULL, 0, 1, &res);
  3771. if (pkey == NULL) {
  3772. RETURN_FALSE;
  3773. }
  3774. ZVAL_RES(return_value, res);
  3775. }
  3776. /* }}} */
  3777. /* {{{ proto void openssl_pkey_free(int key)
  3778. Frees a key */
  3779. PHP_FUNCTION(openssl_pkey_free)
  3780. {
  3781. zval *key;
  3782. EVP_PKEY *pkey;
  3783. if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &key) == FAILURE) {
  3784. RETURN_THROWS();
  3785. }
  3786. if ((pkey = (EVP_PKEY *)zend_fetch_resource(Z_RES_P(key), "OpenSSL key", le_key)) == NULL) {
  3787. RETURN_THROWS();
  3788. }
  3789. zend_list_close(Z_RES_P(key));
  3790. }
  3791. /* }}} */
  3792. /* {{{ proto mixed openssl_pkey_get_private(string key [, string passphrase])
  3793. Gets private keys */
  3794. PHP_FUNCTION(openssl_pkey_get_private)
  3795. {
  3796. zval *cert;
  3797. EVP_PKEY *pkey;
  3798. char * passphrase = "";
  3799. size_t passphrase_len = sizeof("")-1;
  3800. zend_resource *res;
  3801. if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|s", &cert, &passphrase, &passphrase_len) == FAILURE) {
  3802. RETURN_THROWS();
  3803. }
  3804. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(passphrase_len, passphrase);
  3805. pkey = php_openssl_evp_from_zval(cert, 0, passphrase, passphrase_len, 1, &res);
  3806. if (pkey == NULL) {
  3807. RETURN_FALSE;
  3808. }
  3809. ZVAL_RES(return_value, res);
  3810. }
  3811. /* }}} */
  3812. /* {{{ proto mixed openssl_pkey_get_details(resource key)
  3813. returns an array with the key details (bits, pkey, type)*/
  3814. PHP_FUNCTION(openssl_pkey_get_details)
  3815. {
  3816. zval *key;
  3817. EVP_PKEY *pkey;
  3818. BIO *out;
  3819. unsigned int pbio_len;
  3820. char *pbio;
  3821. zend_long ktype;
  3822. if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &key) == FAILURE) {
  3823. RETURN_THROWS();
  3824. }
  3825. if ((pkey = (EVP_PKEY *)zend_fetch_resource(Z_RES_P(key), "OpenSSL key", le_key)) == NULL) {
  3826. RETURN_THROWS();
  3827. }
  3828. out = BIO_new(BIO_s_mem());
  3829. if (!PEM_write_bio_PUBKEY(out, pkey)) {
  3830. BIO_free(out);
  3831. php_openssl_store_errors();
  3832. RETURN_FALSE;
  3833. }
  3834. pbio_len = BIO_get_mem_data(out, &pbio);
  3835. array_init(return_value);
  3836. add_assoc_long(return_value, "bits", EVP_PKEY_bits(pkey));
  3837. add_assoc_stringl(return_value, "key", pbio, pbio_len);
  3838. /*TODO: Use the real values once the openssl constants are used
  3839. * See the enum at the top of this file
  3840. */
  3841. switch (EVP_PKEY_base_id(pkey)) {
  3842. case EVP_PKEY_RSA:
  3843. case EVP_PKEY_RSA2:
  3844. {
  3845. RSA *rsa = EVP_PKEY_get0_RSA(pkey);
  3846. ktype = OPENSSL_KEYTYPE_RSA;
  3847. if (rsa != NULL) {
  3848. zval z_rsa;
  3849. const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp;
  3850. RSA_get0_key(rsa, &n, &e, &d);
  3851. RSA_get0_factors(rsa, &p, &q);
  3852. RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
  3853. array_init(&z_rsa);
  3854. OPENSSL_PKEY_GET_BN(z_rsa, n);
  3855. OPENSSL_PKEY_GET_BN(z_rsa, e);
  3856. OPENSSL_PKEY_GET_BN(z_rsa, d);
  3857. OPENSSL_PKEY_GET_BN(z_rsa, p);
  3858. OPENSSL_PKEY_GET_BN(z_rsa, q);
  3859. OPENSSL_PKEY_GET_BN(z_rsa, dmp1);
  3860. OPENSSL_PKEY_GET_BN(z_rsa, dmq1);
  3861. OPENSSL_PKEY_GET_BN(z_rsa, iqmp);
  3862. add_assoc_zval(return_value, "rsa", &z_rsa);
  3863. }
  3864. }
  3865. break;
  3866. case EVP_PKEY_DSA:
  3867. case EVP_PKEY_DSA2:
  3868. case EVP_PKEY_DSA3:
  3869. case EVP_PKEY_DSA4:
  3870. {
  3871. DSA *dsa = EVP_PKEY_get0_DSA(pkey);
  3872. ktype = OPENSSL_KEYTYPE_DSA;
  3873. if (dsa != NULL) {
  3874. zval z_dsa;
  3875. const BIGNUM *p, *q, *g, *priv_key, *pub_key;
  3876. DSA_get0_pqg(dsa, &p, &q, &g);
  3877. DSA_get0_key(dsa, &pub_key, &priv_key);
  3878. array_init(&z_dsa);
  3879. OPENSSL_PKEY_GET_BN(z_dsa, p);
  3880. OPENSSL_PKEY_GET_BN(z_dsa, q);
  3881. OPENSSL_PKEY_GET_BN(z_dsa, g);
  3882. OPENSSL_PKEY_GET_BN(z_dsa, priv_key);
  3883. OPENSSL_PKEY_GET_BN(z_dsa, pub_key);
  3884. add_assoc_zval(return_value, "dsa", &z_dsa);
  3885. }
  3886. }
  3887. break;
  3888. case EVP_PKEY_DH:
  3889. {
  3890. DH *dh = EVP_PKEY_get0_DH(pkey);
  3891. ktype = OPENSSL_KEYTYPE_DH;
  3892. if (dh != NULL) {
  3893. zval z_dh;
  3894. const BIGNUM *p, *q, *g, *priv_key, *pub_key;
  3895. DH_get0_pqg(dh, &p, &q, &g);
  3896. DH_get0_key(dh, &pub_key, &priv_key);
  3897. array_init(&z_dh);
  3898. OPENSSL_PKEY_GET_BN(z_dh, p);
  3899. OPENSSL_PKEY_GET_BN(z_dh, g);
  3900. OPENSSL_PKEY_GET_BN(z_dh, priv_key);
  3901. OPENSSL_PKEY_GET_BN(z_dh, pub_key);
  3902. add_assoc_zval(return_value, "dh", &z_dh);
  3903. }
  3904. }
  3905. break;
  3906. #ifdef HAVE_EVP_PKEY_EC
  3907. case EVP_PKEY_EC:
  3908. ktype = OPENSSL_KEYTYPE_EC;
  3909. if (EVP_PKEY_get0_EC_KEY(pkey) != NULL) {
  3910. zval ec;
  3911. const EC_GROUP *ec_group;
  3912. const EC_POINT *pub;
  3913. int nid;
  3914. char *crv_sn;
  3915. ASN1_OBJECT *obj;
  3916. // openssl recommends a buffer length of 80
  3917. char oir_buf[80];
  3918. const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey);
  3919. BIGNUM *x = BN_new();
  3920. BIGNUM *y = BN_new();
  3921. const BIGNUM *d;
  3922. ec_group = EC_KEY_get0_group(ec_key);
  3923. // Curve nid (numerical identifier) used for ASN1 mapping
  3924. nid = EC_GROUP_get_curve_name(ec_group);
  3925. if (nid == NID_undef) {
  3926. break;
  3927. }
  3928. array_init(&ec);
  3929. // Short object name
  3930. crv_sn = (char*) OBJ_nid2sn(nid);
  3931. if (crv_sn != NULL) {
  3932. add_assoc_string(&ec, "curve_name", crv_sn);
  3933. }
  3934. obj = OBJ_nid2obj(nid);
  3935. if (obj != NULL) {
  3936. int oir_len = OBJ_obj2txt(oir_buf, sizeof(oir_buf), obj, 1);
  3937. add_assoc_stringl(&ec, "curve_oid", (char*) oir_buf, oir_len);
  3938. ASN1_OBJECT_free(obj);
  3939. }
  3940. pub = EC_KEY_get0_public_key(ec_key);
  3941. if (EC_POINT_get_affine_coordinates_GFp(ec_group, pub, x, y, NULL)) {
  3942. OPENSSL_GET_BN(ec, x, x);
  3943. OPENSSL_GET_BN(ec, y, y);
  3944. } else {
  3945. php_openssl_store_errors();
  3946. }
  3947. if ((d = EC_KEY_get0_private_key(EVP_PKEY_get0_EC_KEY(pkey))) != NULL) {
  3948. OPENSSL_GET_BN(ec, d, d);
  3949. }
  3950. add_assoc_zval(return_value, "ec", &ec);
  3951. BN_free(x);
  3952. BN_free(y);
  3953. }
  3954. break;
  3955. #endif
  3956. default:
  3957. ktype = -1;
  3958. break;
  3959. }
  3960. add_assoc_long(return_value, "type", ktype);
  3961. BIO_free(out);
  3962. }
  3963. /* }}} */
  3964. /* {{{ proto string openssl_dh_compute_key(string pub_key, resource dh_key)
  3965. Computes shared secret for public value of remote DH key and local DH key */
  3966. PHP_FUNCTION(openssl_dh_compute_key)
  3967. {
  3968. zval *key;
  3969. char *pub_str;
  3970. size_t pub_len;
  3971. DH *dh;
  3972. EVP_PKEY *pkey;
  3973. BIGNUM *pub;
  3974. zend_string *data;
  3975. int len;
  3976. if (zend_parse_parameters(ZEND_NUM_ARGS(), "sr", &pub_str, &pub_len, &key) == FAILURE) {
  3977. RETURN_THROWS();
  3978. }
  3979. if ((pkey = (EVP_PKEY *)zend_fetch_resource(Z_RES_P(key), "OpenSSL key", le_key)) == NULL) {
  3980. RETURN_THROWS();
  3981. }
  3982. if (EVP_PKEY_base_id(pkey) != EVP_PKEY_DH) {
  3983. RETURN_FALSE;
  3984. }
  3985. dh = EVP_PKEY_get0_DH(pkey);
  3986. if (dh == NULL) {
  3987. RETURN_FALSE;
  3988. }
  3989. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(pub_len, pub_key);
  3990. pub = BN_bin2bn((unsigned char*)pub_str, (int)pub_len, NULL);
  3991. data = zend_string_alloc(DH_size(dh), 0);
  3992. len = DH_compute_key((unsigned char*)ZSTR_VAL(data), pub, dh);
  3993. if (len >= 0) {
  3994. ZSTR_LEN(data) = len;
  3995. ZSTR_VAL(data)[len] = 0;
  3996. RETVAL_NEW_STR(data);
  3997. } else {
  3998. php_openssl_store_errors();
  3999. zend_string_release_ex(data, 0);
  4000. RETVAL_FALSE;
  4001. }
  4002. BN_free(pub);
  4003. }
  4004. /* }}} */
  4005. /* {{{ proto string openssl_pkey_derive(peer_pub_key, priv_key, int keylen=NULL)
  4006. Computes shared secret for public value of remote and local DH or ECDH key */
  4007. PHP_FUNCTION(openssl_pkey_derive)
  4008. {
  4009. zval *priv_key;
  4010. zval *peer_pub_key;
  4011. EVP_PKEY *pkey;
  4012. EVP_PKEY *peer_key;
  4013. size_t key_size;
  4014. zend_long key_len = 0;
  4015. zend_string *result;
  4016. if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz|l", &peer_pub_key, &priv_key, &key_len) == FAILURE) {
  4017. RETURN_THROWS();
  4018. }
  4019. if (key_len < 0) {
  4020. php_error_docref(NULL, E_WARNING, "keylen < 0, assuming NULL");
  4021. }
  4022. key_size = key_len;
  4023. if ((pkey = php_openssl_evp_from_zval(priv_key, 0, "", 0, 0, NULL)) == NULL
  4024. || (peer_key = php_openssl_evp_from_zval(peer_pub_key, 1, NULL, 0, 0, NULL)) == NULL) {
  4025. RETURN_FALSE;
  4026. }
  4027. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(pkey, NULL);
  4028. if (!ctx) {
  4029. RETURN_FALSE;
  4030. }
  4031. if (EVP_PKEY_derive_init(ctx) > 0
  4032. && EVP_PKEY_derive_set_peer(ctx, peer_key) > 0
  4033. && (key_size > 0 || EVP_PKEY_derive(ctx, NULL, &key_size) > 0)
  4034. && (result = zend_string_alloc(key_size, 0)) != NULL) {
  4035. if (EVP_PKEY_derive(ctx, (unsigned char*)ZSTR_VAL(result), &key_size) > 0) {
  4036. ZSTR_LEN(result) = key_size;
  4037. ZSTR_VAL(result)[key_size] = 0;
  4038. RETVAL_NEW_STR(result);
  4039. } else {
  4040. php_openssl_store_errors();
  4041. zend_string_release_ex(result, 0);
  4042. RETVAL_FALSE;
  4043. }
  4044. } else {
  4045. RETVAL_FALSE;
  4046. }
  4047. EVP_PKEY_CTX_free(ctx);
  4048. }
  4049. /* }}} */
  4050. /* {{{ proto mixed openssl_pbkdf2(string password, string salt, int key_length, int iterations [, string digest_method = "sha1"])
  4051. Generates a PKCS5 v2 PBKDF2 string, defaults to sha1 */
  4052. PHP_FUNCTION(openssl_pbkdf2)
  4053. {
  4054. zend_long key_length = 0, iterations = 0;
  4055. char *password;
  4056. size_t password_len;
  4057. char *salt;
  4058. size_t salt_len;
  4059. char *method;
  4060. size_t method_len = 0;
  4061. zend_string *out_buffer;
  4062. const EVP_MD *digest;
  4063. if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssll|s",
  4064. &password, &password_len,
  4065. &salt, &salt_len,
  4066. &key_length, &iterations,
  4067. &method, &method_len) == FAILURE) {
  4068. RETURN_THROWS();
  4069. }
  4070. if (key_length <= 0) {
  4071. RETURN_FALSE;
  4072. }
  4073. if (method_len) {
  4074. digest = EVP_get_digestbyname(method);
  4075. } else {
  4076. digest = EVP_sha1();
  4077. }
  4078. if (!digest) {
  4079. php_error_docref(NULL, E_WARNING, "Unknown signature algorithm");
  4080. RETURN_FALSE;
  4081. }
  4082. PHP_OPENSSL_CHECK_LONG_TO_INT(key_length, key);
  4083. PHP_OPENSSL_CHECK_LONG_TO_INT(iterations, iterations);
  4084. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(password_len, password);
  4085. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(salt_len, salt);
  4086. out_buffer = zend_string_alloc(key_length, 0);
  4087. if (PKCS5_PBKDF2_HMAC(password, (int)password_len, (unsigned char *)salt, (int)salt_len, (int)iterations, digest, (int)key_length, (unsigned char*)ZSTR_VAL(out_buffer)) == 1) {
  4088. ZSTR_VAL(out_buffer)[key_length] = 0;
  4089. RETURN_NEW_STR(out_buffer);
  4090. } else {
  4091. php_openssl_store_errors();
  4092. zend_string_release_ex(out_buffer, 0);
  4093. RETURN_FALSE;
  4094. }
  4095. }
  4096. /* }}} */
  4097. /* {{{ PKCS7 S/MIME functions */
  4098. /* {{{ proto bool openssl_pkcs7_verify(string filename, int flags [, string signerscerts [, array cainfo [, string extracerts [, string content [, string pk7]]]]])
  4099. Verifys that the data block is intact, the signer is who they say they are, and returns the CERTs of the signers */
  4100. PHP_FUNCTION(openssl_pkcs7_verify)
  4101. {
  4102. X509_STORE * store = NULL;
  4103. zval * cainfo = NULL;
  4104. STACK_OF(X509) *signers= NULL;
  4105. STACK_OF(X509) *others = NULL;
  4106. PKCS7 * p7 = NULL;
  4107. BIO * in = NULL, * datain = NULL, * dataout = NULL, * p7bout = NULL;
  4108. zend_long flags = 0;
  4109. char * filename;
  4110. size_t filename_len;
  4111. char * extracerts = NULL;
  4112. size_t extracerts_len = 0;
  4113. char * signersfilename = NULL;
  4114. size_t signersfilename_len = 0;
  4115. char * datafilename = NULL;
  4116. size_t datafilename_len = 0;
  4117. char * p7bfilename = NULL;
  4118. size_t p7bfilename_len = 0;
  4119. RETVAL_LONG(-1);
  4120. if (zend_parse_parameters(ZEND_NUM_ARGS(), "pl|pappp", &filename, &filename_len,
  4121. &flags, &signersfilename, &signersfilename_len, &cainfo,
  4122. &extracerts, &extracerts_len, &datafilename, &datafilename_len, &p7bfilename, &p7bfilename_len) == FAILURE) {
  4123. RETURN_THROWS();
  4124. }
  4125. if (extracerts) {
  4126. others = php_openssl_load_all_certs_from_file(extracerts);
  4127. if (others == NULL) {
  4128. goto clean_exit;
  4129. }
  4130. }
  4131. flags = flags & ~PKCS7_DETACHED;
  4132. store = php_openssl_setup_verify(cainfo);
  4133. if (!store) {
  4134. goto clean_exit;
  4135. }
  4136. if (php_openssl_open_base_dir_chk(filename)) {
  4137. goto clean_exit;
  4138. }
  4139. in = BIO_new_file(filename, PHP_OPENSSL_BIO_MODE_R(flags));
  4140. if (in == NULL) {
  4141. php_openssl_store_errors();
  4142. goto clean_exit;
  4143. }
  4144. p7 = SMIME_read_PKCS7(in, &datain);
  4145. if (p7 == NULL) {
  4146. #if DEBUG_SMIME
  4147. zend_printf("SMIME_read_PKCS7 failed\n");
  4148. #endif
  4149. php_openssl_store_errors();
  4150. goto clean_exit;
  4151. }
  4152. if (datafilename) {
  4153. if (php_openssl_open_base_dir_chk(datafilename)) {
  4154. goto clean_exit;
  4155. }
  4156. dataout = BIO_new_file(datafilename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY));
  4157. if (dataout == NULL) {
  4158. php_openssl_store_errors();
  4159. goto clean_exit;
  4160. }
  4161. }
  4162. if (p7bfilename) {
  4163. if (php_openssl_open_base_dir_chk(p7bfilename)) {
  4164. goto clean_exit;
  4165. }
  4166. p7bout = BIO_new_file(p7bfilename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY));
  4167. if (p7bout == NULL) {
  4168. php_openssl_store_errors();
  4169. goto clean_exit;
  4170. }
  4171. }
  4172. #if DEBUG_SMIME
  4173. zend_printf("Calling PKCS7 verify\n");
  4174. #endif
  4175. if (PKCS7_verify(p7, others, store, datain, dataout, (int)flags)) {
  4176. RETVAL_TRUE;
  4177. if (signersfilename) {
  4178. BIO *certout;
  4179. if (php_openssl_open_base_dir_chk(signersfilename)) {
  4180. goto clean_exit;
  4181. }
  4182. certout = BIO_new_file(signersfilename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY));
  4183. if (certout) {
  4184. int i;
  4185. signers = PKCS7_get0_signers(p7, NULL, (int)flags);
  4186. if (signers != NULL) {
  4187. for (i = 0; i < sk_X509_num(signers); i++) {
  4188. if (!PEM_write_bio_X509(certout, sk_X509_value(signers, i))) {
  4189. php_openssl_store_errors();
  4190. RETVAL_LONG(-1);
  4191. php_error_docref(NULL, E_WARNING, "Failed to write signer %d", i);
  4192. }
  4193. }
  4194. sk_X509_free(signers);
  4195. } else {
  4196. RETVAL_LONG(-1);
  4197. php_openssl_store_errors();
  4198. }
  4199. BIO_free(certout);
  4200. } else {
  4201. php_openssl_store_errors();
  4202. php_error_docref(NULL, E_WARNING, "Signature OK, but cannot open %s for writing", signersfilename);
  4203. RETVAL_LONG(-1);
  4204. }
  4205. if (p7bout) {
  4206. PEM_write_bio_PKCS7(p7bout, p7);
  4207. }
  4208. }
  4209. } else {
  4210. php_openssl_store_errors();
  4211. RETVAL_FALSE;
  4212. }
  4213. clean_exit:
  4214. if (p7bout) {
  4215. BIO_free(p7bout);
  4216. }
  4217. X509_STORE_free(store);
  4218. BIO_free(datain);
  4219. BIO_free(in);
  4220. BIO_free(dataout);
  4221. PKCS7_free(p7);
  4222. sk_X509_pop_free(others, X509_free);
  4223. }
  4224. /* }}} */
  4225. /* {{{ proto bool openssl_pkcs7_encrypt(string infile, string outfile, mixed recipcerts, array headers [, int flags [, int cipher]])
  4226. Encrypts the message in the file named infile with the certificates in recipcerts and output the result to the file named outfile */
  4227. PHP_FUNCTION(openssl_pkcs7_encrypt)
  4228. {
  4229. zval * zrecipcerts, * zheaders = NULL;
  4230. STACK_OF(X509) * recipcerts = NULL;
  4231. BIO * infile = NULL, * outfile = NULL;
  4232. zend_long flags = 0;
  4233. PKCS7 * p7 = NULL;
  4234. zval * zcertval;
  4235. X509 * cert;
  4236. const EVP_CIPHER *cipher = NULL;
  4237. zend_long cipherid = PHP_OPENSSL_CIPHER_DEFAULT;
  4238. zend_string * strindex;
  4239. char * infilename = NULL;
  4240. size_t infilename_len;
  4241. char * outfilename = NULL;
  4242. size_t outfilename_len;
  4243. RETVAL_FALSE;
  4244. if (zend_parse_parameters(ZEND_NUM_ARGS(), "ppza!|ll", &infilename, &infilename_len,
  4245. &outfilename, &outfilename_len, &zrecipcerts, &zheaders, &flags, &cipherid) == FAILURE) {
  4246. RETURN_THROWS();
  4247. }
  4248. if (php_openssl_open_base_dir_chk(infilename) || php_openssl_open_base_dir_chk(outfilename)) {
  4249. return;
  4250. }
  4251. infile = BIO_new_file(infilename, PHP_OPENSSL_BIO_MODE_R(flags));
  4252. if (infile == NULL) {
  4253. php_openssl_store_errors();
  4254. goto clean_exit;
  4255. }
  4256. outfile = BIO_new_file(outfilename, PHP_OPENSSL_BIO_MODE_W(flags));
  4257. if (outfile == NULL) {
  4258. php_openssl_store_errors();
  4259. goto clean_exit;
  4260. }
  4261. recipcerts = sk_X509_new_null();
  4262. /* get certs */
  4263. if (Z_TYPE_P(zrecipcerts) == IS_ARRAY) {
  4264. ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(zrecipcerts), zcertval) {
  4265. zend_resource *certresource;
  4266. cert = php_openssl_x509_from_zval(zcertval, 0, &certresource);
  4267. if (cert == NULL) {
  4268. goto clean_exit;
  4269. }
  4270. if (certresource != NULL) {
  4271. /* we shouldn't free this particular cert, as it is a resource.
  4272. make a copy and push that on the stack instead */
  4273. cert = X509_dup(cert);
  4274. if (cert == NULL) {
  4275. php_openssl_store_errors();
  4276. goto clean_exit;
  4277. }
  4278. }
  4279. sk_X509_push(recipcerts, cert);
  4280. } ZEND_HASH_FOREACH_END();
  4281. } else {
  4282. /* a single certificate */
  4283. zend_resource *certresource;
  4284. cert = php_openssl_x509_from_zval(zrecipcerts, 0, &certresource);
  4285. if (cert == NULL) {
  4286. goto clean_exit;
  4287. }
  4288. if (certresource != NULL) {
  4289. /* we shouldn't free this particular cert, as it is a resource.
  4290. make a copy and push that on the stack instead */
  4291. cert = X509_dup(cert);
  4292. if (cert == NULL) {
  4293. php_openssl_store_errors();
  4294. goto clean_exit;
  4295. }
  4296. }
  4297. sk_X509_push(recipcerts, cert);
  4298. }
  4299. /* sanity check the cipher */
  4300. cipher = php_openssl_get_evp_cipher_from_algo(cipherid);
  4301. if (cipher == NULL) {
  4302. /* shouldn't happen */
  4303. php_error_docref(NULL, E_WARNING, "Failed to get cipher");
  4304. goto clean_exit;
  4305. }
  4306. p7 = PKCS7_encrypt(recipcerts, infile, (EVP_CIPHER*)cipher, (int)flags);
  4307. if (p7 == NULL) {
  4308. php_openssl_store_errors();
  4309. goto clean_exit;
  4310. }
  4311. /* tack on extra headers */
  4312. if (zheaders) {
  4313. ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(zheaders), strindex, zcertval) {
  4314. zend_string *str = zval_try_get_string(zcertval);
  4315. if (UNEXPECTED(!str)) {
  4316. goto clean_exit;
  4317. }
  4318. if (strindex) {
  4319. BIO_printf(outfile, "%s: %s\n", ZSTR_VAL(strindex), ZSTR_VAL(str));
  4320. } else {
  4321. BIO_printf(outfile, "%s\n", ZSTR_VAL(str));
  4322. }
  4323. zend_string_release(str);
  4324. } ZEND_HASH_FOREACH_END();
  4325. }
  4326. (void)BIO_reset(infile);
  4327. /* write the encrypted data */
  4328. if (!SMIME_write_PKCS7(outfile, p7, infile, (int)flags)) {
  4329. php_openssl_store_errors();
  4330. goto clean_exit;
  4331. }
  4332. RETVAL_TRUE;
  4333. clean_exit:
  4334. PKCS7_free(p7);
  4335. BIO_free(infile);
  4336. BIO_free(outfile);
  4337. if (recipcerts) {
  4338. sk_X509_pop_free(recipcerts, X509_free);
  4339. }
  4340. }
  4341. /* }}} */
  4342. /* {{{ proto bool openssl_pkcs7_read(string P7B, array &certs)
  4343. Exports the PKCS7 file to an array of PEM certificates */
  4344. PHP_FUNCTION(openssl_pkcs7_read)
  4345. {
  4346. zval * zout = NULL, zcert;
  4347. char *p7b;
  4348. size_t p7b_len;
  4349. STACK_OF(X509) *certs = NULL;
  4350. STACK_OF(X509_CRL) *crls = NULL;
  4351. BIO * bio_in = NULL, * bio_out = NULL;
  4352. PKCS7 * p7 = NULL;
  4353. int i;
  4354. if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz", &p7b, &p7b_len,
  4355. &zout) == FAILURE) {
  4356. RETURN_THROWS();
  4357. }
  4358. RETVAL_FALSE;
  4359. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(p7b_len, p7b);
  4360. bio_in = BIO_new(BIO_s_mem());
  4361. if (bio_in == NULL) {
  4362. goto clean_exit;
  4363. }
  4364. if (0 >= BIO_write(bio_in, p7b, (int)p7b_len)) {
  4365. php_openssl_store_errors();
  4366. goto clean_exit;
  4367. }
  4368. p7 = PEM_read_bio_PKCS7(bio_in, NULL, NULL, NULL);
  4369. if (p7 == NULL) {
  4370. php_openssl_store_errors();
  4371. goto clean_exit;
  4372. }
  4373. switch (OBJ_obj2nid(p7->type)) {
  4374. case NID_pkcs7_signed:
  4375. if (p7->d.sign != NULL) {
  4376. certs = p7->d.sign->cert;
  4377. crls = p7->d.sign->crl;
  4378. }
  4379. break;
  4380. case NID_pkcs7_signedAndEnveloped:
  4381. if (p7->d.signed_and_enveloped != NULL) {
  4382. certs = p7->d.signed_and_enveloped->cert;
  4383. crls = p7->d.signed_and_enveloped->crl;
  4384. }
  4385. break;
  4386. default:
  4387. break;
  4388. }
  4389. zout = zend_try_array_init(zout);
  4390. if (!zout) {
  4391. goto clean_exit;
  4392. }
  4393. if (certs != NULL) {
  4394. for (i = 0; i < sk_X509_num(certs); i++) {
  4395. X509* ca = sk_X509_value(certs, i);
  4396. bio_out = BIO_new(BIO_s_mem());
  4397. if (bio_out && PEM_write_bio_X509(bio_out, ca)) {
  4398. BUF_MEM *bio_buf;
  4399. BIO_get_mem_ptr(bio_out, &bio_buf);
  4400. ZVAL_STRINGL(&zcert, bio_buf->data, bio_buf->length);
  4401. add_index_zval(zout, i, &zcert);
  4402. BIO_free(bio_out);
  4403. }
  4404. }
  4405. }
  4406. if (crls != NULL) {
  4407. for (i = 0; i < sk_X509_CRL_num(crls); i++) {
  4408. X509_CRL* crl = sk_X509_CRL_value(crls, i);
  4409. bio_out = BIO_new(BIO_s_mem());
  4410. if (bio_out && PEM_write_bio_X509_CRL(bio_out, crl)) {
  4411. BUF_MEM *bio_buf;
  4412. BIO_get_mem_ptr(bio_out, &bio_buf);
  4413. ZVAL_STRINGL(&zcert, bio_buf->data, bio_buf->length);
  4414. add_index_zval(zout, i, &zcert);
  4415. BIO_free(bio_out);
  4416. }
  4417. }
  4418. }
  4419. RETVAL_TRUE;
  4420. clean_exit:
  4421. if (bio_in != NULL) {
  4422. BIO_free(bio_in);
  4423. }
  4424. if (p7 != NULL) {
  4425. PKCS7_free(p7);
  4426. }
  4427. }
  4428. /* }}} */
  4429. /* {{{ proto bool openssl_pkcs7_sign(string infile, string outfile, mixed signcert, mixed signkey, array headers [, int flags [, string extracertsfilename]])
  4430. Signs the MIME message in the file named infile with signcert/signkey and output the result to file name outfile. headers lists plain text headers to exclude from the signed portion of the message, and should include to, from and subject as a minimum */
  4431. PHP_FUNCTION(openssl_pkcs7_sign)
  4432. {
  4433. zval * zcert, * zprivkey, * zheaders;
  4434. zval * hval;
  4435. X509 * cert = NULL;
  4436. EVP_PKEY * privkey = NULL;
  4437. zend_long flags = PKCS7_DETACHED;
  4438. PKCS7 * p7 = NULL;
  4439. BIO * infile = NULL, * outfile = NULL;
  4440. STACK_OF(X509) *others = NULL;
  4441. zend_resource *certresource = NULL, *keyresource = NULL;
  4442. zend_string * strindex;
  4443. char * infilename;
  4444. size_t infilename_len;
  4445. char * outfilename;
  4446. size_t outfilename_len;
  4447. char * extracertsfilename = NULL;
  4448. size_t extracertsfilename_len;
  4449. if (zend_parse_parameters(ZEND_NUM_ARGS(), "ppzza!|lp!",
  4450. &infilename, &infilename_len, &outfilename, &outfilename_len,
  4451. &zcert, &zprivkey, &zheaders, &flags, &extracertsfilename,
  4452. &extracertsfilename_len) == FAILURE) {
  4453. RETURN_THROWS();
  4454. }
  4455. RETVAL_FALSE;
  4456. if (extracertsfilename) {
  4457. others = php_openssl_load_all_certs_from_file(extracertsfilename);
  4458. if (others == NULL) {
  4459. goto clean_exit;
  4460. }
  4461. }
  4462. privkey = php_openssl_evp_from_zval(zprivkey, 0, "", 0, 0, &keyresource);
  4463. if (privkey == NULL) {
  4464. if (!EG(exception)) {
  4465. php_error_docref(NULL, E_WARNING, "Error getting private key");
  4466. }
  4467. goto clean_exit;
  4468. }
  4469. cert = php_openssl_x509_from_zval(zcert, 0, &certresource);
  4470. if (cert == NULL) {
  4471. php_error_docref(NULL, E_WARNING, "Error getting cert");
  4472. goto clean_exit;
  4473. }
  4474. if (php_openssl_open_base_dir_chk(infilename) || php_openssl_open_base_dir_chk(outfilename)) {
  4475. goto clean_exit;
  4476. }
  4477. infile = BIO_new_file(infilename, PHP_OPENSSL_BIO_MODE_R(flags));
  4478. if (infile == NULL) {
  4479. php_openssl_store_errors();
  4480. php_error_docref(NULL, E_WARNING, "Error opening input file %s!", infilename);
  4481. goto clean_exit;
  4482. }
  4483. outfile = BIO_new_file(outfilename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY));
  4484. if (outfile == NULL) {
  4485. php_openssl_store_errors();
  4486. php_error_docref(NULL, E_WARNING, "Error opening output file %s!", outfilename);
  4487. goto clean_exit;
  4488. }
  4489. p7 = PKCS7_sign(cert, privkey, others, infile, (int)flags);
  4490. if (p7 == NULL) {
  4491. php_openssl_store_errors();
  4492. php_error_docref(NULL, E_WARNING, "Error creating PKCS7 structure!");
  4493. goto clean_exit;
  4494. }
  4495. (void)BIO_reset(infile);
  4496. /* tack on extra headers */
  4497. if (zheaders) {
  4498. int ret;
  4499. ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(zheaders), strindex, hval) {
  4500. zend_string *str = zval_try_get_string(hval);
  4501. if (UNEXPECTED(!str)) {
  4502. goto clean_exit;
  4503. }
  4504. if (strindex) {
  4505. ret = BIO_printf(outfile, "%s: %s\n", ZSTR_VAL(strindex), ZSTR_VAL(str));
  4506. } else {
  4507. ret = BIO_printf(outfile, "%s\n", ZSTR_VAL(str));
  4508. }
  4509. zend_string_release(str);
  4510. if (ret < 0) {
  4511. php_openssl_store_errors();
  4512. }
  4513. } ZEND_HASH_FOREACH_END();
  4514. }
  4515. /* write the signed data */
  4516. if (!SMIME_write_PKCS7(outfile, p7, infile, (int)flags)) {
  4517. php_openssl_store_errors();
  4518. goto clean_exit;
  4519. }
  4520. RETVAL_TRUE;
  4521. clean_exit:
  4522. PKCS7_free(p7);
  4523. BIO_free(infile);
  4524. BIO_free(outfile);
  4525. if (others) {
  4526. sk_X509_pop_free(others, X509_free);
  4527. }
  4528. if (privkey && keyresource == NULL) {
  4529. EVP_PKEY_free(privkey);
  4530. }
  4531. if (cert && certresource == NULL) {
  4532. X509_free(cert);
  4533. }
  4534. }
  4535. /* }}} */
  4536. /* {{{ proto bool openssl_pkcs7_decrypt(string infilename, string outfilename, mixed recipcert [, mixed recipkey])
  4537. Decrypts the S/MIME message in the file name infilename and output the results to the file name outfilename. recipcert is a CERT for one of the recipients. recipkey specifies the private key matching recipcert, if recipcert does not include the key */
  4538. PHP_FUNCTION(openssl_pkcs7_decrypt)
  4539. {
  4540. zval * recipcert, * recipkey = NULL;
  4541. X509 * cert = NULL;
  4542. EVP_PKEY * key = NULL;
  4543. zend_resource *certresval, *keyresval;
  4544. BIO * in = NULL, * out = NULL, * datain = NULL;
  4545. PKCS7 * p7 = NULL;
  4546. char * infilename;
  4547. size_t infilename_len;
  4548. char * outfilename;
  4549. size_t outfilename_len;
  4550. if (zend_parse_parameters(ZEND_NUM_ARGS(), "ppz|z", &infilename, &infilename_len,
  4551. &outfilename, &outfilename_len, &recipcert, &recipkey) == FAILURE) {
  4552. RETURN_THROWS();
  4553. }
  4554. RETVAL_FALSE;
  4555. cert = php_openssl_x509_from_zval(recipcert, 0, &certresval);
  4556. if (cert == NULL) {
  4557. php_error_docref(NULL, E_WARNING, "Unable to coerce parameter 3 to x509 cert");
  4558. goto clean_exit;
  4559. }
  4560. key = php_openssl_evp_from_zval(recipkey ? recipkey : recipcert, 0, "", 0, 0, &keyresval);
  4561. if (key == NULL) {
  4562. if (!EG(exception)) {
  4563. php_error_docref(NULL, E_WARNING, "Unable to get private key");
  4564. }
  4565. goto clean_exit;
  4566. }
  4567. if (php_openssl_open_base_dir_chk(infilename) || php_openssl_open_base_dir_chk(outfilename)) {
  4568. goto clean_exit;
  4569. }
  4570. in = BIO_new_file(infilename, PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY));
  4571. if (in == NULL) {
  4572. php_openssl_store_errors();
  4573. goto clean_exit;
  4574. }
  4575. out = BIO_new_file(outfilename, PHP_OPENSSL_BIO_MODE_W(PKCS7_BINARY));
  4576. if (out == NULL) {
  4577. php_openssl_store_errors();
  4578. goto clean_exit;
  4579. }
  4580. p7 = SMIME_read_PKCS7(in, &datain);
  4581. if (p7 == NULL) {
  4582. php_openssl_store_errors();
  4583. goto clean_exit;
  4584. }
  4585. if (PKCS7_decrypt(p7, key, cert, out, PKCS7_DETACHED)) {
  4586. RETVAL_TRUE;
  4587. } else {
  4588. php_openssl_store_errors();
  4589. }
  4590. clean_exit:
  4591. PKCS7_free(p7);
  4592. BIO_free(datain);
  4593. BIO_free(in);
  4594. BIO_free(out);
  4595. if (cert && certresval == NULL) {
  4596. X509_free(cert);
  4597. }
  4598. if (key && keyresval == NULL) {
  4599. EVP_PKEY_free(key);
  4600. }
  4601. }
  4602. /* }}} */
  4603. /* }}} */
  4604. /* {{{ proto bool openssl_private_encrypt(string data, string &crypted, mixed key [, int padding])
  4605. Encrypts data with private key */
  4606. PHP_FUNCTION(openssl_private_encrypt)
  4607. {
  4608. zval *key, *crypted;
  4609. EVP_PKEY *pkey;
  4610. int cryptedlen;
  4611. zend_string *cryptedbuf = NULL;
  4612. int successful = 0;
  4613. zend_resource *keyresource = NULL;
  4614. char * data;
  4615. size_t data_len;
  4616. zend_long padding = RSA_PKCS1_PADDING;
  4617. if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) {
  4618. RETURN_THROWS();
  4619. }
  4620. RETVAL_FALSE;
  4621. pkey = php_openssl_evp_from_zval(key, 0, "", 0, 0, &keyresource);
  4622. if (pkey == NULL) {
  4623. if (!EG(exception)) {
  4624. php_error_docref(NULL, E_WARNING, "key param is not a valid private key");
  4625. }
  4626. RETURN_FALSE;
  4627. }
  4628. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
  4629. cryptedlen = EVP_PKEY_size(pkey);
  4630. cryptedbuf = zend_string_alloc(cryptedlen, 0);
  4631. switch (EVP_PKEY_id(pkey)) {
  4632. case EVP_PKEY_RSA:
  4633. case EVP_PKEY_RSA2:
  4634. successful = (RSA_private_encrypt((int)data_len,
  4635. (unsigned char *)data,
  4636. (unsigned char *)ZSTR_VAL(cryptedbuf),
  4637. EVP_PKEY_get0_RSA(pkey),
  4638. (int)padding) == cryptedlen);
  4639. break;
  4640. default:
  4641. php_error_docref(NULL, E_WARNING, "key type not supported in this PHP build!");
  4642. }
  4643. if (successful) {
  4644. ZSTR_VAL(cryptedbuf)[cryptedlen] = '\0';
  4645. ZEND_TRY_ASSIGN_REF_NEW_STR(crypted, cryptedbuf);
  4646. cryptedbuf = NULL;
  4647. RETVAL_TRUE;
  4648. } else {
  4649. php_openssl_store_errors();
  4650. }
  4651. if (cryptedbuf) {
  4652. zend_string_release_ex(cryptedbuf, 0);
  4653. }
  4654. if (keyresource == NULL) {
  4655. EVP_PKEY_free(pkey);
  4656. }
  4657. }
  4658. /* }}} */
  4659. /* {{{ proto bool openssl_private_decrypt(string data, string &decrypted, mixed key [, int padding])
  4660. Decrypts data with private key */
  4661. PHP_FUNCTION(openssl_private_decrypt)
  4662. {
  4663. zval *key, *crypted;
  4664. EVP_PKEY *pkey;
  4665. int cryptedlen;
  4666. zend_string *cryptedbuf = NULL;
  4667. unsigned char *crypttemp;
  4668. int successful = 0;
  4669. zend_long padding = RSA_PKCS1_PADDING;
  4670. zend_resource *keyresource = NULL;
  4671. char * data;
  4672. size_t data_len;
  4673. if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) {
  4674. RETURN_THROWS();
  4675. }
  4676. RETVAL_FALSE;
  4677. pkey = php_openssl_evp_from_zval(key, 0, "", 0, 0, &keyresource);
  4678. if (pkey == NULL) {
  4679. if (!EG(exception)) {
  4680. php_error_docref(NULL, E_WARNING, "key parameter is not a valid private key");
  4681. }
  4682. RETURN_FALSE;
  4683. }
  4684. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
  4685. cryptedlen = EVP_PKEY_size(pkey);
  4686. crypttemp = emalloc(cryptedlen + 1);
  4687. switch (EVP_PKEY_id(pkey)) {
  4688. case EVP_PKEY_RSA:
  4689. case EVP_PKEY_RSA2:
  4690. cryptedlen = RSA_private_decrypt((int)data_len,
  4691. (unsigned char *)data,
  4692. crypttemp,
  4693. EVP_PKEY_get0_RSA(pkey),
  4694. (int)padding);
  4695. if (cryptedlen != -1) {
  4696. cryptedbuf = zend_string_alloc(cryptedlen, 0);
  4697. memcpy(ZSTR_VAL(cryptedbuf), crypttemp, cryptedlen);
  4698. successful = 1;
  4699. }
  4700. break;
  4701. default:
  4702. php_error_docref(NULL, E_WARNING, "key type not supported in this PHP build!");
  4703. }
  4704. efree(crypttemp);
  4705. if (successful) {
  4706. ZSTR_VAL(cryptedbuf)[cryptedlen] = '\0';
  4707. ZEND_TRY_ASSIGN_REF_NEW_STR(crypted, cryptedbuf);
  4708. cryptedbuf = NULL;
  4709. RETVAL_TRUE;
  4710. } else {
  4711. php_openssl_store_errors();
  4712. }
  4713. if (keyresource == NULL) {
  4714. EVP_PKEY_free(pkey);
  4715. }
  4716. if (cryptedbuf) {
  4717. zend_string_release_ex(cryptedbuf, 0);
  4718. }
  4719. }
  4720. /* }}} */
  4721. /* {{{ proto bool openssl_public_encrypt(string data, string &crypted, mixed key [, int padding])
  4722. Encrypts data with public key */
  4723. PHP_FUNCTION(openssl_public_encrypt)
  4724. {
  4725. zval *key, *crypted;
  4726. EVP_PKEY *pkey;
  4727. int cryptedlen;
  4728. zend_string *cryptedbuf;
  4729. int successful = 0;
  4730. zend_resource *keyresource = NULL;
  4731. zend_long padding = RSA_PKCS1_PADDING;
  4732. char * data;
  4733. size_t data_len;
  4734. if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) {
  4735. RETURN_THROWS();
  4736. }
  4737. RETVAL_FALSE;
  4738. pkey = php_openssl_evp_from_zval(key, 1, NULL, 0, 0, &keyresource);
  4739. if (pkey == NULL) {
  4740. if (!EG(exception)) {
  4741. php_error_docref(NULL, E_WARNING, "key parameter is not a valid public key");
  4742. }
  4743. RETURN_FALSE;
  4744. }
  4745. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
  4746. cryptedlen = EVP_PKEY_size(pkey);
  4747. cryptedbuf = zend_string_alloc(cryptedlen, 0);
  4748. switch (EVP_PKEY_id(pkey)) {
  4749. case EVP_PKEY_RSA:
  4750. case EVP_PKEY_RSA2:
  4751. successful = (RSA_public_encrypt((int)data_len,
  4752. (unsigned char *)data,
  4753. (unsigned char *)ZSTR_VAL(cryptedbuf),
  4754. EVP_PKEY_get0_RSA(pkey),
  4755. (int)padding) == cryptedlen);
  4756. break;
  4757. default:
  4758. php_error_docref(NULL, E_WARNING, "key type not supported in this PHP build!");
  4759. }
  4760. if (successful) {
  4761. ZSTR_VAL(cryptedbuf)[cryptedlen] = '\0';
  4762. ZEND_TRY_ASSIGN_REF_NEW_STR(crypted, cryptedbuf);
  4763. cryptedbuf = NULL;
  4764. RETVAL_TRUE;
  4765. } else {
  4766. php_openssl_store_errors();
  4767. }
  4768. if (keyresource == NULL) {
  4769. EVP_PKEY_free(pkey);
  4770. }
  4771. if (cryptedbuf) {
  4772. zend_string_release_ex(cryptedbuf, 0);
  4773. }
  4774. }
  4775. /* }}} */
  4776. /* {{{ proto bool openssl_public_decrypt(string data, string &crypted, resource key [, int padding])
  4777. Decrypts data with public key */
  4778. PHP_FUNCTION(openssl_public_decrypt)
  4779. {
  4780. zval *key, *crypted;
  4781. EVP_PKEY *pkey;
  4782. int cryptedlen;
  4783. zend_string *cryptedbuf = NULL;
  4784. unsigned char *crypttemp;
  4785. int successful = 0;
  4786. zend_resource *keyresource = NULL;
  4787. zend_long padding = RSA_PKCS1_PADDING;
  4788. char * data;
  4789. size_t data_len;
  4790. if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) {
  4791. RETURN_THROWS();
  4792. }
  4793. RETVAL_FALSE;
  4794. pkey = php_openssl_evp_from_zval(key, 1, NULL, 0, 0, &keyresource);
  4795. if (pkey == NULL) {
  4796. if (!EG(exception)) {
  4797. php_error_docref(NULL, E_WARNING, "key parameter is not a valid public key");
  4798. }
  4799. RETURN_FALSE;
  4800. }
  4801. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
  4802. cryptedlen = EVP_PKEY_size(pkey);
  4803. crypttemp = emalloc(cryptedlen + 1);
  4804. switch (EVP_PKEY_id(pkey)) {
  4805. case EVP_PKEY_RSA:
  4806. case EVP_PKEY_RSA2:
  4807. cryptedlen = RSA_public_decrypt((int)data_len,
  4808. (unsigned char *)data,
  4809. crypttemp,
  4810. EVP_PKEY_get0_RSA(pkey),
  4811. (int)padding);
  4812. if (cryptedlen != -1) {
  4813. cryptedbuf = zend_string_alloc(cryptedlen, 0);
  4814. memcpy(ZSTR_VAL(cryptedbuf), crypttemp, cryptedlen);
  4815. successful = 1;
  4816. }
  4817. break;
  4818. default:
  4819. php_error_docref(NULL, E_WARNING, "key type not supported in this PHP build!");
  4820. }
  4821. efree(crypttemp);
  4822. if (successful) {
  4823. ZSTR_VAL(cryptedbuf)[cryptedlen] = '\0';
  4824. ZEND_TRY_ASSIGN_REF_NEW_STR(crypted, cryptedbuf);
  4825. cryptedbuf = NULL;
  4826. RETVAL_TRUE;
  4827. } else {
  4828. php_openssl_store_errors();
  4829. }
  4830. if (cryptedbuf) {
  4831. zend_string_release_ex(cryptedbuf, 0);
  4832. }
  4833. if (keyresource == NULL) {
  4834. EVP_PKEY_free(pkey);
  4835. }
  4836. }
  4837. /* }}} */
  4838. /* {{{ proto mixed openssl_error_string(void)
  4839. Returns a description of the last error, and alters the index of the error messages. Returns false when the are no more messages */
  4840. PHP_FUNCTION(openssl_error_string)
  4841. {
  4842. char buf[256];
  4843. unsigned long val;
  4844. if (zend_parse_parameters_none() == FAILURE) {
  4845. RETURN_THROWS();
  4846. }
  4847. php_openssl_store_errors();
  4848. if (OPENSSL_G(errors) == NULL || OPENSSL_G(errors)->top == OPENSSL_G(errors)->bottom) {
  4849. RETURN_FALSE;
  4850. }
  4851. OPENSSL_G(errors)->bottom = (OPENSSL_G(errors)->bottom + 1) % ERR_NUM_ERRORS;
  4852. val = OPENSSL_G(errors)->buffer[OPENSSL_G(errors)->bottom];
  4853. if (val) {
  4854. ERR_error_string_n(val, buf, 256);
  4855. RETURN_STRING(buf);
  4856. } else {
  4857. RETURN_FALSE;
  4858. }
  4859. }
  4860. /* }}} */
  4861. /* {{{ proto bool openssl_sign(string data, &string signature, mixed key[, mixed method])
  4862. Signs data */
  4863. PHP_FUNCTION(openssl_sign)
  4864. {
  4865. zval *key, *signature;
  4866. EVP_PKEY *pkey;
  4867. unsigned int siglen;
  4868. zend_string *sigbuf;
  4869. zend_resource *keyresource = NULL;
  4870. char * data;
  4871. size_t data_len;
  4872. EVP_MD_CTX *md_ctx;
  4873. zval *method = NULL;
  4874. zend_long signature_algo = OPENSSL_ALGO_SHA1;
  4875. const EVP_MD *mdtype;
  4876. if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|z", &data, &data_len, &signature, &key, &method) == FAILURE) {
  4877. RETURN_THROWS();
  4878. }
  4879. pkey = php_openssl_evp_from_zval(key, 0, "", 0, 0, &keyresource);
  4880. if (pkey == NULL) {
  4881. if (!EG(exception)) {
  4882. php_error_docref(NULL, E_WARNING, "Supplied key param cannot be coerced into a private key");
  4883. }
  4884. RETURN_FALSE;
  4885. }
  4886. if (method == NULL || Z_TYPE_P(method) == IS_LONG) {
  4887. if (method != NULL) {
  4888. signature_algo = Z_LVAL_P(method);
  4889. }
  4890. mdtype = php_openssl_get_evp_md_from_algo(signature_algo);
  4891. } else if (Z_TYPE_P(method) == IS_STRING) {
  4892. mdtype = EVP_get_digestbyname(Z_STRVAL_P(method));
  4893. } else {
  4894. php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
  4895. RETURN_FALSE;
  4896. }
  4897. if (!mdtype) {
  4898. php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
  4899. RETURN_FALSE;
  4900. }
  4901. siglen = EVP_PKEY_size(pkey);
  4902. sigbuf = zend_string_alloc(siglen, 0);
  4903. md_ctx = EVP_MD_CTX_create();
  4904. if (md_ctx != NULL &&
  4905. EVP_SignInit(md_ctx, mdtype) &&
  4906. EVP_SignUpdate(md_ctx, data, data_len) &&
  4907. EVP_SignFinal(md_ctx, (unsigned char*)ZSTR_VAL(sigbuf), &siglen, pkey)) {
  4908. ZSTR_VAL(sigbuf)[siglen] = '\0';
  4909. ZSTR_LEN(sigbuf) = siglen;
  4910. ZEND_TRY_ASSIGN_REF_NEW_STR(signature, sigbuf);
  4911. RETVAL_TRUE;
  4912. } else {
  4913. php_openssl_store_errors();
  4914. efree(sigbuf);
  4915. RETVAL_FALSE;
  4916. }
  4917. EVP_MD_CTX_destroy(md_ctx);
  4918. if (keyresource == NULL) {
  4919. EVP_PKEY_free(pkey);
  4920. }
  4921. }
  4922. /* }}} */
  4923. /* {{{ proto int openssl_verify(string data, string signature, mixed key[, mixed method])
  4924. Verifys data */
  4925. PHP_FUNCTION(openssl_verify)
  4926. {
  4927. zval *key;
  4928. EVP_PKEY *pkey;
  4929. int err = 0;
  4930. EVP_MD_CTX *md_ctx;
  4931. const EVP_MD *mdtype;
  4932. zend_resource *keyresource = NULL;
  4933. char * data;
  4934. size_t data_len;
  4935. char * signature;
  4936. size_t signature_len;
  4937. zval *method = NULL;
  4938. zend_long signature_algo = OPENSSL_ALGO_SHA1;
  4939. if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssz|z", &data, &data_len, &signature, &signature_len, &key, &method) == FAILURE) {
  4940. RETURN_THROWS();
  4941. }
  4942. PHP_OPENSSL_CHECK_SIZE_T_TO_UINT(signature_len, signature);
  4943. if (method == NULL || Z_TYPE_P(method) == IS_LONG) {
  4944. if (method != NULL) {
  4945. signature_algo = Z_LVAL_P(method);
  4946. }
  4947. mdtype = php_openssl_get_evp_md_from_algo(signature_algo);
  4948. } else if (Z_TYPE_P(method) == IS_STRING) {
  4949. mdtype = EVP_get_digestbyname(Z_STRVAL_P(method));
  4950. } else {
  4951. php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
  4952. RETURN_FALSE;
  4953. }
  4954. if (!mdtype) {
  4955. php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
  4956. RETURN_FALSE;
  4957. }
  4958. pkey = php_openssl_evp_from_zval(key, 1, NULL, 0, 0, &keyresource);
  4959. if (pkey == NULL) {
  4960. if (!EG(exception)) {
  4961. php_error_docref(NULL, E_WARNING, "Supplied key param cannot be coerced into a public key");
  4962. }
  4963. RETURN_FALSE;
  4964. }
  4965. md_ctx = EVP_MD_CTX_create();
  4966. if (md_ctx == NULL ||
  4967. !EVP_VerifyInit (md_ctx, mdtype) ||
  4968. !EVP_VerifyUpdate (md_ctx, data, data_len) ||
  4969. (err = EVP_VerifyFinal(md_ctx, (unsigned char *)signature, (unsigned int)signature_len, pkey)) < 0) {
  4970. php_openssl_store_errors();
  4971. }
  4972. EVP_MD_CTX_destroy(md_ctx);
  4973. if (keyresource == NULL) {
  4974. EVP_PKEY_free(pkey);
  4975. }
  4976. RETURN_LONG(err);
  4977. }
  4978. /* }}} */
  4979. /* {{{ proto int openssl_seal(string data, &string sealdata, &array ekeys, array pubkeys [, string method [, &string iv]]))
  4980. Seals data */
  4981. PHP_FUNCTION(openssl_seal)
  4982. {
  4983. zval *pubkeys, *pubkey, *sealdata, *ekeys, *iv = NULL;
  4984. HashTable *pubkeysht;
  4985. EVP_PKEY **pkeys;
  4986. zend_resource ** key_resources; /* so we know what to cleanup */
  4987. int i, len1, len2, *eksl, nkeys, iv_len;
  4988. unsigned char iv_buf[EVP_MAX_IV_LENGTH + 1], *buf = NULL, **eks;
  4989. char * data;
  4990. size_t data_len;
  4991. char *method =NULL;
  4992. size_t method_len = 0;
  4993. const EVP_CIPHER *cipher;
  4994. EVP_CIPHER_CTX *ctx;
  4995. if (zend_parse_parameters(ZEND_NUM_ARGS(), "szza|sz", &data, &data_len,
  4996. &sealdata, &ekeys, &pubkeys, &method, &method_len, &iv) == FAILURE) {
  4997. RETURN_THROWS();
  4998. }
  4999. pubkeysht = Z_ARRVAL_P(pubkeys);
  5000. nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
  5001. if (!nkeys) {
  5002. php_error_docref(NULL, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
  5003. RETURN_FALSE;
  5004. }
  5005. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
  5006. if (method) {
  5007. cipher = EVP_get_cipherbyname(method);
  5008. if (!cipher) {
  5009. php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
  5010. RETURN_FALSE;
  5011. }
  5012. } else {
  5013. cipher = EVP_rc4();
  5014. }
  5015. iv_len = EVP_CIPHER_iv_length(cipher);
  5016. if (!iv && iv_len > 0) {
  5017. php_error_docref(NULL, E_WARNING,
  5018. "Cipher algorithm requires an IV to be supplied as a sixth parameter");
  5019. RETURN_FALSE;
  5020. }
  5021. pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
  5022. eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
  5023. eks = safe_emalloc(nkeys, sizeof(*eks), 0);
  5024. memset(eks, 0, sizeof(*eks) * nkeys);
  5025. key_resources = safe_emalloc(nkeys, sizeof(zend_resource*), 0);
  5026. memset(key_resources, 0, sizeof(zend_resource*) * nkeys);
  5027. memset(pkeys, 0, sizeof(*pkeys) * nkeys);
  5028. /* get the public keys we are using to seal this data */
  5029. i = 0;
  5030. ZEND_HASH_FOREACH_VAL(pubkeysht, pubkey) {
  5031. pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, 0, &key_resources[i]);
  5032. if (pkeys[i] == NULL) {
  5033. if (!EG(exception)) {
  5034. php_error_docref(NULL, E_WARNING, "Not a public key (%dth member of pubkeys)", i+1);
  5035. }
  5036. RETVAL_FALSE;
  5037. goto clean_exit;
  5038. }
  5039. eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
  5040. i++;
  5041. } ZEND_HASH_FOREACH_END();
  5042. ctx = EVP_CIPHER_CTX_new();
  5043. if (ctx == NULL || !EVP_EncryptInit(ctx,cipher,NULL,NULL)) {
  5044. EVP_CIPHER_CTX_free(ctx);
  5045. php_openssl_store_errors();
  5046. RETVAL_FALSE;
  5047. goto clean_exit;
  5048. }
  5049. /* allocate one byte extra to make room for \0 */
  5050. buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx));
  5051. EVP_CIPHER_CTX_reset(ctx);
  5052. if (EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) <= 0 ||
  5053. !EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) ||
  5054. !EVP_SealFinal(ctx, buf + len1, &len2)) {
  5055. efree(buf);
  5056. EVP_CIPHER_CTX_free(ctx);
  5057. php_openssl_store_errors();
  5058. RETVAL_FALSE;
  5059. goto clean_exit;
  5060. }
  5061. if (len1 + len2 > 0) {
  5062. ZEND_TRY_ASSIGN_REF_NEW_STR(sealdata, zend_string_init((char*)buf, len1 + len2, 0));
  5063. efree(buf);
  5064. ekeys = zend_try_array_init(ekeys);
  5065. if (!ekeys) {
  5066. EVP_CIPHER_CTX_free(ctx);
  5067. goto clean_exit;
  5068. }
  5069. for (i=0; i<nkeys; i++) {
  5070. eks[i][eksl[i]] = '\0';
  5071. add_next_index_stringl(ekeys, (const char*)eks[i], eksl[i]);
  5072. efree(eks[i]);
  5073. eks[i] = NULL;
  5074. }
  5075. if (iv) {
  5076. iv_buf[iv_len] = '\0';
  5077. ZEND_TRY_ASSIGN_REF_NEW_STR(iv, zend_string_init((char*)iv_buf, iv_len, 0));
  5078. }
  5079. } else {
  5080. efree(buf);
  5081. }
  5082. RETVAL_LONG(len1 + len2);
  5083. EVP_CIPHER_CTX_free(ctx);
  5084. clean_exit:
  5085. for (i=0; i<nkeys; i++) {
  5086. if (key_resources[i] == NULL && pkeys[i] != NULL) {
  5087. EVP_PKEY_free(pkeys[i]);
  5088. }
  5089. if (eks[i]) {
  5090. efree(eks[i]);
  5091. }
  5092. }
  5093. efree(eks);
  5094. efree(eksl);
  5095. efree(pkeys);
  5096. efree(key_resources);
  5097. }
  5098. /* }}} */
  5099. /* {{{ proto bool openssl_open(string data, &string opendata, string ekey, mixed privkey [, string method [, string iv]])
  5100. Opens data */
  5101. PHP_FUNCTION(openssl_open)
  5102. {
  5103. zval *privkey, *opendata;
  5104. EVP_PKEY *pkey;
  5105. int len1, len2, cipher_iv_len;
  5106. unsigned char *buf, *iv_buf;
  5107. zend_resource *keyresource = NULL;
  5108. EVP_CIPHER_CTX *ctx;
  5109. char * data;
  5110. size_t data_len;
  5111. char * ekey;
  5112. size_t ekey_len;
  5113. char *method = NULL, *iv = NULL;
  5114. size_t method_len = 0, iv_len = 0;
  5115. const EVP_CIPHER *cipher;
  5116. if (zend_parse_parameters(ZEND_NUM_ARGS(), "szsz|ss", &data, &data_len, &opendata,
  5117. &ekey, &ekey_len, &privkey, &method, &method_len, &iv, &iv_len) == FAILURE) {
  5118. RETURN_THROWS();
  5119. }
  5120. pkey = php_openssl_evp_from_zval(privkey, 0, "", 0, 0, &keyresource);
  5121. if (pkey == NULL) {
  5122. if (!EG(exception)) {
  5123. php_error_docref(NULL, E_WARNING, "Unable to coerce parameter 4 into a private key");
  5124. }
  5125. RETURN_FALSE;
  5126. }
  5127. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(ekey_len, ekey);
  5128. PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
  5129. if (method) {
  5130. cipher = EVP_get_cipherbyname(method);
  5131. if (!cipher) {
  5132. php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
  5133. RETURN_FALSE;
  5134. }
  5135. } else {
  5136. cipher = EVP_rc4();
  5137. }
  5138. cipher_iv_len = EVP_CIPHER_iv_length(cipher);
  5139. if (cipher_iv_len > 0) {
  5140. if (!iv) {
  5141. php_error_docref(NULL, E_WARNING,
  5142. "Cipher algorithm requires an IV to be supplied as a sixth parameter");
  5143. RETURN_FALSE;
  5144. }
  5145. if ((size_t)cipher_iv_len != iv_len) {
  5146. php_error_docref(NULL, E_WARNING, "IV length is invalid");
  5147. RETURN_FALSE;
  5148. }
  5149. iv_buf = (unsigned char *)iv;
  5150. } else {
  5151. iv_buf = NULL;
  5152. }
  5153. buf = emalloc(data_len + 1);
  5154. ctx = EVP_CIPHER_CTX_new();
  5155. if (ctx != NULL && EVP_OpenInit(ctx, cipher, (unsigned char *)ekey, (int)ekey_len, iv_buf, pkey) &&
  5156. EVP_OpenUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) &&
  5157. EVP_OpenFinal(ctx, buf + len1, &len2) && (len1 + len2 > 0)) {
  5158. buf[len1 + len2] = '\0';
  5159. ZEND_TRY_ASSIGN_REF_NEW_STR(opendata, zend_string_init((char*)buf, len1 + len2, 0));
  5160. RETVAL_TRUE;
  5161. } else {
  5162. php_openssl_store_errors();
  5163. RETVAL_FALSE;
  5164. }
  5165. efree(buf);
  5166. if (keyresource == NULL) {
  5167. EVP_PKEY_free(pkey);
  5168. }
  5169. EVP_CIPHER_CTX_free(ctx);
  5170. }
  5171. /* }}} */
  5172. static void php_openssl_add_method_or_alias(const OBJ_NAME *name, void *arg) /* {{{ */
  5173. {
  5174. add_next_index_string((zval*)arg, (char*)name->name);
  5175. }
  5176. /* }}} */
  5177. static void php_openssl_add_method(const OBJ_NAME *name, void *arg) /* {{{ */
  5178. {
  5179. if (name->alias == 0) {
  5180. add_next_index_string((zval*)arg, (char*)name->name);
  5181. }
  5182. }
  5183. /* }}} */
  5184. /* {{{ proto array openssl_get_md_methods([bool aliases = false])
  5185. Return array of available digest methods */
  5186. PHP_FUNCTION(openssl_get_md_methods)
  5187. {
  5188. zend_bool aliases = 0;
  5189. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &aliases) == FAILURE) {
  5190. RETURN_THROWS();
  5191. }
  5192. array_init(return_value);
  5193. OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH,
  5194. aliases ? php_openssl_add_method_or_alias: php_openssl_add_method,
  5195. return_value);
  5196. }
  5197. /* }}} */
  5198. /* {{{ proto array openssl_get_cipher_methods([bool aliases = false])
  5199. Return array of available cipher methods */
  5200. PHP_FUNCTION(openssl_get_cipher_methods)
  5201. {
  5202. zend_bool aliases = 0;
  5203. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &aliases) == FAILURE) {
  5204. RETURN_THROWS();
  5205. }
  5206. array_init(return_value);
  5207. OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
  5208. aliases ? php_openssl_add_method_or_alias: php_openssl_add_method,
  5209. return_value);
  5210. }
  5211. /* }}} */
  5212. /* {{{ proto array openssl_get_curve_names()
  5213. Return array of available elliptic curves */
  5214. #ifdef HAVE_EVP_PKEY_EC
  5215. PHP_FUNCTION(openssl_get_curve_names)
  5216. {
  5217. EC_builtin_curve *curves = NULL;
  5218. const char *sname;
  5219. size_t i;
  5220. size_t len = EC_get_builtin_curves(NULL, 0);
  5221. if (zend_parse_parameters_none() == FAILURE) {
  5222. RETURN_THROWS();
  5223. }
  5224. curves = emalloc(sizeof(EC_builtin_curve) * len);
  5225. if (!EC_get_builtin_curves(curves, len)) {
  5226. RETURN_FALSE;
  5227. }
  5228. array_init(return_value);
  5229. for (i = 0; i < len; i++) {
  5230. sname = OBJ_nid2sn(curves[i].nid);
  5231. if (sname != NULL) {
  5232. add_next_index_string(return_value, sname);
  5233. }
  5234. }
  5235. efree(curves);
  5236. }
  5237. #endif
  5238. /* }}} */
  5239. /* {{{ proto string openssl_digest(string data, string method [, bool raw_output=false])
  5240. Computes digest hash value for given data using given method, returns raw or binhex encoded string */
  5241. PHP_FUNCTION(openssl_digest)
  5242. {
  5243. zend_bool raw_output = 0;
  5244. char *data, *method;
  5245. size_t data_len, method_len;
  5246. const EVP_MD *mdtype;
  5247. EVP_MD_CTX *md_ctx;
  5248. unsigned int siglen;
  5249. zend_string *sigbuf;
  5250. if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|b", &data, &data_len, &method, &method_len, &raw_output) == FAILURE) {
  5251. RETURN_THROWS();
  5252. }
  5253. mdtype = EVP_get_digestbyname(method);
  5254. if (!mdtype) {
  5255. php_error_docref(NULL, E_WARNING, "Unknown signature algorithm");
  5256. RETURN_FALSE;
  5257. }
  5258. siglen = EVP_MD_size(mdtype);
  5259. sigbuf = zend_string_alloc(siglen, 0);
  5260. md_ctx = EVP_MD_CTX_create();
  5261. if (EVP_DigestInit(md_ctx, mdtype) &&
  5262. EVP_DigestUpdate(md_ctx, (unsigned char *)data, data_len) &&
  5263. EVP_DigestFinal (md_ctx, (unsigned char *)ZSTR_VAL(sigbuf), &siglen)) {
  5264. if (raw_output) {
  5265. ZSTR_VAL(sigbuf)[siglen] = '\0';
  5266. ZSTR_LEN(sigbuf) = siglen;
  5267. RETVAL_STR(sigbuf);
  5268. } else {
  5269. int digest_str_len = siglen * 2;
  5270. zend_string *digest_str = zend_string_alloc(digest_str_len, 0);
  5271. make_digest_ex(ZSTR_VAL(digest_str), (unsigned char*)ZSTR_VAL(sigbuf), siglen);
  5272. ZSTR_VAL(digest_str)[digest_str_len] = '\0';
  5273. zend_string_release_ex(sigbuf, 0);
  5274. RETVAL_NEW_STR(digest_str);
  5275. }
  5276. } else {
  5277. php_openssl_store_errors();
  5278. zend_string_release_ex(sigbuf, 0);
  5279. RETVAL_FALSE;
  5280. }
  5281. EVP_MD_CTX_destroy(md_ctx);
  5282. }
  5283. /* }}} */
  5284. /* Cipher mode info */
  5285. struct php_openssl_cipher_mode {
  5286. zend_bool is_aead;
  5287. zend_bool is_single_run_aead;
  5288. int aead_get_tag_flag;
  5289. int aead_set_tag_flag;
  5290. int aead_ivlen_flag;
  5291. };
  5292. static void php_openssl_load_cipher_mode(struct php_openssl_cipher_mode *mode, const EVP_CIPHER *cipher_type) /* {{{ */
  5293. {
  5294. switch (EVP_CIPHER_mode(cipher_type)) {
  5295. #ifdef EVP_CIPH_GCM_MODE
  5296. case EVP_CIPH_GCM_MODE:
  5297. mode->is_aead = 1;
  5298. mode->is_single_run_aead = 0;
  5299. mode->aead_get_tag_flag = EVP_CTRL_GCM_GET_TAG;
  5300. mode->aead_set_tag_flag = EVP_CTRL_GCM_SET_TAG;
  5301. mode->aead_ivlen_flag = EVP_CTRL_GCM_SET_IVLEN;
  5302. break;
  5303. #endif
  5304. #ifdef EVP_CIPH_CCM_MODE
  5305. case EVP_CIPH_CCM_MODE:
  5306. mode->is_aead = 1;
  5307. mode->is_single_run_aead = 1;
  5308. mode->aead_get_tag_flag = EVP_CTRL_CCM_GET_TAG;
  5309. mode->aead_set_tag_flag = EVP_CTRL_CCM_SET_TAG;
  5310. mode->aead_ivlen_flag = EVP_CTRL_CCM_SET_IVLEN;
  5311. break;
  5312. #endif
  5313. default:
  5314. memset(mode, 0, sizeof(struct php_openssl_cipher_mode));
  5315. }
  5316. }
  5317. /* }}} */
  5318. static int php_openssl_validate_iv(char **piv, size_t *piv_len, size_t iv_required_len,
  5319. zend_bool *free_iv, EVP_CIPHER_CTX *cipher_ctx, struct php_openssl_cipher_mode *mode) /* {{{ */
  5320. {
  5321. char *iv_new;
  5322. /* Best case scenario, user behaved */
  5323. if (*piv_len == iv_required_len) {
  5324. return SUCCESS;
  5325. }
  5326. if (mode->is_aead) {
  5327. if (EVP_CIPHER_CTX_ctrl(cipher_ctx, mode->aead_ivlen_flag, *piv_len, NULL) != 1) {
  5328. php_error_docref(NULL, E_WARNING, "Setting of IV length for AEAD mode failed");
  5329. return FAILURE;
  5330. }
  5331. return SUCCESS;
  5332. }
  5333. iv_new = ecalloc(1, iv_required_len + 1);
  5334. if (*piv_len == 0) {
  5335. /* BC behavior */
  5336. *piv_len = iv_required_len;
  5337. *piv = iv_new;
  5338. *free_iv = 1;
  5339. return SUCCESS;
  5340. }
  5341. if (*piv_len < iv_required_len) {
  5342. php_error_docref(NULL, E_WARNING,
  5343. "IV passed is only %zd bytes long, cipher expects an IV of precisely %zd bytes, padding with \\0",
  5344. *piv_len, iv_required_len);
  5345. memcpy(iv_new, *piv, *piv_len);
  5346. *piv_len = iv_required_len;
  5347. *piv = iv_new;
  5348. *free_iv = 1;
  5349. return SUCCESS;
  5350. }
  5351. php_error_docref(NULL, E_WARNING,
  5352. "IV passed is %zd bytes long which is longer than the %zd expected by selected cipher, truncating",
  5353. *piv_len, iv_required_len);
  5354. memcpy(iv_new, *piv, iv_required_len);
  5355. *piv_len = iv_required_len;
  5356. *piv = iv_new;
  5357. *free_iv = 1;
  5358. return SUCCESS;
  5359. }
  5360. /* }}} */
  5361. static int php_openssl_cipher_init(const EVP_CIPHER *cipher_type,
  5362. EVP_CIPHER_CTX *cipher_ctx, struct php_openssl_cipher_mode *mode,
  5363. char **ppassword, size_t *ppassword_len, zend_bool *free_password,
  5364. char **piv, size_t *piv_len, zend_bool *free_iv,
  5365. char *tag, int tag_len, zend_long options, int enc) /* {{{ */
  5366. {
  5367. unsigned char *key;
  5368. int key_len, password_len;
  5369. size_t max_iv_len;
  5370. *free_password = 0;
  5371. max_iv_len = EVP_CIPHER_iv_length(cipher_type);
  5372. if (enc && *piv_len == 0 && max_iv_len > 0 && !mode->is_aead) {
  5373. php_error_docref(NULL, E_WARNING,
  5374. "Using an empty Initialization Vector (iv) is potentially insecure and not recommended");
  5375. }
  5376. if (!EVP_CipherInit_ex(cipher_ctx, cipher_type, NULL, NULL, NULL, enc)) {
  5377. php_openssl_store_errors();
  5378. return FAILURE;
  5379. }
  5380. if (php_openssl_validate_iv(piv, piv_len, max_iv_len, free_iv, cipher_ctx, mode) == FAILURE) {
  5381. return FAILURE;
  5382. }
  5383. if (mode->is_single_run_aead && enc) {
  5384. if (!EVP_CIPHER_CTX_ctrl(cipher_ctx, mode->aead_set_tag_flag, tag_len, NULL)) {
  5385. php_error_docref(NULL, E_WARNING, "Setting tag length for AEAD cipher failed");
  5386. return FAILURE;
  5387. }
  5388. } else if (!enc && tag && tag_len > 0) {
  5389. if (!mode->is_aead) {
  5390. php_error_docref(NULL, E_WARNING, "The tag cannot be used because the cipher method does not support AEAD");
  5391. } else if (!EVP_CIPHER_CTX_ctrl(cipher_ctx, mode->aead_set_tag_flag, tag_len, (unsigned char *) tag)) {
  5392. php_error_docref(NULL, E_WARNING, "Setting tag for AEAD cipher decryption failed");
  5393. return FAILURE;
  5394. }
  5395. }
  5396. /* check and set key */
  5397. password_len = (int) *ppassword_len;
  5398. key_len = EVP_CIPHER_key_length(cipher_type);
  5399. if (key_len > password_len) {
  5400. if ((OPENSSL_DONT_ZERO_PAD_KEY & options) && !EVP_CIPHER_CTX_set_key_length(cipher_ctx, password_len)) {
  5401. php_openssl_store_errors();
  5402. php_error_docref(NULL, E_WARNING, "Key length cannot be set for the cipher method");
  5403. return FAILURE;
  5404. }
  5405. key = emalloc(key_len);
  5406. memset(key, 0, key_len);
  5407. memcpy(key, *ppassword, password_len);
  5408. *ppassword = (char *) key;
  5409. *ppassword_len = key_len;
  5410. *free_password = 1;
  5411. } else {
  5412. if (password_len > key_len && !EVP_CIPHER_CTX_set_key_length(cipher_ctx, password_len)) {
  5413. php_openssl_store_errors();
  5414. }
  5415. key = (unsigned char*)*ppassword;
  5416. }
  5417. if (!EVP_CipherInit_ex(cipher_ctx, NULL, NULL, key, (unsigned char *)*piv, enc)) {
  5418. php_openssl_store_errors();
  5419. return FAILURE;
  5420. }
  5421. if (options & OPENSSL_ZERO_PADDING) {
  5422. EVP_CIPHER_CTX_set_padding(cipher_ctx, 0);
  5423. }
  5424. return SUCCESS;
  5425. }
  5426. /* }}} */
  5427. static int php_openssl_cipher_update(const EVP_CIPHER *cipher_type,
  5428. EVP_CIPHER_CTX *cipher_ctx, struct php_openssl_cipher_mode *mode,
  5429. zend_string **poutbuf, int *poutlen, char *data, size_t data_len,
  5430. char *aad, size_t aad_len, int enc) /* {{{ */
  5431. {
  5432. int i = 0;
  5433. if (mode->is_single_run_aead && !EVP_CipherUpdate(cipher_ctx, NULL, &i, NULL, (int)data_len)) {
  5434. php_openssl_store_errors();
  5435. php_error_docref(NULL, E_WARNING, "Setting of data length failed");
  5436. return FAILURE;
  5437. }
  5438. if (mode->is_aead && !EVP_CipherUpdate(cipher_ctx, NULL, &i, (unsigned char *)aad, (int)aad_len)) {
  5439. php_openssl_store_errors();
  5440. php_error_docref(NULL, E_WARNING, "Setting of additional application data failed");
  5441. return FAILURE;
  5442. }
  5443. *poutbuf = zend_string_alloc((int)data_len + EVP_CIPHER_block_size(cipher_type), 0);
  5444. if (!EVP_CipherUpdate(cipher_ctx, (unsigned char*)ZSTR_VAL(*poutbuf),
  5445. &i, (unsigned char *)data, (int)data_len)) {
  5446. /* we don't show warning when we fail but if we ever do, then it should look like this:
  5447. if (mode->is_single_run_aead && !enc) {
  5448. php_error_docref(NULL, E_WARNING, "Tag verifycation failed");
  5449. } else {
  5450. php_error_docref(NULL, E_WARNING, enc ? "Encryption failed" : "Decryption failed");
  5451. }
  5452. */
  5453. php_openssl_store_errors();
  5454. zend_string_release_ex(*poutbuf, 0);
  5455. return FAILURE;
  5456. }
  5457. *poutlen = i;
  5458. return SUCCESS;
  5459. }
  5460. /* }}} */
  5461. PHP_OPENSSL_API zend_string* php_openssl_encrypt(char *data, size_t data_len, char *method, size_t method_len, char *password, size_t password_len, zend_long options, char *iv, size_t iv_len, zval *tag, zend_long tag_len, char *aad, size_t aad_len)
  5462. {
  5463. const EVP_CIPHER *cipher_type;
  5464. EVP_CIPHER_CTX *cipher_ctx;
  5465. struct php_openssl_cipher_mode mode;
  5466. int i = 0, outlen;
  5467. zend_bool free_iv = 0, free_password = 0;
  5468. zend_string *outbuf = NULL;
  5469. PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(data_len, data);
  5470. PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(password_len, password);
  5471. PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(aad_len, aad);
  5472. PHP_OPENSSL_CHECK_LONG_TO_INT_NORET(tag_len, tag_len);
  5473. cipher_type = EVP_get_cipherbyname(method);
  5474. if (!cipher_type) {
  5475. php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm");
  5476. return NULL;
  5477. }
  5478. cipher_ctx = EVP_CIPHER_CTX_new();
  5479. if (!cipher_ctx) {
  5480. php_error_docref(NULL, E_WARNING, "Failed to create cipher context");
  5481. return NULL;
  5482. }
  5483. php_openssl_load_cipher_mode(&mode, cipher_type);
  5484. if (php_openssl_cipher_init(cipher_type, cipher_ctx, &mode,
  5485. &password, &password_len, &free_password,
  5486. &iv, &iv_len, &free_iv, NULL, tag_len, options, 1) == FAILURE ||
  5487. php_openssl_cipher_update(cipher_type, cipher_ctx, &mode, &outbuf, &outlen,
  5488. data, data_len, aad, aad_len, 1) == FAILURE) {
  5489. outbuf = NULL;
  5490. } else if (EVP_EncryptFinal(cipher_ctx, (unsigned char *)ZSTR_VAL(outbuf) + outlen, &i)) {
  5491. outlen += i;
  5492. if (options & OPENSSL_RAW_DATA) {
  5493. ZSTR_VAL(outbuf)[outlen] = '\0';
  5494. ZSTR_LEN(outbuf) = outlen;
  5495. } else {
  5496. zend_string *base64_str;
  5497. base64_str = php_base64_encode((unsigned char*)ZSTR_VAL(outbuf), outlen);
  5498. zend_string_release_ex(outbuf, 0);
  5499. outbuf = base64_str;
  5500. }
  5501. if (mode.is_aead && tag) {
  5502. zend_string *tag_str = zend_string_alloc(tag_len, 0);
  5503. if (EVP_CIPHER_CTX_ctrl(cipher_ctx, mode.aead_get_tag_flag, tag_len, ZSTR_VAL(tag_str)) == 1) {
  5504. ZSTR_VAL(tag_str)[tag_len] = '\0';
  5505. ZSTR_LEN(tag_str) = tag_len;
  5506. ZEND_TRY_ASSIGN_REF_NEW_STR(tag, tag_str);
  5507. } else {
  5508. php_error_docref(NULL, E_WARNING, "Retrieving verification tag failed");
  5509. zend_string_release_ex(tag_str, 0);
  5510. zend_string_release_ex(outbuf, 0);
  5511. outbuf = NULL;
  5512. }
  5513. } else if (tag) {
  5514. ZEND_TRY_ASSIGN_REF_NULL(tag);
  5515. php_error_docref(NULL, E_WARNING,
  5516. "The authenticated tag cannot be provided for cipher that doesn not support AEAD");
  5517. } else if (mode.is_aead) {
  5518. php_error_docref(NULL, E_WARNING, "A tag should be provided when using AEAD mode");
  5519. zend_string_release_ex(outbuf, 0);
  5520. outbuf = NULL;
  5521. }
  5522. } else {
  5523. php_openssl_store_errors();
  5524. zend_string_release_ex(outbuf, 0);
  5525. outbuf = NULL;
  5526. }
  5527. if (free_password) {
  5528. efree(password);
  5529. }
  5530. if (free_iv) {
  5531. efree(iv);
  5532. }
  5533. EVP_CIPHER_CTX_reset(cipher_ctx);
  5534. EVP_CIPHER_CTX_free(cipher_ctx);
  5535. return outbuf;
  5536. }
  5537. /* {{{ proto string openssl_encrypt(string data, string method, string password [, int options=0 [, string $iv=''[, string &$tag = ''[, string $aad = ''[, int $tag_length = 16]]]]])
  5538. Encrypts given data with given method and key, returns raw or base64 encoded string */
  5539. PHP_FUNCTION(openssl_encrypt)
  5540. {
  5541. zend_long options = 0, tag_len = 16;
  5542. char *data, *method, *password, *iv = "", *aad = "";
  5543. size_t data_len, method_len, password_len, iv_len = 0, aad_len = 0;
  5544. zend_string *ret;
  5545. zval *tag = NULL;
  5546. if (zend_parse_parameters(ZEND_NUM_ARGS(), "sss|lszsl", &data, &data_len, &method, &method_len,
  5547. &password, &password_len, &options, &iv, &iv_len, &tag, &aad, &aad_len, &tag_len) == FAILURE) {
  5548. RETURN_THROWS();
  5549. }
  5550. if ((ret = php_openssl_encrypt(data, data_len, method, method_len, password, password_len, options, iv, iv_len, tag, tag_len, aad, aad_len))) {
  5551. RETVAL_STR(ret);
  5552. } else {
  5553. RETVAL_FALSE;
  5554. }
  5555. }
  5556. /* }}} */
  5557. PHP_OPENSSL_API zend_string* php_openssl_decrypt(char *data, size_t data_len, char *method, size_t method_len, char *password, size_t password_len, zend_long options, char *iv, size_t iv_len, char *tag, zend_long tag_len, char *aad, size_t aad_len)
  5558. {
  5559. const EVP_CIPHER *cipher_type;
  5560. EVP_CIPHER_CTX *cipher_ctx;
  5561. struct php_openssl_cipher_mode mode;
  5562. int i = 0, outlen;
  5563. zend_string *base64_str = NULL;
  5564. zend_bool free_iv = 0, free_password = 0;
  5565. zend_string *outbuf = NULL;
  5566. PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(data_len, data);
  5567. PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(password_len, password);
  5568. PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(aad_len, aad);
  5569. PHP_OPENSSL_CHECK_SIZE_T_TO_INT_NORET(tag_len, tag);
  5570. cipher_type = EVP_get_cipherbyname(method);
  5571. if (!cipher_type) {
  5572. php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm");
  5573. return NULL;
  5574. }
  5575. cipher_ctx = EVP_CIPHER_CTX_new();
  5576. if (!cipher_ctx) {
  5577. php_error_docref(NULL, E_WARNING, "Failed to create cipher context");
  5578. return NULL;
  5579. }
  5580. php_openssl_load_cipher_mode(&mode, cipher_type);
  5581. if (!(options & OPENSSL_RAW_DATA)) {
  5582. base64_str = php_base64_decode((unsigned char*)data, data_len);
  5583. if (!base64_str) {
  5584. php_error_docref(NULL, E_WARNING, "Failed to base64 decode the input");
  5585. EVP_CIPHER_CTX_free(cipher_ctx);
  5586. return NULL;
  5587. }
  5588. data_len = ZSTR_LEN(base64_str);
  5589. data = ZSTR_VAL(base64_str);
  5590. }
  5591. if (php_openssl_cipher_init(cipher_type, cipher_ctx, &mode,
  5592. &password, &password_len, &free_password,
  5593. &iv, &iv_len, &free_iv, tag, tag_len, options, 0) == FAILURE ||
  5594. php_openssl_cipher_update(cipher_type, cipher_ctx, &mode, &outbuf, &outlen,
  5595. data, data_len, aad, aad_len, 0) == FAILURE) {
  5596. outbuf = NULL;
  5597. } else if (mode.is_single_run_aead ||
  5598. EVP_DecryptFinal(cipher_ctx, (unsigned char *)ZSTR_VAL(outbuf) + outlen, &i)) {
  5599. outlen += i;
  5600. ZSTR_VAL(outbuf)[outlen] = '\0';
  5601. ZSTR_LEN(outbuf) = outlen;
  5602. } else {
  5603. php_openssl_store_errors();
  5604. zend_string_release_ex(outbuf, 0);
  5605. outbuf = NULL;
  5606. }
  5607. if (free_password) {
  5608. efree(password);
  5609. }
  5610. if (free_iv) {
  5611. efree(iv);
  5612. }
  5613. if (base64_str) {
  5614. zend_string_release_ex(base64_str, 0);
  5615. }
  5616. EVP_CIPHER_CTX_reset(cipher_ctx);
  5617. EVP_CIPHER_CTX_free(cipher_ctx);
  5618. return outbuf;
  5619. }
  5620. /* {{{ proto string openssl_decrypt(string data, string method, string password [, int options=0 [, string $iv = ''[, string $tag = ''[, string $aad = '']]]])
  5621. Takes raw or base64 encoded string and decrypts it using given method and key */
  5622. PHP_FUNCTION(openssl_decrypt)
  5623. {
  5624. zend_long options = 0;
  5625. char *data, *method, *password, *iv = "", *tag = NULL, *aad = "";
  5626. size_t data_len, method_len, password_len, iv_len = 0, tag_len = 0, aad_len = 0;
  5627. zend_string *ret;
  5628. if (zend_parse_parameters(ZEND_NUM_ARGS(), "sss|lsss", &data, &data_len, &method, &method_len,
  5629. &password, &password_len, &options, &iv, &iv_len, &tag, &tag_len, &aad, &aad_len) == FAILURE) {
  5630. RETURN_THROWS();
  5631. }
  5632. if (!method_len) {
  5633. php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm");
  5634. RETURN_FALSE;
  5635. }
  5636. if ((ret = php_openssl_decrypt(data, data_len, method, method_len, password, password_len, options, iv, iv_len, tag, tag_len, aad, aad_len))) {
  5637. RETVAL_STR(ret);
  5638. } else {
  5639. RETVAL_FALSE;
  5640. }
  5641. }
  5642. /* }}} */
  5643. PHP_OPENSSL_API zend_long php_openssl_cipher_iv_length(char *method)
  5644. {
  5645. const EVP_CIPHER *cipher_type;
  5646. cipher_type = EVP_get_cipherbyname(method);
  5647. if (!cipher_type) {
  5648. php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm");
  5649. return -1;
  5650. }
  5651. return EVP_CIPHER_iv_length(cipher_type);
  5652. }
  5653. /* {{{ proto int openssl_cipher_iv_length(string $method) */
  5654. PHP_FUNCTION(openssl_cipher_iv_length)
  5655. {
  5656. char *method;
  5657. size_t method_len;
  5658. zend_long ret;
  5659. if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &method, &method_len) == FAILURE) {
  5660. RETURN_THROWS();
  5661. }
  5662. if (!method_len) {
  5663. php_error_docref(NULL, E_WARNING, "Unknown cipher algorithm");
  5664. RETURN_FALSE;
  5665. }
  5666. if ((ret = php_openssl_cipher_iv_length(method)) == -1) {
  5667. RETURN_FALSE;
  5668. }
  5669. RETURN_LONG(ret);
  5670. }
  5671. /* }}} */
  5672. PHP_OPENSSL_API zend_string* php_openssl_random_pseudo_bytes(zend_long buffer_length)
  5673. {
  5674. zend_string *buffer = NULL;
  5675. if (buffer_length <= 0
  5676. #ifndef PHP_WIN32
  5677. || ZEND_LONG_INT_OVFL(buffer_length)
  5678. #endif
  5679. ) {
  5680. zend_argument_error(NULL, 1, "must be greater than 0");
  5681. return NULL;
  5682. }
  5683. buffer = zend_string_alloc(buffer_length, 0);
  5684. #ifdef PHP_WIN32
  5685. /* random/urandom equivalent on Windows */
  5686. if (php_win32_get_random_bytes((unsigned char*)(buffer)->val, (size_t) buffer_length) == FAILURE){
  5687. zend_string_release_ex(buffer, 0);
  5688. zend_throw_exception(zend_ce_exception, "Error reading from source device", 0);
  5689. return NULL;
  5690. }
  5691. #else
  5692. PHP_OPENSSL_CHECK_LONG_TO_INT_NORET(buffer_length, length);
  5693. PHP_OPENSSL_RAND_ADD_TIME();
  5694. /* FIXME loop if requested size > INT_MAX */
  5695. if (RAND_bytes((unsigned char*)ZSTR_VAL(buffer), (int)buffer_length) <= 0) {
  5696. zend_string_release_ex(buffer, 0);
  5697. zend_throw_exception(zend_ce_exception, "Error reading from source device", 0);
  5698. return NULL;
  5699. } else {
  5700. php_openssl_store_errors();
  5701. }
  5702. #endif
  5703. return buffer;
  5704. }
  5705. /* {{{ proto string openssl_random_pseudo_bytes(int length [, &bool returned_strong_result])
  5706. Returns a string of the length specified filled with random pseudo bytes */
  5707. PHP_FUNCTION(openssl_random_pseudo_bytes)
  5708. {
  5709. zend_string *buffer = NULL;
  5710. zend_long buffer_length;
  5711. zval *zstrong_result_returned = NULL;
  5712. if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|z", &buffer_length, &zstrong_result_returned) == FAILURE) {
  5713. RETURN_THROWS();
  5714. }
  5715. if (zstrong_result_returned) {
  5716. ZEND_TRY_ASSIGN_REF_FALSE(zstrong_result_returned);
  5717. }
  5718. if ((buffer = php_openssl_random_pseudo_bytes(buffer_length))) {
  5719. ZSTR_VAL(buffer)[buffer_length] = 0;
  5720. RETVAL_NEW_STR(buffer);
  5721. }
  5722. if (zstrong_result_returned) {
  5723. ZEND_TRY_ASSIGN_REF_TRUE(zstrong_result_returned);
  5724. }
  5725. }
  5726. /* }}} */